hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
726d0c7789a0231e613fa6d96f55ba4dc71990ba | 2,048 |
// =============== sum ===============
// O(n)
func sumOpration1(_ n:Int) -> Int{
var sum = 0
for i in 1 ... n {
sum += i
}
return sum
}
sumOpration1(100)//5050
// O(1)
func sumOpration2(_ n:Int) -> Int{
return (1 + n) * n/2
}
sumOpration2(100)//5050
//O(n ^ 2)
func findTwoSum(_ array: [Int], target: Int) -> (Int, Int)? {
guard array.count > 1 else {
return nil
}
for i in 0..<array.count {
let left = array[i]
for j in (i + 1)..<array.count {
let right = array[j]
if left + right == target {
return (i, j)
}
}
}
return nil
}
let array = [0,2,1,3,6]
if let indexes = findTwoSum(array, target: 8) {
print(indexes)
} else {
print("No pairs are found")
}
//O(n)
func findTwoSumOptimized(_ array: [Int], target: Int) -> (Int, Int)? {
guard array.count > 1 else {
return nil
}
var diffs = Dictionary<Int, Int>()
for i in 0..<array.count {
let left = array[i]
let right = target - left
if let foundIndex = diffs[right] {
return (i, foundIndex)
} else {
diffs[left] = i
}
}
return nil
}
// =============== recursion ===============
//good recursion
func factorial(_ n:Int) -> Int{
return n < 2 ? 1: n * factorial(n-1)
}
factorial(3) //6
factorial(4) //24
// bad recursion - > stack overflow
func factorialInfinite(_ n:Int) -> Int{
return n * factorialInfinite(n-1)
}
//factorialInfinite(3)
// bad recursion - > stack overflow
func sumOperation( _ n:Int) -> Int {
if n == 0 {
return 0
}
return n + sumOperation(n - 1)
}
sumOperation(2) //0
//sumOperation(-1) //stack overflow
// good recursion
func sumOperation1( _ n:Int) -> Int {
if n <= 0 {
return 0
}
return n + sumOperation1(n - 1)
}
sumOperation1(-1) //0
| 15.753846 | 70 | 0.481934 |
e41ea5154ec07e9a8246d5044ee8e7e8b70cb638 | 336 | //
// ViewController.swift
// Tumblr
//
// Created by Brett Stevenson on 9/11/19.
// Copyright © 2019 Brett Stevenson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 16 | 58 | 0.66369 |
62eac360b55a7d86a04f1bde205b1df4224a8d30 | 1,260 | import Flutter
import UIKit
public class SwiftInstallPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "install_plugin", binaryMessenger: registrar.messenger())
let instance = SwiftInstallPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "gotoAppStore":
print(call.arguments ?? "null")
guard let urlString = (call.arguments as? Dictionary<String, Any>)?["urlString"] as? String else {
result(FlutterError(code: "参数url不能为空", message: nil, details: nil))
return
}
gotoAppStore(urlString: urlString)
default:
result(FlutterMethodNotImplemented)
}
}
//跳转到应用的AppStore页页面
func gotoAppStore(urlString: String) {
if let url = URL(string: urlString) {
//根据iOS系统版本,分别处理
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],completionHandler: {(success) in })
} else {
UIApplication.shared.openURL(url)
}
}
}
}
| 34.054054 | 106 | 0.64127 |
f5969c6f566a26fc21d4e095b68484bf167ee333 | 1,928 | //
// ViewController.swift
// Demo
//
// Created by Sergey Shatunov on 8/30/17.
// Copyright © 2017 SHS. All rights reserved.
//
import UIKit
import PhoneNumberFormatter
class ViewController: UIViewController {
@IBOutlet weak var textField: PhoneFormattedTextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.becomeFirstResponder()
textField.textDidChangeBlock = { field in
if let text = field?.text {
print(text)
} else {
print("No text")
}
}
defaultExample()
}
func defaultExample() {
textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "# (###) ###-##-##")
}
func prefixExample() {
textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "(###) ###-##-##")
textField.prefix = "+7 "
let custom = PhoneFormat(phoneFormat: "(###) ###-##-##", regexp: "^[0-689]\\d*$")
textField.config.add(format: custom)
}
func doubleFormatExample() {
textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "##########")
textField.prefix = nil
let custom1 = PhoneFormat(phoneFormat: "+# (###) ###-##-##", regexp: "^7[0-689]\\d*$")
textField.config.add(format: custom1)
let custom2 = PhoneFormat(phoneFormat: "+### ###-##-##", regexp: "^380\\d*$")
textField.config.add(format: custom2)
}
func doubleFormatExamplePrefixed() {
textField.config.defaultConfiguration = PhoneFormat(defaultPhoneFormat: "### ### ###")
textField.prefix = "+7 "
let custom1 = PhoneFormat(phoneFormat: "(###) ###-##-##", regexp: "^1\\d*$")
textField.config.add(format: custom1)
let custom2 = PhoneFormat(phoneFormat: "(###) ###-###", regexp: "^2\\d*$")
textField.config.add(format: custom2)
}
}
| 29.661538 | 100 | 0.580913 |
14610e2e314cb22eb03edc2883fe30ad86b01c5f | 1,402 | //
// GasStationModel.swift
// CarCardLocation
//
// Created by liujianlin on 2018/8/15.
// Copyright © 2018年 liujianlin. All rights reserved.
//
import UIKit
import RealmSwift
import Realm
class GasStationModel: Object, FCCodable {
@objc dynamic var cityName: String = ""
@objc dynamic var company: String = ""
@objc dynamic var region: String = ""
@objc dynamic var name: String = ""
@objc dynamic var address: String = ""
@objc dynamic var latitude: Double = 0
@objc dynamic var longitude: Double = 0
required init(value: Any, schema: RLMSchema) {
fatalError("init(value:schema:) has not been implemented")
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
required init() {
super.init()
}
init(gasStation: GasStationModel) {
super.init()
cityName = gasStation.cityName
company = gasStation.company
region = gasStation.region
name = gasStation.name
address = gasStation.address
latitude = gasStation.latitude
longitude = gasStation.longitude
}
private enum CodingKeys: String, CodingKey {
case company
case region
case name
case address
}
override class func primaryKey() -> String? {
return "address"
}
}
| 25.035714 | 66 | 0.624108 |
7184fdd5c4d44c10f641b1573dfb4da10f42016e | 475 | //
// Copyright © 2020 jm. All rights reserved.
//
import UIKit
import Foundation
public extension Bundle {
static var base_bundle: Bundle? = nil
@objc class func demo_BaseBundle() -> Bundle? {
if self.base_bundle == nil, let path = Bundle(for: LCBaseModule.classForCoder()).path(forResource: "LCBaseModuleBundle", ofType: "bundle") {
self.base_bundle = Bundle(path: path)
}
return self.base_bundle
}
}
| 21.590909 | 148 | 0.629474 |
56d5b951906941dc154120d1c8d1e8a6e604b580 | 436 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{class A{class A:func a{{func a<f:f.c
| 43.6 | 79 | 0.747706 |
d9b0d98f2668686d852651193dc31da18fdecb60 | 2,004 | import Foundation
import SafariServices
@objc(CAPBrowserPlugin)
public class CAPBrowserPlugin : CAPPlugin, SFSafariViewControllerDelegate {
var vc: SFSafariViewController?
@objc func open(_ call: CAPPluginCall) {
guard let urlString = call.getString("url") else {
call.error("Must provide a URL to open")
return
}
if urlString.isEmpty {
call.error("URL must not be empty")
return
}
let toolbarColor = call.getString("toolbarColor")
let url = URL(string: urlString)
if let scheme = url?.scheme, ["http", "https"].contains(scheme.lowercased()) {
DispatchQueue.main.async {
self.vc = SFSafariViewController.init(url: url!)
self.vc!.delegate = self
let presentationStyle = call.getString("presentationStyle")
if presentationStyle != nil && presentationStyle == "popover" {
self.vc!.modalPresentationStyle = .popover
self.setCenteredPopover(self.vc)
} else {
self.vc!.modalPresentationStyle = .fullScreen
}
if toolbarColor != nil {
self.vc!.preferredBarTintColor = UIColor(fromHex: toolbarColor!)
}
self.bridge.viewController.present(self.vc!, animated: true, completion: {
call.success()
})
}
} else {
call.error("Invalid URL")
}
}
@objc func close(_ call: CAPPluginCall) {
if vc == nil {
call.success()
}
DispatchQueue.main.async {
self.bridge.viewController.dismiss(animated: true) {
call.success()
}
}
}
@objc func prefetch(_ call: CAPPluginCall) {
call.unimplemented()
}
public func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
self.notifyListeners("browserFinished", data: [:])
vc = nil
}
public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
self.notifyListeners("browserPageLoaded", data: [:])
}
}
| 28.225352 | 124 | 0.648703 |
76e0d16b8091cd28586742a1b0fb8d923fb4bd1f | 1,874 | import Foundation
/// Describes array type
@objcMembers public final class ArrayType: NSObject, SourceryModel {
/// Type name used in declaration
public var name: String
/// Array element type name
public var elementTypeName: TypeName
// sourcery: skipEquality, skipDescription
/// Array element type, if known
public var elementType: Type?
/// :nodoc:
public init(name: String, elementTypeName: TypeName, elementType: Type? = nil) {
self.name = name
self.elementTypeName = elementTypeName
self.elementType = elementType
}
/// Returns array as generic type
public var asGeneric: GenericType {
GenericType(name: "Array", typeParameters: [
.init(typeName: elementTypeName)
])
}
public var asSource: String {
"[\(elementTypeName.asSource)]"
}
// sourcery:inline:ArrayType.AutoCoding
/// :nodoc:
required public init?(coder aDecoder: NSCoder) {
guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name
guard let elementTypeName: TypeName = aDecoder.decode(forKey: "elementTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["elementTypeName"])); fatalError() }; self.elementTypeName = elementTypeName
self.elementType = aDecoder.decode(forKey: "elementType")
}
/// :nodoc:
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.elementTypeName, forKey: "elementTypeName")
aCoder.encode(self.elementType, forKey: "elementType")
}
// sourcery:end
}
| 36.745098 | 284 | 0.659552 |
1cf656711bd2e476e70ac646934f0375ada7a966 | 394 | //
// ClearNavigationStackSegue.swift
// EmeraldAdmin
//
// Created by Liem Vo on 7/26/17.
// Copyright © 2017 VNG. All rights reserved.
//
import UIKit
class ClearNavigationStackSegue: UIStoryboardSegue {
override func perform() {
source.navigationController?.setViewControllers([destination], animated: true)
destination.navigationItem.hidesBackButton = true
}
}
| 24.625 | 86 | 0.72335 |
39712bd72712bd49a1c0838c8348b3af6613db71 | 21,707 | import Foundation
public enum LegendIcon {
case square(Color)
case shape(ScatterPlotSeriesOptions.ScatterPattern, Color)
}
public struct GraphLayout {
// Inputs.
var backgroundColor: Color = .white
var plotBackgroundColor: Color?
var plotTitle = PlotTitle()
var plotLabel = PlotLabel()
var plotLegend = PlotLegend()
var plotBorder = PlotBorder()
var grid = Grid()
var annotations: [Annotation] = []
var enablePrimaryAxisGrid = true
var enableSecondaryAxisGrid = true
var markerTextSize: Float = 12
/// The amount of (horizontal) space to reserve for markers on the Y-axis.
var yMarkerMaxWidth: Float = 40
struct Results {
/// The size these results have been calculated for; the entire size of the plot.
let totalSize: Size
/// The region of the plot which will actually be filled with chart data.
var plotBorderRect: Rect
struct LabelSizes {
var xLabelSize: Size?
var yLabelSize: Size?
var y2LabelSize: Size?
var titleSize: Size?
}
/// The sizes of various labels outside the chart area.
/// These must be measured _before_ the `plotBorderRect` can be calculated.
var sizes: LabelSizes
var xLabelLocation: Point?
var yLabelLocation: Point?
var y2LabelLocation: Point?
var titleLocation: Point?
var plotMarkers = PlotMarkers()
var xMarkersTextLocation = [Point]()
var yMarkersTextLocation = [Point]()
var y2MarkersTextLocation = [Point]()
var legendLabels: [(String, LegendIcon)] = []
var legendRect: Rect?
}
// Layout.
func layout<T>(size: Size, renderer: Renderer,
calculateMarkers: (Size)->(T, PlotMarkers?, [(String, LegendIcon)]?) ) -> (T, Results) {
// 1. Measure the things outside of the plot's border (axis titles, plot title)
let sizes = measureLabels(renderer: renderer)
// 2. Calculate the plot's border
let borderRect = calcBorder(totalSize: size, labelSizes: sizes, renderer: renderer)
// 3. Lay out the things outside of the plot's border (axis titles, plot title)
var results = Results(totalSize: size, plotBorderRect: borderRect, sizes: sizes)
calcLabelLocations(&results)
// 4. Let the plot calculate its scale, calculate marker positions.
let (drawingData, markers, legendInfo) = calculateMarkers(results.plotBorderRect.size)
markers.map { results.plotMarkers = $0 }
legendInfo.map { results.legendLabels = $0 }
// 5. Lay out remaining chrome.
calcMarkerTextLocations(renderer: renderer, results: &results)
calcLegend(results.legendLabels, renderer: renderer, results: &results)
return (drawingData, results)
}
static let xLabelPadding: Float = 10
static let yLabelPadding: Float = 10
static let titleLabelPadding: Float = 14
/// Measures the sizes of chrome elements outside the plot's borders (axis titles, plot title, etc).
private func measureLabels(renderer: Renderer) -> Results.LabelSizes {
var results = Results.LabelSizes()
if !plotLabel.xLabel.isEmpty {
results.xLabelSize = renderer.getTextLayoutSize(text: plotLabel.xLabel, textSize: plotLabel.size)
}
if !plotLabel.yLabel.isEmpty {
results.yLabelSize = renderer.getTextLayoutSize(text: plotLabel.yLabel, textSize: plotLabel.size)
}
if !plotLabel.y2Label.isEmpty {
results.y2LabelSize = renderer.getTextLayoutSize(text: plotLabel.y2Label, textSize: plotLabel.size)
}
if !plotTitle.title.isEmpty {
results.titleSize = renderer.getTextLayoutSize(text: plotTitle.title, textSize: plotTitle.size)
}
return results
}
/// Calculates the region of the plot which is used for displaying the plot's data (inside all of the chrome).
private func calcBorder(totalSize: Size, labelSizes: Results.LabelSizes, renderer: Renderer) -> Rect {
var borderRect = Rect(
origin: zeroPoint,
size: totalSize
)
if let xLabel = labelSizes.xLabelSize {
borderRect.clampingShift(dy: xLabel.height + 2 * Self.xLabelPadding)
}
if let yLabel = labelSizes.yLabelSize {
borderRect.clampingShift(dx: yLabel.height + 2 * Self.yLabelPadding)
}
if let y2Label = labelSizes.y2LabelSize {
borderRect.size.width -= (y2Label.height + 2 * Self.yLabelPadding)
}
if let titleLabel = labelSizes.titleSize {
borderRect.size.height -= (titleLabel.height + 2 * Self.titleLabelPadding)
} else {
// Add a space to the top when there is no title.
borderRect.size.height -= Self.titleLabelPadding
}
borderRect.contract(by: plotBorder.thickness)
// Give space for the markers.
borderRect.clampingShift(dy: (2 * markerTextSize) + 10) // X markers
// TODO: Better space calculation for Y/Y2 markers.
borderRect.clampingShift(dx: yMarkerMaxWidth + 10) // Y markers
borderRect.size.width -= yMarkerMaxWidth + 10 // Y2 markers
// Sanitize the resulting rectangle.
borderRect.size.width = max(borderRect.size.width, 0)
borderRect.size.height = max(borderRect.size.height, 0)
return borderRect
}
/// Lays out the chrome elements outside the plot's borders (axis titles, plot title, etc).
private func calcLabelLocations(_ results: inout Results) {
if let xLabelSize = results.sizes.xLabelSize {
results.xLabelLocation = Point(results.plotBorderRect.midX - xLabelSize.width/2,
Self.xLabelPadding)
}
if let titleLabelSize = results.sizes.titleSize {
results.titleLocation = Point(results.plotBorderRect.midX - titleLabelSize.width/2,
results.totalSize.height - titleLabelSize.height - Self.titleLabelPadding)
}
if let yLabelSize = results.sizes.yLabelSize {
results.yLabelLocation = Point(Self.yLabelPadding + yLabelSize.height,
results.plotBorderRect.midY - yLabelSize.width/2)
}
if let y2LabelSize = results.sizes.y2LabelSize {
results.y2LabelLocation = Point(results.totalSize.width - Self.yLabelPadding,
results.plotBorderRect.midY - y2LabelSize.width/2)
}
}
private func calcMarkerTextLocations(renderer: Renderer, results: inout Results) {
for i in 0..<results.plotMarkers.xMarkers.count {
let textWidth = renderer.getTextWidth(text: results.plotMarkers.xMarkersText[i], textSize: markerTextSize)
let text_p = Point(results.plotMarkers.xMarkers[i] - (textWidth/2), -2.0 * markerTextSize)
results.xMarkersTextLocation.append(text_p)
}
for i in 0..<results.plotMarkers.yMarkers.count {
var textWidth = renderer.getTextWidth(text: results.plotMarkers.yMarkersText[i], textSize: markerTextSize)
textWidth = min(textWidth, yMarkerMaxWidth)
let text_p = Point(-textWidth - 8, results.plotMarkers.yMarkers[i] - 4)
results.yMarkersTextLocation.append(text_p)
}
for i in 0..<results.plotMarkers.y2Markers.count {
let text_p = Point(results.plotBorderRect.width + 8, results.plotMarkers.y2Markers[i] - 4)
results.y2MarkersTextLocation.append(text_p)
}
}
private func calcLegend(_ labels: [(String, LegendIcon)], renderer: Renderer, results: inout Results) {
guard !labels.isEmpty else { return }
let maxWidth = labels.lazy.map {
renderer.getTextWidth(text: $0.0, textSize: self.plotLegend.textSize)
}.max() ?? 0
let legendWidth = maxWidth + 3.5 * plotLegend.textSize
let legendHeight = (Float(labels.count)*2.0 + 1.0) * plotLegend.textSize
let legendTopLeft = Point(results.plotBorderRect.minX + Float(20),
results.plotBorderRect.maxY - Float(20))
results.legendRect = Rect(
origin: legendTopLeft,
size: Size(width: legendWidth, height: -legendHeight)
).normalized
}
// Drawing.
func drawBackground(results: Results, renderer: Renderer) {
renderer.drawSolidRect(Rect(origin: zeroPoint, size: results.totalSize),
fillColor: backgroundColor, hatchPattern: .none)
if let plotBackgroundColor = plotBackgroundColor {
renderer.drawSolidRect(results.plotBorderRect, fillColor: plotBackgroundColor, hatchPattern: .none)
}
drawGrid(results: results, renderer: renderer)
drawBorder(results: results, renderer: renderer)
drawMarkers(results: results, renderer: renderer)
}
func drawForeground(results: Results, renderer: Renderer) {
drawTitle(results: results, renderer: renderer)
drawLabels(results: results, renderer: renderer)
drawLegend(results.legendLabels, results: results, renderer: renderer)
drawAnnotations(renderer: renderer)
}
private func drawTitle(results: Results, renderer: Renderer) {
if let titleLocation = results.titleLocation {
renderer.drawText(text: plotTitle.title,
location: titleLocation,
textSize: plotTitle.size,
color: plotTitle.color,
strokeWidth: 1.2,
angle: 0)
}
}
private func drawLabels(results: Results, renderer: Renderer) {
if let xLocation = results.xLabelLocation {
renderer.drawText(text: plotLabel.xLabel,
location: xLocation,
textSize: plotLabel.size,
color: plotLabel.color,
strokeWidth: 1.2,
angle: 0)
}
if let yLocation = results.yLabelLocation {
renderer.drawText(text: plotLabel.yLabel,
location: yLocation,
textSize: plotLabel.size,
color: plotLabel.color,
strokeWidth: 1.2,
angle: 90)
}
if let y2Location = results.y2LabelLocation {
renderer.drawText(text: plotLabel.y2Label,
location: y2Location,
textSize: plotLabel.size,
color: plotLabel.color,
strokeWidth: 1.2,
angle: 90)
}
}
private func drawBorder(results: Results, renderer: Renderer) {
renderer.drawRect(results.plotBorderRect,
strokeWidth: plotBorder.thickness,
strokeColor: plotBorder.color)
}
private func drawGrid(results: Results, renderer: Renderer) {
guard enablePrimaryAxisGrid || enablePrimaryAxisGrid else { return }
let rect = results.plotBorderRect
for index in 0..<results.plotMarkers.xMarkers.count {
let p1 = Point(results.plotMarkers.xMarkers[index] + rect.minX, rect.minY)
let p2 = Point(results.plotMarkers.xMarkers[index] + rect.minX, rect.maxY)
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: grid.thickness,
strokeColor: grid.color,
isDashed: false)
}
if (enablePrimaryAxisGrid) {
for index in 0..<results.plotMarkers.yMarkers.count {
let p1 = Point(rect.minX, results.plotMarkers.yMarkers[index] + rect.minY)
let p2 = Point(rect.maxX, results.plotMarkers.yMarkers[index] + rect.minY)
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: grid.thickness,
strokeColor: grid.color,
isDashed: false)
}
}
if (enableSecondaryAxisGrid) {
for index in 0..<results.plotMarkers.y2Markers.count {
let p1 = Point(rect.minX, results.plotMarkers.y2Markers[index] + rect.minY)
let p2 = Point(rect.maxX, results.plotMarkers.y2Markers[index] + rect.minY)
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: grid.thickness,
strokeColor: grid.color,
isDashed: false)
}
}
}
private func drawMarkers(results: Results, renderer: Renderer) {
let rect = results.plotBorderRect
for index in 0..<results.plotMarkers.xMarkers.count {
let p1 = Point(results.plotMarkers.xMarkers[index], -6) + rect.origin
let p2 = Point(results.plotMarkers.xMarkers[index], 0) + rect.origin
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: plotBorder.thickness,
strokeColor: plotBorder.color,
isDashed: false)
renderer.drawText(text: results.plotMarkers.xMarkersText[index],
location: results.xMarkersTextLocation[index] + rect.origin,
textSize: markerTextSize,
color: plotBorder.color,
strokeWidth: 0.7,
angle: 0)
}
for index in 0..<results.plotMarkers.yMarkers.count {
let p1 = Point(-6, results.plotMarkers.yMarkers[index]) + rect.origin
let p2 = Point(0, results.plotMarkers.yMarkers[index]) + rect.origin
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: plotBorder.thickness,
strokeColor: plotBorder.color,
isDashed: false)
renderer.drawText(text: results.plotMarkers.yMarkersText[index],
location: results.yMarkersTextLocation[index] + rect.origin,
textSize: markerTextSize,
color: plotBorder.color,
strokeWidth: 0.7,
angle: 0)
}
if !results.plotMarkers.y2Markers.isEmpty {
for index in 0..<results.plotMarkers.y2Markers.count {
let p1 = Point(results.plotBorderRect.width,
(results.plotMarkers.y2Markers[index])) + rect.origin
let p2 = Point(results.plotBorderRect.width + 6,
(results.plotMarkers.y2Markers[index])) + rect.origin
renderer.drawLine(startPoint: p1,
endPoint: p2,
strokeWidth: plotBorder.thickness,
strokeColor: plotBorder.color,
isDashed: false)
renderer.drawText(text: results.plotMarkers.y2MarkersText[index],
location: results.y2MarkersTextLocation[index] + rect.origin,
textSize: markerTextSize,
color: plotBorder.color,
strokeWidth: 0.7,
angle: 0)
}
}
}
private func drawLegend(_ entries: [(String, LegendIcon)], results: Results, renderer: Renderer) {
guard let legendRect = results.legendRect else { return }
renderer.drawSolidRectWithBorder(legendRect,
strokeWidth: plotLegend.borderThickness,
fillColor: plotLegend.backgroundColor,
borderColor: plotLegend.borderColor)
for i in 0..<entries.count {
let seriesIcon = Rect(
origin: Point(legendRect.origin.x + plotLegend.textSize,
legendRect.maxY - (2.0*Float(i) + 1.0)*plotLegend.textSize),
size: Size(width: plotLegend.textSize, height: -plotLegend.textSize)
)
switch entries[i].1 {
case .square(let color):
renderer.drawSolidRect(seriesIcon,
fillColor: color,
hatchPattern: .none)
case .shape(let shape, let color):
shape.draw(in: seriesIcon,
color: color,
renderer: renderer)
}
let p = Point(seriesIcon.maxX + plotLegend.textSize, seriesIcon.minY)
renderer.drawText(text: entries[i].0,
location: p,
textSize: plotLegend.textSize,
color: plotLegend.textColor,
strokeWidth: 1.2,
angle: 0)
}
}
func drawAnnotations(renderer: Renderer) {
for var annotation in annotations{
annotation.draw(renderer: renderer)
}
}
}
public protocol HasGraphLayout {
var layout: GraphLayout { get set }
// Optional graph features (have default implementations).
var legendLabels: [(String, LegendIcon)] { get }
// Layout and drawing callbacks.
/// The information this graph needs to draw - for example: scaled locations for data points.
associatedtype DrawingData
/// Lays out the chart's data within the rect `{ x: (0...size.width), y: (0...size.height) }`
/// and produces a set of instructions for drawing by the `drawData` function, and optionally
/// a set of axis markers for the `GraphLayout` to draw.
/// - parameters:
/// - size: The size which the chart has to present its data.
/// - renderer: The renderer which will draw the chart. Useful for text-size calculations.
/// - returns: A tuple containing data to be drawn and any axis markers the chart desires.
func layoutData(size: Size, renderer: Renderer) -> (DrawingData, PlotMarkers?)
/// Draws the data calculated by this chart's layout phase in the given renderer.
/// - parameters:
/// - data: The data produced by this chart's `layoutData` method.
/// - size: The size which the chart has to present its data. The same size as was used to calculate `data`.
/// The chart must only draw within the rect `{ x: (0...size.width), y: (0...size.height) }`.
/// - renderer: The renderer in which to draw.
func drawData(_ data: DrawingData, size: Size, renderer: Renderer)
}
extension HasGraphLayout {
// Default implementation.
public var legendLabels: [(String, LegendIcon)] {
return []
}
public var annotations: [Annotation] {
get { layout.annotations }
set { layout.annotations = newValue }
}
public var plotTitle: PlotTitle {
get { layout.plotTitle }
set { layout.plotTitle = newValue }
}
public var plotLabel: PlotLabel {
get { layout.plotLabel }
set { layout.plotLabel = newValue }
}
public var plotLegend: PlotLegend {
get { layout.plotLegend }
set { layout.plotLegend = newValue }
}
public var plotBorder: PlotBorder {
get { layout.plotBorder }
set { layout.plotBorder = newValue }
}
public var grid: Grid {
get { layout.grid }
set { layout.grid = newValue }
}
public var backgroundColor: Color {
get { layout.backgroundColor }
set { layout.backgroundColor = newValue }
}
public var plotBackgroundColor: Color? {
get { layout.plotBackgroundColor }
set { layout.plotBackgroundColor = newValue }
}
public var markerTextSize: Float {
get { layout.markerTextSize }
set { layout.markerTextSize = newValue }
}
}
extension Plot where Self: HasGraphLayout {
public func drawGraph(size: Size, renderer: Renderer) {
let (drawingData, results) = layout.layout(size: size, renderer: renderer) {
size -> (DrawingData, PlotMarkers?, [(String, LegendIcon)]?) in
let tup = layoutData(size: size, renderer: renderer)
return (tup.0, tup.1, self.legendLabels)
}
layout.drawBackground(results: results, renderer: renderer)
renderer.withAdditionalOffset(results.plotBorderRect.origin) { renderer in
drawData(drawingData, size: results.plotBorderRect.size, renderer: renderer)
}
layout.drawForeground(results: results, renderer: renderer)
}
public mutating func addAnnotation(annotation: Annotation) {
layout.annotations.append(annotation)
}
}
| 44.942029 | 118 | 0.574377 |
e2f2a820ab226e6f60586ea0c53226828cd67538 | 567 | //
// UserDataSource.swift
// AccessibilityTest
//
// Created by stakata on 2018/06/25.
// Copyright © 2018年 shiz. All rights reserved.
//
import Foundation
struct UserDataSource {
static func users() -> [User] {
let userList = [
User(id: 1, name: "じろう", imageUrl: "a"),
User(id: 2, name: "かおり", imageUrl: "b"),
User(id: 3, name: "おじいちゃん", imageUrl: "c"),
User(id: 4, name: "おとうさん", imageUrl: "d"),
User(id: 5, name: "おかあさん", imageUrl: "e"),
]
return userList
}
}
| 23.625 | 55 | 0.527337 |
21ff4749d012e5887f9cde8806c945a4abed4a26 | 14,237 | //
// ActivityClassifier.swift
// PoseEstimation-CoreML
//
// Created by Tony Rolletschke on 04.12.19.
// Copyright © 2019 tucan9389. All rights reserved.
//
import UIKit
import Vision
protocol ActivityManagerDelegate {
func didUpdateActivity(prediction :(activity: String?,probability:Double?))
}
class ActivityManager {
private let activityClassificationModel = MyActivityClassifierTony()
struct ModelConstants {
static let numOfFeatures = 16
static let predictionWindowSize = 15
static let hiddenInLength = 200
static let hiddenCellInLength = 200
}
private var predictionWindowDataArray : MLMultiArray? = try? MLMultiArray(shape: [1 , ModelConstants.predictionWindowSize , ModelConstants.numOfFeatures] as [NSNumber], dataType: MLMultiArrayDataType.double)
private var lastHiddenCellOutput: MLMultiArray?
private var lastHiddenOutput: MLMultiArray?
private var currentIndexInPredictionWindow = 0
var delegate: ActivityManagerDelegate?
var videoWidth : CGFloat = 1920.00
var videoHeigth : CGFloat = 1440.00
init() {
//
self.setUpActivtyClassifier()
}
deinit {
self.predictionWindowDataArray = nil
self.lastHiddenCellOutput = nil
self.lastHiddenOutput = nil
self.currentIndexInPredictionWindow = 0
}
func setUpActivtyClassifier(){
predictionWindowDataArray = try? MLMultiArray(shape: [1 , ModelConstants.predictionWindowSize , ModelConstants.numOfFeatures] as [NSNumber], dataType: MLMultiArrayDataType.double)
lastHiddenOutput = try? MLMultiArray(shape:[ModelConstants.hiddenInLength as NSNumber], dataType: MLMultiArrayDataType.double)
lastHiddenCellOutput = try? MLMultiArray(shape:[ModelConstants.hiddenCellInLength as NSNumber], dataType: MLMultiArrayDataType.double)
}
func predictActivty(bodypoints :Any) {
//guard let upperBody = getUpperBodyFromPoseEstimation(points: bodypoints as! [BodyPoint?]) else {return}
let upperBody:UpperBody? = getUpperBodyFromARKit(points: bodypoints as! [Int:CGPoint])
if upperBody != nil {
predictUpperBodyActivity(upperBody: upperBody!)
}else{
delegate?.didUpdateActivity(prediction: ("unknown",0.0))
}
}
func predictUpperBodyActivity(upperBody : UpperBody) {
guard let dataArray = predictionWindowDataArray else {
delegate?.didUpdateActivity(prediction: ("unknown",0.0))
return
}
if upperBody.rshoulder.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,0] as [NSNumber]] = Double(upperBody.rshoulder.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,1] as [NSNumber]] = Double(upperBody.rshoulder.point!.y) as NSNumber
}else{
return
}
if upperBody.relbow.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,2] as [NSNumber]] = Double(upperBody.relbow.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,3] as [NSNumber]] = Double(upperBody.relbow.point!.y) as NSNumber
}else{
return
}
if upperBody.rwrist.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,4] as [NSNumber]] = Double(upperBody.rwrist.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,5] as [NSNumber]] = Double(upperBody.rwrist.point!.y) as NSNumber
}else{
return
}
if upperBody.lshoulder.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,6] as [NSNumber]] = Double(upperBody.lshoulder.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,7] as [NSNumber]] = Double(upperBody.lshoulder.point!.y) as NSNumber
}else{
return
}
if upperBody.lelbow.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,8] as [NSNumber]] = Double(upperBody.lelbow.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,9] as [NSNumber]] = Double(upperBody.lelbow.point!.y) as NSNumber
}else{
return
}
if upperBody.lwrist.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,10] as [NSNumber]] = Double(upperBody.lwrist.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,11] as [NSNumber]] = Double(upperBody.lwrist.point!.y) as NSNumber
}else{
return
}
if upperBody.rhip.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,12] as [NSNumber]] = Double(upperBody.rhip.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,13] as [NSNumber]] = Double(upperBody.rhip.point!.y) as NSNumber
}else{
return
}
if upperBody.lhip.point != nil {
dataArray[[0 , currentIndexInPredictionWindow ,14] as [NSNumber]] = Double(upperBody.lhip.point!.x) as NSNumber
dataArray[[0 , currentIndexInPredictionWindow ,15] as [NSNumber]] = Double(upperBody.lhip.point!.y) as NSNumber
}else{
return
}
// Update the index in the prediction window data array
currentIndexInPredictionWindow += 1
// If the data array is full, call the prediction method to get a new model prediction.
// We assume here for simplicity that the Gyro data was added to the data array as well.
if (currentIndexInPredictionWindow == ModelConstants.predictionWindowSize) {
let predictedActivity = performModelPrediction()
//print("Activity: ", predictedActivity.activity!)
if(predictedActivity.probability?.isNaN == true) {
self.predictionWindowDataArray = nil
self.lastHiddenCellOutput = nil
self.lastHiddenOutput = nil
self.setUpActivtyClassifier()
currentIndexInPredictionWindow = 0
delegate?.didUpdateActivity(prediction: ("Initializing...",0.0))
return
}
delegate?.didUpdateActivity(prediction: predictedActivity)
// Start a new prediction window
currentIndexInPredictionWindow = 0
}
}
func normalizeBodyPoint(bodyPoint:CGPoint, topBodyPoint: CGPoint, normFactor:Double) -> CGPoint {
let normX = (Double(bodyPoint.x * videoWidth)-Double(topBodyPoint.x * videoWidth))/normFactor
let normY = (Double(bodyPoint.y * videoHeigth)-Double(topBodyPoint.y * videoHeigth))/normFactor
return CGPoint(x: normX, y: normY)
}
private func getUpperBodyFromARKit(points: [Int:CGPoint]) -> UpperBody? {
var upperBody = UpperBody()
if(points[1] != nil) {
upperBody.topBodyPart.point = points[1]
}
if(points[16] != nil) {
upperBody.buttomBodyPart.point = points[16]
}
else{
if(points[8] != nil) {
upperBody.buttomBodyPart.point = points[8]
}else{
if(points[11] != nil) {
upperBody.buttomBodyPart.point = points[11]
}else{
return nil
}
}
}
if upperBody.topBodyPart.point != nil && upperBody.buttomBodyPart.point != nil {
let normFactor : Double = Double(upperBody.buttomBodyPart.point!.y * videoHeigth) - Double(upperBody.topBodyPart.point!.y * videoHeigth)
if let rShoulder : CGPoint = points[2]{
upperBody.rshoulder.point = normalizeBodyPoint(bodyPoint: rShoulder, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let rElbow: CGPoint = points[3] {
upperBody.relbow.point = normalizeBodyPoint(bodyPoint: rElbow, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let rWrist: CGPoint = points[4] {
upperBody.rwrist.point = normalizeBodyPoint(bodyPoint: rWrist, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let lShoulder : CGPoint = points[5] {
upperBody.lshoulder.point = normalizeBodyPoint(bodyPoint: lShoulder, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let lElbow: CGPoint = points[6] {
upperBody.lelbow.point = normalizeBodyPoint(bodyPoint: lElbow, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let lWrist: CGPoint = points[7] {
upperBody.lwrist.point = normalizeBodyPoint(bodyPoint: lWrist, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let rHip: CGPoint = points[8] {
upperBody.rhip.point = normalizeBodyPoint(bodyPoint: rHip, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
if let lHip: CGPoint = points[11] {
upperBody.lhip.point = normalizeBodyPoint(bodyPoint: lHip, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
}else{return nil}
}
//print(upperBody)
return upperBody
}
// private func getUpperBodyFromPoseEstimation(points: [BodyPoint?]) -> UpperBody? {
//
// var upperBody = UpperBody()
//
// // top body point is equal to neck
// guard let neck : BodyPoint = points[1] else {return nil}
// upperBody.topBodyPart.point = neck.maxPoint
//
// // botton point is equal to hip right or left
// if let hipRight : BodyPoint = points[8] {
// upperBody.buttomBodyPart.point = hipRight.maxPoint
// }
// else if let hipLeft : BodyPoint = points[11]{
// upperBody.buttomBodyPart.point = hipLeft.maxPoint
// }
// else{
// return nil
// }
//
// //
// if upperBody.topBodyPart.point != nil && upperBody.buttomBodyPart.point != nil {
//
// let normFactor : Double = Double(upperBody.buttomBodyPart.point!.y * videoHeigth) - Double(upperBody.topBodyPart.point!.y * videoHeigth)
//
// if let rShoulder : CGPoint = points[2]?.maxPoint {
// upperBody.rshoulder.point = normalizeBodyPoint(bodyPoint: rShoulder, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let rElbow: CGPoint = points[3]?.maxPoint {
// upperBody.relbow.point = normalizeBodyPoint(bodyPoint: rElbow, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let rWrist: CGPoint = points[4]?.maxPoint {
// upperBody.rwrist.point = normalizeBodyPoint(bodyPoint: rWrist, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let lShoulder : CGPoint = points[5]?.maxPoint {
// upperBody.lshoulder.point = normalizeBodyPoint(bodyPoint: lShoulder, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let lElbow: CGPoint = points[6]?.maxPoint {
// upperBody.lelbow.point = normalizeBodyPoint(bodyPoint: lElbow, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let lWrist: CGPoint = points[7]?.maxPoint {
// upperBody.lwrist.point = normalizeBodyPoint(bodyPoint: lWrist, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let rHip: CGPoint = points[8]?.maxPoint {
// upperBody.rhip.point = normalizeBodyPoint(bodyPoint: rHip, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// if let lHip: CGPoint = points[11]?.maxPoint {
// upperBody.lhip.point = normalizeBodyPoint(bodyPoint: lHip, topBodyPoint: upperBody.topBodyPart.point!, normFactor: normFactor)
// }else{return nil}
// }
//
// return upperBody
// }
func performModelPrediction () -> (activity: String?,probability:Double?) {
guard let dataArray = predictionWindowDataArray else { return (activity: "Error!",probability: 0)}
var probability:Double? = 0
// Perform model prediction
//print("dataArray: \(dataArray[7])")
let modelPrediction = try? activityClassificationModel.prediction(features: dataArray, hiddenIn: lastHiddenOutput, cellIn: lastHiddenCellOutput)
// Update the state vectors
lastHiddenOutput = modelPrediction?.hiddenOut
lastHiddenCellOutput = modelPrediction?.cellOut
if let prediction = modelPrediction {
probability = prediction.activityProbability[prediction.activity]
}
// Return the predicted activity - the activity with the highest probability
return (activity: modelPrediction?.activity,probability: probability)
}
struct UpperBody {
var rshoulder = UpperBodyPoint()
var lshoulder = UpperBodyPoint()
var relbow = UpperBodyPoint()
var lelbow = UpperBodyPoint()
var rwrist = UpperBodyPoint()
var lwrist = UpperBodyPoint()
var rhip = UpperBodyPoint()
var lhip = UpperBodyPoint()
var rankle = UpperBodyPoint()
var lankle = UpperBodyPoint()
var topBodyPart = UpperBodyPoint()
var buttomBodyPart = UpperBodyPoint()
}
struct UpperBodyPoint {
//var point : CGPoint = CGPoint(x: 0.0, y: 0.0)
var point : CGPoint?
var score : Double?
}
}
| 44.630094 | 211 | 0.630751 |
d7bb6e47ba971d2e30b736ce4e8f46c40e6090e0 | 2,604 | //
// SuperHeroData.swift
// marvel-superhero
//
// Created by Antonio de Carvalho Jr on 02/06/18.
// Copyright © 2018 Antonio R de Carvalho Jr. All rights reserved.
//
import Foundation
import CoreData
public class SuperHeroData: NSManagedObject {
public struct Keys {
static let id = "id"
static let name = "name"
static let description = "description"
static let thumbnail = "thumbnail"
static let path = "path"
static let extensionPath = "extension"
static let comics = "comics"
static let series = "series"
static let stories = "stories"
static let events = "events"
}
// MARK: - Properties
@NSManaged public var id: Int
@NSManaged public var name: String
@NSManaged public var descriptionText: String
@NSManaged public var imagePath: String
public var comics: CollectionData?
public var series: CollectionData?
public var stories: CollectionData?
public var events: CollectionData?
public override init(entity: NSEntityDescription,
insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
// MARK: - Initialization
init(dictionary: [String: Any]) {
let context = CoreDataManager.shared.context
let entity = NSEntityDescription.entity(forEntityName: "SuperHero", in: context)
super.init(entity: entity!, insertInto: nil)
id = (dictionary[Keys.id] as? Int) ?? 0
name = (dictionary[Keys.name] as? String) ?? ""
descriptionText = (dictionary[Keys.description] as? String) ?? ""
let thumbnailData = (dictionary[Keys.thumbnail] as? [String: Any]) ?? [:]
let path = (thumbnailData[Keys.path] as? String) ?? ""
let extensionPath = (thumbnailData[Keys.extensionPath] as? String) ?? ""
self.imagePath = path + "." + extensionPath
// Creating the Comic, Series, Stories and Events list
let comicData = (dictionary[Keys.comics] as? [String: Any]) ?? [:]
self.comics = CollectionData(dataDict: comicData, type: .comics)
let seriesData = (dictionary[Keys.series] as? [String: Any]) ?? [:]
self.series = CollectionData(dataDict: seriesData, type: .series)
let storiesData = (dictionary[Keys.stories] as? [String: Any]) ?? [:]
self.stories = CollectionData(dataDict: storiesData, type: .stories)
let eventsData = (dictionary[Keys.events] as? [String: Any]) ?? [:]
self.events = CollectionData(dataDict: eventsData, type: .events)
}
}
| 38.865672 | 88 | 0.644777 |
90a642f3b11eead24f181b0a2289d59ee35086ec | 4,117 | //
// ModalChildExampleTableViewController.swift
// ModalVC_Example
//
// Created by Alessio Boerio on 01/04/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import ZModalVC
class ModalChildExampleTableViewController: ZModalChildViewController {
// MARK: - Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: - Variables
internal var availableIcons: [UIImage] = [#imageLiteral(resourceName: "ic_accessibility"), #imageLiteral(resourceName: "ic_text_fields"), #imageLiteral(resourceName: "ic_credit_card"), #imageLiteral(resourceName: "ic_texture"), #imageLiteral(resourceName: "ic_swap_horizontal")]
internal var availableTexs: [String] = [
"Account",
"Chats",
"Data and Usage",
"Notifications",
"Help Center",
"Terms and Service",
"Logout"
]
var lastVerticalContentOffsetY: CGFloat = 0 {
didSet { tableView.isScrollEnabled = lastVerticalContentOffsetY != 0 }
}
// MARK: - ZModalChildViewController overrides
override func getHeight() -> CGFloat { return tableView.contentSize.height }
// MARK: - Life-cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupTableView()
}
}
// MARK: - Private functions
extension ModalChildExampleTableViewController {
internal func setupUI() {
self.view.backgroundColor = UIColor(red: 248.0/255.0, green: 247.0/255.0, blue: 246.0/255.0, alpha: 1)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(sender:)))
panGesture.delegate = self
view.addGestureRecognizer(panGesture)
}
internal func setupTableView() {
tableView.registerCellNib(SimpleTableViewCell.self)
tableView.tableFooterView = UIView()
tableView.separatorColor = UIColor(red: 105.0/255.0, green: 75.0/255.0, blue: 101.0/255.0, alpha: 1)
tableView.delegate = self
tableView.dataSource = self
}
@objc internal func handlePanGesture(sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
tableView.isScrollEnabled = true
lastVerticalContentOffsetY = tableView.contentOffset.y
case .ended, .cancelled:
self.tableView.isScrollEnabled = true
default:
return
}
}
}
// MARK: - UITableViewDataSource
extension ModalChildExampleTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int.random(in: 3..<availableTexs.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(SimpleTableViewCell.self, indexPath: indexPath) {
let icon = availableIcons[indexPath.row % availableIcons.count]
cell.configure(withText: availableTexs[indexPath.row], andIcon: icon)
cell.separatorInset = indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 ?
UIEdgeInsets(top: 0, left: UIScreen.main.bounds.width, bottom: 0, right: 0) :
UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
return cell
}
return UITableViewCell()
}
}
// MARK: - UITableViewDelegate
extension ModalChildExampleTableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
cell.isSelected = false
}
}
// MARK: - UIGestureRecognizerDelegate
extension ModalChildExampleTableViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 37.427273 | 282 | 0.691523 |
bf6bcc585dc2dc39c1e66eddffef0105b9ff3f3b | 1,672 | //
// bufferWithTrigger.swift
// RxSwiftExt
//
// Created by Patrick Maltagliati on 11/12/18.
// Copyright © 2018 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
public extension ObservableType {
/**
Collects the elements of the source observable, and emits them as an array when the trigger emits.
- parameter trigger: The observable sequence used to signal the emission of the buffered items.
- returns: The buffered observable from elements of the source sequence.
*/
func bufferWithTrigger<Trigger: ObservableType>(_ trigger: Trigger) -> Observable<[Element]> {
return Observable.create { observer in
var buffer: [Element] = []
let lock = NSRecursiveLock()
let triggerDisposable = trigger.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next:
observer.onNext(buffer)
buffer = []
default:
break
}
}
let disposable = self.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next(let element):
buffer.append(element)
case .completed:
observer.onNext(buffer)
observer.onCompleted()
case .error(let error):
observer.onError(error)
buffer = []
}
}
return Disposables.create([disposable, triggerDisposable])
}
}
}
| 33.44 | 103 | 0.54067 |
fb7fc313f32a3fa43fb020676467d93c7165b64c | 1,133 | //
// ActivitySpinner.swift
// BLE-Scanner
//
// Created by Alex - SEEMOO on 27.03.20.
// Copyright © 2020 SEEMOO - TU Darmstadt. All rights reserved.
//
import SwiftUI
import UIKit
struct ActivitySpinner: UIViewRepresentable {
@Binding var animating: Bool
var color: UIColor? = nil
var style: UIActivityIndicatorView.Style? = nil
func makeUIView(context: Context) -> UIActivityIndicatorView {
let actInd = UIActivityIndicatorView()
actInd.hidesWhenStopped = true
return actInd
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {
if let color = self.color {
uiView.color = color
}
if let style = self.style {
uiView.style = style
}
if animating {
uiView.startAnimating()
}else {
uiView.stopAnimating()
}
}
}
struct ActivitySpinner_Previews: PreviewProvider {
@State static var animating = true
static var previews: some View {
ActivitySpinner(animating: $animating)
}
}
| 22.215686 | 76 | 0.602824 |
0180e02d06c6841da1641444ce392373d33ab982 | 3,249 | //
// UIColor+Utilities.swift
//
// Copyright © 2016 Jonathan Cardasis. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
public extension UIColor{
public var hexCode: String {
get{
let colorComponents = self.cgColor.components!
if colorComponents.count < 4 {
return String(format: "%02x%02x%02x", Int(colorComponents[0]*255.0), Int(colorComponents[0]*255.0),Int(colorComponents[0]*255.0)).uppercased()
}
return String(format: "%02x%02x%02x", Int(colorComponents[0]*255.0), Int(colorComponents[1]*255.0),Int(colorComponents[2]*255.0)).uppercased()
}
}
//Amount should be between 0 and 1
public func lighterColor(_ amount: CGFloat) -> UIColor{
return UIColor.blendColors(color: self, destinationColor: UIColor.white, amount: amount)
}
public func darkerColor(_ amount: CGFloat) -> UIColor{
return UIColor.blendColors(color: self, destinationColor: UIColor.black, amount: amount)
}
public static func blendColors(color: UIColor, destinationColor: UIColor, amount : CGFloat) -> UIColor{
var amountToBlend = amount;
if amountToBlend > 1{
amountToBlend = 1.0
}
else if amountToBlend < 0{
amountToBlend = 0
}
var r,g,b, alpha : CGFloat
r = 0
g = 0
b = 0
alpha = 0
color.getRed(&r, green: &g, blue: &b, alpha: &alpha) //gets the rgba values (0-1)
//Get the destination rgba values
var dest_r, dest_g, dest_b, dest_alpha : CGFloat
dest_r = 0
dest_g = 0
dest_b = 0
dest_alpha = 0
destinationColor.getRed(&dest_r, green: &dest_g, blue: &dest_b, alpha: &dest_alpha)
r = amountToBlend * (dest_r * 255) + (1 - amountToBlend) * (r * 255)
g = amountToBlend * (dest_g * 255) + (1 - amountToBlend) * (g * 255)
b = amountToBlend * (dest_b * 255) + (1 - amountToBlend) * (b * 255)
alpha = fabs(alpha / dest_alpha)
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
}
| 41.126582 | 158 | 0.643583 |
6aedb394d794036bed123fc14a737566bdd8874c | 2,331 | //
// ADs.swift
// PangleAd
//
// Created by my on 2021/3/15.
//
import Foundation
import GeADManager
public extension TaskFactoryCategory {
static let `default` = "com.pangle.ad.default.task.factory"
static let express = "com.pangle.ad.express.task.factory"
}
extension ADCategory {
static let splash = "com.pangle.ad.splash.category"
static let rewardVideo = "com.pangle.ad.rewardVideo.category"
static let feed = "com.pangle.ad.feed.category"
static let interstitial = "com.pangle.ad.interstitial.category"
static let fullScreen = "com.pangle.ad.fullScreen.category"
static let banner = "com.pangle.ad.banner.category"
}
public enum ImageSize: Int {
case feed228_150 = 9
case feed690_388 = 10
}
public enum DefaultADs {
case splash(slotId: String, frame: CGRect, tolerateTimeout: Double?, hideSkipButton: Bool?)
case rewardVideo(slotId: String, userId: String, rewardName: String?, rewardAmount: Int?, extra: String?)
case feed(slotId: String, imageSize: ImageSize, count: Int = 1)
}
extension DefaultADs: ADCompatble {
public var taskFactoryCategory: TaskFactoryCategory {
return .default
}
public var category: ADCategory {
switch self {
case .splash:
return .splash
case .rewardVideo:
return .rewardVideo
case .feed:
return .feed
}
}
}
public enum ExpressADs {
case rewardVideo(slotId: String, userId: String, rewardName: String?, rewardAmount: Int?, extra: String?)
case feed(slotId: String, imageSize: ImageSize, count: Int = 1, width: Double, height: Double)
case interstitial(slotId: String, width: Double, height: Double)
case fullScreen(slotId: String)
case banner(slotId: String, interval: Int?, width: Double, height: Double, vc: UIViewController)
}
extension ExpressADs: ADCompatble {
public var taskFactoryCategory: TaskFactoryCategory {
return .express
}
public var category: ADCategory {
switch self {
case .rewardVideo:
return .rewardVideo
case .feed:
return .feed
case .interstitial:
return .interstitial
case .fullScreen:
return .fullScreen
case .banner:
return .banner
}
}
}
| 28.777778 | 109 | 0.659374 |
0a19a0b372946eace7ffb7688b0ab77c52d6fb92 | 245 | //
// Encodable+.swift
//
//
// Created by Branden Smith on 2/24/21.
//
import Foundation
public extension Encodable {
func encode() throws -> Data {
let encoded = try JSONEncoder().encode(self)
return encoded
}
}
| 14.411765 | 52 | 0.608163 |
8fefd0642c3b3ab6fd1212255ce8dd48ad66e7b1 | 6,558 | //
// Body.swift
// Apodini
//
// Created by Paul Schmiedmayer on 6/26/20.
//
import Foundation
import ApodiniUtils
/// Generic Parameter that can be used to mark that the options are meant for `@Parameter`s
public enum ParameterOptionNameSpace { }
/// The `@Parameter` property wrapper can be used to express input in `Components`
@propertyWrapper
public struct Parameter<Element: Codable>: Property, Identifiable {
/// Keys for options that can be passed to an `@Parameter` property wrapper
public typealias OptionKey<T: PropertyOption> = PropertyOptionKey<ParameterOptionNameSpace, T>
/// Type erased options that can be passed to an `@Parameter` property wrapper
public typealias Option = AnyPropertyOption<ParameterOptionNameSpace>
public let id: UUID
let name: String?
internal var options: PropertyOptionSet<ParameterOptionNameSpace>
internal let defaultValue: (() -> Element)?
private var storage: Box<Element?>?
/// The value for the `@Parameter` as defined by the incoming request
public var wrappedValue: Element {
guard let element = storage?.value else {
fatalError("You can only access a parameter while you handle a request")
}
return element
}
/// A `Binding` that reflects this `Parameter`.
public var projectedValue: Binding<Element> {
Binding.parameter(self)
}
private init(
id: UUID = UUID(),
name: String? = nil,
defaultValue: (() -> Element)? = nil,
options: [Option] = []
) {
if let name = name {
precondition(!name.isEmpty, "The name for Parameter cannot be empty!")
}
self.id = id
self.defaultValue = defaultValue
self.name = name
self.options = PropertyOptionSet(options)
if option(for: PropertyOptionKey.http) == .path {
precondition(!isOptional(Element.self), "A `PathParameter` cannot annotate a property with Optional type!")
}
}
/// Creates a new `@Parameter` that indicates input of a `Component` without a default value, different name for the encoding, or special options.
public init() {
// We need to pass any argument otherwise we would call the same initializer again resulting in a infinite loop
self.init(id: UUID())
}
/// Creates a new `@Parameter` that indicates input of a `Component`.
/// - Parameters:
/// - name: The name that identifies this property when decoding the property from the input of a `Component`
/// - options: Options passed on to different interface exporters to clarify the functionality of this `@Parameter` for different API types
public init(_ name: String, _ options: Option...) {
self.init(name: name, options: options)
}
/// Creates a new `@Parameter` that indicates input of a `Component`.
/// - Parameters:
/// - options: Options passed on to different interface exporters to clarify the functionality of this `@Parameter` for different API types
public init(_ options: Option...) {
self.init(options: options)
}
/// Creates a new `@Parameter` that indicates input of a `Component`.
/// - Parameters:
/// - defaultValue: The default value that should be used in case the interface exporter can not decode the value from the input of the `Component`
/// - name: The name that identifies this property when decoding the property from the input of a `Component`
/// - options: Options passed on to different interface exporters to clarify the functionality of this `@Parameter` for different API types
public init(wrappedValue defaultValue: @autoclosure @escaping () -> Element, _ name: String, _ options: Option...) {
self.init(name: name, defaultValue: defaultValue, options: options)
}
/// Creates a new `@Parameter` that indicates input of a `Component`.
/// - Parameters:
/// - defaultValue: The default value that should be used in case the interface exporter can not decode the value from the input of the `Component`
/// - options: Options passed on to different interface exporters to clarify the functionality of this `@Parameter` for different API types
public init(wrappedValue defaultValue: @autoclosure @escaping () -> Element, _ options: Option...) {
self.init(defaultValue: defaultValue, options: options)
}
/// Creates a new `@Parameter` that indicates input of a `Component`.
/// - Parameters:
/// - defaultValue: The default value that should be used in case the interface exporter can not decode the value from the input of the `Component`
public init(wrappedValue defaultValue: @autoclosure @escaping () -> Element) {
self.init(defaultValue: defaultValue)
}
/// Creates a new `@Parameter` that indicates input of a `Component's` `@PathParameter` based on an existing component.
/// - Parameter id: The `UUID` that can be passed in from a parent `Component`'s `@PathParameter`.
/// - Precondition: A `@Parameter` with a specific `http` type `.body` or `.query` can not be passed to a separate component. Please remove the specific `.http` property option or specify the `.http` property option to `.path`.
init(from id: UUID, identifying type: IdentifyingType?) {
var pathParameterOptions: [Option] = [.http(.path)]
if let type = type {
pathParameterOptions.append(.identifying(type))
}
self.init(id: id, options: pathParameterOptions)
}
func option<Option>(for key: OptionKey<Option>) -> Option? {
options.option(for: key)
}
}
extension Parameter: RequestInjectable {
func inject(using request: Request) throws {
guard let storage = self.storage else {
fatalError("Cannot inject request before Parameter was activated.")
}
storage.value = try request.retrieveParameter(self)
}
}
extension Parameter: AnyParameter {
func accept(_ visitor: AnyParameterVisitor) {
visitor.visit(self)
}
}
extension Parameter: Activatable {
mutating func activate() {
self.storage = Box(self.defaultValue?())
}
}
extension _Internal {
/// Returns the option for the given `key` if present.
public static func option<E: Codable, Option>(for key: Parameter<E>.OptionKey<Option>, on parameter: Parameter<E>) -> Option? {
parameter.option(for: key)
}
}
| 40.233129 | 231 | 0.667124 |
0ead9676afb4e27d0a42378b68afa769cd5cad54 | 1,139 | import NumericText
import XCTest
final class StringNumericTests: XCTestCase {
let s = Locale.current.decimalSeparator ?? "."
func testDoubleDecimal() {
XCTAssertEqual("12\(s)3\(s)4".numericValue(allowDecimalSeparator: true), "12\(s)34")
XCTAssertEqual("12\(s)34".numericValue(allowDecimalSeparator: true), "12\(s)34")
XCTAssertEqual("\(s)1234\(s)".numericValue(allowDecimalSeparator: true), "\(s)1234")
}
func testObscureNumericCharacters() throws {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
// DEVANAGARI 5
let fiveString = "५"
XCTAssertEqual(fiveString.numericValue(allowDecimalSeparator: false), fiveString)
let five = try XCTUnwrap(formatter.number(from: fiveString))
XCTAssertEqual(five, 5)
}
func testAlphaNumeric() {
XCTAssertEqual("12a\(s)3b4".numericValue(allowDecimalSeparator: true), "12\(s)34")
XCTAssertEqual("12abc34".numericValue(allowDecimalSeparator: true), "1234")
XCTAssertEqual("a\(s)1234\(s)".numericValue(allowDecimalSeparator: true), "\(s)1234")
}
}
| 37.966667 | 93 | 0.676032 |
c13af8ee59d84c816dcd15f8feb54fa26b4186de | 1,541 | //
// SystemImage.swift
// SwiftWebUI
//
// Created by Helge Heß on 22.06.19.
// Copyright © 2019 Helge Heß. All rights reserved.
//
// Icons we know we have outlines for in SemanticUI
fileprivate let suiOutlineNames : Set<String> = [
"circle",
"envelope",
// "caret" - those do not seem to have outlines
]
fileprivate let sfNameToSUI : [ String : String ] = [
"questionmark" : "question",
"power" : "power off",
"arrowtriangle" : "caret"
]
public extension Image {
init(systemName: String) {
// Semantic UI does such:
// "phone volume"
// "question circle"
// i.e. the Font Awesome naming:
// https://fontawesome.com/icons?d=gallery&q=circle
//
// SF Symbols does such:
// questionmark.circle
//
// We could also use an extra Emoji thing.
let sfClasses : Set<String> = Set(
systemName.split(separator: ".").map(String.init)
)
var suiClasses : Set<String> = Set(
sfClasses.map { sfName in return sfNameToSUI[sfName] ?? sfName }
)
if suiClasses.contains("cart") {
suiClasses.insert("shopping")
// no minus ...
}
// circle.fill => circle
// circle => circle outline
if suiClasses.contains("fill") {
suiClasses.remove("fill")
}
else if !suiClasses.intersection(suiOutlineNames).isEmpty {
suiClasses.insert("outline")
suiClasses.insert("alternate") // ¯\_(ツ)_/¯
}
self.storage = .icon(class: suiClasses.sorted().joined(separator: " "))
}
}
| 24.078125 | 75 | 0.605451 |
75cae9da35b0a5c3cea8df9a8444687180e3261a | 1,387 | // 110_Balanced Binary Tree
// https://leetcode.com/problems/balanced-binary-tree/
//
// Created by Honghao Zhang on 9/18/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a binary tree, determine if it is height-balanced.
//
//For this problem, a height-balanced binary tree is defined as:
//
//a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
//
//Example 1:
//
//Given the following tree [3,9,20,null,null,15,7]:
//
// 3
// / \
// 9 20
// / \
// 15 7
//Return true.
//
//Example 2:
//
//Given the following tree [1,2,2,3,3,null,null,4,4]:
//
// 1
// / \
// 2 2
// / \
// 3 3
// / \
// 4 4
//Return false.
//
import Foundation
class Num110 {
/// Check with max depth but also return if the branch is balanced.
func isBalanced(_ root: TreeNode?) -> Bool {
return isBalancedHelper(root).0
}
/// returns if the tree is balanced and it's depth
private func isBalancedHelper(_ root: TreeNode?) -> (Bool, Int) {
if root == nil {
return (true, 0)
}
let (leftIsBalanced, leftDepth) = isBalancedHelper(root?.left)
let (rightIsBalanced, rightDepth) = isBalancedHelper(root?.right)
let isBalanced = leftIsBalanced && rightIsBalanced && abs(leftDepth - rightDepth) <= 1
return (isBalanced, max(leftDepth, rightDepth) + 1)
}
}
| 23.913793 | 97 | 0.635184 |
cc23cd84cfecb89352ea28deb75b81a105352341 | 3,512 | //
// main.swift
// day17
//
// Created by Moritz Sternemann on 17.12.21.
//
import Common
struct Area {
var horizontal: ClosedRange<Int>
var vertical: ClosedRange<Int>
func contains(_ vector: Vector) -> Bool {
horizontal.contains(vector.x) && vertical.contains(vector.y)
}
}
struct Vector: Equatable {
var x: Int
var y: Int
static var zero: Vector {
Vector(x: 0, y: 0)
}
static func + (lhs: Vector, rhs: Vector) -> Vector {
Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
}
struct Probe {
var position: Vector
var velocity: Vector
func canReachTarget(_ target: Area) -> Bool {
return position.x <= target.horizontal.upperBound
&& position.y >= target.vertical.lowerBound
}
var next: Probe {
let horizontalAcceleration: Int
if velocity.x < 0 {
horizontalAcceleration = 1
} else if velocity.x > 0 {
horizontalAcceleration = -1
} else {
horizontalAcceleration = 0
}
return Probe(
position: position + velocity,
velocity: velocity + Vector(x: horizontalAcceleration, y: -1)
)
}
}
func readTargetArea(_ axis: Substring) -> ClosedRange<Int> {
let parts = axis
.trimmingCharacters(in: .whitespacesAndNewlines)
.split(separator: "=")
let numbers = parts[1].components(separatedBy: "..")
return Int(numbers[0])!...Int(numbers[1])!
}
func vectorsToAllPointsInArea(_ area: Area) -> [Vector] {
area.horizontal
.flatMap { column in
area.vertical
.map { Vector(x: column, y: $0) }
}
}
let input = try Input.loadInput(in: .module)
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "target area: ", with: "")
.split(separator: ",")
let target = Area(horizontal: readTargetArea(input[0]), vertical: readTargetArea(input[1]))
// MARK: - Part 1
func calculateMaxHeightOfProbeWithVelocity(_ velocity: Vector, target: Area) -> Int? {
let probe = Probe(position: .zero, velocity: velocity)
var probes = [probe]
while let probe = probes.last, probe.canReachTarget(target) {
if target.contains(probe.position) {
return probes.max(by: { $0.position.y < $1.position.y })?.position.y
}
probes.append(probe.next)
}
return nil
}
// maximize height of the probe while still reaching the target
let maxHeightProbeRange = Area(horizontal: 0...300, vertical: 0...300)
let probeMaxHeight = vectorsToAllPointsInArea(maxHeightProbeRange)
.compactMap { calculateMaxHeightOfProbeWithVelocity($0, target: target) }
.max()!
print("-- Part 1")
print("Probe can reach max height: \(probeMaxHeight)")
// MARK: - Part 2
func checkProbeReachesTargetWithVelocity(_ velocity: Vector, target: Area) -> Bool {
var probe = Probe(position: .zero, velocity: velocity)
while probe.canReachTarget(target) {
if target.contains(probe.position) {
return true
}
probe = probe.next
}
return false
}
let reachingTargetProbeRange = Area(horizontal: 0...300, vertical: -300...300)
let vectorsReachingTarget = vectorsToAllPointsInArea(reachingTargetProbeRange)
.filter { checkProbeReachesTargetWithVelocity($0, target: target) }
print("-- Part 2")
print("Start vectors where the probe reaches the target: \(vectorsReachingTarget.count)")
| 27.4375 | 91 | 0.63041 |
e0fa32a6d1894806f22436b5b947e48089048b82 | 5,657 | //
// LPModels.swift
// LPTextView <https://github.com/leo-lp/LPTextView>
//
// Created by pengli on 2018/5/25.
// Copyright © 2018年 pengli. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
// MARK: -
// MARK: - LPAtUser
public class LPAtUser: NSObject, NSCoding, NSCopying {
public static let AtCharacter: String = "@"
public let id: Int
public let name: String
public let nameColor: UIColor
public var atName: String { return "\(LPAtUser.AtCharacter)\(name)" }
public init(id: Int, name: String, nameColor: UIColor = #colorLiteral(red: 0, green: 0.8470588235, blue: 0.7882352941, alpha: 1)) {
self.id = id
self.name = name
self.nameColor = nameColor
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
aCoder.encode(nameColor, forKey: "nameColor")
}
public required convenience init?(coder aDecoder: NSCoder) {
let id = aDecoder.decodeInteger(forKey: "id")
let name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
let nameColor = aDecoder.decodeObject(forKey: "nameColor") as? UIColor ?? #colorLiteral(red: 0, green: 0.8470588235, blue: 0.7882352941, alpha: 1)
self.init(id: id, name: name, nameColor: nameColor)
}
public func copy(with zone: NSZone? = nil) -> Any {
return LPAtUser(id: id, name: name, nameColor: nameColor)
}
public override var description: String {
let str: String =
"""
用户ID:\(id)
用户name:\(name)
"""
return str
}
deinit {
#if DEBUG
print("LPAtUser:-> release memory.")
#endif
}
}
// MARK: -
// MARK: - LPEmotion
public class LPEmotion: NSObject, NSCoding, NSCopying {
public var placeholder: String? // 占位符
public var imageScale: CGFloat
public var alignment: LPTextAttachment.LPAlignment
public var font: UIFont?
public var image: UIImage?
public init(placeholder: String?,
imageScale: CGFloat,
alignment: LPTextAttachment.LPAlignment,
font: UIFont?,
image: UIImage?) {
self.placeholder = placeholder
self.imageScale = imageScale
self.alignment = alignment
self.font = font
self.image = image
}
public init(with attachment: LPTextAttachment) {
self.placeholder = attachment.tagName
self.imageScale = attachment.imageScale
self.alignment = attachment.alignment
self.font = attachment.font
self.image = attachment.image
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(placeholder, forKey: "placeholder")
aCoder.encode(imageScale, forKey: "imageScale")
aCoder.encode(alignment.rawValue, forKey: "alignment")
aCoder.encode(font?.pointSize, forKey: "fontSize")
if let image = image, let data = UIImagePNGRepresentation(image) {
aCoder.encode(data, forKey: "imageData")
}
}
public required convenience init?(coder aDecoder: NSCoder) {
let placeholder = aDecoder.decodeObject(forKey: "placeholder") as? String ?? ""
let imageScale = aDecoder.decodeObject(forKey: "imageScale") as? CGFloat ?? 1
let alignmentValue = aDecoder.decodeInteger(forKey: "alignment")
let alignment = LPTextAttachment.LPAlignment(rawValue: alignmentValue) ?? .center
var font: UIFont? = nil
if let fontSize = aDecoder.decodeObject(forKey: "fontSize") as? CGFloat {
font = UIFont.systemFont(ofSize: fontSize)
}
var image: UIImage? = nil
if let imageData = aDecoder.decodeObject(forKey: "imageData") as? Data {
image = UIImage(data: imageData)
}
self.init(placeholder: placeholder,
imageScale: imageScale,
alignment: alignment,
font: font,
image: image)
}
public func copy(with zone: NSZone? = nil) -> Any {
return LPEmotion(placeholder: placeholder,
imageScale: imageScale,
alignment: alignment,
font: font,
image: image)
}
public override var description: String {
let str: String =
"""
表情占位符placeholder:\(String(describing: placeholder))
表情缩放imageScale:\(imageScale)
表情对齐方式alignment:\(alignment.rawValue)
字体font:\(String(describing: font))
表情图片image:\(String(describing: image))
"""
return str
}
deinit {
#if DEBUG
print("LPEmotion:-> release memory.")
#endif
}
}
// MARK: -
// MARK: - LPParseResult
public struct LPParseResult: CustomStringConvertible {
public var attrString: NSMutableAttributedString
public var text: String { return attrString.string }
public var emotionCount: Int
public var emotions: [String: LPEmotion]?
public var users: [(placeholder: String, user: LPAtUser)]?
public var description: String {
let str: String =
"""
文本:\(text)
表情个数:\(emotionCount)
表情:
\(emotions?.description ?? "")
@用户个数:\(users?.count ?? 0)
@用户:
\(users?.description ?? "")
"""
return str
}
}
| 31.427778 | 154 | 0.591126 |
396105dd9ac4d339000e258992ad76940d509bc7 | 839 | //
// UIFont+ChalkboardPreferred.swift
// Delirium
//
// Created by Nikki Vergracht on 31/05/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
/// Example extension you could use in your app with your own fontFamily in order to not having to pass the fontFamily every time.
extension UIFont {
@nonobjc static var fontFamily = "Chalkboard SE" // Don't use this font family, ever.
class func preferredCustomFont(for style: UIFont.TextStyle) -> UIFont {
return UIFont.preferredFont(with: fontFamily, for: style)
}
@available(iOS 10.0, *)
class func preferredCustomFont(for style: UIFont.TextStyle, compatibleWith traitCollection: UITraitCollection?) -> UIFont {
return UIFont.preferredFont(with: fontFamily, for: style, compatibleWith: traitCollection)
}
}
| 33.56 | 130 | 0.715137 |
09d82112638b7cc9fdb3c7321458f179bf5cadf3 | 656 | //
// main.swift
// IntroToConditionalStatements
//
// Created by developer on 1/8/19.
// Copyright © 2019 developer. All rights reserved.
//
import Foundation
func isWeird(n: Int) -> Bool {
if n%2 == 1 {
return true
}
if n >= 2 && n <= 5 {
return false
}
if n >= 6 && n <= 20 {
return true
}
return false
}
func message(isWeird: Bool) -> String {
if isWeird {
return "Weird"
} else {
return "Not Weird"
}
}
guard let N = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
print(message(isWeird: (isWeird(n: N))))
| 18.742857 | 81 | 0.568598 |
33ceb995af9082f1c0a6425f702e36aefe98ad09 | 2,466 | //
// AppDelegate.swift
// Newsville
//
// Created by Vinayak Pal on 03/04/19.
// Copyright © 2019 Vinayak Pal. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// added splash screen as root view controller
let storyBoard = UIStoryboard(name: "Splash", bundle: nil)
let splashVC = storyBoard.instantiateViewController(withIdentifier: "SplashVC") as! SplashVC
self.window?.rootViewController = splashVC
// 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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.528302 | 285 | 0.744526 |
486e9047aa0ef693c4a1194dde76fce8d59c2457 | 5,629 | //
// KBAdvPacketHandler.swift
// KBeacon2
//
// Created by hogen on 2021/5/23.
//
import Foundation
import CoreBluetooth
internal class KBAdvPacketHandler : NSObject
{
internal var mAdvPackets = [Int:KBAdvPacketBase]()
//filter adv type
internal var filterAdvType: Int?
internal var batteryPercent:UInt8?
{
get{
if rawBatteryPercent != nil
{
return rawBatteryPercent!
}
else if let sysAdv = getAdvPacket(KBAdvType.System) as? KBAdvPacketSystem
{
return sysAdv.batteryPercent
}
return nil
}
}
//battery percent
private var rawBatteryPercent:UInt8?
private static var kbAdvPacketTypeObjects = [
Int(KBAdvType.EddyTLM):KBAdvPacketEddyTLM.self,
Int(KBAdvType.EddyUID): KBAdvPacketEddyUID.self,
Int(KBAdvType.EddyURL): KBAdvPacketEddyURL.self,
Int(KBAdvType.IBeacon): KBAdvPacketIBeacon.self,
Int(KBAdvType.Sensor): KBAdvPacketSensor.self,
Int(KBAdvType.System): KBAdvPacketSystem.self
]
internal override init()
{
}
internal static func createAdvPacketByType(_ type:Int)->KBAdvPacketBase?
{
if let instance = kbAdvPacketTypeObjects[type]{
return instance.init()
}
else
{
return nil
}
}
internal func getAdvPacket(_ advType:Int)->KBAdvPacketBase?
{
for (_,advPacket) in mAdvPackets{
if advPacket.getAdvType() == advType{
return advPacket
}
}
return nil
}
internal func removeAdvPacket()
{
self.mAdvPackets.removeAll()
}
internal func parseAdvPacket(_ advData: [String:Any], rssi: Int8)->Bool
{
var bParseDataRslt : Bool = false;
var deviceName: String?
var pAdvData: Data?
//device name
deviceName = advData["kCBAdvDataLocalName"] as? String
//is connectable
guard let advConnable = advData["kCBAdvDataIsConnectable"] as? NSNumber else{
return false;
}
guard let kbServiceData = advData["kCBAdvDataServiceData"] as? Dictionary<CBUUID, NSData> else {
return false
}
var advType = KBAdvType.AdvNull
var advDataIndex = 0
//check if include eddystone data
if let eddyAdvData = kbServiceData[KBUtility.PARCE_UUID_EDDYSTONE] as Data?,
eddyAdvData.count > 1
{
//eddytone url adv
if (eddyAdvData[0] == 0x10
&& eddyAdvData.count >= KBAdvPacketEddyURL.MIN_EDDYSTONE_ADV_LEN)
{
advType = KBAdvType.EddyURL;
}
//eddystone uid adv
else if (eddyAdvData[0] == 0x0
&& eddyAdvData.count >= KBAdvPacketEddyUID.MIN_EDDY_UID_ADV_LEN)
{
advType = KBAdvType.EddyUID;
}
//eddystone tlm adv
else if (eddyAdvData[0] == 0x20
&& eddyAdvData.count >= KBAdvPacketEddyTLM.MIN_EDDY_TLM_ADV_LEN)
{
advType = KBAdvType.EddyTLM;
}
else if (eddyAdvData[0] == 0x21
&& eddyAdvData.count >= KBAdvPacketSensor.MIN_SENSOR_ADV_LEN)
{
advType = KBAdvType.Sensor;
}
else if (eddyAdvData[0] == 0x22
&& eddyAdvData.count >= KBAdvPacketSystem.MIN_ADV_PACKET_LEN)
{
advType = KBAdvType.System;
}
else
{
advType = KBAdvType.AdvNull;
}
advDataIndex = 1
pAdvData = eddyAdvData
}
if let kbResponseData = kbServiceData[KBUtility.PARCE_UUID_KB_EXT_DATA] as Data?
, kbResponseData.count >= 6
{
var nBattPercent = kbResponseData[0];
if (nBattPercent > 100)
{
nBattPercent = 100;
}
rawBatteryPercent = nBattPercent
//beacon extend data
let beaconType = Int(kbResponseData[1])
if ((beaconType & 0x4) > 0
&& advType == KBAdvType.AdvNull)
{
//find ibeacon instance
advType = KBAdvType.IBeacon;
pAdvData = kbResponseData
advDataIndex = 1
}
}
//check filter
if let nFilterAdvType = filterAdvType,
(advType & nFilterAdvType == 0)
{
return false;
}
//parse data
if let advData = pAdvData,
advType != KBAdvType.AdvNull
{
var advPacket = mAdvPackets[advType]
if (advPacket == nil)
{
advPacket = KBAdvPacketHandler.createAdvPacketByType(advType)
mAdvPackets[advType] = advPacket
}
//check if parse advertisment packet success
if (advPacket!.parseAdvPacket(advData, index: advDataIndex))
{
advPacket!.updateBasicInfo(deviceName,
rssi: rssi,
isConnect: advConnable.boolValue)
bParseDataRslt = true;
}
}
return bParseDataRslt;
}
}
| 29.015464 | 104 | 0.517143 |
09c49d515d26ba34c4ef15adf8e807852e2edae8 | 2,841 | //
// VideoContentView.swift
// Wallpaper
//
// Created by Plumk on 2021/4/26.
//
import Cocoa
import AVFoundation
class VideoContentView: ContentView {
var playerLayer: AVPlayerLayer!
override func commInit() {
super.commInit()
self.wantsLayer = true
self.playerLayer = AVPlayerLayer(player: VideoSharePlayer.shared.queuePlayer)
self.playerLayer.frame = self.bounds
self.playerLayer.contentsGravity = .resize
self.playerLayer.videoGravity = .resizeAspectFill
self.layer?.addSublayer(self.playerLayer)
}
override func loadUrl(_ url: URL) {
VideoSharePlayer.shared.loadUrl(url)
}
override func layout() {
super.layout()
self.playerLayer.frame = self.bounds
}
}
// MARK: - VideoSharePlayer
fileprivate class VideoSharePlayer: NSObject {
static let shared = VideoSharePlayer()
let queuePlayer = AVQueuePlayer()
private var looper: AVPlayerLooper?
private var url: URL?
private override init() {
super.init()
self.queuePlayer.isMuted = true
self.queuePlayer.addObserver(self, forKeyPath: "status", options: .new, context: nil)
NotificationCenter.default.addObserver(self, selector: #selector(wallpaperDidChangeNotification), name: WallpaperDidChangeNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(screensDidSleepNotification), name: NSWorkspace.screensDidSleepNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(screensDidWakeNotification), name: NSWorkspace.screensDidWakeNotification, object: nil)
}
@objc func screensDidSleepNotification() {
self.queuePlayer.pause()
}
@objc func screensDidWakeNotification() {
self.queuePlayer.play()
}
@objc func wallpaperDidChangeNotification() {
self.queuePlayer.pause()
self.url = nil
self.looper = nil
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if self.queuePlayer.status == .readyToPlay {
self.queuePlayer.play()
}
}
func loadUrl(_ url: URL) {
if self.url != url {
let item = AVPlayerItem.init(url: url)
guard item.asset.isPlayable else {
return
}
self.url = url
self.looper = AVPlayerLooper(player: self.queuePlayer, templateItem: item)
if self.queuePlayer.status == .readyToPlay {
self.queuePlayer.play()
}
}
}
}
| 28.69697 | 173 | 0.631468 |
de3e543ea2fc4b03f2fb8c9fbcb709c93a311a64 | 2,174 | //
// AppDelegate.swift
// ModCommons
//
// Created by leojportes on 04/13/2021.
// Copyright (c) 2021 leojportes. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.255319 | 285 | 0.75483 |
5602952ec201e4aab31277ae565c1a82fd85e5ab | 374 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
struct Structure {
var a: UInt8
var b: UInt8
var c: UInt8
}
enum Enum: Int {
case One, Two, Three, Four
}
var x: [Enum: (Structure?, Structure?)] = [
.One: (Structure(a: 1, b: 2, c: 3), nil)
]
// CHECK: [main.Enum.One: (Optional(main.Structure(a: 1, b: 2, c: 3)), nil)]
print(x)
| 17.809524 | 76 | 0.606952 |
14097bfbbff620036c76166275649c188f717b6b | 45,316 | import Foundation
import UserNotifications
import BackgroundTasks
import ExposureNotification
import XCTest
@testable import BT
// MARK: == Mocks ==
class MockENExposureDetectionSummary: ENExposureDetectionSummary {
var matchedKeyCountHandler: (() -> UInt64)?
var attenuationDurationsHandler: (() -> [NSNumber])?
override var matchedKeyCount: UInt64 {
return matchedKeyCountHandler?() ?? 0
}
override var attenuationDurations: [NSNumber] {
return attenuationDurationsHandler?() ?? [0,0,0]
}
override var riskScoreSumFullRange: Double {
return 0
}
}
class MockENExposureInfo: ENExposureInfo {
override var date: Date {
return Date()
}
}
class MockDownloadedPackage: DownloadedPackage {
var handler: () throws -> URL
init(handler: @escaping () throws -> URL) {
self.handler = handler
super.init(keysBin: Data(), signature: Data())
}
override func writeSignatureEntry(toDirectory directory: URL, filename: String) throws -> URL {
return try handler()
}
override func writeKeysEntry(toDirectory directory: URL, filename: String) throws -> URL {
return try handler()
}
}
class KeychainServiceMock: KeychainService {
var setRevisionTokenHandler: ((String) -> Void)?
func setRevisionToken(_ token: String) {
setRevisionTokenHandler?(token)
}
var revisionToken: String {
return "revisionToken"
}
}
class BTSecureStorageMock: BTSecureStorage {
var userStateHandler: (() -> UserState)?
var storeExposuresHandler: (([Exposure]) -> Void)?
init(notificationCenter: NotificationCenter) {
super.init(inMemory: true, notificationCenter: notificationCenter)
}
override var userState: UserState {
return userStateHandler?() ?? super.userState
}
override func storeExposures(_ exposures: [Exposure]) {
storeExposuresHandler?(exposures)
}
}
class APIClientMock: APIClient {
var requestHander: (Any, RequestType) -> (Any)
var downloadRequestHander: ((Any, RequestType) -> (Any))?
init(requestHander: @escaping (Any, RequestType) -> (Any)) {
self.requestHander = requestHander
}
static var documentsDirectory: URL? {
return nil
}
func downloadRequest<T>(_ request: T, requestType: RequestType, completion: @escaping (Result<T.ResponseType>) -> Void) where T : APIRequest, T.ResponseType : DownloadableFile {
completion(downloadRequestHander!(request, requestType) as! Result<T.ResponseType>)
}
func request<T>(_ request: T, requestType: RequestType, completion: @escaping GenericCompletion) where T : APIRequest, T.ResponseType == Void {
}
func request<T>(_ request: T, requestType: RequestType, completion: @escaping (Result<JSONObject>) -> Void) where T : APIRequest, T.ResponseType == JSONObject {
}
func request<T>(_ request: T, requestType: RequestType, completion: @escaping (Result<T.ResponseType>) -> Void) where T : APIRequest, T.ResponseType : Decodable {
completion(requestHander(request, requestType) as! Result<T.ResponseType>)
}
func requestList<T>(_ request: T, requestType: RequestType, completion: @escaping (Result<[T.ResponseType.Element]>) -> Void) where T : APIRequest, T.ResponseType : Collection, T.ResponseType.Element : Decodable {
}
func requestString<T>(_ request: T, requestType: RequestType, completion: @escaping (Result<T.ResponseType>) -> Void) where T : APIRequest, T.ResponseType == String {
completion(requestHander(request, requestType) as! Result<T.ResponseType>)
}
func cancelAllRequests() {
}
}
class NotificationCenterMock: NotificationCenter {
var addObserverHandler: ((_ observer: Any,
_ aSelector: Selector,
_ aName: NSNotification.Name?,
_ anObject: Any?) -> Void)?
var postHandler: ((_ notification: Notification) -> Void)?
override func addObserver(_ observer: Any,
selector aSelector: Selector,
name aName: NSNotification.Name?,
object anObject: Any?) {
addObserverHandler?(observer, aSelector, aName, anObject)
}
override func post(_ notification: Notification) {
postHandler?(notification)
}
}
class ENManagerMock: ExposureNotificationManager {
var activateHandler: ((_ completionHandler: @escaping ENErrorHandler) -> Void)?
var invalidateHandler: (() -> Void)?
var setExposureNotificationEnabledHandler: ((_ enabled: Bool, _ completionHandler: @escaping ENErrorHandler) -> Void)?
var exposureNotificationEnabledHandler: (() -> Bool)?
var exposureNotificationStatusHandler: (() -> ENStatus)?
var authorizationStatusHandler: (() -> ENAuthorizationStatus)?
var getDiagnosisKeysHandler: ((ENGetDiagnosisKeysHandler) -> ())?
var detectExposuresHandler: ((_ configuration: ENExposureConfiguration, _ diagnosisKeyURLs: [URL], _ completionHandler: @escaping ENDetectExposuresHandler) -> Progress)?
var getExposureInfoHandler: ((_ summary: ENExposureDetectionSummary, _ userExplanation: String, _ completionHandler: @escaping ENGetExposureInfoHandler) -> Progress)?
var dispatchQueue: DispatchQueue = DispatchQueue.main
var invalidationHandler: (() -> Void)?
func authorizationStatus() -> ENAuthorizationStatus {
return authorizationStatusHandler?() ?? .unknown
}
var exposureNotificationEnabled: Bool {
return exposureNotificationEnabledHandler?() ?? false
}
func detectExposures(configuration: ENExposureConfiguration, diagnosisKeyURLs: [URL], completionHandler: @escaping ENDetectExposuresHandler) -> Progress {
return detectExposuresHandler?(configuration, diagnosisKeyURLs, completionHandler) ?? Progress()
}
func getExposureInfo(summary: ENExposureDetectionSummary, userExplanation: String, completionHandler: @escaping ENGetExposureInfoHandler) -> Progress {
return getExposureInfoHandler?(summary, userExplanation, completionHandler) ?? Progress()
}
func getDiagnosisKeys(completionHandler: @escaping ENGetDiagnosisKeysHandler) {
getDiagnosisKeysHandler?(completionHandler)
}
func getTestDiagnosisKeys(completionHandler: @escaping ENGetDiagnosisKeysHandler) {
}
var exposureNotificationStatus: ENStatus {
return exposureNotificationStatusHandler?() ?? .unknown
}
func activate(completionHandler: @escaping ENErrorHandler) {
activateHandler?(completionHandler)
}
func invalidate() {
invalidateHandler?()
}
func setExposureNotificationEnabled(_ enabled: Bool, completionHandler: @escaping ENErrorHandler) {
setExposureNotificationEnabledHandler?(enabled, completionHandler)
}
}
class BGTaskSchedulerMock: BackgroundTaskScheduler {
var registerHandler: ((_ identifier: String, _ launchHandler: @escaping (BGTask) -> Void) -> Bool)?
var submitHandler: ((_ taskRequest: BGTaskRequest) -> Void)?
func register(forTaskWithIdentifier identifier: String,
using queue: DispatchQueue?,
launchHandler: @escaping (BGTask) -> Void) -> Bool {
return registerHandler?(identifier, launchHandler) ?? false
}
func submit(_ taskRequest: BGTaskRequest) throws {
submitHandler?(taskRequest)
}
}
class UNUserNotificationCenterMock: UserNotificationCenter {
var addHandler: ((_ request: UNNotificationRequest, _ completionHandler: ((Error?) -> Void)?) -> Void)?
var removeDeliveredNotificationsHandler: ((_ identifiers: [String]) -> Void)?
func add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: ((Error?) -> Void)?) {
addHandler?(request, completionHandler)
}
func removeDeliveredNotifications(withIdentifiers identifiers: [String]) {
removeDeliveredNotificationsHandler?(identifiers)
}
}
// MARK: == UNIT TESTS ==
class ExposureManagerTests: XCTestCase {
func testCreatesSharedInstance() {
ExposureManager.createSharedInstance()
XCTAssertNotNil(ExposureManager.shared)
}
func testLifecycle() {
let mockENManager = ENManagerMock()
let activateExpectation = self.expectation(description: "Activate gets called")
let invalidateExpectation = self.expectation(description: "Invalidate gets called")
let registerNotificationExpectation = self.expectation(description: "Registers for authorization changes")
let setExposureNotificationEnabledTrueExpectation = self.expectation(description: "When activated, if authorized and disabled, request to enable exposure notifications")
let notificationCenterMock = NotificationCenterMock()
notificationCenterMock.addObserverHandler = { (_, _, name, _) in
if name == Notification.Name.AuthorizationStatusDidChange {
registerNotificationExpectation.fulfill()
}
}
mockENManager.activateHandler = { completionHandler in
mockENManager.authorizationStatusHandler = {
return .authorized
}
mockENManager.exposureNotificationStatusHandler = {
return .disabled
}
completionHandler(nil)
activateExpectation.fulfill()
}
mockENManager.invalidateHandler = {
invalidateExpectation.fulfill()
}
mockENManager.setExposureNotificationEnabledHandler = { enabled, completionHandler in
if enabled {
setExposureNotificationEnabledTrueExpectation.fulfill()
}
completionHandler(nil)
}
_ = ExposureManager(exposureNotificationManager: mockENManager,
notificationCenter: notificationCenterMock)
wait(for: [activateExpectation,
invalidateExpectation,
registerNotificationExpectation,
setExposureNotificationEnabledTrueExpectation], timeout: 1)
}
func testAwake() {
let exposureConfigurationRequestExpectation = self.expectation(description: "A request to get the exposure configuration is made")
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
exposureConfigurationRequestExpectation.fulfill()
return Result.success(ExposureConfiguration.placeholder) as AnyObject
}
let broadcastAuthorizationStateExpectation = self.expectation(description: "A notification is post with the current authorization and enabled stated")
let notificationCenterMock = NotificationCenterMock()
notificationCenterMock.postHandler = { notification in
if notification.name == .AuthorizationStatusDidChange {
broadcastAuthorizationStateExpectation.fulfill()
}
}
let exposureManager = ExposureManager(apiClient: apiClientMock,
notificationCenter: notificationCenterMock)
exposureManager.awake()
wait(for: [exposureConfigurationRequestExpectation,
broadcastAuthorizationStateExpectation], timeout: 0)
}
func testEnabledtatus() {
let mockENManager = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager)
mockENManager.exposureNotificationEnabledHandler = {
return true
}
XCTAssertEqual(exposureManager.enabledState, ExposureManager.EnabledState.enabled)
mockENManager.exposureNotificationEnabledHandler = {
return false
}
XCTAssertEqual(exposureManager.enabledState, ExposureManager.EnabledState.disabled)
}
func testAuthorizationStatus() {
let mockENManager = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager)
mockENManager.authorizationStatusHandler = {
return .authorized
}
XCTAssertEqual(exposureManager.authorizationState,
ExposureManager.AuthorizationState.authorized)
mockENManager.authorizationStatusHandler = {
return .notAuthorized
}
XCTAssertEqual(exposureManager.authorizationState,
ExposureManager.AuthorizationState.unauthorized)
mockENManager.authorizationStatusHandler = {
return .restricted
}
XCTAssertEqual(exposureManager.authorizationState,
ExposureManager.AuthorizationState.unauthorized)
mockENManager.authorizationStatusHandler = {
return .unknown
}
XCTAssertEqual(exposureManager.authorizationState,
ExposureManager.AuthorizationState.unauthorized)
}
func testBluetoothStatus() {
let mockENManager = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager)
mockENManager.exposureNotificationStatusHandler = {
return .bluetoothOff
}
XCTAssertFalse(exposureManager.isBluetoothEnabled)
mockENManager.exposureNotificationStatusHandler = {
return .active
}
XCTAssertTrue(exposureManager.isBluetoothEnabled)
mockENManager.exposureNotificationStatusHandler = {
return .disabled
}
XCTAssertTrue(exposureManager.isBluetoothEnabled)
mockENManager.exposureNotificationStatusHandler = {
return .paused
}
XCTAssertTrue(exposureManager.isBluetoothEnabled)
mockENManager.exposureNotificationStatusHandler = {
return .restricted
}
XCTAssertTrue(exposureManager.isBluetoothEnabled)
mockENManager.exposureNotificationStatusHandler = {
return .unknown
}
XCTAssertTrue(exposureManager.isBluetoothEnabled)
}
func testCurrentExposures() {
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter())
btSecureStorageMock.userStateHandler = {
let userState = UserState()
userState.exposures.append(Exposure(id: "1",
date: 0,
duration: 10,
totalRiskScore: ENRiskScore(ENRiskScoreMin),
transmissionRiskLevel: ENRiskScore(ENRiskScoreMin)))
return userState
}
let exposureManager = ExposureManager(btSecureStorage: btSecureStorageMock)
let currentExposures = exposureManager.currentExposures
XCTAssertNoThrow(try JSONDecoder().decode(Array<Exposure>.self, from: currentExposures.data(using: .utf8) ?? Data()))
}
func testEnableNotificationsSuccess() {
let setEnabled = true
let setExposureNotificationEnabledExpectation = self.expectation(description: "Request the change of state to the underlying manager")
let mockENManager = ENManagerMock()
mockENManager.setExposureNotificationEnabledHandler = { enabled, completionHandler in
if enabled == setEnabled {
setExposureNotificationEnabledExpectation.fulfill()
}
completionHandler(nil)
}
let broadcastAuthorizationStateExpectation = self.expectation(description: "A notification is post with the current authorization and enabled stated")
let notificationCenterMock = NotificationCenterMock()
notificationCenterMock.postHandler = { notification in
if notification.name == .AuthorizationStatusDidChange {
broadcastAuthorizationStateExpectation.fulfill()
}
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager,
notificationCenter: notificationCenterMock)
exposureManager.requestExposureNotificationAuthorization(enabled: setEnabled) { (error) in
XCTAssertNil(error, "There should be no error")
}
wait(for: [setExposureNotificationEnabledExpectation,
broadcastAuthorizationStateExpectation], timeout: 0)
}
func testEnableNotificationsError() {
let setExposureNotificationEnabledExpectation = self.expectation(description: "Request the change of state to the underlying manager")
let mockENManager = ENManagerMock()
mockENManager.setExposureNotificationEnabledHandler = { enabled, completionHandler in
setExposureNotificationEnabledExpectation.fulfill()
completionHandler(ENError(ENError.Code.unknown))
}
let broadcastAuthorizationStateExpectation = self.expectation(description: "A notification is post with the current authorization and enabled stated")
broadcastAuthorizationStateExpectation.isInverted = true
let notificationCenterMock = NotificationCenterMock()
notificationCenterMock.postHandler = { notification in
if notification.name == .AuthorizationStatusDidChange {
broadcastAuthorizationStateExpectation.fulfill()
}
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager,
notificationCenter: notificationCenterMock)
exposureManager.requestExposureNotificationAuthorization(enabled: false) { (error) in
XCTAssertNotNil(error, "There should be an error")
}
wait(for: [setExposureNotificationEnabledExpectation,
broadcastAuthorizationStateExpectation], timeout: 0)
}
func testGetCurrentENPermissionsStatus() {
let mockENManager = ENManagerMock()
mockENManager.authorizationStatusHandler = {
return .authorized
}
mockENManager.exposureNotificationEnabledHandler = {
return true
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager)
exposureManager.getCurrentENPermissionsStatus { (authorized, enabled) in
XCTAssertEqual(authorized, ExposureManager.AuthorizationState.authorized.rawValue)
XCTAssertEqual(enabled, ExposureManager.EnabledState.enabled.rawValue)
}
}
func testBluetoothNotificationOn() {
let addNotificatiionRequestExpectation = self.expectation(description: "A notification request is added with the proper title and body")
let removeNotificationsExpectation = self.expectation(description: "when is not authorized and bluetooth is not off we just remove all delivered notifications")
let unUserNotificationCenterMock = UNUserNotificationCenterMock()
unUserNotificationCenterMock.addHandler = { request, completionHandler in
addNotificatiionRequestExpectation.fulfill()
let content = request.content
XCTAssertEqual(request.identifier, String.bluetoothNotificationIdentifier)
XCTAssertEqual(content.title, String.bluetoothNotificationTitle.localized)
XCTAssertEqual(content.body, String.bluetoothNotificationBody.localized)
//we execute the callback with an error just to get more test coverage :)
completionHandler?(GenericError.unknown)
}
let mockENManager = ENManagerMock()
mockENManager.authorizationStatusHandler = {
return .authorized
}
mockENManager.exposureNotificationStatusHandler = {
return .bluetoothOff
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager,
userNotificationCenter: unUserNotificationCenterMock)
addNotificatiionRequestExpectation.isInverted = false
removeNotificationsExpectation.isInverted = true
exposureManager.notifyUserBlueToothOffIfNeeded()
wait(for: [addNotificatiionRequestExpectation, removeNotificationsExpectation], timeout: 0)
}
func testBluetoothNotificationOff() {
let addNotificatiionRequestExpectation = self.expectation(description: "A notification request is added with the proper title and body")
let removeNotificationsExpectation = self.expectation(description: "when is not authorized and bluetooth is not off we just remove all delivered notifications")
let unUserNotificationCenterMock = UNUserNotificationCenterMock()
unUserNotificationCenterMock.removeDeliveredNotificationsHandler = { identifiers in
removeNotificationsExpectation.fulfill()
XCTAssertEqual(identifiers[0], String.bluetoothNotificationIdentifier)
}
let mockENManager = ENManagerMock()
mockENManager.exposureNotificationStatusHandler = {
return .active
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager,
userNotificationCenter: unUserNotificationCenterMock)
addNotificatiionRequestExpectation.isInverted = true
removeNotificationsExpectation.isInverted = false
exposureManager.notifyUserBlueToothOffIfNeeded()
wait(for: [addNotificatiionRequestExpectation, removeNotificationsExpectation], timeout: 0)
}
func testFetchExposureKeys() {
let mockENManager = ENManagerMock()
let expectation = self.expectation(description: "a call is made to get the diagnosis keys")
mockENManager.getDiagnosisKeysHandler = { callback in
expectation.fulfill()
callback([ENTemporaryExposureKey()], nil)
}
let exposureManager = ExposureManager(exposureNotificationManager: mockENManager)
exposureManager.fetchExposureKeys { (keys, error) in
XCTAssertNil(error)
XCTAssertEqual(keys?.count, 1)
}
wait(for: [expectation], timeout: 0)
mockENManager.getDiagnosisKeysHandler = { callback in
callback(nil, GenericError.unknown)
}
exposureManager.fetchExposureKeys { (keys, error) in
XCTAssertEqual(error?.errorCode, ExposureManagerErrorCode.noExposureKeysFound.rawValue)
XCTAssertNotNil(error?.underlyingError)
}
}
func testFetchLastDetectionDate() {
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter.default)
let userState = UserState()
btSecureStorageMock.userStateHandler = {
return userState
}
let exposureManager = ExposureManager(btSecureStorage: btSecureStorageMock)
exposureManager.fetchLastDetectionDate { (posixDate, error) in
XCTAssertNil(posixDate)
XCTAssertEqual(error?.errorCode, ExposureManagerErrorCode.detectionNeverPerformed.rawValue)
}
let date = Date()
userState.dateLastPerformedFileCapacityReset = date
exposureManager.fetchLastDetectionDate { (posixDate, error) in
XCTAssertNil(error)
XCTAssertEqual(posixDate, NSNumber(value: date.posixRepresentation))
}
}
func testDebugFetchDiagnosisKeys() {
let debugAction = DebugAction.fetchDiagnosisKeys
let enManagerMock = ENManagerMock()
enManagerMock.getDiagnosisKeysHandler = { callback in
callback([ENTemporaryExposureKey()], nil)
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpetactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpetactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpetactionResolve, successExpectationReject], timeout: 0)
let failExpectationResolve = self.expectation(description: "resolve is not called")
failExpectationResolve.isInverted = true
let failExpectationReject = self.expectation(description: "reject is called")
enManagerMock.getDiagnosisKeysHandler = { callback in
callback(nil, ExposureManagerError(errorCode: ExposureManagerErrorCode.noExposureKeysFound,
localizedMessage: "Message"))
}
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
failExpectationResolve.fulfill()
}) { (_, _, _) in
failExpectationReject.fulfill()
}
wait(for: [failExpectationResolve, failExpectationReject], timeout: 0)
}
func testDebugDetectExposuresNow() {
let debugAction = DebugAction.detectExposuresNow
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter())
btSecureStorageMock.userStateHandler = {
let userState = UserState()
userState.remainingDailyFileProcessingCapacity = 0
return userState
}
var exposureManager = ExposureManager(btSecureStorage: btSecureStorageMock)
let failureExpectactionResolve = self.expectation(description: "resolve is not called")
let failureExpectationReject = self.expectation(description: "reject is called")
failureExpectactionResolve.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
failureExpectactionResolve.fulfill()
}) { (_, _, _) in
failureExpectationReject.fulfill()
}
wait(for: [failureExpectactionResolve, failureExpectationReject], timeout: 0)
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<String>.failure(GenericError.unknown) as AnyObject
}
let failExpectationResolve = self.expectation(description: "resolve is not called")
failExpectationResolve.isInverted = true
let failExpectationReject = self.expectation(description: "reject is called")
exposureManager = ExposureManager(apiClient: apiClientMock, btSecureStorage: btSecureStorageMock)
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
failExpectationResolve.fulfill()
}) { (_, _, _) in
failExpectationReject.fulfill()
}
wait(for: [failExpectationResolve, failExpectationReject], timeout: 0)
}
func testDebugSimulateExposureDetectionError() {
let debugAction = DebugAction.simulateExposureDetectionError
let enManagerMock = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpectactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpectactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpectactionResolve, successExpectationReject], timeout: 0)
}
func testDebugSimulateExposure() {
let debugAction = DebugAction.simulateExposure
let enManagerMock = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpectactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpectactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpectactionResolve, successExpectationReject], timeout: 0)
}
func testDebugFetchExposures() {
let debugAction = DebugAction.fetchExposures
let enManagerMock = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpetactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpetactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpetactionResolve, successExpectationReject], timeout: 0)
}
func testDebugResetExposures() {
let debugAction = DebugAction.resetExposures
let enManagerMock = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpetactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpetactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpetactionResolve, successExpectationReject], timeout: 0)
}
func testDebugToggleENAuthorization() {
let debugAction = DebugAction.toggleENAuthorization
let enManagerMock = ENManagerMock()
enManagerMock.setExposureNotificationEnabledHandler = { enabled, completionHandler in
completionHandler(nil)
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpetactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpetactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpetactionResolve, successExpectationReject], timeout: 0)
}
func testDebugShowLastProcessedFilePath() {
let debugAction = DebugAction.showLastProcessedFilePath
let enManagerMock = ENManagerMock()
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock)
let successExpetactionResolve = self.expectation(description: "resolve is called")
let successExpectationReject = self.expectation(description: "reject is not called")
successExpectationReject.isInverted = true
exposureManager.handleDebugAction(debugAction, resolve: { (success) in
successExpetactionResolve.fulfill()
}) { (_, _, _) in
successExpectationReject.fulfill()
}
wait(for: [successExpetactionResolve, successExpectationReject], timeout: 0)
}
func testDetectExposuresDisalowConcurrentExposures() {
let exposureManager = ExposureManager()
exposureManager.detectExposures { (result) in
//no op
}
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertNotNil(error)
default: XCTFail()
}
}
}
func testDetectExposuresLimitCap() {
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter())
btSecureStorageMock.userStateHandler = {
let userState = UserState()
userState.remainingDailyFileProcessingCapacity = 0
return userState
}
let exposureManager = ExposureManager(btSecureStorage: btSecureStorageMock)
exposureManager.detectExposures { (result) in
switch result {
case .success(let newCases):
XCTAssertEqual(newCases, 0)
default: XCTFail()
}
}
}
func testDetectExposuresKeysDownloadingError() {
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<String>.failure(GenericError.unknown) as AnyObject
}
let exposureManager = ExposureManager(apiClient: apiClientMock)
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertEqual(error.localizedDescription, GenericError.unknown.localizedDescription)
default: XCTFail()
}
}
}
func testDetectExposuresFailsDownloadingKeysError() {
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<String>.success("indexFilePath\nanotherFilePath") as AnyObject
}
apiClientMock.downloadRequestHander = { (request, requestType) in
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.failure(GenericError.unknown)
}
let exposureManager = ExposureManager(apiClient: apiClientMock)
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertEqual(error.localizedDescription, GenericError.unknown.localizedDescription)
default: XCTFail()
}
}
}
func testDetectExposuresUnpackagingError() {
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<String>.success("indexFilePath\nanotherFilePath") as AnyObject
}
let mockDownloadedPackage = MockDownloadedPackage { () -> URL in
throw GenericError.unknown
}
apiClientMock.downloadRequestHander = { (request, requestType) in
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.success(mockDownloadedPackage)
}
let exposureManager = ExposureManager(apiClient: apiClientMock)
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertEqual(error.localizedDescription, GenericError.unknown.localizedDescription)
default: XCTFail()
}
}
}
func testDetectExposuresDetectExposureError() {
let enManagerMock = ENManagerMock()
enManagerMock.detectExposuresHandler = { configuration, diagnosisKeys, completionHandler in
completionHandler(nil, GenericError.unknown)
return Progress()
}
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
return Result<String>.success("indexFilePath") as AnyObject
}
let mockDownloadedPackage = MockDownloadedPackage { () -> URL in
return URL(fileURLWithPath: "url")
}
apiClientMock.downloadRequestHander = { (request, requestType) in
switch requestType {
case .downloadKeys:
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.success(mockDownloadedPackage)
default:
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder)
}
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock,
apiClient: apiClientMock)
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertEqual(error.localizedDescription, GenericError.unknown.localizedDescription)
default: XCTFail()
}
}
}
func testDetectExposuresGetExposureInfoError() {
let enManagerMock = ENManagerMock()
enManagerMock.detectExposuresHandler = { configuration, diagnosisKeys, completionHandler in
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 1
}
enExposureSummary.attenuationDurationsHandler = {
return [900,0,0]
}
completionHandler(enExposureSummary, nil)
return Progress()
}
enManagerMock.getExposureInfoHandler = { summary, explanation, completionHandler in
completionHandler(nil, GenericError.unknown)
return Progress()
}
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
if requestType == RequestType.downloadKeys {
return Result<String>.success("indexFilePath") as AnyObject
}
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder) as AnyObject
}
let mockDownloadedPackage = MockDownloadedPackage { () -> URL in
return URL(fileURLWithPath: "url")
}
apiClientMock.downloadRequestHander = { (request, requestType) in
switch requestType {
case .downloadKeys:
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.success(mockDownloadedPackage)
default:
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder)
}
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock,
apiClient: apiClientMock)
exposureManager.detectExposures { (result) in
switch result {
case .failure(let error):
XCTAssertEqual(error.localizedDescription, GenericError.unknown.localizedDescription)
default: XCTFail()
}
}
}
func testExposureSummaryScoringMatchedKey0() {
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 0
}
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: ExposureConfiguration.placeholder))
}
func testExposureSummaryScoringMatchedKey1() {
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 1
}
enExposureSummary.attenuationDurationsHandler = {
return [900,0,0]
}
let configuration = ExposureConfiguration.placeholder
XCTAssertTrue(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [800,0,0]
}
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [0,900,0]
}
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [600,600,0]
}
XCTAssertTrue(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [0,0,1800]
}
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
}
func testExposureSummaryScoringMatchedKey3() {
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 3
}
enExposureSummary.attenuationDurationsHandler = {
return [900,1800,0]
}
let configuration = ExposureConfiguration.placeholder
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [1800,1800,0]
}
XCTAssertTrue(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
}
func testExposureSummaryScoringMatchedKey4() {
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 4
}
enExposureSummary.attenuationDurationsHandler = {
return [900,1800,0]
}
let configuration = ExposureConfiguration.placeholder
XCTAssertFalse(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
enExposureSummary.attenuationDurationsHandler = {
return [1800,1800,0]
}
XCTAssertTrue(ExposureManager.isAboveScoreThreshold(summary: enExposureSummary,
with: configuration))
}
func testDetectExposuresSuccessScoreBellow() {
let storeExposureExpectation = self.expectation(description: "The exposure does not gets stored")
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter())
btSecureStorageMock.userStateHandler = {
return UserState()
}
btSecureStorageMock.storeExposuresHandler = { exposures in
storeExposureExpectation.fulfill()
XCTAssertEqual(exposures.count, 0)
}
let enManagerMock = ENManagerMock()
enManagerMock.detectExposuresHandler = { configuration, diagnosisKeys, completionHandler in
completionHandler(MockENExposureDetectionSummary(), nil)
return Progress()
}
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
if requestType == RequestType.downloadKeys {
return Result<String>.success("indexFilePath") as AnyObject
}
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder) as AnyObject
}
let mockDownloadedPackage = MockDownloadedPackage { () -> URL in
return URL(fileURLWithPath: "url")
}
apiClientMock.downloadRequestHander = { (request, requestType) in
switch requestType {
case .downloadKeys:
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.success(mockDownloadedPackage)
default:
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder)
}
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock,
apiClient: apiClientMock,
btSecureStorage: btSecureStorageMock)
exposureManager.detectExposures { (result) in
switch result {
case .success(let files):
XCTAssertEqual(files, 1)
default: XCTFail()
}
}
wait(for: [storeExposureExpectation], timeout:1)
}
func testDetectExposuresSuccessScoreAbove() {
let btSecureStorageMock = BTSecureStorageMock(notificationCenter: NotificationCenter())
btSecureStorageMock.storeExposuresHandler = { exposures in
XCTAssertEqual(exposures.count, 1)
}
btSecureStorageMock.userStateHandler = {
return UserState()
}
let enManagerMock = ENManagerMock()
enManagerMock.detectExposuresHandler = { configuration, diagnosisKeys, completionHandler in
let enExposureSummary = MockENExposureDetectionSummary()
enExposureSummary.matchedKeyCountHandler = {
return 1
}
enExposureSummary.attenuationDurationsHandler = {
return [900,0,0]
}
completionHandler(enExposureSummary, nil)
return Progress()
}
enManagerMock.getExposureInfoHandler = { summary, useExplanation, completionHandler in
completionHandler([MockENExposureInfo()], nil)
return Progress()
}
let apiClientMock = APIClientMock { (request, requestType) -> (AnyObject) in
if requestType == RequestType.downloadKeys {
return Result<String>.success("indexFilePath") as AnyObject
}
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder) as AnyObject
}
let mockDownloadedPackage = MockDownloadedPackage { () -> URL in
return URL(fileURLWithPath: "url")
}
apiClientMock.downloadRequestHander = { (request, requestType) in
switch requestType {
case .downloadKeys:
let diagnosisKeyUrlRequest = request as! DiagnosisKeyUrlRequest
XCTAssertEqual(diagnosisKeyUrlRequest.method, .get)
XCTAssertEqual(requestType, RequestType.downloadKeys)
return Result<DownloadedPackage>.success(mockDownloadedPackage)
default:
return Result<ExposureConfiguration>.success(ExposureConfiguration.placeholder)
}
}
let exposureManager = ExposureManager(exposureNotificationManager: enManagerMock,
apiClient: apiClientMock,
btSecureStorage: btSecureStorageMock)
exposureManager.detectExposures { (result) in
switch result {
case .success(let files):
XCTAssertEqual(files, 1)
default: XCTFail()
}
}
}
func testRegisterBackgroundTask() {
let registerExpectation = self.expectation(description: "A background task with the given identifier is registered")
let bgSchedulerMock = BGTaskSchedulerMock()
bgSchedulerMock.registerHandler = { identifier, launchHanlder in
registerExpectation.fulfill()
return true
}
let exposureManager = ExposureManager(backgroundTaskScheduler: bgSchedulerMock)
exposureManager.registerBackgroundTask()
wait(for: [registerExpectation], timeout: 0)
}
func testSubmitBackgroundTask() {
let mockEnManager = ENManagerMock()
mockEnManager.authorizationStatusHandler = {
return .authorized
}
let submitExpectation = self.expectation(description: "A background task request issubmitted")
let bgSchedulerMock = BGTaskSchedulerMock()
bgSchedulerMock.submitHandler = { taskRequest in
submitExpectation.fulfill()
}
let exposureManager = ExposureManager(exposureNotificationManager: mockEnManager,
backgroundTaskScheduler: bgSchedulerMock)
exposureManager.scheduleBackgroundTaskIfNeeded()
wait(for: [submitExpectation], timeout: 0)
}
}
| 41.084316 | 215 | 0.726565 |
017e1f8ae2b261957cd45d8d301431aea1c63fc7 | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f {
b> Any {
}
}
}
class A {
{
}
enum B {
class A {
protocol P {
typealias B : B
| 15 | 87 | 0.694118 |
5b48889a5e0648ef3063a7f663674913d7990c20 | 35,233 | // swiftlint:disable file_length
import Argo
import KsApi
import Library
import LiveStream
import Prelude
import ReactiveSwift
import Result
public struct HockeyConfigData {
public let appIdentifier: String
public let disableUpdates: Bool
public let userId: String
public let userName: String
}
extension HockeyConfigData: Equatable {}
public func == (lhs: HockeyConfigData, rhs: HockeyConfigData) -> Bool {
return lhs.appIdentifier == rhs.appIdentifier
&& lhs.disableUpdates == rhs.disableUpdates
&& lhs.userId == rhs.userId
&& lhs.userName == rhs.userName
}
public protocol AppDelegateViewModelInputs {
/// Call when the application is handed off to.
func applicationContinueUserActivity(_ userActivity: NSUserActivity) -> Bool
/// Call when the application finishes launching.
func applicationDidFinishLaunching(application: UIApplication?, launchOptions: [AnyHashable: Any]?)
/// Call when the application will enter foreground.
func applicationWillEnterForeground()
/// Call when the application enters background.
func applicationDidEnterBackground()
/// Call when the aplication receives memory warning from the system.
func applicationDidReceiveMemoryWarning()
/// Call to open a url that was sent to the app
func applicationOpenUrl(application: UIApplication?,
url: URL,
sourceApplication: String?,
annotation: Any) -> Bool
/// Call when the application receives a request to perform a shortcut action.
func applicationPerformActionForShortcutItem(_ item: UIApplicationShortcutItem)
/// Call after having invoked AppEnvironemt.updateCurrentUser with a fresh user.
func currentUserUpdatedInEnvironment()
/// Call when the app delegate receives a remote notification.
func didReceive(remoteNotification notification: [AnyHashable: Any], applicationIsActive: Bool)
/// Call when the app delegate gets notice of a successful notification registration.
func didRegisterForRemoteNotifications(withDeviceTokenData data: Data)
/// Call when the redirect URL has been found, see `findRedirectUrl` for more information.
func foundRedirectUrl(_ url: URL)
/// Call when the user taps "OK" from the notification alert.
func openRemoteNotificationTappedOk()
/// Call when the controller has received a user session ended notification.
func userSessionEnded()
/// Call when the controller has received a user session started notification.
func userSessionStarted()
/// Call when the app has crashed
func crashManagerDidFinishSendingCrashReport()
}
public protocol AppDelegateViewModelOutputs {
/// The value to return from the delegate's `application:didFinishLaunchingWithOptions:` method.
var applicationDidFinishLaunchingReturnValue: Bool { get }
/// Emits an app identifier that should be used to configure the hockey app manager.
var configureHockey: Signal<HockeyConfigData, NoError> { get }
/// Return this value in the delegate method.
var continueUserActivityReturnValue: MutableProperty<Bool> { get }
/// Return this value in the delegate method.
var facebookOpenURLReturnValue: MutableProperty<Bool> { get }
/// Emits when the view needs to figure out the redirect URL for the emitted URL.
var findRedirectUrl: Signal<URL, NoError> { get }
/// Emits when opening the app with an invalid access token.
var forceLogout: Signal<(), NoError> { get }
/// Emits when the root view controller should navigate to activity.
var goToActivity: Signal<(), NoError> { get }
/// Emits when the root view controller should navigate to the creator dashboard.
var goToDashboard: Signal<Param?, NoError> { get }
/// Emits when the root view controller should navigate to the creator dashboard.
var goToDiscovery: Signal<DiscoveryParams?, NoError> { get }
/// Emits everything needed to go a particular live stream of a project.
var goToLiveStream: Signal<(Project, LiveStreamEvent, RefTag?), NoError> { get }
/// Emits when the root view controller should navigate to the login screen.
var goToLogin: Signal<(), NoError> { get }
/// Emits a message thread when we should navigate to it.
var goToMessageThread: Signal<MessageThread, NoError> { get }
/// Emits when the root view controller should navigate to the user's profile.
var goToProfile: Signal<(), NoError> { get }
/// Emits a URL when we should open it in the safari browser.
var goToMobileSafari: Signal<URL, NoError> { get }
/// Emits when the root view controller should navigate to search.
var goToSearch: Signal<(), NoError> { get }
/// Emits an Notification that should be immediately posted.
var postNotification: Signal<Notification, NoError> { get }
/// Emits a message when a remote notification alert should be displayed to the user.
var presentRemoteNotificationAlert: Signal<String, NoError> { get }
/// Emits when a view controller should be presented.
var presentViewController: Signal<UIViewController, NoError> { get }
/// Emits when the push token has been successfully registered on the server.
var pushTokenSuccessfullyRegistered: Signal<(), NoError> { get }
/// Emits when we should attempt registering the user for notifications.
var registerUserNotificationSettings: Signal<(), NoError> { get }
/// Emits an array of short cut items to put into the shared application.
var setApplicationShortcutItems: Signal<[ShortcutItem], NoError> { get }
/// Emits to synchronize iCloud on app launch.
var synchronizeUbiquitousStore: Signal<(), NoError> { get }
/// Emits when we should unregister the user from notifications.
var unregisterForRemoteNotifications: Signal<(), NoError> { get }
/// Emits a fresh user to be updated in the app environment.
var updateCurrentUserInEnvironment: Signal<User, NoError> { get }
/// Emits a config value that should be updated in the environment.
var updateConfigInEnvironment: Signal<Config, NoError> { get }
}
public protocol AppDelegateViewModelType {
var inputs: AppDelegateViewModelInputs { get }
var outputs: AppDelegateViewModelOutputs { get }
}
// swiftlint:disable:next type_body_length
public final class AppDelegateViewModel: AppDelegateViewModelType, AppDelegateViewModelInputs,
AppDelegateViewModelOutputs {
// swiftlint:disable function_body_length
// swiftlint:disable cyclomatic_complexity
public init() {
let currentUserEvent = Signal
.merge(
self.applicationWillEnterForegroundProperty.signal,
self.applicationLaunchOptionsProperty.signal.ignoreValues(),
self.userSessionEndedProperty.signal,
self.userSessionStartedProperty.signal
)
.ksr_debounce(.seconds(5), on: AppEnvironment.current.scheduler)
.switchMap { _ -> SignalProducer<Event<User?, ErrorEnvelope>, NoError> in
AppEnvironment.current.apiService.isAuthenticated || AppEnvironment.current.currentUser != nil
? AppEnvironment.current.apiService.fetchUserSelf().wrapInOptional().materialize()
: SignalProducer(value: .value(nil))
}
self.updateCurrentUserInEnvironment = currentUserEvent
.values()
.skipNil()
self.forceLogout = currentUserEvent
.errors()
.filter { $0.ksrCode == .AccessTokenInvalid }
.ignoreValues()
self.updateConfigInEnvironment = Signal.merge([
self.applicationWillEnterForegroundProperty.signal,
self.applicationLaunchOptionsProperty.signal.ignoreValues()
])
.switchMap { AppEnvironment.current.apiService.fetchConfig().demoteErrors() }
self.postNotification = self.currentUserUpdatedInEnvironmentProperty.signal
.mapConst(Notification(name: .ksr_userUpdated, object: nil))
self.applicationLaunchOptionsProperty.signal.skipNil()
.take(first: 1)
.observeValues { appOptions in
_ = AppEnvironment.current.facebookAppDelegate.application(
appOptions.application,
didFinishLaunchingWithOptions: appOptions.options
)
}
let openUrl = self.applicationOpenUrlProperty.signal.skipNil()
self.facebookOpenURLReturnValue <~ openUrl.map {
AppEnvironment.current.facebookAppDelegate.application(
$0.application, open: $0.url, sourceApplication: $0.sourceApplication, annotation: $0.annotation
)
}
// iCloud
self.synchronizeUbiquitousStore = self.applicationLaunchOptionsProperty.signal.ignoreValues()
// Push notifications
self.registerUserNotificationSettings = Signal.merge(
self.applicationWillEnterForegroundProperty.signal,
self.applicationLaunchOptionsProperty.signal.ignoreValues(),
self.userSessionStartedProperty.signal
)
.filter { AppEnvironment.current.currentUser != nil }
self.unregisterForRemoteNotifications = self.userSessionEndedProperty.signal
self.pushTokenSuccessfullyRegistered = self.deviceTokenDataProperty.signal
.map(deviceToken(fromData:))
.ksr_debounce(.seconds(5), on: AppEnvironment.current.scheduler)
.switchMap {
AppEnvironment.current.apiService.register(pushToken: $0)
.demoteErrors()
}
.ignoreValues()
let remoteNotificationFromLaunch = self.applicationLaunchOptionsProperty.signal.skipNil()
.map { _, options in options?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] }
.skipNil()
let localNotificationFromLaunch = self.applicationLaunchOptionsProperty.signal.skipNil()
.map { _, options in options?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification }
.map { $0?.userInfo }
.skipNil()
let notificationAndIsActive = Signal.merge(
self.remoteNotificationAndIsActiveProperty.signal.skipNil(),
remoteNotificationFromLaunch.map { ($0, false) },
localNotificationFromLaunch.map { ($0, false) }
)
let pushEnvelopeAndIsActive = notificationAndIsActive
.flatMap { (notification, isActive) -> SignalProducer<(PushEnvelope, Bool), NoError> in
guard let envelope = (decode(notification) as Decoded<PushEnvelope>).value else { return .empty }
return SignalProducer(value: (envelope, isActive))
}
self.presentRemoteNotificationAlert = pushEnvelopeAndIsActive
.filter(second)
.map { env, _ in env.aps.alert }
let explicitlyOpenedNotification = pushEnvelopeAndIsActive
.takeWhen(self.openRemoteNotificationTappedOkProperty.signal)
let pushEnvelope = Signal.merge(
pushEnvelopeAndIsActive.filter(negate • second),
explicitlyOpenedNotification
)
.map(first)
let deepLinkFromNotification = pushEnvelope
.map(navigation(fromPushEnvelope:))
// Deep links
let continueUserActivity = self.applicationContinueUserActivityProperty.signal.skipNil()
let continueUserActivityWithNavigation = continueUserActivity
.filter { $0.activityType == NSUserActivityTypeBrowsingWeb }
.map { activity in (activity, activity.webpageURL.flatMap(Navigation.match)) }
.filter(isNotNil • second)
self.continueUserActivityReturnValue <~ continueUserActivityWithNavigation.mapConst(true)
let deepLinkUrl = Signal
.merge(
openUrl.map { $0.url },
self.foundRedirectUrlProperty.signal.skipNil(),
continueUserActivity
.filter { $0.activityType == NSUserActivityTypeBrowsingWeb }
.map { $0.webpageURL }
.skipNil()
)
let deepLinkFromUrl = deepLinkUrl.map(Navigation.match)
let performShortcutItem = Signal.merge(
self.performActionForShortcutItemProperty.signal.skipNil(),
self.applicationLaunchOptionsProperty.signal
.map { $0?.options?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem }
.skipNil()
)
.map { ShortcutItem(typeString: $0.type) }
.skipNil()
let deepLinkFromShortcut = performShortcutItem
.switchMap(navigation(fromShortcutItem:))
let deepLink = Signal
.merge(
deepLinkFromUrl,
deepLinkFromNotification,
deepLinkFromShortcut
)
.skipNil()
self.findRedirectUrl = deepLinkUrl
.filter {
switch Navigation.match($0) {
case .some(.emailClick(_)), .some(.emailLink): return true
default: return false
}
}
self.goToDiscovery = deepLink
.map { link -> [String: String]?? in
guard case let .tab(.discovery(rawParams)) = link else { return nil }
return .some(rawParams)
}
.skipNil()
.switchMap { rawParams -> SignalProducer<DiscoveryParams?, NoError> in
guard
let rawParams = rawParams,
let params = DiscoveryParams.decode(.init(rawParams)).value
else { return .init(value: nil) }
guard
let rawCategoryParam = rawParams["category_id"],
let categoryParam = Param.decode(.string(rawCategoryParam)).value
else { return .init(value: params) }
return AppEnvironment.current.apiService.fetchCategory(param: categoryParam)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.demoteErrors()
.map { params |> DiscoveryParams.lens.category .~ $0 }
}
self.goToLiveStream = deepLink
.switchMap(liveStreamData(fromNavigation:))
self.goToActivity = deepLink
.filter { $0 == .tab(.activity) }
.ignoreValues()
self.goToSearch = deepLink
.filter { $0 == .tab(.search) }
.ignoreValues()
self.goToLogin = deepLink
.filter { $0 == .tab(.login) }
.ignoreValues()
self.goToMessageThread = deepLink
.map { navigation -> Int? in
guard case let .messages(messageThreadId) = navigation else { return nil }
return .some(messageThreadId)
}
.skipNil()
.switchMap {
AppEnvironment.current.apiService.fetchMessageThread(messageThreadId: $0)
.demoteErrors()
.map { env in env.messageThread }
}
self.goToProfile = deepLink
.filter { $0 == .tab(.me) }
.ignoreValues()
self.goToMobileSafari = self.foundRedirectUrlProperty.signal.skipNil()
.filter { Navigation.match($0) == nil }
let projectLink = deepLink
.filter { link in
// NB: have to do this cause we handle the live stream subpage in a different manner than we do
// the other subpages.
if case .project(_, .liveStream(_), _) = link { return false }
return true
}
.map { link -> (Param, Navigation.Project, RefTag?)? in
guard case let .project(param, subpage, refTag) = link else { return nil }
return (param, subpage, refTag)
}
.skipNil()
.switchMap { param, subpage, refTag in
AppEnvironment.current.apiService.fetchProject(param: param)
.demoteErrors()
.observeForUI()
.map { project -> (Project, Navigation.Project, [UIViewController]) in
(project, subpage,
[ProjectPamphletViewController.configuredWith(projectOrParam: .left(project), refTag: refTag)])
}
}
self.goToDashboard = deepLink
.map { link -> Param?? in
guard case let .tab(.dashboard(param)) = link else { return nil }
return .some(param)
}
.skipNil()
let projectRootLink = projectLink
.filter { _, subpage, _ in subpage == .root }
.map { _, _, vcs in vcs }
let projectCommentsLink = projectLink
.filter { _, subpage, _ in subpage == .comments }
.map { project, _, vcs in vcs + [CommentsViewController.configuredWith(project: project, update: nil)] }
let surveyResponseLink = deepLink
.map { link -> Int? in
guard case let .user(_, .survey(surveyResponseId)) = link else { return nil }
return surveyResponseId
}
.skipNil()
.switchMap { surveyResponseId in
AppEnvironment.current.apiService.fetchSurveyResponse(surveyResponseId: surveyResponseId)
.demoteErrors()
.observeForUI()
.map { surveyResponse -> [UIViewController] in
[SurveyResponseViewController.configuredWith(surveyResponse: surveyResponse)]
}
}
let updatesLink = projectLink
.filter { _, subpage, _ in subpage == .updates }
.map { project, _, vcs in vcs + [ProjectUpdatesViewController.configuredWith(project: project)] }
let updateLink = projectLink
.map { project, subpage, vcs -> (Project, Int, Navigation.Project.Update, [UIViewController])? in
guard case let .update(id, updateSubpage) = subpage else { return nil }
return (project, id, updateSubpage, vcs)
}
.skipNil()
.switchMap { project, id, updateSubpage, vcs in
AppEnvironment.current.apiService.fetchUpdate(updateId: id, projectParam: .id(project.id))
.demoteErrors()
.observeForUI()
.map { update -> (Project, Update, Navigation.Project.Update, [UIViewController]) in
(
project,
update,
updateSubpage,
vcs + [UpdateViewController.configuredWith(project: project,
update: update,
context: .deepLink)]
)
}
}
let updateRootLink = updateLink
.filter { _, _, subpage, _ in subpage == .root }
.map { _, _, _, vcs in vcs }
let updateCommentsLink = updateLink
.observeForUI()
.map { project, update, subpage, vcs -> [UIViewController]? in
guard case .comments = subpage else { return nil }
return vcs + [CommentsViewController.configuredWith(project: project, update: update)]
}
.skipNil()
self.presentViewController = Signal
.merge(
projectRootLink,
projectCommentsLink,
surveyResponseLink,
updatesLink,
updateRootLink,
updateCommentsLink
)
.map { UINavigationController() |> UINavigationController.lens.viewControllers .~ $0 }
self.configureHockey = Signal.merge(
self.applicationLaunchOptionsProperty.signal.ignoreValues(),
self.userSessionStartedProperty.signal,
self.userSessionEndedProperty.signal
)
.map { _ in
let mainBundle = AppEnvironment.current.mainBundle
let appIdentifier = mainBundle.isRelease
? KsApi.Secrets.HockeyAppId.production
: KsApi.Secrets.HockeyAppId.beta
return HockeyConfigData(
appIdentifier: appIdentifier,
disableUpdates: mainBundle.isRelease || mainBundle.isAlpha,
userId: (AppEnvironment.current.currentUser?.id).map(String.init) ?? "0",
userName: AppEnvironment.current.currentUser?.name ?? "anonymous"
)
}
self.setApplicationShortcutItems = currentUserEvent
.values()
.switchMap(shortcutItems(forUser:))
self.applicationDidFinishLaunchingReturnValueProperty <~ self.applicationLaunchOptionsProperty.signal
.skipNil()
.map { _, options in options?[UIApplicationLaunchOptionsKey.shortcutItem] == nil }
// Koala
Signal.merge(
self.applicationLaunchOptionsProperty.signal.ignoreValues(),
self.applicationWillEnterForegroundProperty.signal
)
.observeValues { AppEnvironment.current.koala.trackAppOpen() }
self.applicationDidEnterBackgroundProperty.signal
.observeValues { AppEnvironment.current.koala.trackAppClose() }
self.applicationDidReceiveMemoryWarningProperty.signal
.observeValues { AppEnvironment.current.koala.trackMemoryWarning() }
self.crashManagerDidFinishSendingCrashReportProperty.signal
.observeValues { AppEnvironment.current.koala.trackCrashedApp() }
self.applicationLaunchOptionsProperty.signal
.take(first: 1)
.observeValues { _ in
visitorCookies().forEach(AppEnvironment.current.cookieStorage.setCookie)
}
Signal.combineLatest(
performShortcutItem.enumerated(),
self.setApplicationShortcutItems
)
.skipRepeats { lhs, rhs in lhs.0.idx == rhs.0.idx }
.map { idxAndShortcutItem, availableShortcutItems in
(idxAndShortcutItem.value, availableShortcutItems)
}
.observeValues {
AppEnvironment.current.koala.trackPerformedShortcutItem($0, availableShortcutItems: $1)
}
openUrl
.map { URLComponents(url: $0.url, resolvingAgainstBaseURL: false) }
.skipNil()
.map(dictionary(fromUrlComponents:))
.filter { $0["app_banner"] == "1" }
.observeValues { AppEnvironment.current.koala.trackOpenedAppBanner($0) }
continueUserActivityWithNavigation
.map(first)
.observeValues { AppEnvironment.current.koala.trackUserActivity($0) }
deepLinkFromNotification
.observeValues { _ in AppEnvironment.current.koala.trackNotificationOpened() }
}
// swiftlint:enable function_body_length
// swiftlint:enable cyclomatic_complexity
public var inputs: AppDelegateViewModelInputs { return self }
public var outputs: AppDelegateViewModelOutputs { return self }
fileprivate let applicationContinueUserActivityProperty = MutableProperty<NSUserActivity?>(nil)
public func applicationContinueUserActivity(_ userActivity: NSUserActivity) -> Bool {
self.applicationContinueUserActivityProperty.value = userActivity
return self.continueUserActivityReturnValue.value
}
fileprivate typealias ApplicationWithOptions = (application: UIApplication?, options: [AnyHashable: Any]?)
fileprivate let applicationLaunchOptionsProperty = MutableProperty<ApplicationWithOptions?>(nil)
public func applicationDidFinishLaunching(application: UIApplication?,
launchOptions: [AnyHashable: Any]?) {
self.applicationLaunchOptionsProperty.value = (application, launchOptions)
}
fileprivate let applicationWillEnterForegroundProperty = MutableProperty()
public func applicationWillEnterForeground() {
self.applicationWillEnterForegroundProperty.value = ()
}
fileprivate let applicationDidEnterBackgroundProperty = MutableProperty()
public func applicationDidEnterBackground() {
self.applicationDidEnterBackgroundProperty.value = ()
}
fileprivate let applicationDidReceiveMemoryWarningProperty = MutableProperty()
public func applicationDidReceiveMemoryWarning() {
self.applicationDidReceiveMemoryWarningProperty.value = ()
}
fileprivate let performActionForShortcutItemProperty = MutableProperty<UIApplicationShortcutItem?>(nil)
public func applicationPerformActionForShortcutItem(_ item: UIApplicationShortcutItem) {
self.performActionForShortcutItemProperty.value = item
}
fileprivate let currentUserUpdatedInEnvironmentProperty = MutableProperty()
public func currentUserUpdatedInEnvironment() {
self.currentUserUpdatedInEnvironmentProperty.value = ()
}
fileprivate let configUpdatedInEnvironmentProperty = MutableProperty()
public func configUpdatedInEnvironment() {
self.configUpdatedInEnvironmentProperty.value = ()
}
fileprivate let remoteNotificationAndIsActiveProperty = MutableProperty<([AnyHashable: Any], Bool)?>(nil)
public func didReceive(remoteNotification notification: [AnyHashable: Any], applicationIsActive: Bool) {
self.remoteNotificationAndIsActiveProperty.value = (notification, applicationIsActive)
}
fileprivate let deviceTokenDataProperty = MutableProperty(Data())
public func didRegisterForRemoteNotifications(withDeviceTokenData data: Data) {
self.deviceTokenDataProperty.value = data
}
private let foundRedirectUrlProperty = MutableProperty<URL?>(nil)
public func foundRedirectUrl(_ url: URL) {
self.foundRedirectUrlProperty.value = url
}
fileprivate let crashManagerDidFinishSendingCrashReportProperty = MutableProperty()
public func crashManagerDidFinishSendingCrashReport() {
self.crashManagerDidFinishSendingCrashReportProperty.value = ()
}
fileprivate typealias ApplicationOpenUrl = (
application: UIApplication?,
url: URL,
sourceApplication: String?,
annotation: Any
)
fileprivate let applicationOpenUrlProperty = MutableProperty<ApplicationOpenUrl?>(nil)
public func applicationOpenUrl(application: UIApplication?,
url: URL,
sourceApplication: String?,
annotation: Any) -> Bool {
self.applicationOpenUrlProperty.value = (application, url, sourceApplication, annotation)
return self.facebookOpenURLReturnValue.value
}
fileprivate let openRemoteNotificationTappedOkProperty = MutableProperty()
public func openRemoteNotificationTappedOk() {
self.openRemoteNotificationTappedOkProperty.value = ()
}
fileprivate let userSessionEndedProperty = MutableProperty()
public func userSessionEnded() {
self.userSessionEndedProperty.value = ()
}
fileprivate let userSessionStartedProperty = MutableProperty()
public func userSessionStarted() {
self.userSessionStartedProperty.value = ()
}
fileprivate let applicationDidFinishLaunchingReturnValueProperty = MutableProperty(true)
public var applicationDidFinishLaunchingReturnValue: Bool {
return applicationDidFinishLaunchingReturnValueProperty.value
}
public let configureHockey: Signal<HockeyConfigData, NoError>
public let continueUserActivityReturnValue = MutableProperty(false)
public let facebookOpenURLReturnValue = MutableProperty(false)
public let findRedirectUrl: Signal<URL, NoError>
public let forceLogout: Signal<(), NoError>
public let goToActivity: Signal<(), NoError>
public let goToDashboard: Signal<Param?, NoError>
public let goToDiscovery: Signal<DiscoveryParams?, NoError>
public let goToLiveStream: Signal<(Project, LiveStreamEvent, RefTag?), NoError>
public let goToLogin: Signal<(), NoError>
public let goToMessageThread: Signal<MessageThread, NoError>
public let goToProfile: Signal<(), NoError>
public let goToMobileSafari: Signal<URL, NoError>
public let goToSearch: Signal<(), NoError>
public let postNotification: Signal<Notification, NoError>
public let presentRemoteNotificationAlert: Signal<String, NoError>
public let presentViewController: Signal<UIViewController, NoError>
public let pushTokenSuccessfullyRegistered: Signal<(), NoError>
public let registerUserNotificationSettings: Signal<(), NoError>
public let setApplicationShortcutItems: Signal<[ShortcutItem], NoError>
public let synchronizeUbiquitousStore: Signal<(), NoError>
public let unregisterForRemoteNotifications: Signal<(), NoError>
public let updateCurrentUserInEnvironment: Signal<User, NoError>
public let updateConfigInEnvironment: Signal<Config, NoError>
}
private func deviceToken(fromData data: Data) -> String {
return data
.map { String(format: "%02.2hhx", $0 as CVarArg) }
.joined()
}
// swiftlint:disable:next cyclomatic_complexity
private func navigation(fromPushEnvelope envelope: PushEnvelope) -> Navigation? {
if let activity = envelope.activity {
switch activity.category {
case .backing, .failure, .launch, .success, .cancellation, .suspension:
guard let projectId = activity.projectId else { return nil }
if envelope.forCreator == true {
return .tab(.dashboard(project: .id(projectId)))
}
return .project(.id(projectId), .root, refTag: .push)
case .update:
guard let projectId = activity.projectId, let updateId = activity.updateId else { return nil }
return .project(.id(projectId), .update(updateId, .root), refTag: .push)
case .commentPost:
guard let projectId = activity.projectId, let updateId = activity.updateId else { return nil }
return .project(.id(projectId), .update(updateId, .comments), refTag: .push)
case .commentProject:
guard let projectId = activity.projectId else { return nil }
return .project(.id(projectId), .comments, refTag: .push)
case .backingAmount, .backingCanceled, .backingDropped, .backingReward:
guard let projectId = activity.projectId else { return nil }
return .tab(.dashboard(project: .id(projectId)))
case .follow:
return .tab(.activity)
case .funding, .unknown, .watch:
return nil
}
}
if let liveStream = envelope.liveStream, let project = envelope.project {
return .project(.id(project.id), .liveStream(eventId: liveStream.id), refTag: .push)
}
if let project = envelope.project {
if envelope.forCreator == true {
return .tab(.dashboard(project: .id(project.id)))
}
return .project(.id(project.id), .root, refTag: .push)
}
if let message = envelope.message {
return .messages(messageThreadId: message.messageThreadId)
}
if let survey = envelope.survey {
return .user(.slug("self"), .survey(survey.id))
}
if let update = envelope.update {
return .project(.id(update.projectId), .update(update.id, .root), refTag: .push)
}
return nil
}
// Figures out a `Navigation` to route the user to from a shortcut item.
private func navigation(fromShortcutItem shortcutItem: ShortcutItem) -> SignalProducer<Navigation?, NoError> {
switch shortcutItem {
case .creatorDashboard:
return SignalProducer(value: .tab(.dashboard(project: nil)))
case .recommendedForYou:
let params = .defaults
|> DiscoveryParams.lens.recommended .~ true
|> DiscoveryParams.lens.sort .~ .magic
return SignalProducer(value: .tab(.discovery(params.queryParams)))
case .projectOfTheDay:
let params = .defaults
|> DiscoveryParams.lens.includePOTD .~ true
|> DiscoveryParams.lens.perPage .~ 1
|> DiscoveryParams.lens.sort .~ .magic
return AppEnvironment.current.apiService.fetchDiscovery(params: params)
.demoteErrors()
.map { env -> Navigation? in
guard let project = env.projects.first, project.isPotdToday(
today: AppEnvironment.current.dateType.init().date) else { return nil }
return .project(.id(project.id), .root, refTag: RefTag.unrecognized("shortcut"))
}
case .projectsWeLove:
let params = .defaults
|> DiscoveryParams.lens.staffPicks .~ true
|> DiscoveryParams.lens.sort .~ .magic
return SignalProducer(value: .tab(.discovery(params.queryParams)))
case .search:
return SignalProducer(value: .tab(.search))
}
}
// Figures out which shortcut items to show to a user.
private func shortcutItems(forUser user: User?) -> SignalProducer<[ShortcutItem], NoError> {
guard let user = user else {
return SignalProducer(value: shortcutItems(isProjectMember: false, hasRecommendations: false))
}
let recommendationParams = .defaults
|> DiscoveryParams.lens.recommended .~ true
|> DiscoveryParams.lens.state .~ .live
|> DiscoveryParams.lens.perPage .~ 1
let recommendationsCount = AppEnvironment.current.apiService.fetchDiscovery(params: recommendationParams)
.map { $0.stats.count }
.flatMapError { _ in SignalProducer<Int, NoError>(value: 0) }
return recommendationsCount
.map { recommendationsCount in
shortcutItems(
isProjectMember: (user.stats.memberProjectsCount ?? 0) > 0,
hasRecommendations: recommendationsCount > 0
)
}
.demoteErrors()
}
// Figures out which shortcut items to show to a user based on whether they are a project member and/or
// has recommendations.
private func shortcutItems(isProjectMember: Bool, hasRecommendations: Bool)
-> [ShortcutItem] {
var items: [ShortcutItem] = []
if isProjectMember {
items.append(.creatorDashboard)
}
items.append(.projectOfTheDay)
if hasRecommendations {
items.append(.recommendedForYou)
}
items.append(.projectsWeLove)
if items.count < 4 {
items.append(.search)
}
return items
}
private func dictionary(fromUrlComponents urlComponents: URLComponents) -> [String:String] {
let queryItems = urlComponents.queryItems ?? []
return [String: String?].keyValuePairs(queryItems.map { ($0.name, $0.value) }).compact()
}
extension ShortcutItem {
public var applicationShortcutItem: UIApplicationShortcutItem {
switch self {
case .creatorDashboard:
return .init(
type: self.typeString,
localizedTitle: Strings.accessibility_discovery_buttons_creator_dashboard(),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "shortcut-icon-bars"),
userInfo: nil
)
case .projectOfTheDay:
return .init(
type: self.typeString,
localizedTitle: Strings.discovery_baseball_card_metadata_project_of_the_Day(),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "shortcut-icon-potd"),
userInfo: nil
)
case .projectsWeLove:
return .init(
type: self.typeString,
localizedTitle: Strings.Projects_We_Love(),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "shortcut-icon-k"),
userInfo: nil
)
case .recommendedForYou:
return .init(
type: self.typeString,
localizedTitle: Strings.Recommended(),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "shortcut-icon-heart"),
userInfo: nil
)
case .search:
return .init(
type: self.typeString,
localizedTitle: Strings.tabbar_search(),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "shortcut-icon-search"),
userInfo: nil
)
}
}
}
private func liveStreamData(fromNavigation nav: Navigation)
-> SignalProducer<(Project, LiveStreamEvent, RefTag?), NoError> {
guard case let .project(projectParam, .liveStream(eventId), refTag) = nav else { return .empty }
return SignalProducer.zip(
AppEnvironment.current.apiService.fetchProject(param: projectParam)
.demoteErrors(),
AppEnvironment.current.liveStreamService
.fetchEvent(eventId: eventId, uid: AppEnvironment.current.currentUser?.id)
.demoteErrors()
)
.map { project, liveStreamEvent -> (Project, LiveStreamEvent, RefTag?)? in
return (project, liveStreamEvent, refTag)
}
.skipNil()
}
private func visitorCookies() -> [HTTPCookie] {
let uuidString = (AppEnvironment.current.device.identifierForVendor ?? UUID()).uuidString
return [HTTPCookie?].init(arrayLiteral:
HTTPCookie(
properties: [
.name: "vis",
.value: uuidString,
.domain: AppEnvironment.current.apiService.serverConfig.webBaseUrl.host as Any,
.path: "/",
.version: 0,
.expires: Date.distantFuture,
.secure: true,
]
),
HTTPCookie(
properties: [
.name: "vis",
.value: uuidString,
.domain: AppEnvironment.current.apiService.serverConfig.apiBaseUrl.host as Any,
.path: "/",
.version: 0,
.expires: Date.distantFuture,
.secure: true,
]
)
)
.compact()
}
| 37.087368 | 110 | 0.70522 |
23eb9c16a6f9d4ea849e06de6e40d4f7111cd959 | 803 | /*
* ViewController.swift
* Target 1
*
* Created by François Lamboley on 11/09/2020.
*/
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// print("“\(Bundle.main.infoDictionary!["TEST_SPACES"]!)”")
// print("“\(Bundle.main.infoDictionary!["TEST_INCLUDES"]!)”")
// print("“\(Bundle.main.infoDictionary!["TEST_INCLUDES_2"]!)”")
print(NSLocalizedString("key_whose_value_is_the_key", value: "not in strings", comment: "yes, this is valid 🤦♂️"))
print(NSLocalizedString("key_whose_value_is_the_key_in_quotes", value: "not in strings", comment: "yes, this is valid 🤦♂️"))
for (k, v) in Bundle.main.infoDictionary!.sorted(by: { $0.key < $1.key }) {
print("“\(k)” -> “\(v)”")
}
NSApplication.shared.terminate(nil)
}
}
| 27.689655 | 127 | 0.671233 |
1df0e6dc60620b1a466e3fad21be64551eeb3152 | 1,019 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "DiskUtil",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "DiskUtil",
targets: ["DiskUtil"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "DiskUtil",
dependencies: []),
.testTarget(
name: "DiskUtilTests",
dependencies: ["DiskUtil"]),
]
)
| 35.137931 | 122 | 0.618253 |
3818adf0c1f4fb99ef7131f9618a7bcc58cfd837 | 83 | import Foundation
class Version {
static let version: String = "1.0.2"
}
| 11.857143 | 40 | 0.638554 |
8a51ff1a153b41687312388d140ea29cbbb01858 | 384 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "PureLayout",
platforms: [.iOS(.v8), .macOS(.v10_10), .tvOS(.v9)],
products: [
.library(
name: "PureLayout",
targets: ["PureLayout"])
],
targets: [
.target(
name: "PureLayout",
path: "PureLayout/PureLayout")
]
)
| 20.210526 | 56 | 0.526042 |
ed7d1a3a5603b7ae1da76528d17d53d3c78585d4 | 10,059 | //
// DZAlertView.swift
// DZ_UIKit
//
// Created by Dora.Yuan on 14/10/25.
// Copyright (c) 2014年 Dora.Yuan All rights reserved.
//
import Foundation
import UIKit
// MARK: - delegate protocol
internal protocol DZAlertViewDelegate {
func onButtonClicked(atIndex index: Int);
func onCancelButtonClicked();
}
open class DZAlertView : UIView {
// MARK: - Class define
let ONLY_ONE_BUTTON_FRAME:CGRect = CGRect(x: 10.0, y: 0.0, width: 260.0, height: 45.0);
let BUTTON_FRAME:CGRect = CGRect(x: 0.0, y: 0.0, width: 125.0, height: 45.0);
let ALERT_VIEW_WIDTH:CGFloat = 280.0;
let CANCEL_BUTTON_TAG:Int = 0;
// MARK: - public properties
internal fileprivate(set) var title: String = "";
internal fileprivate(set) var message: String?;
// cancel button color / text color
fileprivate let cancelButtonColor:UIColor = RGB(92, 177, 173);
fileprivate let cancelButtonTextColor:UIColor = RGB(255, 255, 255);
// normal button color / text color
fileprivate let normalButtonColor:UIColor = RGB(136, 136, 136);
fileprivate let normalButtonTextColor:UIColor = RGB(255, 255, 255);
// MARK: - internal properties
// MARK: - private properties
fileprivate var buttonArray = [UIButton]();
fileprivate var blockDictionary = [Int: DZBlock]();
fileprivate var titleLabel:UILabel = UILabel();
fileprivate var messageLabel:UILabel = UILabel();
//fileprivate var buttonBgView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light));
// MARK: - delegate
var delegate: DZAlertViewDelegate?;
// MARK: - init
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal init(title: String, message: String? = nil, cancelTitle: String = "Cancel") {
let rect:CGRect = CGRect(x: 0, y: 0, width: ALERT_VIEW_WIDTH, height: 100);
super.init(frame: rect);
self.frame = CGRect(x: 0, y: 0, width: ALERT_VIEW_WIDTH, height: 100);
// cancel button
self.addCancelButton(title: cancelTitle);
self.backgroundColor = RGB_HEX("ffffff", 0.7);
self.title = title;
self.message = message;
}
// MARK: - internal functions
internal func addCancelButton(title: String) {
let btn = UIButton(type: .custom);
btn.setTitle(title, for: .normal);
btn.setBackgroundImage(UIImage.imageWithColor(self.cancelButtonColor), for: .normal);
btn.setBackgroundImage(UIImage.imageWithColor(self.cancelButtonColor.withAlphaComponent(0.6)), for: .highlighted);
btn.frame = BUTTON_FRAME;
btn.tag = CANCEL_BUTTON_TAG;
btn.clipsToBounds = true;
btn.addTarget(self, action: #selector(cancelButtonClicked), for: .touchUpInside);
self.buttonArray.append(btn);
}
@objc internal func cancelButtonClicked() {
self.delegate?.onCancelButtonClicked();
}
@objc internal func buttonClicked(sender: AnyObject) {
let btnIdx = sender.tag;
self.delegate?.onButtonClicked(atIndex: btnIdx!);
return;
}
// MARK: - public functions
public func setCancelButton(title: String, bgColor: UIColor? = nil, textColor: UIColor? = nil) {
var btn:UIButton! = self.buttonArray[CANCEL_BUTTON_TAG];
if ( btn == nil ) {
btn = UIButton(type: .custom);
btn.frame = BUTTON_FRAME;
btn.tag = CANCEL_BUTTON_TAG;
btn.addTarget(self, action: #selector(cancelButtonClicked), for: .touchUpInside);
}
btn.setTitle(title, for: .normal);
let _bgColor = bgColor ?? self.cancelButtonColor;
let _textColor = textColor ?? self.cancelButtonTextColor;
btn.setBackgroundImage(UIImage.imageWithColor(_bgColor), for: .normal);
btn.setBackgroundImage(UIImage.imageWithColor(_bgColor.withAlphaComponent(0.6)), for: .highlighted);
btn.setTitleColor(_textColor, for: .normal);
return;
}
public func addButton(title: String, bgColor: UIColor? = nil, textColor: UIColor? = nil) -> Int {
let btn = UIButton(type: .custom);
btn.setTitle(title, for: .normal);
self.buttonArray.append(btn);
let _bgColor = bgColor ?? self.normalButtonColor;
let _textColor = textColor ?? self.normalButtonTextColor;
btn.setBackgroundImage(UIImage.imageWithColor(_bgColor), for: .normal);
btn.setBackgroundImage(UIImage.imageWithColor(_bgColor.withAlphaComponent(0.6)), for: .highlighted);
btn.setTitleColor(_textColor, for: .normal);
btn.frame = BUTTON_FRAME;
let index = self.buttonArray.index(of: btn)!;
btn.tag = index;
btn.clipsToBounds = true;
btn.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside);
return index;
}
// MARK: - layoutSubviews
open override func layoutSubviews() {
self.layer.cornerRadius = 8.0;
var rect:CGRect = CGRect(x: 10, y: 5, width: ALERT_VIEW_WIDTH - 20, height: 40);
self.layer.shadowColor = UIColor.gray.cgColor;
self.layer.shadowOffset = CGSize(width: 0, height: 0);
self.layer.shadowRadius = 4.0;
self.layer.shadowOpacity = 0.6;
//self.buttonBgView.layer.cornerRadius = 8.0;
//self.buttonBgView.clipsToBounds = true;
//self.buttonBgView.backgroundColor = RGB_HEX("ffffff", 0.3);
//self.addSubview(self.buttonBgView);
var alertViewHeight:CGFloat = rect.size.height + 10.0;
// labels
self.titleLabel.frame = rect;
self.titleLabel.textAlignment = NSTextAlignment.center;
self.titleLabel.backgroundColor = UIColor.clear;
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 18.0);
self.titleLabel.textColor = UIColor.darkText;
self.titleLabel.text = self.title;
self.addSubview(self.titleLabel);
if self.message != nil {
let msgRect:CGRect = self.message!.boundingRect(
with: CGSize(width: ALERT_VIEW_WIDTH - 20, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)],
context: nil);
rect = CGRect(x: 10, y: 10 + 40, width: ALERT_VIEW_WIDTH-20, height: msgRect.size.height);
alertViewHeight += (msgRect.size.height + 30.0);
self.messageLabel.frame = rect;
self.messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping;
self.messageLabel.numberOfLines = 0;
if ( msgRect.size.height > 20 ) {
self.messageLabel.textAlignment = NSTextAlignment.center;
}
else {
self.messageLabel.textAlignment = NSTextAlignment.center;
}
self.messageLabel.backgroundColor = UIColor.clear;
self.messageLabel.font = UIFont.systemFont(ofSize: 16.0);
self.messageLabel.textColor = UIColor.darkText;
self.messageLabel.text = self.message;
self.addSubview(self.messageLabel);
}
else {
alertViewHeight += 10.0;
}
//
if ( self.buttonArray.count <= 2 ) {
alertViewHeight += 45.0;
}
else {
alertViewHeight += (45.0 + 10.0) * CGFloat(self.buttonArray.count) - 10;
}
self.frame = CGRect(x: 0, y: 0, width: 280, height: alertViewHeight);
self.center = CGPoint(x: SCREEN_BOUNDS().size.width/2,
y: SCREEN_BOUNDS().size.height/2);
self.alpha = 0.2;
// buttons
if ( self.buttonArray.count == 1 ) {
let btn = self.buttonArray[0];
self.addSubview(btn);
let btnIdx:Int = btn.tag;
btn.layer.cornerRadius = 4.0;
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18.0);
btn.frame = CGRect(
x: 10.0 + 135.0 * CGFloat(btnIdx),
y: self.frame.size.height - 55.0,
width: ONLY_ONE_BUTTON_FRAME.size.width,
height: ONLY_ONE_BUTTON_FRAME.size.height);
}
else if ( self.buttonArray.count == 2 ) {
for btn in self.buttonArray {
self.addSubview(btn);
let btnIdx:Int = btn.tag;
btn.layer.cornerRadius = 4.0;
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18.0);
btn.frame = CGRect(
x: 10.0 + 135.0 * CGFloat(1 - btnIdx),
y: self.frame.size.height - 55.0,
width: BUTTON_FRAME.size.width,
height: BUTTON_FRAME.size.height);
}
}
else
{
for btn in self.buttonArray {
self.addSubview(btn);
let btnIdx:Int = btn.tag;
btn.layer.cornerRadius = 4.0;
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18.0);
btn.frame = CGRect(
x: 10.0,
y: self.frame.size.height - 55.0 * CGFloat(btnIdx+1),
width: ONLY_ONE_BUTTON_FRAME.size.width,
height: ONLY_ONE_BUTTON_FRAME.size.height);
}
}
}
}
| 38.247148 | 122 | 0.571727 |
d9201576317be26b3012fe3bec26121e51fe0c0c | 65,823 | //
// ParsingHelpers.swift
// SwiftFormat
//
// Created by Nick Lockwood on 08/04/2019.
// Copyright © 2019 Nick Lockwood. All rights reserved.
//
import Foundation
// MARK: shared helper methods
public extension Formatter {
/// Returns the index of the first token of the line containing the specified index
func startOfLine(at index: Int) -> Int {
var index = index
while let token = token(at: index - 1) {
if case .linebreak = token {
break
}
index -= 1
}
return index
}
/// Returns the index of the linebreak token at the end of the line containing the specified index
func endOfLine(at index: Int) -> Int {
var index = index
while let token = token(at: index) {
if case .linebreak = token {
break
}
index += 1
}
return index
}
/// Whether or not the two indicies represent tokens on the same line
func onSameLine(_ lhs: Int, _ rhs: Int) -> Bool {
return startOfLine(at: lhs) == startOfLine(at: rhs)
}
/// Returns the space at the start of the line containing the specified index
func indentForLine(at index: Int) -> String {
if case let .space(string)? = token(at: startOfLine(at: index)) {
return string
}
return ""
}
/// Returns the length (in characters) of the specified token
func tokenLength(_ token: Token) -> Int {
let tabWidth = options.tabWidth > 0 ? options.tabWidth : options.indent.count
return token.columnWidth(tabWidth: tabWidth)
}
/// Returns the length (in characters) of the line at the specified index
func lineLength(at index: Int) -> Int {
return lineLength(upTo: endOfLine(at: index))
}
/// Returns the length (in characters) up to (but not including) the specified token index
func lineLength(upTo index: Int) -> Int {
return lineLength(from: startOfLine(at: index), upTo: index)
}
/// Returns the length (in characters) of the specified token range
func lineLength(from start: Int, upTo end: Int) -> Int {
if options.assetLiteralWidth == .actualWidth {
return tokens[start ..< end].reduce(0) { total, token in
total + tokenLength(token)
}
}
var length = 0
var index = start
while index < end {
let token = tokens[index]
switch token {
case .keyword("#colorLiteral"), .keyword("#imageLiteral"):
guard let startIndex = self.index(of: .startOfScope("("), after: index),
let endIndex = endOfScope(at: startIndex)
else {
fallthrough
}
length += 2 // visible length of asset literal in Xcode
index = endIndex + 1
default:
length += tokenLength(token)
index += 1
}
}
return length
}
/// Returns white space made up of indent characters equivalent to the specified width
func spaceEquivalentToWidth(_ width: Int) -> String {
if !options.smartTabs, options.useTabs, options.tabWidth > 0 {
let tabs = width / options.tabWidth
let remainder = width % options.tabWidth
return String(repeating: "\t", count: tabs) + String(repeating: " ", count: remainder)
}
return String(repeating: " ", count: width)
}
/// Returns white space made up of indent characters equvialent to the specified token range
func spaceEquivalentToTokens(from start: Int, upTo end: Int) -> String {
if !options.smartTabs, options.useTabs, options.tabWidth > 0 {
return spaceEquivalentToWidth(lineLength(from: start, upTo: end))
}
var result = ""
var index = start
while index < end {
let token = tokens[index]
switch token {
case let .space(string):
result += string
case .keyword("#colorLiteral"), .keyword("#imageLiteral"):
guard let startIndex = self.index(of: .startOfScope("("), after: index),
let endIndex = endOfScope(at: startIndex)
else {
fallthrough
}
let length = lineLength(from: index, upTo: endIndex + 1)
result += String(repeating: " ", count: length)
index = endIndex
default:
result += String(repeating: " ", count: tokenLength(token))
}
index += 1
}
return result
}
/// Returns the starting token for the containing scope at the specified index
func currentScope(at index: Int) -> Token? {
return last(.startOfScope, before: index)
}
/// Returns the index of the ending token for the current scope
// TODO: should this return the closing `}` for `switch { ...` instead of nested `case`?
func endOfScope(at index: Int) -> Int? {
var startIndex: Int
guard var startToken = token(at: index) else { return nil }
if case .startOfScope = startToken {
startIndex = index
} else if let index = self.index(of: .startOfScope, before: index) {
startToken = tokens[index]
startIndex = index
} else {
return nil
}
guard startToken == .startOfScope("{") else {
return self.index(after: startIndex, where: {
$0.isEndOfScope(startToken)
})
}
while let endIndex = self.index(after: startIndex, where: {
$0.isEndOfScope(startToken)
}), let token = token(at: endIndex) {
if token == .endOfScope("}") {
return endIndex
}
startIndex = endIndex
startToken = token
}
return nil
}
/// Returns the end of the expression at the specified index, optionally stopping at any of the specified tokens
func endOfExpression(at index: Int, upTo delimiters: [Token]) -> Int? {
var lastIndex = index
var index: Int? = index
var wasOperator = true
while var i = index {
let token = tokens[i]
if delimiters.contains(token) {
return lastIndex
}
switch token {
case .operator(_, .infix):
wasOperator = true
case .operator(_, .prefix) where wasOperator, .operator(_, .postfix):
break
case .keyword("as"):
wasOperator = true
if case let .operator(name, .postfix)? = self.token(at: i + 1),
["?", "!"].contains(name)
{
i += 1
}
case .number, .identifier:
guard wasOperator else {
return lastIndex
}
wasOperator = false
case .startOfScope where wasOperator,
.startOfScope("{") where isStartOfClosure(at: i),
.startOfScope("(") where isSubscriptOrFunctionCall(at: i),
.startOfScope("[") where isSubscriptOrFunctionCall(at: i):
wasOperator = false
guard let endIndex = endOfScope(at: i) else {
return nil
}
i = endIndex
default:
return lastIndex
}
lastIndex = i
index = self.index(of: .nonSpaceOrCommentOrLinebreak, after: i)
}
return lastIndex
}
}
enum ScopeType {
case array
case arrayType
case captureList
case dictionary
case dictionaryType
case `subscript`
case tuple
case tupleType
var isType: Bool {
switch self {
case .array, .captureList, .dictionary, .subscript, .tuple:
return false
case .arrayType, .dictionaryType, .tupleType:
return true
}
}
}
extension Formatter {
func scopeType(at index: Int) -> ScopeType? {
guard let token = self.token(at: index) else {
return nil
}
guard case .startOfScope = token else {
guard let startIndex = self.index(of: .startOfScope, before: index) else {
return nil
}
return scopeType(at: startIndex)
}
switch token {
case .startOfScope("["), .startOfScope("("):
guard let endIndex = endOfScope(at: index) else {
return nil
}
var isType = false
if let nextIndex = self.index(of: .nonSpaceOrCommentOrLinebreak, after: endIndex, if: {
$0.isOperator(".")
}), [.identifier("self"), .identifier("init")]
.contains(next(.nonSpaceOrCommentOrLinebreak, after: nextIndex))
{
isType = true
} else if next(.nonSpaceOrComment, after: endIndex) == .startOfScope("(") {
isType = true
} else if let prevIndex = self.index(of: .nonSpaceOrCommentOrLinebreak, before: index) {
switch tokens[prevIndex] {
case .identifier, .endOfScope(")"), .endOfScope("]"),
.operator("?", _), .operator("!", _),
.endOfScope where token.isStringDelimiter:
if tokens[prevIndex + 1 ..< index].contains(where: { $0.isLinebreak }) {
break
}
return .subscript
case .startOfScope("{") where isInClosureArguments(at: index):
return .captureList
case .delimiter(":"), .delimiter(","):
// Check for type declaration
if let scopeStart = self.index(of: .startOfScope, before: prevIndex) {
switch tokens[scopeStart] {
case .startOfScope("("):
if last(.keyword, before: scopeStart) == .keyword("func") {
isType = true
} else {
fallthrough
}
case .startOfScope("["):
guard let type = scopeType(at: scopeStart) else {
return nil
}
isType = type.isType
default:
break
}
break
}
if let token = last(.keyword, before: index),
[.keyword("let"), .keyword("var")].contains(token)
{
isType = true
}
case .operator("->", _), .startOfScope("<"):
isType = true
case .startOfScope("["), .startOfScope("("):
guard let type = scopeType(at: prevIndex) else {
return nil
}
isType = type.isType
default:
break
}
}
if token == .startOfScope("(") {
return isType ? .tupleType : .tuple
}
if !isType {
return self.index(of: .delimiter(":"), after: index) == nil ? .array : .dictionary
}
return self.index(of: .delimiter(":"), after: index) == nil ? .arrayType : .dictionaryType
default:
return nil
}
}
func modifiersForDeclaration(at index: Int, contains: (Int, String) -> Bool) -> Bool {
var index = index
while var prevIndex = self.index(of: .nonSpaceOrCommentOrLinebreak, before: index) {
let token = tokens[prevIndex]
switch token {
case _ where token.isModifierKeyword || token.isAttribute:
if contains(prevIndex, token.string) {
return true
}
case .endOfScope(")"):
guard let startIndex = self.index(of: .startOfScope("("), before: prevIndex),
last(.nonSpaceOrCommentOrLinebreak, before: startIndex, if: {
$0.isAttribute || _FormatRules.aclModifiers.contains($0.string)
}) != nil
else {
return false
}
prevIndex = startIndex
case .identifier:
guard let startIndex = startOfAttribute(at: prevIndex),
let nextIndex = self.index(of: .operator(".", .infix), after: startIndex)
else {
return false
}
prevIndex = nextIndex
default:
return false
}
index = prevIndex
}
return false
}
func modifiersForDeclaration(at index: Int, contains: String) -> Bool {
return modifiersForDeclaration(at: index, contains: { $1 == contains })
}
func indexOfModifier(_ modifier: String, forTypeAt index: Int) -> Int? {
var i: Int?
return modifiersForDeclaration(at: index, contains: {
i = $0
return $1 == modifier
}) ? i : nil
}
// first index of modifier list
func startOfModifiers(at index: Int, includingAttributes: Bool) -> Int {
var startIndex = index
_ = modifiersForDeclaration(at: index, contains: { i, name in
if !includingAttributes, name.hasPrefix("@") {
return true
}
startIndex = i
return false
})
return startIndex
}
// gather declared variable names, starting at index after let/var keyword
func processDeclaredVariables(at index: inout Int, names: inout Set<String>) {
processDeclaredVariables(at: &index, names: &names, removeSelf: false)
}
/// Returns true if token is inside the return type of a function or subscript
func isInReturnType(at i: Int) -> Bool {
return startOfReturnType(at: i) != nil
}
/// Returns the index of the `->` operator for the current return type declaration if
/// the specified index is in a return type declaration.
func startOfReturnType(at i: Int) -> Int? {
guard let startIndex = indexOfLastSignificantKeyword(
at: i, excluding: ["throws", "rethrows", "async"]
), ["func", "subscript"].contains(tokens[startIndex].string) else {
return nil
}
let endIndex = index(of: .startOfScope("{"), after: i) ?? i
return index(of: .operator("->", .infix), in: startIndex + 1 ..< endIndex)
}
func isStartOfClosure(at i: Int, in _: Token? = nil) -> Bool {
guard token(at: i) == .startOfScope("{") else {
return false
}
if isConditionalStatement(at: i) {
if let endIndex = endOfScope(at: i),
next(.nonSpaceOrComment, after: endIndex) == .startOfScope("(") ||
next(.nonSpaceOrCommentOrLinebreak, after: endIndex) == .startOfScope("{")
{
return true
}
return false
}
guard var prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i) else {
return true
}
switch tokens[prevIndex] {
case .startOfScope("("), .startOfScope("["), .startOfScope("{"),
.operator(_, .infix), .operator(_, .prefix), .delimiter, .keyword("return"),
.keyword("in"), .keyword("where"), .keyword("try"), .keyword("throw"), .keyword("await"):
return true
case .operator(_, .none),
.keyword("deinit"), .keyword("catch"), .keyword("else"), .keyword("repeat"),
.keyword("throws"), .keyword("rethrows"), .keyword("async"):
return false
case .endOfScope("}"):
guard let startOfScope = index(of: .startOfScope("{"), before: prevIndex) else {
return false
}
return !isStartOfClosure(at: startOfScope)
case .endOfScope(")"), .endOfScope(">"):
guard var startOfScope = index(of: .startOfScope, before: prevIndex),
var prev = index(of: .nonSpaceOrCommentOrLinebreak, before: startOfScope)
else {
return true
}
if tokens[prevIndex] == .endOfScope(">"), tokens[prev] == .endOfScope(")") {
startOfScope = index(of: .startOfScope, before: prev) ?? startOfScope
prev = index(of: .nonSpaceOrCommentOrLinebreak, before: startOfScope) ?? prev
}
switch tokens[prev] {
case .identifier:
prevIndex = prev
case .operator("?", .postfix), .operator("!", .postfix):
switch token(at: prev - 1) {
case .identifier?:
prevIndex = prev - 1
case .keyword("init")?:
return false
default:
return true
}
case .operator("->", .infix), .keyword("init"),
.keyword("subscript"), .endOfScope(">"):
return false
default:
if let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: i),
isAccessorKeyword(at: nextIndex) || isAccessorKeyword(at: prevIndex)
{
return false
} else {
return !isConditionalStatement(at: startOfScope)
}
}
fallthrough
case .endOfScope where tokens[prevIndex].isStringDelimiter, .identifier, .number:
if let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: i),
isAccessorKeyword(at: nextIndex) || isAccessorKeyword(at: prevIndex)
{
return false
}
guard let prevKeywordIndex = indexOfLastSignificantKeyword(at: prevIndex) else {
return true
}
switch tokens[prevKeywordIndex].string {
case "var":
if lastIndex(of: .operator("=", .infix), in: prevKeywordIndex + 1 ..< i) != nil {
return true
}
var index = prevKeywordIndex
while let nextIndex = self.index(of: .nonSpaceOrComment, after: index),
nextIndex < i
{
switch tokens[nextIndex] {
case .operator("=", .infix):
return true
case .linebreak:
guard let nextIndex =
self.index(of: .nonSpaceOrCommentOrLinebreak, after: nextIndex)
else {
return true
}
if tokens[nextIndex] != .startOfScope("{"),
isEndOfStatement(at: index), isStartOfStatement(at: nextIndex)
{
return true
}
index = nextIndex
default:
index = nextIndex
}
}
return false
case "func", "subscript", "class", "struct", "protocol", "enum", "extension",
"throws", "rethrows", "async", "catch":
return false
default:
return true
}
case .operator("?", .postfix), .operator("!", .postfix),
.keyword, .endOfScope("]"), .endOfScope(">"):
return false
default:
return true
}
}
func isInClosureArguments(at i: Int) -> Bool {
var i = i
while let token = self.token(at: i) {
switch token {
case .keyword("in"), .keyword("throws"), .keyword("rethrows"), .keyword("async"):
guard let scopeIndex = index(of: .startOfScope, before: i, if: {
$0 == .startOfScope("{")
}) else {
return false
}
return isStartOfClosure(at: scopeIndex)
case .startOfScope("("), .startOfScope("["), .startOfScope("<"),
.endOfScope(")"), .endOfScope("]"), .endOfScope(">"),
.keyword where token.isAttribute:
break
case .keyword, .startOfScope, .endOfScope:
return false
default:
break
}
i += 1
}
return false
}
func isAccessorKeyword(at i: Int, checkKeyword: Bool = true) -> Bool {
guard !checkKeyword ||
["get", "set", "willSet", "didSet"].contains(token(at: i)?.string ?? ""),
var prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i)
else {
return false
}
if tokens[prevIndex] == .endOfScope("}"),
let startIndex = index(of: .startOfScope("{"), before: prevIndex),
let prev = index(of: .nonSpaceOrCommentOrLinebreak, before: startIndex)
{
prevIndex = prev
if tokens[prevIndex] == .endOfScope(")"),
let startIndex = index(of: .startOfScope("("), before: prevIndex),
let prev = index(of: .nonSpaceOrCommentOrLinebreak, before: startIndex)
{
prevIndex = prev
}
return isAccessorKeyword(at: prevIndex)
} else if tokens[prevIndex] == .startOfScope("{") {
switch lastSignificantKeyword(at: prevIndex, excluding: ["where"]) {
case "var"?, "subscript"?:
return true
default:
return false
}
}
return false
}
func isConditionalStatement(at i: Int) -> Bool {
return startOfConditionalStatement(at: i) != nil
}
func startOfConditionalStatement(at i: Int) -> Int? {
guard let index = indexOfLastSignificantKeyword(at: i) else {
return nil
}
func isAfterBrace(_ index: Int) -> Bool {
guard let braceIndex = lastIndex(of: .endOfScope("}"), in: index ..< i) else {
return false
}
return self.index(of: .nonSpaceOrCommentOrLinebreak, in: braceIndex + 1 ..< i) != nil
}
switch tokens[index].string {
case "let", "var":
guard let prevIndex = self
.index(of: .nonSpaceOrCommentOrLinebreak, before: index)
else {
return nil
}
switch tokens[prevIndex] {
case .delimiter(","):
return prevIndex
case let .keyword(name) where
["if", "guard", "while", "for", "case", "catch"].contains(name):
return isAfterBrace(prevIndex) ? nil : prevIndex
default:
return nil
}
case "if", "guard", "while", "for", "case", "where", "switch":
return isAfterBrace(index) ? nil : index
default:
return nil
}
}
func lastSignificantKeyword(at i: Int, excluding: [String] = []) -> String? {
guard let index = indexOfLastSignificantKeyword(at: i, excluding: excluding),
case let .keyword(keyword) = tokens[index]
else {
return nil
}
return keyword
}
func indexOfLastSignificantKeyword(at i: Int, excluding: [String] = []) -> Int? {
guard let token = token(at: i),
let index = token.isKeyword ? i : index(of: .keyword, before: i),
case let .keyword(keyword) = tokens[index]
else {
return nil
}
switch keyword {
case let name where
name.hasPrefix("#") || name.hasPrefix("@") || excluding.contains(name):
fallthrough
case "in", "is", "as", "try", "await":
return indexOfLastSignificantKeyword(at: index - 1, excluding: excluding)
default:
guard let braceIndex = self.index(of: .startOfScope("{"), in: index ..< i),
let endIndex = endOfScope(at: braceIndex),
next(.nonSpaceOrComment, after: endIndex) != .startOfScope("(")
else {
return index
}
if keyword == "if" || ["var", "let"].contains(keyword) &&
last(.nonSpaceOrCommentOrLinebreak, before: index) == .keyword("if"),
self.index(of: .startOfScope("{"), in: endIndex ..< i) == nil
{
return index
}
return nil
}
}
func isAttribute(at i: Int) -> Bool {
return startOfAttribute(at: i) != nil
}
func startOfAttribute(at i: Int) -> Int? {
switch tokens[i] {
case let token where token.isAttribute:
return i
case .endOfScope(")"):
guard let openParenIndex = index(of: .startOfScope("("), before: i),
let prevTokenIndex = index(of: .nonSpaceOrComment, before: openParenIndex)
else {
return nil
}
return startOfAttribute(at: prevTokenIndex)
case .identifier:
guard let dotIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i, if: {
$0.isOperator(".")
}), let prevTokenIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: dotIndex) else {
return nil
}
return startOfAttribute(at: prevTokenIndex)
default:
return nil
}
}
func endOfAttribute(at i: Int) -> Int? {
guard let startIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: i) else {
return i
}
switch tokens[startIndex] {
case .startOfScope("(") where !tokens[i + 1 ..< startIndex].contains(where: { $0.isLinebreak }):
guard let closeParenIndex = index(of: .endOfScope(")"), after: startIndex) else {
return nil
}
return closeParenIndex
case .operator(".", .infix):
guard let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: startIndex) else {
return nil
}
return endOfAttribute(at: nextIndex)
default:
return i
}
}
// Determine if next line after this token should be indented
func isEndOfStatement(at i: Int, in scope: Token? = nil) -> Bool {
guard let token = self.token(at: i) else { return true }
switch token {
case .endOfScope("case"), .endOfScope("default"):
return false
case let .keyword(string):
// TODO: handle context-specific keywords
// associativity, convenience, dynamic, didSet, final, get, infix, indirect,
// lazy, left, mutating, none, nonmutating, open, optional, override, postfix,
// precedence, prefix, Protocol, required, right, set, Type, unowned, weak, willSet
switch string {
case "let", "func", "var", "if", "as", "import", "try", "guard", "case",
"for", "init", "switch", "throw", "where", "subscript", "is",
"while", "associatedtype", "inout", "await":
return false
case "in":
return lastSignificantKeyword(at: i) != "for"
case "return":
guard let nextToken = next(.nonSpaceOrCommentOrLinebreak, after: i) else {
return true
}
switch nextToken {
case .keyword, .endOfScope("case"), .endOfScope("default"):
return true
default:
return false
}
default:
return true
}
case .delimiter(","):
guard let scope = scope ?? currentScope(at: i) else {
return false
}
// For arrays or argument lists, we already indent
return ["<", "[", "(", "case", "default"].contains(scope.string)
case .delimiter(":"):
guard let scope = scope ?? currentScope(at: i) else {
return false
}
// For arrays or argument lists, we already indent
return ["case", "default", "("].contains(scope.string)
case .operator(_, .infix), .operator(_, .prefix):
return false
case .operator("?", .postfix), .operator("!", .postfix):
switch self.token(at: i - 1) {
case .keyword("as")?, .keyword("try")?:
return false
default:
return true
}
default:
if let attributeIndex = startOfAttribute(at: i),
let prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: attributeIndex)
{
return isEndOfStatement(at: prevIndex, in: scope)
}
return true
}
}
// Determine if line starting with this token should be indented
func isStartOfStatement(at i: Int, in scope: Token? = nil) -> Bool {
guard let token = self.token(at: i) else { return true }
switch token {
case let .keyword(string) where [ // TODO: handle "in"
"where", "dynamicType", "rethrows", "throws", "async",
].contains(string):
return false
case .keyword("as"):
// For case statements, we already indent
return (scope ?? currentScope(at: i))?.string == "case"
case .keyword("in"):
let scope = (scope ?? currentScope(at: i))?.string
// For case statements and closures, we already indent
return scope == "case" || (scope == "{" && lastSignificantKeyword(at: i) != "for")
case .keyword("is"):
guard let lastToken = last(.nonSpaceOrCommentOrLinebreak, before: i) else {
return false
}
return [.endOfScope("case"), .keyword("case"), .delimiter(",")].contains(lastToken)
case .delimiter(","):
guard let scope = scope ?? currentScope(at: i) else {
return false
}
// For arrays, dictionaries, cases, or argument lists, we already indent
return ["<", "[", "(", "case"].contains(scope.string)
case .delimiter, .operator(_, .infix), .operator(_, .postfix):
return false
case .endOfScope("}"), .endOfScope("]"), .endOfScope(")"), .endOfScope(">"):
return false
case .startOfScope("{") where isStartOfClosure(at: i):
guard last(.nonSpaceOrComment, before: i)?.isLinebreak == true,
let prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i),
let prevToken = self.token(at: prevIndex)
else {
return false
}
if prevToken.isIdentifier, !["true", "false", "nil"].contains(prevToken.string) {
return false
}
if [.endOfScope(")"), .endOfScope("]")].contains(prevToken),
let startIndex = index(of: .startOfScope, before: prevIndex),
!tokens[startIndex ..< prevIndex].contains(where: { $0.isLinebreak })
|| indentForLine(at: startIndex) == indentForLine(at: prevIndex)
{
return false
}
return true
case .keyword:
return true
default:
if let prevToken = last(.nonSpaceOrCommentOrLinebreak, before: i),
prevToken == .keyword("return") || prevToken.isOperator(ofType: .infix)
{
return false
}
return true
}
}
func isSubscriptOrFunctionCall(at i: Int) -> Bool {
guard case let .startOfScope(string)? = token(at: i), ["[", "("].contains(string),
let prevToken = last(.nonSpaceOrComment, before: i)
else {
return false
}
switch prevToken {
case .identifier, .operator(_, .postfix),
.endOfScope("]"), .endOfScope(")"), .endOfScope("}"),
.endOfScope where prevToken.isStringDelimiter:
return true
default:
return false
}
}
// Detect if currently inside a String literal
func isStringLiteral(at index: Int) -> Bool {
for token in tokens[..<index].reversed() {
switch token {
case .stringBody:
return true
case .endOfScope where token.isStringDelimiter, .linebreak:
return false
default:
continue
}
}
return false
}
// Detect if code is inside a ViewBuilder
func isInViewBuilder(at i: Int) -> Bool {
var i = i
while let startIndex = index(of: .startOfScope("{"), before: i) {
guard let prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: startIndex) else {
return false
}
if tokens[prevIndex] == .identifier("View"),
let prevToken = last(.nonSpaceOrCommentOrLinebreak, before: prevIndex),
[.delimiter(":"), .identifier("some")].contains(prevToken)
{
return true
}
i = prevIndex
}
return false
}
// Detect if identifier requires backtick escaping
func backticksRequired(at i: Int, ignoreLeadingDot: Bool = false) -> Bool {
guard let token = token(at: i), token.isIdentifier else {
return false
}
let unescaped = token.unescaped()
if !unescaped.isSwiftKeyword {
switch unescaped {
case "super", "self", "nil", "true", "false":
if options.swiftVersion < "4" {
return true
}
case "Self", "Any":
if let prevToken = last(.nonSpaceOrCommentOrLinebreak, before: i),
[.delimiter(":"), .operator("->", .infix)].contains(prevToken)
{
// TODO: check for other cases where it's safe to use unescaped
return false
}
case "Type":
if currentScope(at: i) == .startOfScope("{") {
// TODO: check it's actually inside a type declaration, otherwise backticks aren't needed
return true
}
if last(.nonSpaceOrCommentOrLinebreak, before: i)?.isOperator(".") == true {
return true
}
return false
case "get", "set", "willSet", "didSet":
return isAccessorKeyword(at: i, checkKeyword: false)
default:
return false
}
}
if let prevIndex = index(of: .nonSpaceOrCommentOrLinebreak, before: i, if: {
$0.isOperator(".")
}) {
if unescaped == "init" {
return true
}
if options.swiftVersion >= "5" || self.token(at: prevIndex - 1)?.isOperator("\\") != true {
return ignoreLeadingDot
}
return true
}
guard !["let", "var"].contains(unescaped) else {
return true
}
return !isArgumentPosition(at: i)
}
// Is token at argument position
func isArgumentPosition(at i: Int) -> Bool {
assert(tokens[i].isIdentifierOrKeyword)
guard let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: i) else {
return false
}
let nextToken = tokens[nextIndex]
if nextToken == .delimiter(":") || (nextToken.isIdentifier &&
next(.nonSpaceOrCommentOrLinebreak, after: nextIndex) == .delimiter(":")),
currentScope(at: i) == .startOfScope("(")
{
return true
}
return false
}
func isCommentedCode(at i: Int) -> Bool {
if token(at: i) == .startOfScope("//"), token(at: i - 1)?.isSpace != true {
switch token(at: i + 1) {
case nil, .linebreak?:
return true
case let .space(space)? where space.hasPrefix(options.indent):
return true
default:
break
}
}
return false
}
func isParameterList(at i: Int) -> Bool {
assert([.startOfScope("("), .startOfScope("<")].contains(tokens[i]))
guard let endIndex = endOfScope(at: i),
let nextIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: endIndex)
else { return false }
switch tokens[nextIndex] {
case .operator("->", .infix), .keyword("throws"), .keyword("rethrows"), .keyword("async"):
return true
case .identifier("async"):
if let nextToken = next(.nonSpaceOrCommentOrLinebreak, after: nextIndex),
[.operator("->", .infix), .keyword("throws"), .keyword("rethrows")].contains(nextToken)
{
return true
}
default:
if let funcIndex = index(of: .keyword, before: i, if: {
[.keyword("func"), .keyword("init"), .keyword("subscript")].contains($0)
}), lastIndex(of: .endOfScope("}"), in: funcIndex ..< i) == nil {
// Is parameters at start of function
return true
}
}
return false
}
func isEnumCase(at i: Int) -> Bool {
assert(tokens[i] == .keyword("case"))
switch last(.nonSpaceOrCommentOrLinebreak, before: i) {
case .identifier?, .endOfScope(")")?, .startOfScope("{")?:
return true
default:
return false
}
}
struct ImportRange: Comparable {
var module: String
var range: Range<Int>
var isTestable: Bool
static func < (lhs: ImportRange, rhs: ImportRange) -> Bool {
let la = lhs.module.lowercased()
let lb = rhs.module.lowercased()
return la == lb ? lhs.module < rhs.module : la < lb
}
}
// Shared import rules implementation
func parseImports() -> [[ImportRange]] {
var importStack = [[ImportRange]]()
var importRanges = [ImportRange]()
forEach(.keyword("import")) { i, _ in
func pushStack() {
importStack.append(importRanges)
importRanges.removeAll()
}
// Get start of line
var startIndex = index(of: .linebreak, before: i) ?? 0
// Check for attributes
var previousKeywordIndex = index(of: .keyword, before: i)
while let previousIndex = previousKeywordIndex {
var nextStart: Int? // workaround for Swift Linux bug
if tokens[previousIndex].isAttribute {
if previousIndex < startIndex {
nextStart = index(of: .linebreak, before: previousIndex) ?? 0
}
previousKeywordIndex = index(of: .keyword, before: previousIndex)
startIndex = nextStart ?? startIndex
} else if previousIndex >= startIndex {
// Can't handle another keyword on same line as import
return
} else {
break
}
}
// Gather comments
let codeStartIndex = startIndex
var prevIndex = index(of: .linebreak, before: startIndex) ?? 0
while startIndex > 0,
next(.nonSpace, after: prevIndex)?.isComment == true,
next(.nonSpaceOrComment, after: prevIndex)?.isLinebreak == true
{
if prevIndex == 0, index(of: .startOfScope("#if"), before: startIndex) != nil {
break
}
startIndex = prevIndex
prevIndex = index(of: .linebreak, before: startIndex) ?? 0
}
// Check if comment is potentially a file header
if last(.nonSpaceOrCommentOrLinebreak, before: startIndex) == nil {
for case let .commentBody(body) in tokens[startIndex ..< codeStartIndex] {
if body.contains("created") || body.contains("Created") ||
body.contains(options.fileInfo.fileName ?? ".swift")
{
startIndex = codeStartIndex
break
}
}
}
// Get end of line
let endIndex = index(of: .linebreak, after: i) ?? tokens.count
// Get name
if let firstPartIndex = index(of: .identifier, after: i) {
var name = tokens[firstPartIndex].string
var partIndex = firstPartIndex
loop: while let nextPartIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: partIndex) {
switch tokens[nextPartIndex] {
case .operator(".", .infix):
name += "."
case let .identifier(string):
name += string
default:
break loop
}
partIndex = nextPartIndex
}
let range = startIndex ..< endIndex as Range
importRanges.append(ImportRange(
module: name,
range: range,
isTestable: tokens[range].contains(.keyword("@testable"))
))
} else {
// Error
pushStack()
return
}
if next(.spaceOrCommentOrLinebreak, after: endIndex)?.isLinebreak == true {
// Blank line after - consider this the end of a block
pushStack()
return
}
if var nextTokenIndex = index(of: .nonSpaceOrCommentOrLinebreak, after: endIndex) {
while tokens[nextTokenIndex].isAttribute {
guard let nextIndex = index(of: .nonSpaceOrLinebreak, after: nextTokenIndex) else {
// End of imports
pushStack()
return
}
nextTokenIndex = nextIndex
}
if tokens[nextTokenIndex] != .keyword("import") {
// End of imports
pushStack()
return
}
}
}
// End of imports
importStack.append(importRanges)
return importStack
}
enum Declaration: Equatable {
/// A type-like declaration with body of additional declarations (`class`, `struct`, etc)
indirect case type(kind: String, open: [Token], body: [Declaration], close: [Token])
/// A simple declaration (like a property or function)
case declaration(kind: String, tokens: [Token])
/// A #if ... #endif conditional compilation block with a body of additional declarations
indirect case conditionalCompilation(open: [Token], body: [Declaration], close: [Token])
/// The tokens in this declaration
var tokens: [Token] {
switch self {
case let .declaration(_, tokens):
return tokens
case let .type(_, openTokens, bodyDeclarations, closeTokens),
let .conditionalCompilation(openTokens, bodyDeclarations, closeTokens):
return openTokens + bodyDeclarations.flatMap { $0.tokens } + closeTokens
}
}
/// The opening tokens of the declaration (before the body)
var openTokens: [Token] {
switch self {
case .declaration:
return tokens
case let .type(_, open, _, _),
let .conditionalCompilation(open, _, _):
return open
}
}
/// The body of this declaration, if applicable
var body: [Declaration]? {
switch self {
case .declaration:
return nil
case let .type(_, _, body, _),
let .conditionalCompilation(_, body, _):
return body
}
}
/// The closing tokens of the declaration (after the body)
var closeTokens: [Token] {
switch self {
case .declaration:
return []
case let .type(_, _, _, close),
let .conditionalCompilation(_, _, close):
return close
}
}
/// The keyword that determines the specific type of declaration that this is
/// (`class`, `func`, `let`, `var`, etc.)
var keyword: String {
switch self {
case let .declaration(kind, _),
let .type(kind, _, _, _):
return kind
case .conditionalCompilation:
return "#if"
}
}
/// The name of this type or variable
var name: String? {
let parser = Formatter(openTokens)
guard let keywordIndex = openTokens.firstIndex(of: .keyword(keyword)),
let nameIndex = parser.index(of: .identifier, after: keywordIndex)
else {
return nil
}
return parser.fullyQualifiedName(startingAt: nameIndex).name
}
}
/// The fully qualified name starting at the given index
func fullyQualifiedName(startingAt index: Int) -> (name: String, endIndex: Int) {
// If the identifier is followed by a dot, it's actually the first
// part of the fully-qualified name and we should skip through
// to the last component of the name.
var name = tokens[index].string
var index = index
while token(at: index + 1)?.string == ".",
let nextIdentifier = token(at: index + 2),
nextIdentifier.is(.identifier) == true
{
name = "\(name).\(nextIdentifier.string)"
index += 2
}
return (name, index)
}
// get type of declaration starting at index of declaration keyword
func declarationType(at index: Int) -> String? {
guard let token = self.token(at: index), token.isDeclarationTypeKeyword,
case let .keyword(keyword) = token
else {
return nil
}
if keyword == "class" {
var nextIndex = index
while let i = self.index(of: .nonSpaceOrCommentOrLinebreak, after: nextIndex) {
let nextToken = tokens[i]
if nextToken.isDeclarationTypeKeyword {
return nextToken.string
}
guard nextToken.isModifierKeyword else {
break
}
nextIndex = i
}
return keyword
}
return keyword
}
// gather declared name(s), starting at index of declaration keyword
func namesInDeclaration(at index: Int) -> Set<String>? {
guard case let .keyword(keyword)? = token(at: index) else {
return nil
}
switch keyword {
case "let", "var":
var index = index + 1
var names = Set<String>()
processDeclaredVariables(at: &index, names: &names, removeSelf: false)
return names
case "func", "class", "struct", "enum":
guard let name = next(.identifier, after: index) else {
return nil
}
return [name.string]
default:
return nil
}
}
func parseDeclarations() -> [Declaration] {
var declarations = [Declaration]()
var startOfDeclaration = 0
forEachToken(onlyWhereEnabled: false) { i, token in
guard i >= startOfDeclaration,
token.isDeclarationTypeKeyword || token == .startOfScope("#if")
else {
return
}
// Get declaration keyword
var searchIndex = i
let declarationKeyword = declarationType(at: i) ?? "#if"
switch token {
case .startOfScope("#if"):
// For conditional compilation blocks, the `declarationKeyword` _is_ the `startOfScope`
// so we can immediately skip to the corresponding #endif
if let endOfConditionalCompilationScope = endOfScope(at: i) {
searchIndex = endOfConditionalCompilationScope
}
case .keyword("class") where declarationKeyword != "class":
// Most declarations will include exactly one token that `isDeclarationTypeKeyword` in
// - `class func` methods will have two (and the first one will be incorrect!)
searchIndex = index(of: .keyword(declarationKeyword), after: i) ?? searchIndex
case .keyword("import"):
// Symbol imports (like `import class Module.Type`) will have an extra `isDeclarationTypeKeyword`
// immediately following their `declarationKeyword`, so we need to skip them.
if let symbolTypeKeywordIndex = index(of: .nonSpaceOrComment, after: i),
tokens[symbolTypeKeywordIndex].isDeclarationTypeKeyword
{
searchIndex = symbolTypeKeywordIndex
}
case .keyword("protocol"), .keyword("struct"), .keyword("enum"), .keyword("extension"):
if let scopeStart = index(of: .startOfScope("{"), after: i) {
searchIndex = endOfScope(at: scopeStart) ?? searchIndex
}
default:
break
}
// Search for the next declaration so we know where this declaration ends.
let nextDeclarationKeywordIndex = index(after: searchIndex, where: {
$0.isDeclarationTypeKeyword || $0 == .startOfScope("#if")
})
// Search backward from the next declaration keyword to find where declaration begins.
var endOfDeclaration = nextDeclarationKeywordIndex.flatMap {
index(before: startOfModifiers(at: $0, includingAttributes: true), where: {
!$0.isSpaceOrCommentOrLinebreak
}).map { endOfLine(at: $0) }
}
// Prefer keeping linebreaks at the end of a declaration's tokens,
// instead of the start of the next delaration's tokens
while let linebreakSearchIndex = endOfDeclaration,
self.token(at: linebreakSearchIndex + 1)?.isLinebreak == true
{
endOfDeclaration = linebreakSearchIndex + 1
}
let declarationRange = startOfDeclaration ... min(endOfDeclaration ?? .max, tokens.count - 1)
startOfDeclaration = declarationRange.upperBound + 1
let declaration = Array(tokens[declarationRange])
declarations.append(.declaration(kind: isEnabled ? declarationKeyword : "", tokens: declaration))
}
if startOfDeclaration < tokens.count {
let declaration = Array(tokens[startOfDeclaration...])
declarations.append(.declaration(kind: "", tokens: declaration))
}
return declarations.map { declaration in
let declarationParser = Formatter(declaration.tokens)
/// Parses this declaration into a body of declarations separate from the start and end tokens
func parseBody(in bodyRange: ClosedRange<Int>) -> (start: [Token], body: [Declaration], end: [Token]) {
var startTokens = declarationParser.tokens[...bodyRange.lowerBound]
var bodyTokens = declarationParser.tokens[bodyRange.lowerBound + 1 ..< bodyRange.upperBound]
var endTokens = declarationParser.tokens[bodyRange.upperBound...]
// Move the leading newlines from the `body` into the `start` tokens
// so the first body token is the start of the first declaration
while bodyTokens.first?.isLinebreak == true {
startTokens.append(bodyTokens.removeFirst())
}
// Move the closing brace's indentation token from the `body` into the `end` tokens
if bodyTokens.last?.isSpace == true {
endTokens.insert(bodyTokens.removeLast(), at: endTokens.startIndex)
}
// Parse the inner body declarations of the type
let bodyDeclarations = Formatter(Array(bodyTokens)).parseDeclarations()
return (Array(startTokens), bodyDeclarations, Array(endTokens))
}
// If this declaration represents a type, we need to parse its inner declarations as well.
let typelikeKeywords = ["class", "struct", "enum", "protocol", "extension"]
if typelikeKeywords.contains(declaration.keyword),
let declarationTypeKeywordIndex = declarationParser
.index(after: -1, where: { $0.string == declaration.keyword }),
let startOfBody = declarationParser
.index(of: .startOfScope("{"), after: declarationTypeKeywordIndex),
let endOfBody = declarationParser.endOfScope(at: startOfBody)
{
let (startTokens, bodyDeclarations, endTokens) = parseBody(in: startOfBody ... endOfBody)
return .type(
kind: declaration.keyword,
open: startTokens,
body: bodyDeclarations,
close: endTokens
)
}
// If this declaration represents a conditional compilation block,
// we also have to parse its inner declarations.
else if declaration.keyword == "#if",
let declarationTypeKeywordIndex = declarationParser
.index(after: -1, where: { $0.string == declaration.keyword }),
let endOfBody = declarationParser.endOfScope(at: declarationTypeKeywordIndex)
{
let startOfBody = declarationParser.endOfLine(at: declarationTypeKeywordIndex)
let (startTokens, bodyDeclarations, endTokens) = parseBody(in: startOfBody ... endOfBody)
return .conditionalCompilation(
open: startTokens,
body: bodyDeclarations,
close: endTokens
)
} else {
return declaration
}
}
}
// Swift modifier keywords, in preferred order
var modifierOrder: [String] {
var priorities = [String: Int]()
for (i, modifiers) in _FormatRules.defaultModifierOrder.enumerated() {
for modifier in modifiers {
priorities[modifier] = i
}
}
var order = options.modifierOrder.flatMap { _FormatRules.mapModifiers($0) ?? [] }
for (i, modifiers) in _FormatRules.defaultModifierOrder.enumerated() {
let insertionPoint = order.firstIndex(where: { modifiers.contains($0) }) ??
order.firstIndex(where: { (priorities[$0] ?? 0) > i }) ?? order.count
order.insert(contentsOf: modifiers.filter { !order.contains($0) }, at: insertionPoint)
}
return order
}
/// Returns the index where the `wrap` rule should add the next linebreak in the line at the selected index.
///
/// If the line does not need to be wrapped, this will return `nil`.
///
/// - Note: This checks the entire line from the start of the line, the linebreak may be an index preceding the
/// `index` passed to the function.
func indexWhereLineShouldWrapInLine(at index: Int) -> Int? {
return indexWhereLineShouldWrap(from: startOfLine(at: index))
}
func indexWhereLineShouldWrap(from index: Int) -> Int? {
var lineLength = self.lineLength(upTo: index)
var stringLiteralDepth = 0
var currentPriority = 0
var lastBreakPoint: Int?
var lastBreakPointPriority = Int.min
let maxWidth = options.maxWidth
guard maxWidth > 0 else { return nil }
func addBreakPoint(at i: Int, relativePriority: Int) {
guard stringLiteralDepth == 0, currentPriority + relativePriority >= lastBreakPointPriority,
!isInClosureArguments(at: i + 1)
else {
return
}
let i = self.index(of: .nonSpace, before: i + 1) ?? i
if token(at: i + 1)?.isLinebreak == true || token(at: i)?.isLinebreak == true {
return
}
lastBreakPoint = i
lastBreakPointPriority = currentPriority + relativePriority
}
var i = index
let endIndex = endOfLine(at: index)
while i < endIndex {
var token = tokens[i]
switch token {
case .linebreak:
return nil
case .keyword("#colorLiteral"), .keyword("#imageLiteral"):
guard let startIndex = self.index(of: .startOfScope("("), after: i),
let endIndex = endOfScope(at: startIndex)
else {
return nil // error
}
token = .space(spaceEquivalentToTokens(from: i, upTo: endIndex + 1)) // hack to get correct length
i = endIndex
case let .delimiter(string) where options.noWrapOperators.contains(string),
let .operator(string, .infix) where options.noWrapOperators.contains(string):
// TODO: handle as/is
break
case .delimiter(","):
addBreakPoint(at: i, relativePriority: 0)
case .operator("=", .infix) where self.token(at: i + 1)?.isSpace == true:
addBreakPoint(at: i, relativePriority: -9)
case .operator(".", .infix):
addBreakPoint(at: i - 1, relativePriority: -2)
case .operator("->", .infix):
if isInReturnType(at: i) {
currentPriority -= 5
}
addBreakPoint(at: i - 1, relativePriority: -5)
case .operator(_, .infix) where self.token(at: i + 1)?.isSpace == true:
addBreakPoint(at: i, relativePriority: -3)
case .startOfScope("{"):
if !isStartOfClosure(at: i) ||
next(.keyword, after: i) != .keyword("in"),
next(.nonSpace, after: i) != .endOfScope("}")
{
addBreakPoint(at: i, relativePriority: -6)
}
if isInReturnType(at: i) {
currentPriority += 5
}
currentPriority -= 6
case .endOfScope("}"):
currentPriority += 6
if last(.nonSpace, before: i) != .startOfScope("{") {
addBreakPoint(at: i - 1, relativePriority: -6)
}
case .startOfScope("("):
currentPriority -= 7
case .endOfScope(")"):
currentPriority += 7
case .startOfScope("["):
currentPriority -= 8
case .endOfScope("]"):
currentPriority += 8
case .startOfScope("<"):
currentPriority -= 9
case .endOfScope(">"):
currentPriority += 9
case .startOfScope where token.isStringDelimiter:
stringLiteralDepth += 1
case .endOfScope where token.isStringDelimiter:
stringLiteralDepth -= 1
case .keyword("else"), .keyword("where"):
addBreakPoint(at: i - 1, relativePriority: -1)
case .keyword("in"):
if last(.keyword, before: i) == .keyword("for") {
addBreakPoint(at: i, relativePriority: -11)
break
}
addBreakPoint(at: i, relativePriority: -5 - currentPriority)
default:
break
}
lineLength += tokenLength(token)
if lineLength > maxWidth, let breakPoint = lastBreakPoint, breakPoint < i {
return breakPoint
}
i += 1
}
return nil
}
/// Indent level to use for wrapped lines at the specified position (based on statement type)
func linewrapIndent(at index: Int) -> String {
guard let commaIndex = self.index(of: .nonSpaceOrCommentOrLinebreak, before: index + 1, if: {
$0 == .delimiter(",")
}), case let lineStart = startOfLine(at: commaIndex),
let firstToken = self.index(of: .nonSpace, after: lineStart - 1),
let firstNonBrace = (firstToken ..< commaIndex).first(where: {
let token = self.tokens[$0]
return !token.isEndOfScope && !token.isSpaceOrComment
}) else {
return options.indent
}
if case .endOfScope = tokens[firstToken],
next(.nonSpaceOrCommentOrLinebreak, after: firstNonBrace - 1) == .delimiter(",")
{
return ""
}
guard let keywordIndex = lastIndex(in: firstNonBrace ..< commaIndex, where: {
[.keyword("if"), .keyword("guard"), .keyword("while")].contains($0)
}) ?? lastIndex(in: firstNonBrace ..< commaIndex, where: {
[.keyword("let"), .keyword("var"), .keyword("case")].contains($0)
}), let nextTokenIndex = self.index(of: .nonSpace, after: keywordIndex) else {
return options.indent
}
return spaceEquivalentToTokens(from: firstToken, upTo: nextTokenIndex)
}
}
extension _FormatRules {
// Short date formater. Used by fileHeader rule
static var shortDateFormatter: (Date) -> String = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
return { formatter.string(from: $0) }
}()
// Year formater. Used by fileHeader rule
static var yearFormatter: (Date) -> String = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
return { formatter.string(from: $0) }
}()
// Current year. Used by fileHeader rule
static var currentYear: String = {
yearFormatter(Date())
}()
// All modifiers
static let allModifiers = Set(defaultModifierOrder.flatMap { $0 })
// ACL modifiers
static let aclModifiers = ["private", "fileprivate", "internal", "public", "open"]
// ACL setter modifiers
static let aclSetterModifiers = aclModifiers.map { "\($0)(set)" }
// Modifier mapping (designed to match SwiftLint)
static func mapModifiers(_ input: String) -> [String]? {
switch input.lowercased() {
case "acl":
return aclModifiers
case "setteracl":
return aclSetterModifiers
case "mutators":
return ["mutating", "nonmutating"]
case "typemethods":
return [] // Not clear what this is for - legacy?
case "owned":
return ["weak", "unowned"]
default:
return allModifiers.contains(input) ? [input] : nil
}
}
// Swift modifier keywords, in default order
static let defaultModifierOrder = [
["override"],
aclModifiers,
aclSetterModifiers,
["final", "dynamic"],
["optional", "required"],
["convenience"],
["indirect"],
["lazy"],
["weak", "unowned"],
["static", "class"],
["mutating", "nonmutating"],
["prefix", "infix", "postfix"],
]
}
extension Token {
/// Whether or not this token "defines" the specific type of declaration
/// - A valid declaration will usually include exactly one of these keywords in its outermost scope.
/// - Notable exceptions are `class func` and symbol imports (like `import class Module.Type`)
/// which will include two of these keywords.
var isDeclarationTypeKeyword: Bool {
guard case let .keyword(keyword) = self else {
return false
}
// All of the keywords that map to individual Declaration grammars
// https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#grammar_declaration
return ["import", "let", "var", "typealias", "func", "enum", "case",
"struct", "class", "protocol", "init", "deinit",
"extension", "subscript", "operator", "precedencegroup"].contains(keyword)
}
var isModifierKeyword: Bool {
switch self {
case let .keyword(keyword), let .identifier(keyword):
return _FormatRules.allModifiers.contains(keyword)
default:
return false
}
}
}
| 40.234108 | 116 | 0.523996 |
e2d57c3106593dd67726d81762f6a210e8a1a83f | 6,081 | @_exported import Foundation
@available(swift, obsoleted: 4.2, renamed: "UITouch.Phase")
typealias UITouchPhase = UITouch.Phase
extension UITouch {
enum Phase : Int {
init?(rawValue: Int)
var rawValue: Int { get }
typealias RawValue = Int
case began
@available(swift, obsoleted: 3, renamed: "began")
static var Began: UITouch.Phase { get }
case moved
@available(swift, obsoleted: 3, renamed: "moved")
static var Moved: UITouch.Phase { get }
case stationary
@available(swift, obsoleted: 3, renamed: "stationary")
static var Stationary: UITouch.Phase { get }
case ended
@available(swift, obsoleted: 3, renamed: "ended")
static var Ended: UITouch.Phase { get }
case cancelled
@available(swift, obsoleted: 3, renamed: "cancelled")
static var Cancelled: UITouch.Phase { get }
@available(iOS 13.4, *)
case regionEntered
@available(iOS 13.4, *)
@available(swift, obsoleted: 3, renamed: "regionEntered")
static var RegionEntered: UITouch.Phase { get }
@available(iOS 13.4, *)
case regionMoved
@available(iOS 13.4, *)
@available(swift, obsoleted: 3, renamed: "regionMoved")
static var RegionMoved: UITouch.Phase { get }
@available(iOS 13.4, *)
case regionExited
@available(iOS 13.4, *)
@available(swift, obsoleted: 3, renamed: "regionExited")
static var RegionExited: UITouch.Phase { get }
}
@available(iOS 9.0, *)
enum TouchType : Int {
init?(rawValue: Int)
var rawValue: Int { get }
typealias RawValue = Int
case direct
@available(swift, obsoleted: 3, renamed: "direct")
static var Direct: UITouch.TouchType { get }
case indirect
@available(swift, obsoleted: 3, renamed: "indirect")
static var Indirect: UITouch.TouchType { get }
@available(iOS 9.1, *)
case pencil
@available(iOS 9.1, *)
@available(swift, obsoleted: 3, renamed: "pencil")
static var Pencil: UITouch.TouchType { get }
@available(iOS 9.1, *)
static var stylus: UITouch.TouchType { get }
@available(iOS 13.4, *)
case indirectPointer
@available(iOS 13.4, *)
@available(swift, obsoleted: 3, renamed: "indirectPointer")
static var IndirectPointer: UITouch.TouchType { get }
}
@available(iOS 9.1, *)
struct Properties : OptionSet {
init(rawValue: Int)
let rawValue: Int
typealias RawValue = Int
typealias Element = UITouch.Properties
typealias ArrayLiteralElement = UITouch.Properties
static var force: UITouch.Properties { get }
@available(swift, obsoleted: 3, renamed: "force")
static var Force: UITouch.Properties { get }
static var azimuth: UITouch.Properties { get }
@available(swift, obsoleted: 3, renamed: "azimuth")
static var Azimuth: UITouch.Properties { get }
static var altitude: UITouch.Properties { get }
@available(swift, obsoleted: 3, renamed: "altitude")
static var Altitude: UITouch.Properties { get }
static var location: UITouch.Properties { get }
@available(swift, obsoleted: 3, renamed: "location")
static var Location: UITouch.Properties { get }
}
}
enum UIForceTouchCapability : Int {
init?(rawValue: Int)
var rawValue: Int { get }
typealias RawValue = Int
case unknown
@available(swift, obsoleted: 3, renamed: "unknown")
static var Unknown: UIForceTouchCapability { get }
case unavailable
@available(swift, obsoleted: 3, renamed: "unavailable")
static var Unavailable: UIForceTouchCapability { get }
case available
@available(swift, obsoleted: 3, renamed: "available")
static var Available: UIForceTouchCapability { get }
}
@available(iOS 9.0, *)
@available(swift, obsoleted: 4.2, renamed: "UITouch.TouchType")
typealias UITouchType = UITouch.TouchType
@available(iOS 9.1, *)
@available(swift, obsoleted: 4.2, renamed: "UITouch.Properties")
typealias UITouchProperties = UITouch.Properties
@available(iOS 2.0, *)
class UITouch : NSObject {
var timestamp: TimeInterval { get }
var phase: UITouch.Phase { get }
var tapCount: Int { get }
@available(iOS 9.0, *)
var type: UITouch.TouchType { get }
@available(iOS 8.0, *)
var majorRadius: CGFloat { get }
@available(iOS 8.0, *)
var majorRadiusTolerance: CGFloat { get }
var window: UIWindow? { get }
var view: UIView? { get }
@available(iOS 3.2, *)
var gestureRecognizers: [UIGestureRecognizer]? { get }
func location(in view: UIView?) -> CGPoint
@available(swift, obsoleted: 3, renamed: "location(in:)")
func locationInView(_ view: UIView?) -> CGPoint
func previousLocation(in view: UIView?) -> CGPoint
@available(swift, obsoleted: 3, renamed: "previousLocation(in:)")
func previousLocationInView(_ view: UIView?) -> CGPoint
@available(iOS 9.1, *)
func preciseLocation(in view: UIView?) -> CGPoint
@available(iOS 9.1, *)
@available(swift, obsoleted: 3, renamed: "preciseLocation(in:)")
func preciseLocationInView(_ view: UIView?) -> CGPoint
@available(iOS 9.1, *)
func precisePreviousLocation(in view: UIView?) -> CGPoint
@available(iOS 9.1, *)
@available(swift, obsoleted: 3, renamed: "precisePreviousLocation(in:)")
func precisePreviousLocationInView(_ view: UIView?) -> CGPoint
@available(iOS 9.0, *)
var force: CGFloat { get }
@available(iOS 9.0, *)
var maximumPossibleForce: CGFloat { get }
@available(iOS 9.1, *)
func azimuthAngle(in view: UIView?) -> CGFloat
@available(iOS 9.1, *)
@available(swift, obsoleted: 3, renamed: "azimuthAngle(in:)")
func azimuthAngleInView(_ view: UIView?) -> CGFloat
@available(iOS 9.1, *)
func azimuthUnitVector(in view: UIView?) -> CGVector
@available(iOS 9.1, *)
@available(swift, obsoleted: 3, renamed: "azimuthUnitVector(in:)")
func azimuthUnitVectorInView(_ view: UIView?) -> CGVector
@available(iOS 9.1, *)
var altitudeAngle: CGFloat { get }
@available(iOS 9.1, *)
var estimationUpdateIndex: NSNumber? { get }
@available(iOS 9.1, *)
var estimatedProperties: UITouch.Properties { get }
@available(iOS 9.1, *)
var estimatedPropertiesExpectingUpdates: UITouch.Properties { get }
init()
}
| 37.770186 | 74 | 0.688703 |
28943cd595089aa89416a1ebcb6760cf6157e1dc | 810 | //
// UIColorExtension.swift
// ColorPicker
//
// Created by Matsuoka Yoshiteru on 2018/10/20.
// Copyright © 2018年 culumn. All rights reserved.
//
import Foundation
public extension UIColor {
var hsb: HSB {
var hue = CGFloat()
var saturation = CGFloat()
var brightness = CGFloat()
var alpha = CGFloat()
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return HSB(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
var rgb: RGB {
var red = CGFloat()
var green = CGFloat()
var blue = CGFloat()
var alpha = CGFloat()
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return RGB(red: red, green: green, blue: blue, alpha: alpha)
}
}
| 24.545455 | 90 | 0.604938 |
69d55e43f608411e62124e9570c37ff9c73471c7 | 945 | //
// DouYuTests.swift
// DouYuTests
//
// Created by 曹林 on 2018/6/30.
// Copyright © 2018年 曹林. All rights reserved.
//
import XCTest
@testable import DouYu
class DouYuTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.540541 | 111 | 0.624339 |
e6d711c07afc0711fb9c77b2e6881f28fdf37ffe | 2,855 | //
// Format.swift
// ObjSer
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Greg Omelaenko
//
// 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.
//
/// Defines the ObjSer formats.
enum Format: Byte {
/// 0x00 – 0x3f
case Ref6 = 0x00
case Ref8 = 0x40
case Ref16 = 0x60
case Ref32 = 0x70
/// 0x80 – 0xbf
case PosInt6 = 0x80
/// 0xe0 – 0xff
case NegInt5 = 0xe0
case False = 0xc0
case True = 0xc1
case Nil = 0xc2
case Int8 = 0xc3
case Int16 = 0xc4
case Int32 = 0xc5
case Int64 = 0xc6
case UInt8 = 0xc7
case UInt16 = 0xc8
case UInt32 = 0xc9
case UInt64 = 0xca
case Float32 = 0xcb
case Float64 = 0xcc
/// 0x71 – 0x7f
case FString = 0x71
case VString = 0xcd
case EString = 0xce
/// 0x61 – 0x6f
case FData = 0x61
case VData8 = 0xd0
case VData16 = 0xd1
case VData32 = 0xd2
case EData = 0xd3
/// 0x41 – 0x5f
case FArray = 0x41
case VArray = 0xd4
case EArray = 0xd5
case Map = 0xd6
case EMap = 0xd7
case TypeID = 0xd8
case Sentinel = 0xcf
/// 0xd9 – 0xdf
case Reserved = 0xd9
var byte: Byte {
switch self {
case .FString: return 0x70
case .FData: return 0x60
case .FArray: return 0x40
default: return rawValue
}
}
var range: ClosedInterval<Byte> {
switch self {
case .Ref6: return 0x00...0x3f
case .PosInt6: return 0x80...0xbf
case .NegInt5: return 0xe0...0xff
case .FString: return 0x71...0x7f
case .FData: return 0x61...0x6f
case .FArray: return 0x41...0x5f
case .Reserved: return 0xd9...0xdf
default: return rawValue...rawValue
}
}
}
| 26.682243 | 82 | 0.628371 |
bf70e7ee900049574cfe133ce15d89cafa87bdb2 | 46,607 | //
// ModalPresenter.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-25.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
import LocalAuthentication
import BRCore
class ModalPresenter : Subscriber, Trackable {
//MARK: - Public
let primaryWalletManager: BTCWalletManager
var walletManagers: [String: WalletManager]
lazy var supportCenter: SupportCenterContainer = {
return SupportCenterContainer(walletManagers: self.walletManagers, noAuthApiClient: Store.state.isLoginRequired ? self.noAuthApiClient : nil)
}()
init(walletManagers: [String: WalletManager], window: UIWindow, apiClient: BRAPIClient) {
self.window = window
self.walletManagers = walletManagers
self.primaryWalletManager = walletManagers[Currencies.btc.code]! as! BTCWalletManager
self.modalTransitionDelegate = ModalTransitionDelegate(type: .regular)
self.wipeNavigationDelegate = StartNavigationDelegate()
self.noAuthApiClient = apiClient
addSubscriptions()
}
deinit {
Store.unsubscribe(self)
}
//MARK: - Private
private let window: UIWindow
private let alertHeight: CGFloat = 260.0
private let modalTransitionDelegate: ModalTransitionDelegate
private let messagePresenter = MessageUIPresenter()
private let securityCenterNavigationDelegate = SecurityCenterNavigationDelegate()
private let verifyPinTransitionDelegate = PinTransitioningDelegate()
private let noAuthApiClient: BRAPIClient
private var currentRequest: PaymentRequest?
private var reachability = ReachabilityMonitor()
private var notReachableAlert: InAppAlert?
private let wipeNavigationDelegate: StartNavigationDelegate
private func addSubscriptions() {
Store.lazySubscribe(self,
selector: { $0.rootModal != $1.rootModal},
callback: { [weak self] in self?.presentModal($0.rootModal) })
Store.lazySubscribe(self,
selector: { $0.alert != $1.alert && $1.alert != .none },
callback: { [weak self] in self?.handleAlertChange($0.alert) })
Store.subscribe(self, name: .presentFaq("", nil), callback: { [weak self] in
guard let trigger = $0 else { return }
if case .presentFaq(let articleId, let currency) = trigger {
self?.presentFaq(articleId: articleId, currency: currency)
}
})
//Subscribe to prompt actions
Store.subscribe(self, name: .promptUpgradePin, callback: { [weak self] _ in
self?.presentUpgradePin()
})
Store.subscribe(self, name: .promptPaperKey, callback: { [weak self] _ in
self?.presentWritePaperKey()
})
Store.subscribe(self, name: .promptBiometrics, callback: { [weak self] _ in
self?.presentBiometricsMenuItem()
})
Store.subscribe(self, name: .promptShareData, callback: { [weak self] _ in
self?.promptShareData()
})
Store.subscribe(self, name: .openFile(Data()), callback: { [weak self] in
guard let trigger = $0 else { return }
if case .openFile(let file) = trigger {
self?.handleFile(file)
}
})
for walletManager in walletManagers.values {
// TODO: show alert and automatic rescan instead of showing the rescan screen
Store.subscribe(self, name: .recommendRescan(walletManager.currency), callback: { [weak self] _ in
self?.presentRescan(currency: walletManager.currency)
})
}
//URLs
Store.subscribe(self, name: .receivedPaymentRequest(nil), callback: { [weak self] in
guard let trigger = $0 else { return }
if case let .receivedPaymentRequest(request) = trigger {
if let request = request {
self?.handlePaymentRequest(request: request)
}
}
})
Store.subscribe(self, name: .scanQr, callback: { [weak self] _ in
self?.handleScanQrURL()
})
Store.subscribe(self, name: .copyWalletAddresses(nil, nil), callback: { [weak self] in
guard let trigger = $0 else { return }
if case .copyWalletAddresses(let success, let error) = trigger {
self?.handleCopyAddresses(success: success, error: error)
}
})
Store.subscribe(self, name: .authenticateForPlatform("", true, {_ in}), callback: { [unowned self] in
guard let trigger = $0 else { return }
if case .authenticateForPlatform(let prompt, let allowBiometricAuth, let callback) = trigger {
self.authenticateForPlatform(prompt: prompt, allowBiometricAuth: allowBiometricAuth, callback: callback)
}
})
Store.subscribe(self, name: .confirmTransaction(Currencies.btc, Amount.empty, Amount.empty, "", {_ in}), callback: { [unowned self] in
guard let trigger = $0 else { return }
if case .confirmTransaction(let currency, let amount, let fee, let address, let callback) = trigger {
self.confirmTransaction(currency: currency, amount: amount, fee: fee, address: address, callback: callback)
}
})
reachability.didChange = { [weak self] isReachable in
if isReachable {
self?.hideNotReachable()
} else {
self?.showNotReachable()
}
}
Store.subscribe(self, name: .lightWeightAlert(""), callback: { [weak self] in
guard let trigger = $0 else { return }
if case let .lightWeightAlert(message) = trigger {
self?.showLightWeightAlert(message: message)
}
})
Store.subscribe(self, name: .showAlert(nil), callback: { [weak self] in
guard let trigger = $0 else { return }
if case let .showAlert(alert) = trigger {
if let alert = alert {
self?.topViewController?.present(alert, animated: true, completion: nil)
}
}
})
Store.subscribe(self, name: .wipeWalletNoPrompt, callback: { [weak self] _ in
self?.wipeWalletNoPrompt()
})
Store.subscribe(self, name: .showCurrency(Currencies.btc), callback: { [unowned self] in
guard let trigger = $0 else { return }
if case .showCurrency(let currency) = trigger {
self.showAccountView(currency: currency, animated: true, completion: nil)
}
})
}
private func presentModal(_ type: RootModal, configuration: ((UIViewController) -> Void)? = nil) {
guard type != .loginScan else { return presentLoginScan() }
guard let vc = rootModalViewController(type) else {
Store.perform(action: RootModalActions.Present(modal: .none))
return
}
vc.transitioningDelegate = modalTransitionDelegate
vc.modalPresentationStyle = .overFullScreen
vc.modalPresentationCapturesStatusBarAppearance = true
configuration?(vc)
topViewController?.present(vc, animated: true) {
Store.perform(action: RootModalActions.Present(modal: .none))
Store.trigger(name: .hideStatusBar)
}
}
private func handleAlertChange(_ type: AlertType) {
guard type != .none else { return }
presentAlert(type, completion: {
Store.perform(action: Alert.Hide())
})
}
private func presentAlert(_ type: AlertType, completion: @escaping ()->Void) {
let alertView = AlertView(type: type)
let window = UIApplication.shared.keyWindow!
let size = window.bounds.size
window.addSubview(alertView)
let topConstraint = alertView.constraint(.top, toView: window, constant: size.height)
alertView.constrain([
alertView.constraint(.width, constant: size.width),
alertView.constraint(.height, constant: alertHeight + 25.0),
alertView.constraint(.leading, toView: window, constant: nil),
topConstraint ])
window.layoutIfNeeded()
UIView.spring(0.6, animations: {
topConstraint?.constant = size.height - self.alertHeight
window.layoutIfNeeded()
}, completion: { _ in
alertView.animate()
UIView.spring(0.6, delay: 2.0, animations: {
topConstraint?.constant = size.height
window.layoutIfNeeded()
}, completion: { _ in
//TODO - Make these callbacks generic
if case .paperKeySet(let callback) = type {
callback()
}
if case .pinSet(let callback) = type {
callback()
}
if case .sweepSuccess(let callback) = type {
callback()
}
completion()
alertView.removeFromSuperview()
})
})
}
func presentFaq(articleId: String? = nil, currency: CurrencyDef? = nil) {
supportCenter.modalPresentationStyle = .overFullScreen
supportCenter.modalPresentationCapturesStatusBarAppearance = true
supportCenter.transitioningDelegate = supportCenter
var url: String
if let articleId = articleId {
url = "/support/article?slug=\(articleId)"
if let currency = currency {
url += "¤cy=\(currency.code.lowercased())"
}
} else {
url = "/support?"
}
supportCenter.navigate(to: url)
topViewController?.present(supportCenter, animated: true, completion: {})
}
private func rootModalViewController(_ type: RootModal) -> UIViewController? {
switch type {
case .none:
return nil
case .send(let currency):
return makeSendView(currency: currency)
case .receive(let currency):
return receiveView(currency: currency, isRequestAmountVisible: (currency.urlSchemes != nil))
case .loginScan:
return nil //The scan view needs a custom presentation
case .loginAddress:
return receiveView(currency: Currencies.btc, isRequestAmountVisible: false)
case .requestAmount(let currency):
guard let walletManager = walletManagers[currency.code] else { return nil }
var address: String?
switch currency.code {
case Currencies.btc.code:
address = walletManager.wallet?.receiveAddress
case Currencies.bch.code:
address = walletManager.wallet?.receiveAddress.bCashAddr
case Currencies.eth.code:
address = (walletManager as? EthWalletManager)?.address
default:
if currency is ERC20Token {
address = (walletManager as? EthWalletManager)?.address
}
}
guard let receiveAddress = address else { return nil }
let requestVc = RequestAmountViewController(currency: currency, receiveAddress: receiveAddress)
requestVc.presentEmail = { [weak self] bitcoinURL, image in
self?.messagePresenter.presenter = self?.topViewController
self?.messagePresenter.presentMailCompose(bitcoinURL: bitcoinURL, image: image)
}
requestVc.presentText = { [weak self] bitcoinURL, image in
self?.messagePresenter.presenter = self?.topViewController
self?.messagePresenter.presentMessageCompose(bitcoinURL: bitcoinURL, image: image)
}
return ModalViewController(childViewController: requestVc)
case .buy(let currency):
var url = "/buy"
if let currency = currency {
url += "?currency=\(currency.code)"
}
presentPlatformWebViewController(url)
return nil
case .sell(let currency):
var url = "/sell"
if let currency = currency {
url += "?currency=\(currency.code)"
}
presentPlatformWebViewController(url)
return nil
case .trade:
presentPlatformWebViewController("/trade")
return nil
}
}
private func makeSendView(currency: CurrencyDef) -> UIViewController? {
guard !(currency.state?.isRescanning ?? false) else {
let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil))
topViewController?.present(alert, animated: true, completion: nil)
return nil
}
guard let walletManager = walletManagers[currency.code] else { return nil }
guard let kvStore = walletManager.apiClient?.kv else { return nil }
guard let sender = currency.createSender(walletManager: walletManager, kvStore: kvStore) else { return nil }
let sendVC = SendViewController(sender: sender,
initialRequest: currentRequest,
currency: currency)
currentRequest = nil
if Store.state.isLoginRequired {
sendVC.isPresentedFromLock = true
}
let root = ModalViewController(childViewController: sendVC)
sendVC.presentScan = presentScan(parent: root, currency: currency)
sendVC.presentVerifyPin = { [weak self, weak root] bodyText, success in
guard let myself = self else { return }
let walletManager = myself.primaryWalletManager
let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: walletManager, success: success)
vc.transitioningDelegate = self?.verifyPinTransitionDelegate
vc.modalPresentationStyle = .overFullScreen
vc.modalPresentationCapturesStatusBarAppearance = true
root?.view.isFrameChangeBlocked = true
root?.present(vc, animated: true, completion: nil)
}
sendVC.onPublishSuccess = { [weak self] in
self?.presentAlert(.sendSuccess, completion: {})
}
return root
}
private func receiveView(currency: CurrencyDef, isRequestAmountVisible: Bool) -> UIViewController? {
let receiveVC = ReceiveViewController(currency: currency, isRequestAmountVisible: isRequestAmountVisible)
let root = ModalViewController(childViewController: receiveVC)
receiveVC.presentEmail = { [weak self, weak root] address, image in
guard let root = root, let uri = currency.addressURI(address) else { return }
self?.messagePresenter.presenter = root
self?.messagePresenter.presentMailCompose(uri: uri, image: image)
}
receiveVC.presentText = { [weak self, weak root] address, image in
guard let root = root, let uri = currency.addressURI(address) else { return }
self?.messagePresenter.presenter = root
self?.messagePresenter.presentMessageCompose(uri: uri, image: image)
}
return root
}
private func presentLoginScan() {
//TODO:BCH URL support
guard let top = topViewController else { return }
let present = presentScan(parent: top, currency: Currencies.btc)
Store.perform(action: RootModalActions.Present(modal: .none))
present({ paymentRequest in
guard let request = paymentRequest else { return }
self.currentRequest = request
self.presentModal(.send(currency: Currencies.btc))
})
}
// MARK: Settings
func presentMenu() {
guard let top = topViewController else { return }
let btcWalletManager = primaryWalletManager
let menuNav = UINavigationController()
menuNav.setDarkStyle()
var btcItems: [MenuItem] = [
// Touch ID Spending Limit // TODO: verify if this applies to BCH or not
// Rescan
MenuItem(title: S.Settings.sync, callback: {
menuNav.pushViewController(ReScanViewController(currency: Currencies.btc), animated: true)
}),
// Nodes
MenuItem(title: S.NodeSelector.title, callback: {
let nodeSelector = NodeSelectorViewController(walletManager: btcWalletManager)
menuNav.pushViewController(nodeSelector, animated: true)
}),
//TODO: universal scan -- remove
MenuItem(title: S.Settings.importTile, callback: {
menuNav.dismiss(animated: true, completion: { [unowned self] in
if let walletManager = self.walletManagers[Currencies.btc.code] as? BTCWalletManager {
self.presentKeyImport(walletManager: walletManager)
}
})
})
]
if UserDefaults.isBiometricsEnabled {
let biometricSpendingLimitItem = MenuItem(title: LAContext.biometricType() == .face ? S.Settings.faceIdLimit : S.Settings.touchIdLimit, accessoryText: {
guard let rate = Currencies.btc.state?.currentRate else { return "" }
let amount = Amount(amount: UInt256(btcWalletManager.spendingLimit), currency: Currencies.btc, rate: rate)
return amount.fiatDescription
}, callback: { [weak self] in
self?.pushBiometricsSpendingLimit(onNc: menuNav)
})
btcItems.insert(biometricSpendingLimitItem, at: 0)
}
let bchItems: [MenuItem] = [
// Rescan
MenuItem(title: S.Settings.sync, callback: {
menuNav.pushViewController(ReScanViewController(currency: Currencies.bch), animated: true)
}),
//TODO: universal scan -- remove
MenuItem(title: S.Settings.importTile, callback: {
menuNav.dismiss(animated: true, completion: { [unowned self] in
if let walletManager = self.walletManagers[Currencies.bch.code] as? BTCWalletManager {
self.presentKeyImport(walletManager: walletManager)
}
})
})
]
let preferencesItems: [MenuItem] = [
// Display Currency
MenuItem(title: S.Settings.currency, accessoryText: {
let code = Store.state.defaultCurrencyCode
let components: [String : String] = [NSLocale.Key.currencyCode.rawValue : code]
let identifier = Locale.identifier(fromComponents: components)
return Locale(identifier: identifier).currencyCode ?? ""
}, callback: {
menuNav.pushViewController(DefaultCurrencyViewController(walletManager: btcWalletManager), animated: true)
}),
// Bitcoin Settings
MenuItem(title: String(format: S.Settings.currencyPageTitle, Currencies.btc.name), subMenu: btcItems, rootNav: menuNav),
// Bitcoin Cash Settings
MenuItem(title: String(format: S.Settings.currencyPageTitle, Currencies.bch.name), subMenu: bchItems, rootNav: menuNav),
// Share Anonymous Data
MenuItem(title: S.Settings.shareData, callback: {
menuNav.pushViewController(ShareDataViewController(), animated: true)
}),
// Reset Wallets
MenuItem(title: S.Settings.resetCurrencies, callback: {
menuNav.dismiss(animated: true, completion: {
Store.trigger(name: .resetDisplayCurrencies)
})
})
]
let securityItems: [MenuItem] = [
// Unlink
MenuItem(title: S.Settings.wipe) { [unowned self] in
let nc = ModalNavigationController()
nc.setClearNavbar()
nc.setWhiteStyle()
nc.delegate = self.wipeNavigationDelegate
let start = StartWipeWalletViewController { [unowned self] in
let recover = EnterPhraseViewController(walletManager: btcWalletManager, reason: .validateForWipingWallet({
self.wipeWallet()
}))
nc.pushViewController(recover, animated: true)
}
start.addCloseNavigationItem(tintColor: .white)
start.navigationItem.title = S.WipeWallet.title
let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.wipeWallet)
faqButton.tintColor = .white
start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)]
nc.viewControllers = [start]
menuNav.dismiss(animated: true) {
self.topViewController?.present(nc, animated: true, completion: nil)
}
},
// Update PIN
MenuItem(title: S.UpdatePin.updateTitle) {
let updatePin = UpdatePinViewController(walletManager: btcWalletManager, type: .update)
menuNav.pushViewController(updatePin, animated: true)
},
// Biometrics
MenuItem(title: LAContext.biometricType() == .face ? S.SecurityCenter.Cells.faceIdTitle : S.SecurityCenter.Cells.touchIdTitle) { [unowned self] in
let biometricsSettings = BiometricsSettingsViewController(walletManager: btcWalletManager)
biometricsSettings.presentSpendingLimit = {
self.pushBiometricsSpendingLimit(onNc: menuNav)
}
menuNav.pushViewController(biometricsSettings, animated: true)
},
// Paper key
MenuItem(title: S.SecurityCenter.Cells.paperKeyTitle) { [unowned self] in
self.presentWritePaperKey(fromViewController: menuNav)
},
]
var rootItems: [MenuItem] = [
// Manage Wallets
MenuItem(title: S.MenuButton.manageWallets, icon: #imageLiteral(resourceName: "wallet")) {
guard let kvStore = btcWalletManager.apiClient?.kv else { return }
let vc = EditWalletsViewController(type: .manage, kvStore: kvStore)
menuNav.pushViewController(vc, animated: true)
},
// Preferences
MenuItem(title: S.Settings.preferences, icon: #imageLiteral(resourceName: "prefs"), subMenu: preferencesItems, rootNav: menuNav),
// Security
MenuItem(title: S.MenuButton.security, icon: #imageLiteral(resourceName: "security"), subMenu: securityItems, rootNav: menuNav),
// Support
MenuItem(title: S.MenuButton.support, icon: #imageLiteral(resourceName: "support")) { [unowned self] in
self.presentFaq()
},
// Review
MenuItem(title: S.Settings.review, icon: #imageLiteral(resourceName: "review")) {
if let url = URL(string: C.reviewLink) {
UIApplication.shared.open(url)
}
},
// About
MenuItem(title: S.Settings.about, icon: #imageLiteral(resourceName: "about")) {
menuNav.pushViewController(AboutViewController(), animated: true)
},
]
// TODO: cleanup
if E.isTestFlight {
let sendLogs = MenuItem(title: S.Settings.sendLogs, callback: { [unowned self] in
self.showEmailLogsModal()
})
rootItems.append(sendLogs)
}
let settings = MenuViewController(items: rootItems, title: S.Settings.title)
settings.addCloseNavigationItem(side: .right)
menuNav.viewControllers = [settings]
top.present(menuNav, animated: true, completion: nil)
}
private func presentScan(parent: UIViewController, currency: CurrencyDef) -> PresentScan {
return { [weak parent] scanCompletion in
guard ScanViewController.isCameraAllowed else {
self.saveEvent("scan.cameraDenied")
if let parent = parent {
ScanViewController.presentCameraUnavailableAlert(fromRoot: parent)
}
return
}
let vc = ScanViewController(currency: currency, completion: { paymentRequest in
scanCompletion(paymentRequest)
parent?.view.isFrameChangeBlocked = false
})
parent?.view.isFrameChangeBlocked = true
parent?.present(vc, animated: true, completion: {})
}
}
private func pushBiometricsSpendingLimit(onNc: UINavigationController) {
let verify = VerifyPinViewController(bodyText: S.VerifyPin.continueBody, pinLength: Store.state.pinLength, walletManager: primaryWalletManager, success: { pin in
let spendingLimit = BiometricsSpendingLimitViewController(walletManager: self.primaryWalletManager)
onNc.pushViewController(spendingLimit, animated: true)
})
verify.transitioningDelegate = verifyPinTransitionDelegate
verify.modalPresentationStyle = .overFullScreen
verify.modalPresentationCapturesStatusBarAppearance = true
onNc.present(verify, animated: true, completion: nil)
}
private func presentWritePaperKey(fromViewController vc: UIViewController) {
let paperPhraseNavigationController = UINavigationController()
paperPhraseNavigationController.setClearNavbar()
paperPhraseNavigationController.setWhiteStyle()
paperPhraseNavigationController.modalPresentationStyle = .overFullScreen
let start = StartPaperPhraseViewController(callback: { [weak self] in
guard let `self` = self else { return }
let verify = VerifyPinViewController(bodyText: S.VerifyPin.continueBody, pinLength: Store.state.pinLength, walletManager: self.primaryWalletManager, success: { pin in
self.pushWritePaperPhrase(navigationController: paperPhraseNavigationController, pin: pin)
})
verify.transitioningDelegate = self.verifyPinTransitionDelegate
verify.modalPresentationStyle = .overFullScreen
verify.modalPresentationCapturesStatusBarAppearance = true
paperPhraseNavigationController.present(verify, animated: true, completion: nil)
})
start.addCloseNavigationItem(tintColor: .white)
start.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle
let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.paperKey)
faqButton.tintColor = .white
start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)]
paperPhraseNavigationController.viewControllers = [start]
vc.present(paperPhraseNavigationController, animated: true, completion: nil)
}
private func pushWritePaperPhrase(navigationController: UINavigationController, pin: String) {
let walletManager = primaryWalletManager
var writeViewController: WritePaperPhraseViewController?
writeViewController = WritePaperPhraseViewController(walletManager: walletManager, pin: pin, callback: {
var confirm: ConfirmPaperPhraseViewController?
confirm = ConfirmPaperPhraseViewController(walletManager: walletManager, pin: pin, callback: {
confirm?.dismiss(animated: true, completion: {
Store.perform(action: Alert.Show(.paperKeySet(callback: {
Store.perform(action: HideStartFlow())
})))
})
})
writeViewController?.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle
if let confirm = confirm {
navigationController.pushViewController(confirm, animated: true)
}
})
writeViewController?.addCloseNavigationItem(tintColor: .white)
writeViewController?.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle
guard let writeVC = writeViewController else { return }
navigationController.pushViewController(writeVC, animated: true)
}
private func presentPlatformWebViewController(_ mountPoint: String) {
let vc = BRWebViewController(bundleName: C.webBundle, mountPoint: mountPoint, walletManagers: walletManagers)
vc.startServer()
vc.preload()
vc.modalPresentationStyle = .overFullScreen
self.topViewController?.present(vc, animated: true, completion: nil)
}
private func presentRescan(currency: CurrencyDef) {
let vc = ReScanViewController(currency: currency)
let nc = UINavigationController(rootViewController: vc)
nc.setClearNavbar()
vc.addCloseNavigationItem()
topViewController?.present(nc, animated: true, completion: nil)
}
private func wipeWallet() {
let alert = UIAlertController(title: S.WipeWallet.alertTitle, message: S.WipeWallet.alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.cancel, style: .default, handler: nil))
alert.addAction(UIAlertAction(title: S.WipeWallet.wipe, style: .default, handler: { _ in
self.topViewController?.dismiss(animated: true, completion: {
self.wipeWalletNoPrompt()
})
}))
topViewController?.present(alert, animated: true, completion: nil)
}
private func wipeWalletNoPrompt() {
let activity = BRActivityViewController(message: S.WipeWallet.wiping)
self.topViewController?.present(activity, animated: true, completion: nil)
DispatchQueue.walletQueue.async {
self.walletManagers.values.forEach({ $0.peerManager?.disconnect() })
DispatchQueue.walletQueue.asyncAfter(deadline: .now() + 2.0, execute: {
let success = self.primaryWalletManager.wipeWallet(pin: "forceWipe")
DispatchQueue.main.async {
activity.dismiss(animated: true) {
if success {
Store.trigger(name: .reinitWalletManager({
Store.trigger(name: .resetDisplayCurrencies)
}))
} else {
let failure = UIAlertController(title: S.WipeWallet.failedTitle, message: S.WipeWallet.failedMessage, preferredStyle: .alert)
failure.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: nil))
self.topViewController?.present(failure, animated: true, completion: nil)
}
}
}
})
}
}
private func presentKeyImport(walletManager: BTCWalletManager) {
let nc = ModalNavigationController()
nc.setClearNavbar()
nc.setWhiteStyle()
let start = StartImportViewController(walletManager: walletManager)
start.addCloseNavigationItem(tintColor: .white)
start.navigationItem.title = S.Import.title
let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.importWallet, currency: walletManager.currency)
faqButton.tintColor = .white
start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)]
nc.viewControllers = [start]
topViewController?.present(nc, animated: true, completion: nil)
}
//MARK: - Prompts
func presentBiometricsMenuItem() {
let walletManager = primaryWalletManager
let biometricsSettings = BiometricsSettingsViewController(walletManager: walletManager)
biometricsSettings.addCloseNavigationItem(tintColor: .white)
let nc = ModalNavigationController(rootViewController: biometricsSettings)
biometricsSettings.presentSpendingLimit = strongify(self) { myself in
myself.pushBiometricsSpendingLimit(onNc: nc)
}
nc.setDefaultStyle()
nc.isNavigationBarHidden = true
nc.delegate = securityCenterNavigationDelegate
topViewController?.present(nc, animated: true, completion: nil)
}
private func promptShareData() {
let shareData = ShareDataViewController()
let nc = ModalNavigationController(rootViewController: shareData)
nc.setDefaultStyle()
nc.isNavigationBarHidden = true
nc.delegate = securityCenterNavigationDelegate
shareData.addCloseNavigationItem()
topViewController?.present(nc, animated: true, completion: nil)
}
func presentWritePaperKey() {
guard let vc = topViewController else { return }
presentWritePaperKey(fromViewController: vc)
}
func presentUpgradePin() {
let walletManager = primaryWalletManager
let updatePin = UpdatePinViewController(walletManager: walletManager, type: .update)
let nc = ModalNavigationController(rootViewController: updatePin)
nc.setDefaultStyle()
nc.isNavigationBarHidden = true
nc.delegate = securityCenterNavigationDelegate
updatePin.addCloseNavigationItem()
topViewController?.present(nc, animated: true, completion: nil)
}
private func handleFile(_ file: Data) {
if let request = PaymentProtocolRequest(data: file) {
if let topVC = topViewController as? ModalViewController {
let attemptConfirmRequest: () -> Bool = {
if let send = topVC.childViewController as? SendViewController {
send.confirmProtocolRequest(request)
return true
}
return false
}
if !attemptConfirmRequest() {
modalTransitionDelegate.reset()
topVC.dismiss(animated: true, completion: {
//TODO:BCH
Store.perform(action: RootModalActions.Present(modal: .send(currency: Currencies.btc)))
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { //This is a hack because present has no callback
let _ = attemptConfirmRequest()
})
})
}
}
} else if let ack = PaymentProtocolACK(data: file) {
if let memo = ack.memo {
let alert = UIAlertController(title: "", message: memo, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil))
topViewController?.present(alert, animated: true, completion: nil)
}
//TODO - handle payment type
} else {
let alert = UIAlertController(title: S.Alert.error, message: S.PaymentProtocol.Errors.corruptedDocument, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil))
topViewController?.present(alert, animated: true, completion: nil)
}
}
private func handlePaymentRequest(request: PaymentRequest) {
self.currentRequest = request
guard !Store.state.isLoginRequired else { presentModal(.send(currency: request.currency)); return }
showAccountView(currency: request.currency, animated: false) {
self.presentModal(.send(currency: request.currency))
}
}
private func showAccountView(currency: CurrencyDef, animated: Bool, completion: (() -> Void)?) {
let pushAccountView = {
guard let nc = self.topViewController?.navigationController as? RootNavigationController,
nc.viewControllers.count == 1 else { return }
guard let walletManager = self.walletManagers[currency.code] else { return }
let accountViewController = AccountViewController(currency: currency, walletManager: walletManager)
nc.pushViewController(accountViewController, animated: animated)
completion?()
}
if let accountVC = topViewController as? AccountViewController {
if accountVC.currency.matches(currency) {
completion?()
} else {
accountVC.navigationController?.popToRootViewController(animated: false)
pushAccountView()
}
} else if topViewController is HomeScreenViewController {
pushAccountView()
} else if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController {
if let nc = presented.presentingViewController as? RootNavigationController, nc.viewControllers.count > 1 {
// modal on top of another account screen
presented.dismiss(animated: false) {
self.showAccountView(currency: currency, animated: animated, completion: completion)
}
} else {
presented.dismiss(animated: true) {
pushAccountView()
}
}
}
}
private func handleScanQrURL() {
guard !Store.state.isLoginRequired else { presentLoginScan(); return }
if topViewController is AccountViewController || topViewController is LoginViewController {
presentLoginScan()
} else {
if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController {
presented.dismiss(animated: true, completion: {
self.presentLoginScan()
})
}
}
}
private func handleCopyAddresses(success: String?, error: String?) {
let walletManager = primaryWalletManager // TODO:BCH
let alert = UIAlertController(title: S.URLHandling.addressListAlertTitle, message: S.URLHandling.addressListAlertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: S.URLHandling.copy, style: .default, handler: { [weak self] _ in
let verify = VerifyPinViewController(bodyText: S.URLHandling.addressListVerifyPrompt, pinLength: Store.state.pinLength, walletManager: walletManager, success: { [weak self] pin in
self?.copyAllAddressesToClipboard()
Store.perform(action: Alert.Show(.addressesCopied))
if let success = success, let url = URL(string: success) {
UIApplication.shared.open(url)
}
})
verify.transitioningDelegate = self?.verifyPinTransitionDelegate
verify.modalPresentationStyle = .overFullScreen
verify.modalPresentationCapturesStatusBarAppearance = true
self?.topViewController?.present(verify, animated: true, completion: nil)
}))
topViewController?.present(alert, animated: true, completion: nil)
}
private func authenticateForPlatform(prompt: String, allowBiometricAuth: Bool, callback: @escaping (PlatformAuthResult) -> Void) {
if UserDefaults.isBiometricsEnabled && allowBiometricAuth {
primaryWalletManager.authenticate(biometricsPrompt: prompt, completion: { result in
switch result {
case .success:
return callback(.success(nil))
case .cancel:
return callback(.cancelled)
case .failure:
self.verifyPinForPlatform(prompt: prompt, callback: callback)
case .fallback:
self.verifyPinForPlatform(prompt: prompt, callback: callback)
}
})
} else {
self.verifyPinForPlatform(prompt: prompt, callback: callback)
}
}
private func verifyPinForPlatform(prompt: String, callback: @escaping (PlatformAuthResult) -> Void) {
let verify = VerifyPinViewController(bodyText: prompt, pinLength: Store.state.pinLength, walletManager: primaryWalletManager, success: { pin in
callback(.success(pin))
})
verify.didCancel = { callback(.cancelled) }
verify.transitioningDelegate = verifyPinTransitionDelegate
verify.modalPresentationStyle = .overFullScreen
verify.modalPresentationCapturesStatusBarAppearance = true
topViewController?.present(verify, animated: true, completion: nil)
}
private func confirmTransaction(currency: CurrencyDef, amount: Amount, fee: Amount, address: String, callback: @escaping (Bool) -> Void) {
let confirm = ConfirmationViewController(amount: amount,
fee: fee,
feeType: .regular,
address: address,
isUsingBiometrics: false,
currency: currency)
let transitionDelegate = PinTransitioningDelegate()
transitionDelegate.shouldShowMaskView = true
confirm.transitioningDelegate = transitionDelegate
confirm.modalPresentationStyle = .overFullScreen
confirm.modalPresentationCapturesStatusBarAppearance = true
confirm.successCallback = {
callback(true)
}
confirm.cancelCallback = {
callback(false)
}
topViewController?.present(confirm, animated: true, completion: nil)
}
private func copyAllAddressesToClipboard() {
guard let wallet = primaryWalletManager.wallet else { return } // TODO:BCH
let addresses = wallet.allAddresses.filter({wallet.addressIsUsed($0)})
UIPasteboard.general.string = addresses.joined(separator: "\n")
}
private var topViewController: UIViewController? {
var viewController = window.rootViewController
if let nc = viewController as? UINavigationController {
viewController = nc.topViewController
}
while viewController?.presentedViewController != nil {
viewController = viewController?.presentedViewController
}
return viewController
}
private func showNotReachable() {
guard notReachableAlert == nil else { return }
let alert = InAppAlert(message: S.Alert.noInternet, image: #imageLiteral(resourceName: "BrokenCloud"))
notReachableAlert = alert
let window = UIApplication.shared.keyWindow!
let size = window.bounds.size
window.addSubview(alert)
let bottomConstraint = alert.bottomAnchor.constraint(equalTo: window.topAnchor, constant: 0.0)
alert.constrain([
alert.constraint(.width, constant: size.width),
alert.constraint(.height, constant: InAppAlert.height),
alert.constraint(.leading, toView: window, constant: nil),
bottomConstraint ])
window.layoutIfNeeded()
alert.bottomConstraint = bottomConstraint
alert.hide = {
self.hideNotReachable()
}
UIView.spring(C.animationDuration, animations: {
alert.bottomConstraint?.constant = InAppAlert.height
window.layoutIfNeeded()
}, completion: {_ in})
}
private func hideNotReachable() {
UIView.animate(withDuration: C.animationDuration, animations: {
self.notReachableAlert?.bottomConstraint?.constant = 0.0
self.notReachableAlert?.superview?.layoutIfNeeded()
}, completion: { _ in
self.notReachableAlert?.removeFromSuperview()
self.notReachableAlert = nil
})
}
private func showLightWeightAlert(message: String) {
let alert = LightWeightAlert(message: message)
let view = UIApplication.shared.keyWindow!
view.addSubview(alert)
alert.constrain([
alert.centerXAnchor.constraint(equalTo: view.centerXAnchor),
alert.centerYAnchor.constraint(equalTo: view.centerYAnchor) ])
alert.background.effect = nil
UIView.animate(withDuration: 0.6, animations: {
alert.background.effect = alert.effect
}, completion: { _ in
UIView.animate(withDuration: 0.6, delay: 1.0, options: [], animations: {
alert.background.effect = nil
}, completion: { _ in
alert.removeFromSuperview()
})
})
}
private func showEmailLogsModal() {
self.messagePresenter.presenter = self.topViewController
self.messagePresenter.presentEmailLogs()
}
}
class SecurityCenterNavigationDelegate : NSObject, UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
guard let coordinator = navigationController.topViewController?.transitionCoordinator else { return }
if coordinator.isInteractive {
coordinator.notifyWhenInteractionChanges { context in
//We only want to style the view controller if the
//pop animation wasn't cancelled
if !context.isCancelled {
self.setStyle(navigationController: navigationController, viewController: viewController)
}
}
} else {
setStyle(navigationController: navigationController, viewController: viewController)
}
}
func setStyle(navigationController: UINavigationController, viewController: UIViewController) {
navigationController.isNavigationBarHidden = false
if viewController is BiometricsSettingsViewController {
navigationController.setWhiteStyle()
} else {
navigationController.setDefaultStyle()
}
}
}
| 47.509684 | 191 | 0.621344 |
de0b3cf0bba6affc094e28be0533e714719f2347 | 2,195 | //
// AppDelegate.swift
// ExampleOfiOSLiDAR
//
// Created by TokyoYoshida on 2021/01/07.
//
import UIKit
import ARKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if !ARWorldTrackingConfiguration.supportsFrameSemantics(.sceneDepth) {
// Ensure that the device supports scene depth and present
// an error-message view controller, if not.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "unsupportedDeviceMessage")
}
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 invalidate graphics rendering callbacks. 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.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
}
| 45.729167 | 285 | 0.742141 |
6166ca7cbee6082cb2932b33dc95729bc917210e | 501 | //
// ViewController.swift
// LithoModels
//
// Created by Elliot on 09/01/2021.
// Copyright (c) 2021 Elliot. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.04 | 80 | 0.668663 |
1876b46ac92dc4ee372b31ca01ac3d7dfca444ae | 571 | //
// Utils.swift
// MessagingApp
//
// Created by eren on 31.08.2019.
// Copyright © 2019 Eren Kulan. All rights reserved.
//
import Foundation
class Utils {
static func hourMinFromDate(_ date: Date) -> String {
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
return String(format: "%d:%d", hour, minute)
}
static func getCurrentHourMinute() -> String {
let date = Date()
return Utils.hourMinFromDate(date)
}
}
| 21.961538 | 60 | 0.628722 |
11d64777f311ea4d6a94ee2e4a33803bea82ecfa | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<Int
class A {
func e {
func g: B<Int>
}
deinit {
struct c<T where f: AnyObject {
let : Int
| 20.692308 | 87 | 0.728625 |
ab648a706156ef9aec023e347d65c83bf9dac642 | 4,402 | //
// AspectRatioSettable.swift
//
// Created by Chen Qizhi on 2019/10/18.
//
import UIKit
public protocol AspectRatioSettable {
func setAspectRatio(_ aspectRatio: AspectRatio)
func setAspectRatioValue(_ aspectRatioValue: CGFloat)
}
extension AspectRatioSettable where Self: CropperViewController {
public func setAspectRatio(_ aspectRatio: AspectRatio) {
switch aspectRatio {
case .original:
var width: CGFloat
var height: CGFloat
let angle = standardizeAngle(rotationAngle)
if angle.isEqual(to: .pi / 2.0, accuracy: 0.001) ||
angle.isEqual(to: .pi * 1.5, accuracy: 0.001) {
width = originalImage.size.height
height = originalImage.size.width
} else {
width = originalImage.size.width
height = originalImage.size.height
}
if aspectRatioPicker.rotated {
swap(&width, &height)
}
if width > height {
aspectRatioPicker.selectedBox = .horizontal
} else if width < height {
aspectRatioPicker.selectedBox = .vertical
} else {
aspectRatioPicker.selectedBox = .none
}
setAspectRatioValue(width / height)
aspectRatioLocked = true
case .freeForm:
aspectRatioPicker.selectedBox = .none
aspectRatioLocked = false
case .square:
aspectRatioPicker.selectedBox = .none
setAspectRatioValue(1)
aspectRatioLocked = true
case let .ratio(width, height):
if width > height {
aspectRatioPicker.selectedBox = .horizontal
} else if width < height {
aspectRatioPicker.selectedBox = .vertical
} else {
aspectRatioPicker.selectedBox = .none
}
setAspectRatioValue(CGFloat(width) / CGFloat(height))
aspectRatioLocked = true
}
}
public func setAspectRatioValue(_ aspectRatioValue: CGFloat) {
guard aspectRatioValue > 0 else { return }
// topBar.isUserInteractionEnabled = false
bottomView.isUserInteractionEnabled = false
aspectRatioLocked = true
currentAspectRatioValue = aspectRatioValue
var targetCropBoxFrame: CGRect
let height: CGFloat = maxCropRegion.size.width / aspectRatioValue
if height <= maxCropRegion.size.height {
targetCropBoxFrame = CGRect(center: defaultCropBoxCenter, size: CGSize(width: maxCropRegion.size.width, height: height))
} else {
let width = maxCropRegion.size.height * aspectRatioValue
targetCropBoxFrame = CGRect(center: defaultCropBoxCenter, size: CGSize(width: width, height: maxCropRegion.size.height))
}
targetCropBoxFrame = safeCropBoxFrame(targetCropBoxFrame)
let currentCropBoxFrame = overlay.cropBoxFrame
/// The content of the image is getting bigger and bigger when switching the aspect ratio.
/// Make a fake cropBoxFrame to help calculate how much the image should be scaled.
var contentBiggerThanCurrentTargetCropBoxFrame: CGRect
if currentCropBoxFrame.size.width / currentCropBoxFrame.size.height > aspectRatioValue {
contentBiggerThanCurrentTargetCropBoxFrame = CGRect(center: defaultCropBoxCenter, size: CGSize(width: currentCropBoxFrame.size.width, height: currentCropBoxFrame.size.width / aspectRatioValue))
} else {
contentBiggerThanCurrentTargetCropBoxFrame = CGRect(center: defaultCropBoxCenter, size: CGSize(width: currentCropBoxFrame.size.height * aspectRatioValue, height: currentCropBoxFrame.size.height))
}
let extraZoomScale = max(targetCropBoxFrame.size.width / contentBiggerThanCurrentTargetCropBoxFrame.size.width, targetCropBoxFrame.size.height / contentBiggerThanCurrentTargetCropBoxFrame.size.height)
overlay.gridLinesAlpha = 0
matchScrollViewAndCropView(animated: true, targetCropBoxFrame: targetCropBoxFrame, extraZoomScale: extraZoomScale, blurLayerAnimated: true, animations: nil, completion: {
// self.topBar.isUserInteractionEnabled = true
self.bottomView.isUserInteractionEnabled = true
self.updateButtons()
})
}
}
| 43.156863 | 208 | 0.656747 |
bf9757ef11217e05612a3893ac377f4e75c6d14b | 12,942 | //
// Copyright © 2021年 Sweetman, Inc. All rights reserved.
//
import UIKit
import Photos
public class InstagramPhotosLibraryView: UIView {
struct Measurements {
static let imageCellName = "InstagramPhotosImageCell"
static let libraryViewName = "InstagramPhotosLibraryView"
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var showAlbumsButton: UIButton!
@IBOutlet weak var squareMask: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var addingMoreImageVisualView: UIVisualEffectView!
@IBOutlet weak var progressView: InstagramPhotosProgressView!
@IBOutlet weak var addingMoreButton: UIButton!
@IBOutlet weak var actionViewHeightConstraint: NSLayoutConstraint!
lazy var imageView: UIImageView = {
let i = UIImageView()
i.contentMode = .scaleAspectFill
i.clipsToBounds = true
return i
}()
var currentAsset: PHAsset?
var currentImageRequestID: PHImageRequestID?
var isOnDownloadingImage: Bool = true
var images: PHFetchResult<PHAsset>!
var imageManager: PHCachingImageManager?
var phAsset: PHAsset!
var scale: CGFloat = 1.0
var scaleRect: CGRect = CGRect.zero
var imageScale: CGFloat = 1.0
var pickingInteractor: InstagramPhotosPickingInteracting?
private var isDisplayingLimitedLibraryPicker = false
private let albumsProvider: InstagramPhotosAlbumsProviding = InstagramPhotosAlbumsProvider()
private let authorizationProvider: InstagramPhotosAuthorizationProviding = InstagramPhotosAuthorizationProvider()
public static func instance() -> InstagramPhotosLibraryView {
let view = UINib(nibName: Measurements.libraryViewName,
bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! InstagramPhotosLibraryView
view.initialize()
InstagramPhotosLocalizationManager.main.addLocalizationConponent(localizationUpdateable: view)
return view
}
func initialize() {
if images != nil { return }
settingFirstAlbum()
scrollView.addSubview(imageView)
imageView.frame = scrollView.frame
let cellNib = UINib(nibName: Measurements.imageCellName,
bundle: Bundle(for: InstagramPhotosLibraryView.classForCoder()))
collectionView.register(cellNib, forCellWithReuseIdentifier: Measurements.imageCellName)
addingMoreImageVisualView.clipsToBounds = true
addingMoreImageVisualView.layer.cornerRadius = 23.0
collectionView.selectItem(at: IndexPath.init(row: 0, section: 0), animated: false, scrollPosition: .bottom)
switch authorizationProvider.authorizationStatus() {
case .limited:
let provider = InstagramPhotosLocalizationManager.main.localizationsProviding
showAlbumsButton.setTitle(provider.photosLimitedAccessModeText(), for: .normal)
showAlbumsButton.isUserInteractionEnabled = false
addingMoreButton.layer.cornerRadius = 22.0
default:
addingMoreImageVisualView.isHidden = true
}
PHPhotoLibrary.shared().register(self)
}
func settingFirstAlbum() {
guard let firstAlbum = InstagramPhotosAlbumsProvider().listAllAlbums().first else { return }
images = firstAlbum.assets
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.collectionView.reloadData()
}
currentAsset = firstAlbum.assets.firstObject
loadingAlbumFirstImage(album: firstAlbum)
}
func setupFirstLoadingImageAttrabute(image: UIImage) {
self.imageView.image = image
let se = self.cacuclateContentSize(original: image.size, target: self.scrollView.frame.size)
self.scrollView.contentSize = se
self.imageView.frame = CGRect(origin: CGPoint.zero, size: se)
self.scaleRect = CGRect(origin: CGPoint.zero, size: scrollView.frame.size)
self.scrollView.zoomScale = 1.0
self.scale = 1.0
}
public override func layoutSubviews() {
super.layoutSubviews()
actionViewHeightConstraint.constant = InstagramPhotoDimensionalProvider().libraryActionViewheight()
}
func cacuclateContentSize(original: CGSize, target: CGSize) -> CGSize {
var size = CGSize(width: 0, height: 0)
if original.width > original.height {
let scale = original.height / target.height
let w = original.width / scale
self.imageScale = scale
size = CGSize(width: w, height: target.height)
}else{
let scale = original.width / target.width
let w = original.height / scale
self.imageScale = scale
size = CGSize(width: target.width, height: w)
}
return size
}
func updateShowAlbumButton(title: String) {
switch authorizationProvider.authorizationStatus() {
case .limited:
let provider = InstagramPhotosLocalizationManager.main.localizationsProviding
showAlbumsButton.setTitle(provider.photosLimitedAccessModeText(), for: .normal)
showAlbumsButton.isUserInteractionEnabled = false
default:
showAlbumsButton.setTitle(title, for: .normal)
showAlbumsButton.isUserInteractionEnabled = true
}
}
private func loadingAlbumFirstImage(album: InstagramPhotosAlbum) {
guard let firstAsset = albumsProvider.fetchAlbumFirstAsset(collection: album.collection) else { return }
albumsProvider.fetchAssetImage(asset: firstAsset, size: .original) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let image):
self.setupFirstLoadingImageAttrabute(image: image)
default:
print("Selected ablum loading first image failure")
}
}
}
}
extension InstagramPhotosLibraryView: InstagramPhotosLocalizationUpdateable {
public func localizationContents() {
let provider = InstagramPhotosLocalizationManager.main.localizationsProviding
updateShowAlbumButton(title: provider.pinkingControllerDefaultAlbumName())
addingMoreButton.setTitle(provider.pinkingControllerAddingImageAccessButtonText(), for: .normal)
}
}
extension InstagramPhotosLibraryView {
@IBAction func showAlbumsButtonAction(_ sender: Any) {
guard let interactor = pickingInteractor else { return }
interactor.showAlbumsView()
}
@IBAction func addingMoreButtonAction(_ sender: UIButton) {
isDisplayingLimitedLibraryPicker = true
pickingInteractor?.presentLimitedLibraryPicker()
}
}
extension InstagramPhotosLibraryView: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Measurements.imageCellName, for: indexPath) as! InstagramPhotosImageCell
let asset = self.images[indexPath.row]
PHImageManager.default().requestImage(for: asset,
targetSize: CGSize(width: 300, height: 300),
contentMode: .aspectFill,
options: nil) { (image, info) in
cell.image = image
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images == nil ? 0 : images.count
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (UIScreen.main.bounds.width - 3) / 4.00
return CGSize(width: width, height: width)
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let asset = images[indexPath.row]
currentAsset = asset
displayThubnailImage(asset: asset)
displayOriginalImage(asset: asset)
}
private func displayThubnailImage(asset: PHAsset) {
if let requestID = currentImageRequestID {
PHImageManager.default().cancelImageRequest(requestID)
}
PHImageManager.default().requestImage(for: asset,
targetSize: CGSize(width: 300, height: 300),
contentMode: .aspectFill,
options: nil) { [weak self] image, info in
guard let self = self, let unwrapImage = image else { return }
DispatchQueue.main.async {
self.setupFirstLoadingImageAttrabute(image: unwrapImage)
}
}
}
private func displayOriginalImage(asset: PHAsset) {
isOnDownloadingImage = true
let targetSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
progressView.isHidden = true
let requestOptions = PHImageRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed = true
requestOptions.version = .original
requestOptions.progressHandler = { [weak self] progress, err, pointer, info in
guard let self = self else { return }
self.displayProgressView(progress: progress)
}
DispatchQueue.global(qos: .userInteractive).async {
self.currentImageRequestID = PHImageManager.default().requestImage(for: asset,
targetSize: targetSize,
contentMode: .aspectFill,
options: requestOptions) { [weak self] image, info in
guard let self = self else { return }
self.isOnDownloadingImage = false
self.currentImageRequestID = nil
guard let unwrapImage = image else { return }
DispatchQueue.main.async {
self.setupFirstLoadingImageAttrabute(image: unwrapImage)
}
}
}
}
private func displayProgressView(progress: Double) {
DispatchQueue.main.async {
if self.progressView.isHidden {
self.progressView.isHidden = false
}
self.progressView.progress = CGFloat(progress)
if progress == 1.0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3, execute: {
self.progressView.progress = 0.0
self.progressView.isHidden = true
})
}
}
}
}
extension InstagramPhotosLibraryView {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
self.squareMask.isHidden = false
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self.scrollView{
self.squareMask.isHidden = true
self.scaleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.frame.size)
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == self.scrollView{
self.squareMask.isHidden = true
self.scaleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.frame.size)
}
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
self.squareMask.isHidden = false
}
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
if scrollView == self.scrollView{
self.scale = scale
self.squareMask.isHidden = true
self.scaleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.frame.size)
}
}
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
extension InstagramPhotosLibraryView: PHPhotoLibraryChangeObserver {
public func photoLibraryDidChange(_ changeInstance: PHChange) {
if isDisplayingLimitedLibraryPicker {
settingFirstAlbum()
isDisplayingLimitedLibraryPicker = false
}
}
}
| 42.712871 | 167 | 0.647968 |
e83154b1ef0b44c881b6cc4844fb2f63ba259fbc | 10,674 | //
// ImagesProcessor.swift
// FSNotes
//
// Created by Oleksandr Glushchenko on 1/12/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
public class ImagesProcessor {
#if os(OSX)
typealias Size = NSSize
typealias Image = NSImage
#else
typealias Size = CGSize
typealias Image = UIImage
#endif
var textStorageNSString: NSString
var styleApplier: NSMutableAttributedString
var range: NSRange?
var note: Note
var paragraphRange: NSRange
var offset = 0
var newLineOffset = 0
init(styleApplier: NSMutableAttributedString, range: NSRange? = nil, note: Note) {
self.styleApplier = styleApplier
self.range = range
self.note = note
self.textStorageNSString = styleApplier.string as NSString
if let unwrappedRange = range {
paragraphRange = unwrappedRange
} else {
paragraphRange = NSRange(0..<styleApplier.length)
}
}
public func load() {
var offset = 0
#if NOT_EXTENSION || os(OSX)
NotesTextProcessor.imageInlineRegex.matches(self.styleApplier.string, range: paragraphRange) { (result) -> Void in
guard var range = result?.range else { return }
range = NSRange(location: range.location - offset, length: range.length)
let mdLink = self.styleApplier.attributedSubstring(from: range).string
let title = self.getTitle(link: mdLink)
if var font = UserDefaultsManagement.noteFont {
#if os(iOS)
if #available(iOS 11.0, *) {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
#endif
self.styleApplier.addAttribute(.font, value: font, range: range)
}
if !UserDefaultsManagement.liveImagesPreview {
NotesTextProcessor.imageOpeningSquareRegex.matches(self.styleApplier.string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
self.styleApplier.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.imageClosingSquareRegex.matches(self.styleApplier.string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
self.styleApplier.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
NotesTextProcessor.parenRegex.matches(self.styleApplier.string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
var url: URL?
let filePath = self.getFilePath(innerRange: innerRange)
if let localNotePath = self.getLocalNotePath(path: filePath, innerRange: innerRange), FileManager.default.fileExists(atPath: localNotePath) {
url = URL(fileURLWithPath: localNotePath)
} else if let fs = URL(string: filePath) {
url = fs
}
guard let imageUrl = url else { return }
let invalidateRange = NSRange(location: range.location, length: 1)
let cacheUrl = self.note.project.url.appendingPathComponent("/.cache/")
let imageAttachment = ImageAttachment(title: title, path: filePath, url: imageUrl, cache: cacheUrl, invalidateRange: invalidateRange)
if let attributedStringWithImage = imageAttachment.getAttributedString() {
offset += mdLink.count - 1
self.styleApplier.replaceCharacters(in: range, with: attributedStringWithImage)
}
}
}
#endif
}
public func unLoad() {
note.content = NSMutableAttributedString(attributedString: styleApplier.attributedSubstring(from: NSRange(0..<styleApplier.length)))
var offset = 0
self.styleApplier.enumerateAttribute(.attachment, in: NSRange(location: 0, length: self.styleApplier.length)) { (value, range, stop) in
if value != nil, self.styleApplier.attribute(.todo, at: range.location, effectiveRange: nil) == nil {
let newRange = NSRange(location: range.location + offset, length: range.length)
let filePathKey = NSAttributedStringKey(rawValue: "co.fluder.fsnotes.image.path")
let titleKey = NSAttributedStringKey(rawValue: "co.fluder.fsnotes.image.title")
guard
let path = self.styleApplier.attribute(filePathKey, at: range.location, effectiveRange: nil) as? String,
let title = self.styleApplier.attribute(titleKey, at: range.location, effectiveRange: nil) as? String else { return }
if let pathEncoded = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
self.note.content.replaceCharacters(in: newRange, with: ")")
offset += 4 + path.count + title.count
}
}
}
}
func computeMarkdownTitleLength(mdLink: String) -> Int {
var mdTitleLength = 0
if let match = mdLink.range(of: "\\[(.+)\\]", options: .regularExpression) {
mdTitleLength = mdLink[match].count - 2
}
return mdTitleLength
}
private func getTitle(link: String) -> String {
if let match = link.range(of: "\\[(.+)\\]", options: .regularExpression) {
let title = link[match]
return String(title.dropLast().dropFirst())
}
return ""
}
func getLocalNotePath(path: String, innerRange: NSRange) -> String? {
let noteStorage = self.note.project
var notePath: String
let storagePath = noteStorage.url.path
if path.starts(with: "/i/") {
let path = getFilePath(innerRange: innerRange)
return note.project.url.path + path
}
if path.starts(with: "http://") || path.starts(with: "https://"), let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
notePath = storagePath + "/i/" + encodedPath
return notePath
}
if note.type == .TextBundle {
if let name = path.removingPercentEncoding {
return "\(note.url.path)/\(name)"
}
}
let path = getFilePath(innerRange: innerRange)
notePath = storagePath + "/" + path
return notePath
}
func getFilePath(innerRange: NSRange) -> String {
let link = NSRange(location: innerRange.location + 1 + offset, length: innerRange.length - 2)
if let path = styleApplier.attributedSubstring(from: link).string.removingPercentEncoding {
return path
}
return ""
}
public static func getFileName(from: URL? = nil, to: URL) -> String? {
let path = from?.absoluteString ?? to.absoluteString
var name: String?
if path.starts(with: "http://") || path.starts(with: "https://"), let webName = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
name = webName
}
if path.starts(with: "file://") {
var i = 0
var pathComponent = "1.jpg"
var ext = "jpg"
if let from = from {
pathComponent = from.lastPathComponent
ext = from.pathExtension
}
while name == nil {
let destination = to.appendingPathComponent(pathComponent)
if FileManager.default.fileExists(atPath: destination.path) {
i = i + 1
pathComponent = "\(i).\(ext)"
continue
}
name = pathComponent
}
}
return name
}
public static func writeImage(data: Data, url: URL? = nil, note: Note) -> String? {
if note.type == .TextBundle {
let assetsUrl = note.url.appendingPathComponent("assets")
if !FileManager.default.fileExists(atPath: assetsUrl.path, isDirectory: nil) {
try? FileManager.default.createDirectory(at: assetsUrl, withIntermediateDirectories: true, attributes: nil)
}
let destination = URL(fileURLWithPath: assetsUrl.path)
guard let fileName = ImagesProcessor.getFileName(from: url, to: destination) else {
return nil
}
let to = destination.appendingPathComponent(fileName)
do {
try data.write(to: to, options: .atomic)
} catch {
print(error)
}
return fileName
}
let project = note.project
let destination = URL(fileURLWithPath: project.url.path + "/i/")
do {
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false, attributes: nil)
} catch {
}
guard let fileName = ImagesProcessor.getFileName(from: url, to: destination) else {
return nil
}
let to = destination.appendingPathComponent(fileName)
try? data.write(to: to, options: .atomic)
return fileName
}
func isContainAttachment(innerRange: NSRange, mdTitleLength: Int) -> Bool {
let j = offset + newLineOffset - mdTitleLength
if innerRange.lowerBound >= 5 + mdTitleLength {
return self.styleApplier.containsAttachments(in: NSMakeRange(innerRange.lowerBound - 5 + j, 1))
}
return false
}
func isContainNewLine(innerRange: NSRange, mdTitleLength: Int) -> Bool {
let j = offset + newLineOffset - mdTitleLength
if innerRange.lowerBound >= 4 + mdTitleLength {
return (self.styleApplier.attributedSubstring(from: NSMakeRange(innerRange.lowerBound - 4 + j, 1)).string == "\n")
}
return false
}
}
| 38.121429 | 161 | 0.577384 |
fbd5dd45e2329e2a0bce5ec8d138cfd45a997f11 | 5,633 | //
// TapMessaging.swift
// TapMessaging
//
// Created by Dennis Pashkov on 12/26/17.
// Copyright © 2017 Tap Payments. All rights reserved.
//
import TapAdditionsKitV2
import MessageUI
import UIKit
/// Tap Messaging class.
public class TapMessaging: NSObject {
// MARK: - Public -
public typealias DeliveryResultClosure = (DeliveryResult) -> Void
// MARK: Properties
/// Shared instance.
public static let shared = TapMessaging()
/// Defines if emails can be sent from current device.
public var canSendMail: Bool {
return MFMailComposeViewController.canSendMail()
}
/// Defines is SMS can be sent from current device.
public var canSendSMSText: Bool {
return MFMessageComposeViewController.canSendText()
}
/// Defines if current device can send SMS subject.
public var canSendSMSSubject: Bool {
return MFMessageComposeViewController.canSendSubject()
}
/// Defines if current device can send SMS attachments.
public var canSendSMSAttachments: Bool {
return MFMessageComposeViewController.canSendAttachments()
}
// MARK: Methods
/// Shows mail compose controller with the given parameters.
///
/// - Parameters:
/// - subject: Mail subject.
/// - recipients: Mail recipients.
/// - body: Mail body.
/// - attachments: Mail attachment (if any).
/// - completion: Completion closure that is called after mail compose controller is closed.
public func showMailComposeController(with subject: String?, recipients: [String]?, body: MailBody, attachments: [Attachment]?, completion: @escaping DeliveryResultClosure) {
guard self.canSendMail else {
completion(.failed(nil))
return
}
let controller = MFMailComposeViewController()
controller.mailComposeDelegate = self
if let nonnullSubject = subject {
controller.setSubject(nonnullSubject)
}
controller.setToRecipients(recipients)
controller.setBody(body)
if let nonnullAttachments = attachments {
controller.addAttachments(nonnullAttachments)
}
self.callbacks[controller.description] = completion
DispatchQueue.main.async {
(controller as UIViewController).tap_className
}
}
/// Shows message compose controller with the given parameters.
///
/// - Parameters:
/// - subject: Message subject.
/// - recipients: Message recipients.
/// - body: Message body.
/// - attachments: Message attachment (if any).
/// - completion: Completion closure that is called after message compose controller is closed.
public func showMessageComposeController(with subject: String?, recipients: [String]?, body: String, attachments: [Attachment]?, completion: @escaping DeliveryResultClosure) {
guard self.canSendSMSText else {
completion(.failed(nil))
return
}
let controller = MFMessageComposeViewController()
controller.messageComposeDelegate = self
controller.recipients = recipients
controller.body = body
if self.canSendSMSSubject {
controller.subject = subject
}
if let nonnullAttachments = attachments, self.canSendSMSAttachments {
controller.addAttachments(nonnullAttachments)
}
self.callbacks[controller.description] = completion
DispatchQueue.main.async {
let controllerr:UIViewController = .init()
controllerr.tap_currentPresentedViewController?.present(controller, animated: true, completion: nil)
//controllerr.tap
//controller.tap_show//showOnSeparateWindow(true, completion: nil)
}
}
// MARK: - Private -
// MARK: Properties
private lazy var callbacks: [String: DeliveryResultClosure] = [:]
// MARK: Methods
private override init() { super.init() }
private func messagingController(_ controller: UIViewController, didFinishWith result: DeliveryResult) {
let key = controller.description
guard let completion = self.callbacks[key] else { return }
controller.tap_dismissFromSeparateWindow(true) {
completion(result)
self.callbacks.removeValue(forKey: key)
}
}
}
// MARK: - MFMailComposeViewControllerDelegate
extension TapMessaging: MFMailComposeViewControllerDelegate {
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
var deliveryResult: DeliveryResult
switch result {
case .cancelled, .saved:
deliveryResult = .cancelled
case .sent:
deliveryResult = .sent
case .failed:
deliveryResult = .failed(error)
}
self.messagingController(controller, didFinishWith: deliveryResult)
}
}
// MARK: - MFMessageComposeViewControllerDelegate
extension TapMessaging: MFMessageComposeViewControllerDelegate {
public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
var deliveryResult: DeliveryResult
switch result {
case .cancelled:
deliveryResult = .cancelled
case .sent:
deliveryResult = .sent
case .failed:
deliveryResult = .failed(nil)
}
self.messagingController(controller, didFinishWith: deliveryResult)
}
}
| 27.748768 | 179 | 0.66359 |
16679354f00a8aa59973c202dbbd60b05a1e2429 | 23,990 | import UIKit
import VerIDCore
import VerIDUI
@objc(VerIDPlugin) public class VerIDPlugin: CDVPlugin, VerIDFactoryDelegate, VerIDSessionDelegate {
private var veridSessionCallbackId: String?
private var verid: VerID?
private var TESTING_MODE: Bool = false
@objc public func load(_ command: CDVInvokedUrlCommand) {
self.loadVerID(command) { _ in
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK), callbackId: command.callbackId)
}
}
@objc public func unload(_ command: CDVInvokedUrlCommand) {
self.verid = nil
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "OK"), callbackId: command.callbackId)
}
@objc public func registerUser(_ command: CDVInvokedUrlCommand) {
if self.TESTING_MODE {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: self.getAttachmentMockup()), callbackId: command.callbackId)
} else {
do {
let settings: RegistrationSessionSettings = try self.createSettings(command.arguments)
self.startSession(command: command, settings: settings)
} catch {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: command.callbackId)
}
}
}
@objc public func authenticate(_ command: CDVInvokedUrlCommand) {
if self.TESTING_MODE {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: self.getAttachmentMockup()), callbackId: command.callbackId)
} else {
do {
let settings: AuthenticationSessionSettings = try self.createSettings(command.arguments)
self.startSession(command: command, settings: settings)
} catch {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: command.callbackId)
}
}
}
@objc public func captureLiveFace(_ command: CDVInvokedUrlCommand) {
if self.TESTING_MODE {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: self.getAttachmentMockup()), callbackId: command.callbackId)
} else {
do {
let settings: LivenessDetectionSessionSettings = try self.createSettings(command.arguments)
self.startSession(command: command, settings: settings)
} catch {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: command.callbackId)
}
}
}
@objc public func getRegisteredUsers(_ command: CDVInvokedUrlCommand) {
self.loadVerID(command) { verid in
var err: String = "Unknown error"
do {
let users = try verid.userManagement.users()
if let usersString = String(data: try JSONEncoder().encode(users), encoding: .utf8) {
let usersResult = self.TESTING_MODE ? "[\"user1\", \"user2\", \"user3\"]" : usersString;
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: usersResult)
self.commandDelegate.send(result, callbackId: command.callbackId)
return
} else {
err = "Failed to encode JSON as UTF-8 string"
}
} catch {
err = error.localizedDescription
}
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err), callbackId: command.callbackId)
}
}
@objc public func deleteUser(_ command: CDVInvokedUrlCommand) {
if let userId = command.arguments?.compactMap({ ($0 as? [String:String])?["userId"] }).first {
self.loadVerID(command) { verid in
verid.userManagement.deleteUsers([userId]) { error in
if let err = error {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription), callbackId: command.callbackId)
return
}
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "OK")
self.commandDelegate.send(result, callbackId: command.callbackId)
}
}
} else {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Unable to parse userId argument"), callbackId: command.callbackId)
}
}
@objc public func compareFaces(_ command: CDVInvokedUrlCommand) {
if let t1 = command.arguments?.compactMap({ ($0 as? [String:String])?["face1"] }).first?.data(using: .utf8), let t2 = command.arguments?.compactMap({ ($0 as? [String:String])?["face2"] }).first?.data(using: .utf8) {
self.loadVerID(command) { verid in
self.commandDelegate.run {
do {
if let template1 = try JSONDecoder().decode(CodableFace.self, from: t1).recognizable,
let template2 = try JSONDecoder().decode(CodableFace.self, from: t2).recognizable {
let score = try verid.faceRecognition.compareSubjectFaces([template1], toFaces: [template2]).floatValue
DispatchQueue.main.async {
let message: [String:Any] = ["score":score,"authenticationThreshold":verid.faceRecognition.authenticationScoreThreshold.floatValue,"max":verid.faceRecognition.maxAuthenticationScore.floatValue];
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message), callbackId: command.callbackId)
}
} else {
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Unable to parse template1 and/or template2 arguments"), callbackId: command.callbackId)
}
}
} catch {
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: command.callbackId)
}
}
}
}
} else {
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Unable to parse template1 and/or template2 arguments"), callbackId: command.callbackId)
}
}
}
@objc public func detectFaceInImage(_ command: CDVInvokedUrlCommand) {
self.loadVerID(command) { verid in
self.commandDelegate.run(inBackground: {
do {
guard let imageString = command.arguments?.compactMap({ ($0 as? [String:String])?["image"] }).first else {
throw VerIDPluginError.invalidArgument
}
guard imageString.starts(with: "data:image/"), let mimeTypeEndIndex = imageString.firstIndex(of: ";"), let commaIndex = imageString.firstIndex(of: ",") else {
throw VerIDPluginError.invalidArgument
}
let dataIndex = imageString.index(commaIndex, offsetBy: 1)
guard String(imageString[mimeTypeEndIndex..<imageString.index(mimeTypeEndIndex, offsetBy: 7)]) == ";base64" else {
throw VerIDPluginError.invalidArgument
}
guard let data = Data(base64Encoded: String(imageString[dataIndex...])) else {
throw VerIDPluginError.invalidArgument
}
guard let image = UIImage(data: data), let cgImage = image.cgImage else {
throw VerIDPluginError.invalidArgument
}
let orientation: CGImagePropertyOrientation
switch image.imageOrientation {
case .up:
orientation = .up
case .down:
orientation = .down
case .left:
orientation = .left
case .right:
orientation = .right
case .upMirrored:
orientation = .upMirrored
case .downMirrored:
orientation = .downMirrored
case .leftMirrored:
orientation = .leftMirrored
case .rightMirrored:
orientation = .rightMirrored
@unknown default:
orientation = .up
}
let veridImage = VerIDImage(cgImage: cgImage, orientation: orientation)
let faces = try verid.faceDetection.detectFacesInImage(veridImage, limit: 1, options: 0)
guard let recognizableFace = try verid.faceRecognition.createRecognizableFacesFromFaces(faces, inImage: veridImage).first else {
throw VerIDPluginError.faceTemplateExtractionError
}
let encodableFace = CodableFace(face: faces[0], recognizable: recognizableFace)
guard let encodedFace = String(data: try JSONEncoder().encode(encodableFace), encoding: .utf8) else {
throw VerIDPluginError.encodingError
}
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: encodedFace), callbackId: command.callbackId)
}
} catch {
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: command.callbackId)
}
}
})
}
}
// MARK: - VerID Session Delegate
public func session(_ session: VerIDSession, didFinishWithResult result: VerIDSessionResult) {
guard let callbackId = self.veridSessionCallbackId, !callbackId.isEmpty else {
return
}
self.veridSessionCallbackId = nil
self.commandDelegate.run {
var err = "Unknown error"
do {
if let message = String(data: try JSONEncoder().encode(CodableSessionResult(result)), encoding: .utf8) {
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message), callbackId: callbackId)
}
return
} else {
err = "Unabe to encode JSON as UTF-8 string"
}
} catch {
err = error.localizedDescription
}
DispatchQueue.main.async {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err), callbackId: callbackId)
}
}
}
public func sessionWasCanceled(_ session: VerIDSession) {
guard let callbackId = self.veridSessionCallbackId else {
return
}
self.veridSessionCallbackId = nil
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK), callbackId: callbackId)
}
// MARK: - Session helpers
private func createSettings<T: VerIDSessionSettings>(_ args: [Any]?) throws -> T {
guard let string = args?.compactMap({ ($0 as? [String:String])?["settings"] }).first, let data = string.data(using: .utf8) else {
NSLog("Unable to parse settings")
throw VerIDPluginError.parsingError
}
let settings: T = try JSONDecoder().decode(T.self, from: data)
NSLog("Decoded settings %@ from %@", String(describing: T.self), string)
return settings
}
private func defaultSettings<T: VerIDSessionSettings>() -> T {
switch T.self {
case is RegistrationSessionSettings.Type:
return RegistrationSessionSettings(userId: "default") as! T
case is AuthenticationSessionSettings.Type:
return AuthenticationSessionSettings(userId: "default") as! T
case is LivenessDetectionSessionSettings.Type:
return LivenessDetectionSessionSettings() as! T
default:
return VerIDSessionSettings() as! T
}
}
private func startSession<T: VerIDSessionSettings>(command: CDVInvokedUrlCommand, settings: T) {
guard self.veridSessionCallbackId == nil || self.veridSessionCallbackId!.isEmpty else {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR), callbackId: command.callbackId)
return
}
self.loadVerID(command) { verid in
self.veridSessionCallbackId = command.callbackId
let session = VerIDSession(environment: verid, settings: settings)
session.delegate = self
session.start()
}
}
func loadVerID(_ command: CDVInvokedUrlCommand, callback: @escaping (VerID) -> Void) {
if let verid = self.verid {
callback(verid)
return
}
self.veridSessionCallbackId = command.callbackId
let veridFactory: VerIDFactory
if let password = command.arguments?.compactMap({ ($0 as? [String:String])?["password"] }).first {
veridFactory = VerIDFactory(veridPassword: password)
} else {
veridFactory = VerIDFactory()
}
veridFactory.delegate = self
veridFactory.createVerID()
}
public func veridFactory(_ factory: VerIDFactory, didCreateVerID instance: VerID) {
if let callbackId = self.veridSessionCallbackId {
self.veridSessionCallbackId = nil
self.verid = instance
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK), callbackId: callbackId)
}
}
public func veridFactory(_ factory: VerIDFactory, didFailWithError error: Error) {
if let callbackId = self.veridSessionCallbackId {
self.veridSessionCallbackId = nil
self.verid = nil
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription), callbackId: callbackId)
}
}
//Start Methods For Testing
//Cordova action: setTestingMode
@objc public func setTestingMode(_ command: CDVInvokedUrlCommand) {
if let mode: Bool = command.arguments[0] as? Bool {
NSLog("SetTestingMode Called:" + mode.description)
self.TESTING_MODE = mode
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK), callbackId: command.callbackId)
} else {
self.commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "Not or Invalid Argutments provided"), callbackId: command.callbackId)
}
}
//Functions to get Mockup data
private func getAttachmentMockup() -> String {
let faceMockup : String = self.getFaceMockup()
var mockup = "{\"attachments\": [";
mockup += "{\"recognizableFace\": " + faceMockup + ", \"image\": \"TESTING_IMAGE\", \"bearing\": \"STRAIGHT\"}";
mockup += "]}";
return mockup
}
private func getFaceMockup() -> String {
var faceMockup : String = "{\"x\":-8.384888,\"y\":143.6514,\"width\":331.54974,\"height\":414.43723,\"yaw\":-0.07131743,";
faceMockup += "\"pitch\":-6.6307373,\"roll\":-2.5829313,\"quality\":9.658932,";
faceMockup += "\"leftEye\":[101,322.5],\"rightEye\":[213,321],";
faceMockup += "\"data\":\"TESTING_DATA\",";
faceMockup += "\"faceTemplate\":{\"data\":\"FACE_TEMPLATE_TEST_DATA\",\"version\":1}}";
return faceMockup;
}
//End Methods For Testing
}
public enum VerIDPluginError: Int, Error {
case parsingError, invalidArgument, encodingError, faceTemplateExtractionError
}
class CodableSessionResult: Codable {
enum CodingKeys: String, CodingKey {
case attachments, error
}
enum AttachmentCodingKeys: String, CodingKey {
case recognizableFace, bearing, image
}
let original: VerIDSessionResult
init(_ result: VerIDSessionResult) {
self.original = result
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let error = try container.decodeIfPresent(String.self, forKey: .error) {
self.original = VerIDSessionResult(error: NSError(domain: kVerIDErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: error]))
} else {
var attachments: [DetectedFace] = []
var attachmentsContainer = try container.nestedUnkeyedContainer(forKey: .attachments)
while !attachmentsContainer.isAtEnd {
let attachmentContainer = try attachmentsContainer.nestedContainer(keyedBy: AttachmentCodingKeys.self)
let codableFace = try attachmentContainer.decode(CodableFace.self, forKey: .recognizableFace)
let bearing = try attachmentContainer.decode(Bearing.self, forKey: .bearing)
let imageURL: URL?
if let imageString = try attachmentContainer.decodeIfPresent(String.self, forKey: .image) {
let pattern = "^data:(.+?);base64,(.+)$"
let regex = try NSRegularExpression(pattern: pattern, options: [])
let all = NSMakeRange(0, imageString.utf16.count)
guard let result = regex.firstMatch(in: imageString, options: [], range: all), result.numberOfRanges == 3 else {
throw DecodingError.dataCorruptedError(forKey: AttachmentCodingKeys.image, in: attachmentContainer, debugDescription: "Failed to parse image")
}
let data = (imageString as NSString).substring(with: result.range(at: 2))
guard let imageData = Data(base64Encoded: data) else {
throw DecodingError.dataCorruptedError(forKey: AttachmentCodingKeys.image, in: attachmentContainer, debugDescription: "Failed to decode image data")
}
imageURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathExtension("jpg")
try imageData.write(to: imageURL!)
} else {
imageURL = nil
}
let attachment = DetectedFace(face: codableFace.recognizableFace ?? codableFace.face, bearing: bearing, imageURL: imageURL)
attachments.append(attachment)
}
self.original = VerIDSessionResult(attachments: attachments)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var attachmentsContainer = container.nestedUnkeyedContainer(forKey: .attachments)
try self.original.attachments.forEach({
var attachmentContainer = attachmentsContainer.nestedContainer(keyedBy: AttachmentCodingKeys.self)
try attachmentContainer.encode(CodableFace(face: $0.face, recognizable: $0.face as? Recognizable), forKey: .recognizableFace)
try attachmentContainer.encode($0.bearing, forKey: .bearing)
if let imageURL = $0.imageURL, let data = try? Data(contentsOf: imageURL), let image = UIImage(data: data), let jpeg = image.jpegData(compressionQuality: 0.8)?.base64EncodedString() {
try attachmentContainer.encode(String(format: "data:image/jpeg;base64,%@", jpeg), forKey: .image)
}
})
if let error = original.error {
try container.encode(error.localizedDescription, forKey: .error)
}
}
}
class CodableFace: NSObject, Codable {
enum CodingKeys: String, CodingKey {
case data, faceTemplate, height, leftEye, pitch, quality, rightEye, roll, width, x, y, yaw
}
enum FaceTemplateCodingKeys: String, CodingKey {
case data, version
}
let face: Face
let recognizable: Recognizable?
lazy var recognizableFace: RecognizableFace? = {
guard let recognizable = self.recognizable else {
return nil
}
return RecognizableFace(face: self.face, recognitionData: recognizable.recognitionData, version: recognizable.version)
}()
init(face: Face, recognizable: Recognizable?) {
self.face = face
self.recognizable = recognizable
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.face = Face()
self.face.data = try container.decode(Data.self, forKey: .data)
self.face.leftEye = try container.decode(CGPoint.self, forKey: .leftEye)
self.face.rightEye = try container.decode(CGPoint.self, forKey: .rightEye)
self.face.bounds = CGRect(x: try container.decode(CGFloat.self, forKey: .x), y: try container.decode(CGFloat.self, forKey: .y), width: try container.decode(CGFloat.self, forKey: .width), height: try container.decode(CGFloat.self, forKey: .height))
self.face.angle = EulerAngle(yaw: try container.decode(CGFloat.self, forKey: .yaw), pitch: try container.decode(CGFloat.self, forKey: .pitch), roll: try container.decode(CGFloat.self, forKey: .roll))
self.face.quality = try container.decode(CGFloat.self, forKey: .quality)
if container.contains(.faceTemplate) {
let faceTemplateContainer = try container.nestedContainer(keyedBy: FaceTemplateCodingKeys.self, forKey: .faceTemplate)
self.recognizable = RecognitionFace(recognitionData: try faceTemplateContainer.decode(Data.self, forKey: .data))
self.recognizable?.version = try faceTemplateContainer.decode(Int32.self, forKey: .version)
} else {
self.recognizable = nil
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.face.data, forKey: .data)
try container.encode(self.face.leftEye, forKey: .leftEye)
try container.encode(self.face.rightEye, forKey: .rightEye)
try container.encode(self.face.quality, forKey: .quality)
try container.encode(self.face.bounds.minX, forKey: .x)
try container.encode(self.face.bounds.minY, forKey: .y)
try container.encode(self.face.bounds.width, forKey: .width)
try container.encode(self.face.bounds.height, forKey: .height)
try container.encode(self.face.angle.yaw, forKey: .yaw)
try container.encode(self.face.angle.pitch, forKey: .pitch)
try container.encode(self.face.angle.roll, forKey: .roll)
if let recognizable = self.recognizable {
var faceTemplateContainer = container.nestedContainer(keyedBy: FaceTemplateCodingKeys.self, forKey: .faceTemplate)
try faceTemplateContainer.encode(recognizable.recognitionData, forKey: .data)
try faceTemplateContainer.encode(recognizable.version, forKey: .version)
}
}
}
| 51.37045 | 255 | 0.617966 |
def9729bcc944862b0e560da8044442db03211e7 | 3,384 | //
// ENTTView.swift
// ENUUI
//
// Created by ENUUI on 2017/7/13.
// Copyright © 2017年 fuhui. All rights reserved.
//
import UIKit
public typealias ENClosour = ()->Void
fileprivate let TTSCREEN_SIZE = UIScreen.main.bounds
public class ENTTView: UIView {
convenience init(height: CGFloat) {
let rect = CGRect(x: 0, y: -height, width: TTSCREEN_SIZE.width, height: height)
self.init(frame: rect)
setup()
}
fileprivate func setup() {
self.addSubview(backgroudImageView)
self.addSubview(titleLabel)
self.addSubview(indicator)
self.backgroundColor = UIColor.brown
}
var ttHeight: CGFloat {
return self.frame.height
}
var backgroudImage: UIImage? {
didSet {
guard let img = backgroudImage else { return }
backgroudImageView.image = img
backgroudImageView.frame = self.bounds
backgroudImageView.contentMode = .scaleAspectFill
}
}
lazy var backgroudImageView = UIImageView()
var title: String? {
didSet {
setupSubViews()
}
}
lazy var titleLabel: UILabel = {
let lbl = UILabel()
lbl.font = UIFont.systemFont(ofSize: 12.0)
return lbl
}()
lazy var indicator: UIActivityIndicatorView = {
let ind = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
return ind
}()
lazy var cancelButton: UIButton = {
let btn = UIButton()
btn.addTarget(self, action: #selector(clickCancelBtn(sender:)), for: .touchUpInside)
btn.setImage(UIImage.en_imageNamed("close"), for: .normal)
return btn
}()
func clickCancelBtn(sender: UIButton) {
clickCancel?()
}
func showCancel( _ clickCancel: ENClosour?) {
showCancel = true
cancelButton.frame = CGRect(x: TTSCREEN_SIZE.width - 40, y: 0.3 * ttHeight, width: 0.4 * ttHeight, height: 0.4 * ttHeight)
self.addSubview(cancelButton)
self.clickCancel = clickCancel
}
// MARK: - private
fileprivate var clickCancel: ENClosour?
fileprivate var showCancel: Bool = false
fileprivate func setupSubViews() {
titleLabel.text = title
titleLabel.sizeToFit()
var maxX = TTSCREEN_SIZE.width * 0.8
var lblMargin = TTSCREEN_SIZE.width * 0.2
let titleLabelTextH = titleLabel.frame.height
var lblW = titleLabel.frame.width
if showCancel {
maxX = cancelButton.frame.origin.x - 10.0
lblMargin = TTSCREEN_SIZE.width - maxX
}
var lblX = lblMargin
if lblW > TTSCREEN_SIZE.width - 2 * lblMargin {
lblW = TTSCREEN_SIZE.width - 2 * lblMargin
} else {
lblX = (TTSCREEN_SIZE.width - lblW) * 0.5
}
titleLabel.frame = CGRect(x: lblX, y: 0, width: lblW, height: ttHeight)
indicator.frame = CGRect(x: lblX - 10.0 - titleLabelTextH, y: (ttHeight - titleLabelTextH) * 0.5, width: titleLabelTextH, height: titleLabelTextH)
indicator.startAnimating()
cancelButton.frame = CGRect(origin: cancelButton.frame.origin, size: CGSize(width: titleLabelTextH, height: titleLabelTextH))
}
}
| 29.684211 | 154 | 0.603723 |
67cc732d3cf88543e0d9baa8f518ddbae4727ba3 | 4,247 | //
// QRScannerView.swift
// OmiseGO
//
// Created by Mederic Petit on 9/2/2018.
// Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved.
//
import UIKit
class QRScannerView: UIView {
lazy var overlayView: UIView = {
let overlayView = QRScannerOverlayView()
overlayView.backgroundColor = .clear
overlayView.clipsToBounds = true
overlayView.translatesAutoresizingMaskIntoConstraints = false
return overlayView
}()
let cameraView: UIView = {
let cameraView = UIView()
cameraView.clipsToBounds = true
cameraView.translatesAutoresizingMaskIntoConstraints = false
return cameraView
}()
lazy var cancelButton: UIButton = {
let cancelButton = UIButton()
cancelButton.translatesAutoresizingMaskIntoConstraints = false
return cancelButton
}()
var readerPreviewLayer: CALayer!
init(frame: CGRect, readerPreviewLayer: CALayer) {
super.init(frame: frame)
self.readerPreviewLayer = readerPreviewLayer
self.setup()
}
required init?(coder _: NSCoder) {
omiseGOWarn("init(coder:) shouldn't be called direcly, please use the designed init(frame:readerPreviewLayer:) instead")
return nil
}
public override func layoutSubviews() {
super.layoutSubviews()
self.readerPreviewLayer.frame = self.bounds
}
// swiftlint:disable:next function_body_length
func setup() {
self.addSubview(self.cameraView)
self.addSubview(self.overlayView)
self.addSubview(self.cancelButton)
self.cameraView.layer.addSublayer(self.readerPreviewLayer)
self.addConstraint(NSLayoutConstraint(item: self.cancelButton,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 50))
self.addConstraint(NSLayoutConstraint(item: self.cancelButton,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1,
constant: -16))
[.leading, .trailing].forEach({ attribute in
self.addConstraint(NSLayoutConstraint(item: self.cancelButton,
attribute: attribute,
relatedBy: .equal,
toItem: self,
attribute: attribute,
multiplier: 1,
constant: 0))
})
[.left, .top, .right, .bottom].forEach({ attribute in
self.addConstraint(NSLayoutConstraint(item: self.cameraView,
attribute: attribute,
relatedBy: .equal,
toItem: self,
attribute: attribute,
multiplier: 1,
constant: 0))
})
[.left, .top, .right, .bottom].forEach({ attribute in
self.addConstraint(NSLayoutConstraint(item: self.overlayView,
attribute: attribute,
relatedBy: .equal,
toItem: self.cameraView,
attribute: attribute,
multiplier: 1,
constant: 0))
})
}
}
| 42.049505 | 128 | 0.451377 |
e825c0c0ce6bc7fd73049c0ab405c80a553bbf0a | 2,183 | //
// AppDelegate.swift
// Agora-iOS-Voice-Tutorial
//
// Created by GongYuhua on 2017/4/10.
// Copyright © 2017年 Agora. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.446809 | 285 | 0.755383 |
67929b4278538fbfb85b0f411a7e64e3dbe71c46 | 3,978 | import UIKit
class SampleCardFooterView: UIView {
private var label = UILabel()
private var gradientLayer: CAGradientLayer?
init(withTitle title: String?, subtitle: String?) {
super.init(frame: CGRect.zero)
backgroundColor = .clear
layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
layer.cornerRadius = 10
clipsToBounds = true
isOpaque = false
initialize(title: title, subtitle: subtitle)
}
init(withTitle title: String?, subtitle: String?, withColor: UIColor) {
super.init(frame: CGRect.zero)
backgroundColor = .clear
layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
layer.cornerRadius = 10
clipsToBounds = true
isOpaque = false
initialize(title: title, subtitle: subtitle, withColor: withColor)
}
required init?(coder aDecoder: NSCoder) {
return nil
}
private func initialize(title: String?, subtitle: String?) {
let attributedText = NSMutableAttributedString(string: (title ?? "") + "\n", attributes: NSAttributedString.Key.titleAttributes)
if let subtitle = subtitle, subtitle != "" {
attributedText.append(NSMutableAttributedString(string: subtitle, attributes: NSAttributedString.Key.subtitleAttributes))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
paragraphStyle.lineBreakMode = .byTruncatingTail
attributedText.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: attributedText.length))
label.numberOfLines = 2
}
label.attributedText = attributedText
addSubview(label)
}
private func initialize(title: String?, subtitle: String?, withColor: UIColor) {
let attributedText = NSMutableAttributedString(string: (title ?? "") + "\n", attributes: NSAttributedString.Key.titleAttributes)
if let subtitle = subtitle, subtitle != "" {
attributedText.append(NSMutableAttributedString(string: subtitle, attributes: NSAttributedString.Key.subtitleAttributes))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
paragraphStyle.lineBreakMode = .byTruncatingTail
attributedText.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: attributedText.length))
label.numberOfLines = 2
}
label.attributedText = attributedText
label.textColor = withColor
addSubview(label)
}
override func layoutSubviews() {
let padding: CGFloat = 20
label.frame = CGRect(x: padding,
y: bounds.height - label.intrinsicContentSize.height - padding,
width: bounds.width - 2 * padding,
height: label.intrinsicContentSize.height)
}
}
extension NSAttributedString.Key {
static var shadowAttribute: NSShadow = {
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 0, height: 1)
shadow.shadowBlurRadius = 2
shadow.shadowColor = UIColor.black.withAlphaComponent(0.3)
return shadow
}()
static var titleAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: UIFont(name: "ArialRoundedMTBold", size: 24)!,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.shadow: NSAttributedString.Key.shadowAttribute
]
static var subtitleAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: UIFont(name: "Arial", size: 17)!,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.shadow: NSAttributedString.Key.shadowAttribute
]
}
| 41.873684 | 157 | 0.66189 |
d57c27de5473cf5c91bdae2551735c6caa535e93 | 1,854 | //
// DetailViewController.swift
// GitHub_API
//
// Created by Túlio Bazan da Silva on 12/01/16.
// Copyright © 2016 TulioBZ. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
// MARK: - Variables
var repo : Array<Repository>?
@IBOutlet var tableView: UITableView!
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
self.title = repo?.first?.ownerLogin
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - UITableViewDelegate
extension DetailViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {}
}
// MARK: - UITableViewDataSource
extension DetailViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repo?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if let reuseblecell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? UITableViewCell {
//Repository Name and Description
if let description = repo?[indexPath.row].description{
reuseblecell.detailTextLabel?.text = description
}
if let name = repo?[indexPath.row].name,let id = repo?[indexPath.row].id{
reuseblecell.textLabel?.text = "\(name) - ID: \(id)"
}
//Image
reuseblecell.imageView?.image = UIImage(named: "githubPlaceHolder")
cell = reuseblecell
}
return cell
}
}
| 31.423729 | 128 | 0.653722 |
87acc61baee724b842070e7ae28300e05c902118 | 132 | import XCTest
import CodableSaveLoadTests
var tests = [XCTestCaseEntry]()
tests += CodableSaveLoadTests.allTests()
XCTMain(tests)
| 16.5 | 40 | 0.80303 |
755aa73fabbced9f77faaf30fb8c0e3ee31d3881 | 472 | //
// DeviceAndroidCell.swift
// Example
//
// Created by Petr Zvoníček on 22.06.18.
// Copyright © 2018 FUNTASTY Digital, s.r.o. All rights reserved.
//
import UIKit
import CellKit
final class DeviceAndroidCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
}
extension DeviceAndroidCell: CellConfigurable {
func configure(with model: DeviceAndroidCellModel) {
self.nameLabel.text = model.name + " tapped: \(model.numberOfTaps)"
}
}
| 22.47619 | 75 | 0.716102 |
09be5958d9c077f47df817f574b1efad61168039 | 305 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: GPL-3.0
*/
import Foundation
func dispatchInQueueWhenPossible(_ queue: DispatchQueue?, block: @escaping () -> Void ) {
if let queue = queue {
queue.async(execute: block)
} else {
block()
}
}
| 20.333333 | 89 | 0.639344 |
28adc2eebdf67eec013459358af6f1784ceb18f8 | 693 | //
// AppDelegate.swift
// Tutorial2
//
// Created by Su Van Ho on 07/05/2021.
//
import UIKit
import SnapKit
@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
| 28.875 | 179 | 0.760462 |
d9ad56488a141e9c9218cba448d4660ad4698610 | 11,963 | //
// VGSAddressDataFormConfigurationManager.swift
// VGSCheckoutSDK
import Foundation
#if canImport(UIKit)
import UIKit
#endif
/// Encapsulates address form setup with collect.
internal class VGSAddressDataFormConfigurationManager {
internal static func setupAddressForm(with vaultConfiguration: VGSCheckoutCustomConfiguration, vgsCollect: VGSCollect, addressFormView: VGSBillingAddressDetailsSectionView) {
let countryTextField = addressFormView.countryFieldView.countryTextField
let addressLine1TextField = addressFormView.addressLine1FieldView.textField
let addressLine2TextField = addressFormView.addressLine2FieldView.textField
let cityTextField = addressFormView.cityFieldView.textField
let postalCodeTextField = addressFormView.postalCodeFieldView.textField
let countryOptions = vaultConfiguration.billingAddressCountryFieldOptions
let addressLine1Options = vaultConfiguration.billingAddressLine1FieldOptions
let addressLine2Options = vaultConfiguration.billingAddressLine2FieldOptions
let cityOptions = vaultConfiguration.billingAddressCityFieldOptions
let postalCodeOptions = vaultConfiguration.billingAddressPostalCodeFieldOptions
let addressVisibility = vaultConfiguration.formConfiguration.billingAddressVisibility
switch addressVisibility {
case .hidden:
addressFormView.isHidden = true
return
case .visible:
break
}
let countryConfiguration = VGSPickerTextFieldConfiguration(collector: vgsCollect, fieldName: countryOptions.fieldName)
let validCountriesDataSource = VGSCountryPickerDataSource(validCountryISOCodes: countryOptions.validCountries)
countryConfiguration.dataProvider = VGSPickerDataSourceProvider(dataSource: validCountriesDataSource)
countryConfiguration.type = .none
countryConfiguration.isRequiredValidOnly = true
countryTextField.configuration = countryConfiguration
// Force select first row in picker.
countryTextField.selectFirstRow()
let addressLine1Configuration = VGSConfiguration(collector: vgsCollect, fieldName: addressLine1Options.fieldName)
addressLine1Configuration.type = .none
addressLine1Configuration.keyboardType = .default
addressLine1Configuration.isRequiredValidOnly = true
addressLine1Configuration.validationRules = VGSValidationRuleSet(rules: [
VGSValidationRuleLength(min: 1, max: 64, error: VGSValidationErrorType.length.rawValue)
])
addressLine1TextField.configuration = addressLine1Configuration
let addressLine2Configuration = VGSConfiguration(collector: vgsCollect, fieldName: addressLine2Options.fieldName)
addressLine2Configuration.type = .none
addressLine2Configuration.keyboardType = .default
addressLine2Configuration.isRequiredValidOnly = false
addressLine2TextField.placeholder = VGSCheckoutLocalizationUtils.vgsLocalizedString(forKey: "vgs_checkout_address_info_address_line2_hint")
addressFormView.addressLine2FieldView.placeholderView.hintLabel.text = VGSCheckoutLocalizationUtils.vgsLocalizedString(forKey: "vgs_checkout_address_info_address_line2_subtitle")
addressLine2TextField.configuration = addressLine2Configuration
let cityConfiguration = VGSConfiguration(collector: vgsCollect, fieldName: cityOptions.fieldName)
cityConfiguration.type = .none
cityConfiguration.keyboardType = .default
cityConfiguration.isRequiredValidOnly = true
cityConfiguration.validationRules = VGSValidationRuleSet(rules: [
VGSValidationRuleLength(min: 1, max: 64, error: VGSValidationErrorType.length.rawValue)
])
cityTextField.configuration = cityConfiguration
let postalCodeConfiguration = VGSConfiguration(collector: vgsCollect, fieldName: postalCodeOptions.fieldName)
postalCodeConfiguration.type = .none
postalCodeConfiguration.isRequiredValidOnly = true
postalCodeConfiguration.validationRules = VGSValidationRuleSet(rules: [
VGSValidationRuleLength(min: 1, max: 64, error: VGSValidationErrorType.length.rawValue)
])
postalCodeConfiguration.returnKeyType = .done
let firstCountryRawCode = validCountriesDataSource.countries.first?.code ?? "US"
let firstCountryISOCode = VGSCountriesISO(rawValue: firstCountryRawCode) ?? VGSAddressCountriesDataProvider.defaultFirstCountryCode
postalCodeConfiguration.validationRules = VGSValidationRuleSet(rules: VGSPostalCodeValidationRulesFactory.validationRules(for: firstCountryISOCode))
postalCodeTextField.configuration = postalCodeConfiguration
VGSPostalCodeFieldView.updateUI(for: addressFormView.postalCodeFieldView, countryISOCode: firstCountryISOCode)
}
/*
{
name,
number,
exp_month,
exp_year,
cvc,
billing_address: {
name, //require
company,
address1, //require
address2,
city, //require
region, //require (Principal subdivision in ISO 3166-2)
country, //require (Country code in ISO 3166-1 alpha-2)
state,
country,
postal_code, //require
phone,
},
},
*/
/*
name: John Doe
number: 41111111111111
exp_month: 10
exp_year: 2030
cvc: 123,
billing_address:
name: John Doe
company: John Doe Company
address1: 555 Unblock Us St
address2: M13 9PL
city: New York
region: NY
country: US
postal_code: 12301
phone: '+14842634673'
*/
internal static func setupAddressForm(with configuration: VGSCheckoutPayoptBasicConfiguration, vgsCollect: VGSCollect, addressFormView: VGSBillingAddressDetailsSectionView) {
let countryTextField = addressFormView.countryFieldView.countryTextField
let addressLine1TextField = addressFormView.addressLine1FieldView.textField
let addressLine2TextField = addressFormView.addressLine2FieldView.textField
let cityTextField = addressFormView.cityFieldView.textField
let postalCodeTextField = addressFormView.postalCodeFieldView.textField
let addressVisibility = configuration.formConfiguration.billingAddressVisibility
switch addressVisibility {
case .hidden:
addressFormView.isHidden = true
return
case .visible:
break
}
let countryConfiguration = VGSPickerTextFieldConfiguration(collector: vgsCollect, fieldName: "card.billing_address.country")
let countryOptions = configuration.billingAddressCountryFieldOptions
let validCountriesDataSource = VGSCountryPickerDataSource(validCountryISOCodes: countryOptions.validCountries)
countryConfiguration.dataProvider = VGSPickerDataSourceProvider(dataSource: validCountriesDataSource)
countryConfiguration.type = .none
countryConfiguration.isRequiredValidOnly = true
countryTextField.configuration = countryConfiguration
// Force select first row in picker.
countryTextField.selectFirstRow()
let addressLine1Configuration = VGSConfiguration(collector: vgsCollect, fieldName: "card.billing_address.address1")
addressLine1Configuration.type = .none
addressLine1Configuration.keyboardType = .default
addressLine1Configuration.isRequiredValidOnly = true
addressLine1TextField.configuration = addressLine1Configuration
let addressLine2Configuration = VGSConfiguration(collector: vgsCollect, fieldName: "card.billing_address.adddressLine2")
addressLine2Configuration.type = .none
addressLine2Configuration.keyboardType = .default
addressLine2Configuration.isRequiredValidOnly = false
addressLine2TextField.configuration = addressLine2Configuration
let cityConfiguration = VGSConfiguration(collector: vgsCollect, fieldName: "card.billing_address.city")
cityConfiguration.type = .none
cityConfiguration.keyboardType = .default
cityConfiguration.isRequiredValidOnly = true
cityTextField.configuration = cityConfiguration
let postalCodeConfiguration = VGSConfiguration(collector: vgsCollect, fieldName: "card.billing_address.postal_code")
postalCodeConfiguration.type = .none
postalCodeConfiguration.isRequiredValidOnly = true
let firstCountryRawCode = validCountriesDataSource.countries.first?.code ?? "US"
let firstCountryISOCode = VGSCountriesISO(rawValue: firstCountryRawCode) ?? VGSAddressCountriesDataProvider.defaultFirstCountryCode
postalCodeConfiguration.validationRules = VGSValidationRuleSet(rules: VGSPostalCodeValidationRulesFactory.validationRules(for: firstCountryISOCode))
postalCodeTextField.configuration = postalCodeConfiguration
VGSPostalCodeFieldView.updateUI(for: addressFormView.postalCodeFieldView, countryISOCode: firstCountryISOCode)
}
/// Updates postal code field view if needed.
/// - Parameters:
/// - countryISO: `VGSCountriesISO` object, new country ISO.
/// - checkoutConfigurationType: `VGScheckoutConfigurationType` object, payment instrument.
/// - addressFormView: `VGSBillingAddressDetailsSectionView` object, address form view.
/// - vgsCollect: `VGSCollect` object, an instance of VGSColelct.
/// - formValidationHelper: `VGSFormValidationHelper` object, validation helper.
internal static func updatePostalCodeViewIfNeeded(with countryISO: VGSCountriesISO, addressFormView: VGSBillingAddressDetailsSectionView, vgsCollect: VGSCollect, formValidationHelper: VGSFormValidationHelper) {
let postalCodeFieldView = addressFormView.postalCodeFieldView
let postalCodeTextField = addressFormView.postalCodeFieldView.textField
// 1. Unhide/hide postal code field view.
// 2. Register/unregister postal code text field in collect.
// 3. Add/remove postal code field view from validation helper.
if countryISO.hasPostalCode {
postalCodeFieldView.isHiddenInCheckoutStackView = false
vgsCollect.registerTextFields(textField: [postalCodeTextField])
formValidationHelper.fieldViewsManager.appendFieldViews([postalCodeFieldView])
} else {
postalCodeFieldView.isHiddenInCheckoutStackView = true
vgsCollect.unsubscribeTextField(postalCodeTextField)
formValidationHelper.fieldViewsManager.removeFieldView(postalCodeFieldView)
}
}
/*
Update form for counries without address verification support.
internal static func updateAddressForm(with countryISO: VGSCountriesISO, checkoutConfigurationType: VGScheckoutConfigurationType, addressFormView: VGSBillingAddressDetailsSectionView, vgsCollect: VGSCollect, formValidationHelper: VGSFormValidationHelper) {
switch checkoutConfigurationType {
case .vault:
break
case .payoptAddCArd:
// If country does not support Address verification hide all other fields and unregister them from collect.
// Otherwise register and show fields again. Only for payopt flow.
let isAddressVerificationAvailable = VGSBillingAddressUtils.isAddressVerificationAvailable(for: countryISO)
if isAddressVerificationAvailable {
addressFormView.cityAndPostalCodeStackView.isHiddenInCheckoutStackView = false
addressFormView.fieldViews.forEach { fieldView in
let fieldType = fieldView.fieldType
switch fieldType {
case .addressLine1, .addressLine2, .city, .state, .postalCode:
if let view = fieldView as? UIView {
view.isHiddenInCheckoutStackView = false
}
vgsCollect.registerTextFields(textField: [fieldView.textField])
default:
break
}
}
// Add address fields to validation manager again in the correct order.
formValidationHelper.fieldViewsManager.appendFieldViews([addressFormView.addressLine1FieldView, addressFormView.addressLine2FieldView, addressFormView.cityFieldView, addressFormView.postalCodeFieldView])
} else {
addressFormView.cityAndPostalCodeStackView.isHiddenInCheckoutStackView = true
addressFormView.fieldViews.forEach { fieldView in
let fieldType = fieldView.fieldType
switch fieldType {
case .addressLine1, .addressLine2, .city, .state, .postalCode:
if let view = fieldView as? UIView {
view.isHiddenInCheckoutStackView = true
}
formValidationHelper.fieldViewsManager.removeFieldView(fieldView)
vgsCollect.unsubscribeTextField(fieldView.textField)
default:
break
}
}
}
}
}
*/
}
| 42.725 | 257 | 0.805484 |
72a1063b8f22c30482a3cc15993ac566df561b6f | 602 | import Foundation
public typealias DataTaskOutput = (Data?, URLResponse?, Error?)
public typealias DataTaskCompletion = (Data?, URLResponse?, Error?) -> Void
public protocol URLSessionProtocol {
func dataTask(
with urlRequest: URLRequest,
completion: @escaping DataTaskCompletion
) -> URLSessionTaskProtocol
}
extension URLSession: URLSessionProtocol {
public func dataTask(
with urlRequest: URLRequest,
completion: @escaping DataTaskCompletion
) -> URLSessionTaskProtocol {
dataTask(with: urlRequest, completionHandler: completion)
}
}
| 26.173913 | 75 | 0.72093 |
87590f603fedb3eb0646f7458567fe9c0428b475 | 304 | //
// Message.swift
// UniSpace
//
// Created by KiKan Ng on 28/2/2019.
// Copyright © 2019 KiKan Ng. All rights reserved.
//
import Foundation
protocol Message {
var id: Int { get set }
var senderId: Int { get set }
var message: String { get set }
var time: Double { get set }
}
| 16 | 51 | 0.618421 |
1dd96e2c1038ec7861e47450cdb7a5fc26f0cd45 | 399 | //
// ViewController.swift
// AstraDemo
//
// Created by cuong on 3/18/22.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func upgradeToPremiumTapped(_ sender: Any) {
UpgradeToPremiumViewController.show(from: self)
}
}
| 17.347826 | 58 | 0.649123 |
de270c6dc5e6445578a509df904cbc7dd73c08e5 | 291 | //
// Time.swift
// eqMac
//
// Created by Romans Kisils on 30/06/2019.
// Copyright © 2019 Romans Kisils. All rights reserved.
//
import Foundation
class Time {
static var stamp: Int {
get {
return Int(NSDate().timeIntervalSince1970 * 1000)
}
}
}
| 15.315789 | 61 | 0.591065 |
76b63783a52d3f9d53706523ea129fce7654ef58 | 1,743 | //
// EventsHistoryFilePropertiesTableViewController.swift
// AirLockSDK
//
// Created by Gil Fuchs on 27/04/2020.
//
import UIKit
class EventsHistoryFilePropertiesTableViewController: UITableViewController {
let dateFormatter = DateFormatter()
var fileName = ""
var fileInfo: FileInfo?
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.dateFormat = "MM/dd/yyyy h:mm:ss a"
self.title = fileName
fileInfo = EventsHistoryInfo.sharedInstance.getFileInfo(fileName)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let fileInfo = self.fileInfo else {
return
}
if indexPath.row == 0 {
cell.detailTextLabel?.text = formatSize(fileInfo.size)
} else if indexPath.row == 1 {
cell.detailTextLabel?.text = "\(fileInfo.numberOfItems)"
} else if indexPath.row == 2 {
cell.detailTextLabel?.text = formatDate(fileInfo.fromDate)
} else if indexPath.row == 3 {
cell.detailTextLabel?.text = formatDate(fileInfo.toDate)
}
}
func formatSize(_ sizeInBytes: UInt64) -> String {
let sizeInKB: Double = Double(sizeInBytes) / 1000.0
return String(format: "%.2f KB", sizeInKB)
}
func formatDate(_ epocTime: TimeInterval) -> String {
if epocTime == 0 || epocTime == TimeInterval.greatestFiniteMagnitude {
return "n/a"
}
let date = Date(timeIntervalSince1970: epocTime/1000.0)
return dateFormatter.string(from:date)
}
}
| 26.815385 | 121 | 0.704532 |
cc37084aab65507e58f8c9b12314a1e9f45974ad | 4,192 | //
// NSError+Stripe.swift
// Stripe
//
// Created by Brian Dorfman on 8/4/17.
// Copyright © 2017 Stripe, Inc. All rights reserved.
//
import Foundation
extension NSError {
@objc @_spi(STP) public class func stp_genericConnectionError() -> NSError {
let userInfo = [
NSLocalizedDescriptionKey: self.stp_unexpectedErrorMessage(),
STPError.errorMessageKey: "There was an error connecting to Stripe.",
]
return NSError(
domain: STPError.stripeDomain, code: STPErrorCode.connectionError.rawValue,
userInfo: userInfo
)
}
@objc @_spi(STP) public class func stp_genericFailedToParseResponseError() -> NSError {
let userInfo = [
NSLocalizedDescriptionKey: self.stp_unexpectedErrorMessage(),
STPError.errorMessageKey:
"The response from Stripe failed to get parsed into valid JSON.",
]
return NSError(
domain: STPError.stripeDomain, code: STPErrorCode.apiError.rawValue, userInfo: userInfo)
}
@objc @_spi(STP) public class func stp_ephemeralKeyDecodingError() -> NSError {
let userInfo = [
NSLocalizedDescriptionKey: self.stp_unexpectedErrorMessage(),
STPError.errorMessageKey:
"Failed to decode the ephemeral key. Make sure your backend is sending the unmodified JSON of the ephemeral key to your app.",
]
return NSError(
domain: STPError.stripeDomain, code: STPErrorCode.ephemeralKeyDecodingError.rawValue,
userInfo: userInfo)
}
@objc @_spi(STP) public class func stp_clientSecretError() -> NSError {
let userInfo = [
NSLocalizedDescriptionKey: self.stp_unexpectedErrorMessage(),
STPError.errorMessageKey:
"The `secret` format does not match expected client secret formatting.",
]
return NSError(
domain: STPError.stripeDomain, code: STPErrorCode.invalidRequestError.rawValue,
userInfo: userInfo)
}
// TODO(davide): We'll want to move these into StripePayments, once it exists.
// MARK: Strings
@objc class func stp_cardErrorInvalidNumberUserMessage() -> String {
return STPLocalizedString(
"Your card's number is invalid", "Error when the card number is not valid")
}
@objc class func stp_cardInvalidCVCUserMessage() -> String {
return STPLocalizedString(
"Your card's security code is invalid", "Error when the card's CVC is not valid")
}
@objc class func stp_cardErrorInvalidExpMonthUserMessage() -> String {
return STPLocalizedString(
"Your card's expiration month is invalid",
"Error when the card's expiration month is not valid")
}
@objc class func stp_cardErrorInvalidExpYearUserMessage() -> String {
return STPLocalizedString(
"Your card's expiration year is invalid",
"Error when the card's expiration year is not valid"
)
}
@objc class func stp_cardErrorExpiredCardUserMessage() -> String {
return STPLocalizedString(
"Your card has expired", "Error when the card has already expired")
}
@objc class func stp_cardErrorDeclinedUserMessage() -> String {
return STPLocalizedString(
"Your card was declined", "Error when the card was declined by the credit card networks"
)
}
@objc class func stp_cardErrorProcessingErrorUserMessage() -> String {
return STPLocalizedString(
"There was an error processing your card -- try again in a few seconds",
"Error when there is a problem processing the credit card")
}
static var stp_invalidOwnerName: String {
return STPLocalizedString(
"Your name is invalid.",
"Error when customer's name is invalid"
)
}
@_spi(STP) public static var stp_invalidBankAccountIban: String {
return STPLocalizedString(
"The IBAN you entered is invalid.",
"An error message displayed when the customer's iban is invalid."
)
}
}
| 37.428571 | 142 | 0.647662 |
bfed65c05deaa2540f056ba9166b6a36bf1ed35a | 2,635 | //
// ImplementationListViewController.swift
// MVVMAnimation
//
// Created by Florian LUDOT on 7/11/19.
// Copyright © 2019 Florian LUDOT. All rights reserved.
//
import UIKit
class ImplementationListViewController: UITableViewController {
let items = [
"Static views",
"Reusable views + Caching",
"Reusable views + Diffing",
]
init() {
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Implementations"
navigationController?.navigationBar.prefersLargeTitles = true
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
}
extension ImplementationListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
}
extension ImplementationListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.setSelected(false, animated: true)
let title = items[indexPath.row]
let pushedViewController: UIViewController
switch indexPath.row {
case 0:
let interactor = StaticInteractor()
pushedViewController = ImplementationStaticViewsViewController(title: title,
interactor: interactor)
case 1:
let interactor = CachingInteractor()
pushedViewController = ImplementationCachingCollectionViewController(title: title,
interactor: interactor)
case 2:
let interactor = DiffingInteractor()
pushedViewController = ImplementationDiffingCollectionViewController(title: title,
interactor: interactor)
default:
preconditionFailure("Out of bounds")
}
navigationController?.pushViewController(pushedViewController, animated: true)
}
}
| 35.133333 | 109 | 0.626186 |
2956b787529dfb0332486a6abbbc3e012905a2db | 13,336 | import Foundation
@objc(PhotoLibrary) class PhotoLibrary : CDVPlugin {
lazy var concurrentQueue: DispatchQueue = DispatchQueue(label: "photo-library.queue.plugin", qos: DispatchQoS.utility, attributes: [.concurrent])
override func pluginInitialize() {
// Do not call PhotoLibraryService here, as it will cause permission prompt to appear on app start.
URLProtocol.registerClass(PhotoLibraryProtocol.self)
}
override func onMemoryWarning() {
// self.service.stopCaching()
NSLog("-- MEMORY WARNING --")
}
// Will sort by creation date
@objc(getLibrary:) func getLibrary(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let options = command.arguments[0] as! NSDictionary
let thumbnailWidth = options["thumbnailWidth"] as! Int
let thumbnailHeight = options["thumbnailHeight"] as! Int
let itemsInChunk = options["itemsInChunk"] as! Int
let chunkTimeSec = options["chunkTimeSec"] as! Double
let useOriginalFileNames = options["useOriginalFileNames"] as! Bool
let includeAlbumData = options["includeAlbumData"] as! Bool
let includeCloudData = options["includeCloudData"] as! Bool
let includeVideos = options["includeVideos"] as! Bool
let includeImages = options["includeImages"] as! Bool
let maxItems = options["maxItems"] as! Int
func createResult (library: [NSDictionary], chunkNum: Int, isLastChunk: Bool) -> [String: AnyObject] {
let result: NSDictionary = [
"chunkNum": chunkNum,
"isLastChunk": isLastChunk,
"library": library
]
return result as! [String: AnyObject]
}
let getLibraryOptions = PhotoLibraryGetLibraryOptions(thumbnailWidth: thumbnailWidth,
thumbnailHeight: thumbnailHeight,
itemsInChunk: itemsInChunk,
chunkTimeSec: chunkTimeSec,
useOriginalFileNames: useOriginalFileNames,
includeImages: includeImages,
includeAlbumData: includeAlbumData,
includeCloudData: includeCloudData,
includeVideos: includeVideos,
maxItems: maxItems)
service.getLibrary(getLibraryOptions,
completion: { (library, chunkNum, isLastChunk) in
let result = createResult(library: library, chunkNum: chunkNum, isLastChunk: isLastChunk)
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result)
pluginResult!.setKeepCallbackAs(!isLastChunk)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
}
)
}
}
@objc(getAlbums:) func getAlbums(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let albums = service.getAlbums()
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: albums)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
}
}
@objc(getPhotosFromAlbum:) func getPhotosFromAlbum(_ command: CDVInvokedUrlCommand) {
print("C getPhotosFromAlbum 0");
concurrentQueue.async {
print("C getPhotosFromAlbum 1");
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
print("C getPhotosFromAlbum 2");
let service = PhotoLibraryService.instance
let albumTitle = command.arguments[0] as! String
let photos = service.getPhotosFromAlbum(albumTitle);
print("C getPhotosFromAlbum 3");
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: photos)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
}
}
@objc(isAuthorized:) func isAuthorized(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: PhotoLibraryService.hasPermission())
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
}
}
@objc(getThumbnail:) func getThumbnail(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let photoId = command.arguments[0] as! String
let options = command.arguments[1] as! NSDictionary
let thumbnailWidth = options["thumbnailWidth"] as! Int
let thumbnailHeight = options["thumbnailHeight"] as! Int
let quality = options["quality"] as! Float
service.getThumbnail(photoId, thumbnailWidth: thumbnailWidth, thumbnailHeight: thumbnailHeight, quality: quality) { (imageData) in
let pluginResult = imageData != nil ?
CDVPluginResult(
status: CDVCommandStatus_OK,
messageAsMultipart: [imageData!.data, imageData!.mimeType])
:
CDVPluginResult(
status: CDVCommandStatus_ERROR,
messageAs: "Could not fetch the thumbnail")
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}
}
}
@objc(getPhoto:) func getPhoto(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let photoId = command.arguments[0] as! String
service.getPhoto(photoId) { (imageData) in
let pluginResult = imageData != nil ?
CDVPluginResult(
status: CDVCommandStatus_OK,
messageAsMultipart: [imageData!.data, imageData!.mimeType])
:
CDVPluginResult(
status: CDVCommandStatus_ERROR,
messageAs: "Could not fetch the image")
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}
}
}
@objc(getLibraryItem:) func getLibraryItem(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let info = command.arguments[0] as! NSDictionary
let mime_type = info["mimeType"] as! String
service.getLibraryItem(info["id"] as! String, mimeType: mime_type, completion: { (base64: String?) in
self.returnPictureData(callbackId: command.callbackId, base64: base64, mimeType: mime_type)
})
}
}
func returnPictureData(callbackId : String, base64: String?, mimeType: String?) {
let pluginResult = (base64 != nil) ?
CDVPluginResult(
status: CDVCommandStatus_OK,
messageAsMultipart: [base64!, mimeType!])
:
CDVPluginResult(
status: CDVCommandStatus_ERROR,
messageAs: "Could not fetch the image")
self.commandDelegate!.send(pluginResult, callbackId: callbackId)
}
@objc(stopCaching:) func stopCaching(_ command: CDVInvokedUrlCommand) {
let service = PhotoLibraryService.instance
service.stopCaching()
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}
@objc(requestAuthorization:) func requestAuthorization(_ command: CDVInvokedUrlCommand) {
let service = PhotoLibraryService.instance
service.requestAuthorization({
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}, failure: { (err) in
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
})
}
@objc(saveImage:) func saveImage(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let url = command.arguments[0] as! String
let album = command.arguments[1] as! String
service.saveImage(url, album: album) { (libraryItem: NSDictionary?, error: String?) in
if (error != nil) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
} else {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: libraryItem as! [String: AnyObject]?)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}
}
}
}
@objc(saveVideo:) func saveVideo(_ command: CDVInvokedUrlCommand) {
concurrentQueue.async {
if !PhotoLibraryService.hasPermission() {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
return
}
let service = PhotoLibraryService.instance
let url = command.arguments[0] as! String
let album = command.arguments[1] as! String
service.saveVideo(url, album: album) { (assetId: String?, error: String?) in
if (error != nil) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId)
} else {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: assetId)
self.commandDelegate!.send(pluginResult, callbackId: command.callbackId )
}
}
}
}
}
| 42.471338 | 150 | 0.587058 |
795997865f71c9925b8eaf023e4411715f2fa73c | 16,667 | // PagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: Protocols
public protocol IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
}
public protocol PagerTabStripDelegate: class {
func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int)
}
public protocol PagerTabStripIsProgressiveDelegate: PagerTabStripDelegate {
func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
}
public protocol PagerTabStripDataSource: class {
func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
}
// MARK: PagerTabStripViewController
open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak public var containerView: UIScrollView!
open weak var delegate: PagerTabStripDelegate?
open weak var datasource: PagerTabStripDataSource?
open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true)
open private(set) var viewControllers = [UIViewController]()
open private(set) var currentIndex = 0
open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible
open var pageWidth: CGFloat {
return containerView.bounds.width
}
open var scrollPercentage: CGFloat {
if swipeDirection != .right {
let module = fmod(containerView.contentOffset.x, pageWidth)
return module == 0.0 ? 1.0 : module / pageWidth
}
return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth
}
open var swipeDirection: SwipeDirection {
if containerView.contentOffset.x > lastContentOffset {
return .left
} else if containerView.contentOffset.x < lastContentOffset {
return .right
}
return .none
}
override open func viewDidLoad() {
super.viewDidLoad()
let conteinerViewAux = containerView ?? {
let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return containerView
}()
containerView = conteinerViewAux
if containerView.superview == nil {
view.addSubview(containerView)
}
containerView.bounces = true
containerView.alwaysBounceHorizontal = true
containerView.alwaysBounceVertical = false
containerView.scrollsToTop = false
containerView.delegate = self
containerView.isScrollEnabled = false
containerView.showsVerticalScrollIndicator = false
containerView.showsHorizontalScrollIndicator = false
containerView.isPagingEnabled = true
reloadViewControllers()
let childController = viewControllers[currentIndex]
addChild(childController)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
containerView.addSubview(childController.view)
childController.didMove(toParent: self)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isViewAppearing = true
children.forEach { $0.beginAppearanceTransition(true, animated: animated) }
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
lastSize = containerView.bounds.size
updateIfNeeded()
let needToUpdateCurrentChild = preCurrentIndex != currentIndex
if needToUpdateCurrentChild {
moveToViewController(at: preCurrentIndex)
}
isViewAppearing = false
children.forEach { $0.endAppearanceTransition() }
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
children.forEach { $0.beginAppearanceTransition(false, animated: animated) }
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
children.forEach { $0.endAppearanceTransition() }
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateIfNeeded()
}
open override var shouldAutomaticallyForwardAppearanceMethods: Bool {
return false
}
open func moveToViewController(at index: Int, animated: Bool = true) {
guard isViewLoaded && view.window != nil && currentIndex != index else {
preCurrentIndex = index
return
}
if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 {
var tmpViewControllers = viewControllers
let currentChildVC = viewControllers[currentIndex]
let fromIndex = currentIndex < index ? index - 1 : index + 1
let fromChildVC = viewControllers[fromIndex]
tmpViewControllers[currentIndex] = fromChildVC
tmpViewControllers[fromIndex] = currentChildVC
pagerTabStripChildViewControllersForScrolling = tmpViewControllers
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false)
(navigationController?.view ?? view).isUserInteractionEnabled = !animated
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true)
} else {
(navigationController?.view ?? view).isUserInteractionEnabled = !animated
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated)
}
}
open func moveTo(viewController: UIViewController, animated: Bool = true) {
moveToViewController(at: viewControllers.firstIndex(of: viewController)!, animated: animated)
}
// MARK: - PagerTabStripDataSource
open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method")
return []
}
// MARK: - Helpers
open func updateIfNeeded() {
if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) {
updateContent()
}
}
open func canMoveTo(index: Int) -> Bool {
return currentIndex != index && viewControllers.count > index
}
open func pageOffsetForChild(at index: Int) -> CGFloat {
return CGFloat(index) * containerView.bounds.width
}
open func offsetForChild(at index: Int) -> CGFloat {
return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5)
}
open func offsetForChild(viewController: UIViewController) throws -> CGFloat {
guard let index = viewControllers.firstIndex(of: viewController) else {
throw PagerTabStripError.viewControllerOutOfBounds
}
return offsetForChild(at: index)
}
open func pageFor(contentOffset: CGFloat) -> Int {
let result = virtualPageFor(contentOffset: contentOffset)
return pageFor(virtualPage: result)
}
open func virtualPageFor(contentOffset: CGFloat) -> Int {
return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1
}
open func pageFor(virtualPage: Int) -> Int {
if virtualPage < 0 {
return 0
}
if virtualPage > viewControllers.count - 1 {
return viewControllers.count - 1
}
return virtualPage
}
open func updateContent() {
if lastSize.width != containerView.bounds.size.width {
lastSize = containerView.bounds.size
containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
}
lastSize = containerView.bounds.size
let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers
containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height)
for (index, childController) in pagerViewControllers.enumerated() {
let pageOffsetForChild = self.pageOffsetForChild(at: index)
if abs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width {
if childController.parent != nil {
childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
} else {
childController.beginAppearanceTransition(true, animated: false)
addChild(childController)
childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
containerView.addSubview(childController.view)
childController.didMove(toParent: self)
childController.endAppearanceTransition()
}
} else {
if childController.parent != nil {
childController.beginAppearanceTransition(false, animated: false)
childController.willMove(toParent: nil)
childController.view.removeFromSuperview()
childController.removeFromParent()
childController.endAppearanceTransition()
}
}
}
let oldCurrentIndex = currentIndex
let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x)
let newCurrentIndex = pageFor(virtualPage: virtualPage)
currentIndex = newCurrentIndex
preCurrentIndex = currentIndex
let changeCurrentIndex = newCurrentIndex != oldCurrentIndex
if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator {
let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage)
progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex)
} else {
delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex)
}
}
open func reloadPagerTabStripView() {
guard isViewLoaded else { return }
for childController in viewControllers where childController.parent != nil {
childController.beginAppearanceTransition(false, animated: false)
childController.willMove(toParent: nil)
childController.view.removeFromSuperview()
childController.removeFromParent()
childController.endAppearanceTransition()
}
reloadViewControllers()
containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height)
if currentIndex >= viewControllers.count {
currentIndex = viewControllers.count - 1
}
preCurrentIndex = currentIndex
containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
updateContent()
}
// MARK: - UIScrollViewDelegate
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if containerView == scrollView {
updateContent()
lastContentOffset = scrollView.contentOffset.x
}
}
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if containerView == scrollView {
lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x)
}
}
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if containerView == scrollView {
pagerTabStripChildViewControllersForScrolling = nil
(navigationController?.view ?? view).isUserInteractionEnabled = true
updateContent()
}
}
// MARK: - Orientation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
isViewRotating = true
pageBeforeRotate = currentIndex
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
guard let me = self else { return }
me.isViewRotating = false
me.currentIndex = me.pageBeforeRotate
me.preCurrentIndex = me.currentIndex
me.updateIfNeeded()
}
}
// MARK: Private
private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) {
let count = viewControllers.count
var fromIndex = currentIndex
var toIndex = currentIndex
let direction = swipeDirection
if direction == .left {
if virtualPage > count - 1 {
fromIndex = count - 1
toIndex = count
} else {
if self.scrollPercentage >= 0.5 {
fromIndex = max(toIndex - 1, 0)
} else {
toIndex = fromIndex + 1
}
}
} else if direction == .right {
if virtualPage < 0 {
fromIndex = 0
toIndex = -1
} else {
if self.scrollPercentage > 0.5 {
fromIndex = min(toIndex + 1, count - 1)
} else {
toIndex = fromIndex - 1
}
}
}
let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage)
return (fromIndex, toIndex, scrollPercentage)
}
private func reloadViewControllers() {
guard let dataSource = datasource else {
fatalError("dataSource must not be nil")
}
viewControllers = dataSource.viewControllers(for: self)
// viewControllers
guard !viewControllers.isEmpty else {
fatalError("viewControllers(for:) should provide at least one child view controller")
}
viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }}
}
private var pagerTabStripChildViewControllersForScrolling: [UIViewController]?
private var lastPageNumber = 0
private var lastContentOffset: CGFloat = 0.0
private var pageBeforeRotate = 0
private var lastSize = CGSize(width: 0, height: 0)
internal var isViewRotating = false
internal var isViewAppearing = false
}
| 41.876884 | 213 | 0.673727 |
5bcd7c59244d4c6455836460a11d4b4cc51b1d8f | 291 | import Foundation
import SwiftSyntax
import IndexStoreDB
public protocol Rule {}
public protocol SourceCollectRule: Rule {
func skip(_ node: Syntax, location: SourceLocation) -> Bool
}
public protocol AnalyzeRule: Rule {
func analyze(_ source: SourceDetail) -> Bool
}
| 16.166667 | 63 | 0.728522 |
160cb93c88c09239df20df784a034a0bec056dca | 2,161 | //
// DSFlexibleHeader.swift
// Pods
//
// Created by Andrei Erusaev on 8/23/17.
//
//
open
class DSFlexibleHeader: UIView {
open
var maxHeight: CGFloat {
100
}
open
var minHeight: CGFloat {
0
}
var scrollOffset: CGPoint = .zero {
didSet {
guard let beginScrollOffset = beginScrollOffset else { return }
let diffPoint = CGPoint(x: beginScrollOffset.x - scrollOffset.x, y: beginScrollOffset.y - scrollOffset.y)
let newConstant = beginHeightHeader + diffPoint.y
if newConstant > maxHeight {
heightConstraint?.constant = maxHeight
} else if newConstant < minHeight {
heightConstraint?.constant = minHeight
} else {
heightConstraint?.constant = newConstant
}
}
}
open
var heightConstraint: NSLayoutConstraint?
private
var beginScrollOffset: CGPoint?
private
var beginHeightHeader: CGFloat = 0
func willBeginDragging(scrollOffset: CGPoint) {
beginScrollOffset = scrollOffset
beginHeightHeader = heightConstraint?.constant ?? 0
}
func didEndDragging(velocity: CGPoint) {
beginScrollOffset = nil
layoutIfNeeded()
var newConstant = heightConstraint?.constant ?? 0
if velocity.y < 0 {
newConstant = minHeight
} else if velocity.y > 0 {
newConstant = maxHeight
}
heightConstraint?.constant = newConstant
UIView.animate(withDuration: 0.2) { [weak self] in
self?.superview?.layoutIfNeeded()
}
}
public
init() {
super.init(frame: .zero)
setup()
}
public override
init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required
init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private
func setup() {
heightConstraint = heightAnchor.constraint(equalToConstant: maxHeight)
heightConstraint?.priority = .required
heightConstraint?.isActive = true
}
}
| 23.747253 | 117 | 0.591856 |
9cb71387af75b7e31d2ee86c42b4fd4afa2de07b | 709 | //
// OVHVPS+CoreDataProperties.swift
// OVHAPIWrapper-Example-watchOS
//
// Created by Cyril on 06/12/2016.
// Copyright © 2016 OVH SAS. All rights reserved.
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
extension OVHVPS {
@nonobjc public class func fetchRequest() -> NSFetchRequest<OVHVPS> {
return NSFetchRequest<OVHVPS>(entityName: "OVHVPS");
}
@NSManaged public var displayName: String?
@NSManaged public var name: String?
@NSManaged public var offerType: String?
@NSManaged public var state: String?
@NSManaged public var waitingTask: NSNumber?
@NSManaged public var currentTask: OVHVPSTask?
}
| 25.321429 | 73 | 0.720733 |
d6eac6a38fe45f1a487c3c96e6f16bd524b37c70 | 4,443 | // Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSImage
internal typealias AssetColorTypeAlias = NSColor
internal typealias Image = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
internal typealias AssetColorTypeAlias = UIColor
internal typealias Image = UIImage
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
internal struct ColorAsset {
internal fileprivate(set) var name: String
#if swift(>=3.2)
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
internal var color: AssetColorTypeAlias {
return AssetColorTypeAlias(asset: self)
}
#endif
}
internal extension AssetColorTypeAlias {
#if swift(>=3.2)
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
convenience init!(asset: ColorAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: asset.name, bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
#endif
}
@available(*, deprecated, renamed: "ImageAsset")
internal typealias AssetType = ImageAsset
internal struct ImageAsset {
internal fileprivate(set) var name: String
internal var image: Image {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
let image = bundle.image(forResource: name)
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else { fatalError("Unable to load image named \(name).") }
return result
}
}
internal extension Image {
@available(iOS 1.0, tvOS 1.0, watchOS 1.0, *)
@available(OSX, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init!(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = Bundle(for: BundleToken.self)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX) || os(watchOS)
self.init(named: asset.name)
#endif
}
}
// MARK: Assets
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Colors {
internal enum _24Vision {
internal static let background = ColorAsset(name: "24Vision/Background")
internal static let primary = ColorAsset(name: "24Vision/Primary")
}
internal static let orange = ImageAsset(name: "Orange")
internal enum Vengo {
internal static let primary = ColorAsset(name: "Vengo/Primary")
internal static let tint = ColorAsset(name: "Vengo/Tint")
}
// swiftlint:disable trailing_comma
internal static let allColors: [ColorAsset] = [
_24Vision.background,
_24Vision.primary,
Vengo.primary,
Vengo.tint,
]
internal static let allImages: [ImageAsset] = [
orange,
]
// swiftlint:enable trailing_comma
@available(*, deprecated, renamed: "allImages")
internal static let allValues: [AssetType] = allImages
}
internal enum Images {
internal enum Exotic {
internal static let banana = ImageAsset(name: "Exotic/Banana")
internal static let mango = ImageAsset(name: "Exotic/Mango")
}
internal enum Round {
internal static let apricot = ImageAsset(name: "Round/Apricot")
internal enum Red {
internal static let apple = ImageAsset(name: "Round/Apple")
internal enum Double {
internal static let cherry = ImageAsset(name: "Round/Double/Cherry")
}
internal static let tomato = ImageAsset(name: "Round/Tomato")
}
}
internal static let `private` = ImageAsset(name: "private")
// swiftlint:disable trailing_comma
internal static let allColors: [ColorAsset] = [
]
internal static let allImages: [ImageAsset] = [
Exotic.banana,
Exotic.mango,
Round.apricot,
Round.Red.apple,
Round.Red.Double.cherry,
Round.Red.tomato,
`private`,
]
// swiftlint:enable trailing_comma
@available(*, deprecated, renamed: "allImages")
internal static let allValues: [AssetType] = allImages
}
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
private final class BundleToken {}
| 31.510638 | 93 | 0.686698 |
ccc553bb9d0573956748a03592c456bdaae12efc | 1,243 | import Foundation
final class PXAdditionalInfoConfiguration: NSObject, Codable {
var flowId: String?
init(flowId: String?) {
self.flowId = flowId
}
enum PXAdditionalInfoConfigurationKeys: String, CodingKey {
case flowId = "flow_id"
}
required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PXAdditionalInfoConfigurationKeys.self)
let flowId: String? = try container.decodeIfPresent(String.self, forKey: .flowId)
self.init(flowId: flowId)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: PXAdditionalInfoConfigurationKeys.self)
try container.encodeIfPresent(flowId, forKey: .flowId)
}
func toJSONString() throws -> String? {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)
}
func toJSON() throws -> Data {
let encoder = JSONEncoder()
return try encoder.encode(self)
}
class func fromJSON(data: Data) throws -> PXAdditionalInfoConfiguration {
return try JSONDecoder().decode(PXAdditionalInfoConfiguration.self, from: data)
}
}
| 31.075 | 94 | 0.678198 |
22cdf53ec396f2527b1e6d380db7285be92acda0 | 2,427 | //
// MainTableViewController.swift
// ProcessingKitExample
//
// Created by AtsuyaSato on 2017/08/16.
// Copyright © 2017年 Atsuya Sato. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath {
case IndexPath(row: 0, section: 0): //Text
transition(viewController: TextSampleViewController.create())
return
case IndexPath(row: 1, section: 0): //Rect
transition(viewController: RectSampleViewController.create())
return
case IndexPath(row: 2, section: 0): //Ellipse
transition(viewController: EllipseSampleViewController.create())
return
case IndexPath(row: 3, section: 0): //Arc
transition(viewController: ArcSampleViewController.create())
return
case IndexPath(row: 4, section: 0): //Triangle
transition(viewController: TriangleSampleViewController.create())
return
case IndexPath(row: 5, section: 0): //Quad
transition(viewController: QuadSampleViewController.create())
return
case IndexPath(row: 6, section: 0): //Curve
transition(viewController: CurveSampleViewController.create())
return
case IndexPath(row: 7, section: 0): //Image
transition(viewController: ImageSampleViewController.create())
return
case IndexPath(row: 0, section: 1): //Simple Tap
transition(viewController: TouchSampleViewController.create())
case IndexPath(row: 0, section: 2): //Particles
transition(viewController: ParticlesSampleViewController.create())
case IndexPath(row: 1, section: 2): //Clock Sample
transition(viewController: ClockSampleViewController.create())
return
default:
return
}
}
func transition(viewController: UIViewController){
self.navigationController?.pushViewController(viewController, animated: true)
}
}
| 37.921875 | 92 | 0.652246 |
5d84d5f3edb5ed222218d65e520305525182eca7 | 4,849 | //
// RestAPI.swift
// KocomojoKit
//
// Created by Antonio Bello on 1/26/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
class RestAPI {
// Singleton
private struct Static {
static var instance: RestAPI = RestAPI()
}
class var instance: RestAPI { return Static.instance }
private lazy var _queue: NSOperationQueue = NSOperationQueue()
private init() {}
}
/// MARK: - Interface
extension RestAPI {
func getCountries(completion: ApiResult<CountriesResponse> -> ()) {
let (verb, url) = ApiUrl.absoluteUrl(ApiUrl.Countries)
invokeUrl(verb: verb, url: url, callback: completion)
}
func getPlans(completion: ApiResult<PlansResponse> -> ()) {
let (verb, url) = ApiUrl.absoluteUrl(ApiUrl.Plans)
invokeUrl(verb: verb, url: url, callback: completion)
}
}
private extension RestAPI {
func invokeUrl<T where T: JsonDecodable, T: ApiResponseData>(# verb: HttpVerb, url: String, headers:[String:String] = [:], jsonDict: JsonDictionary? = nil, callback: ApiResult<T> -> ()) {
var response: NSURLResponse
var error: NSError?
var requestHeaders = headers
// Transform the json dictionary into the string and data counterparts
let (jsonString, jsonData) = encodeFromJsonDict(jsonDict)
// If the verb is GET and there's json data, encode the data in the query string
let actualUrl = { () -> String in
switch (verb) {
case .GET where jsonString != nil:
return "\(url)?\(jsonString!.utf8)"
default:
return url
}
}()
let requestUrl = NSURL(string:actualUrl)
let request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = requestUrl
request.HTTPMethod = verb.rawValue
// Set the request body for PUT, POST and DELETE if json data is provided
if let json = jsonString {
if verb != .GET {
request.setValue("application/json; charset=utf-8", forHTTPHeaderField:"Content-Type")
request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
}
}
self.fillHeaders(&requestHeaders)
for (key, value) in requestHeaders {
request.addValue(value, forHTTPHeaderField: key)
}
// Send the request out
NSURLConnection.sendAsynchronousRequest(request, queue: _queue) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> () in
var result: ApiResult<T>
if let error = error {
result = .InvocationError(error)
} else {
var error: NSError?
let dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as? [String : AnyObject]
if let error = error {
result = .InvocationError(error)
} else {
if let dict = dict {
if let entity = ApiResponse<T>.decode(dict) {
if let data = entity.data {
result = .Value(data)
} else {
result = .InvocationError(NSError(domain: "kocomojo.kit", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"]))
}
} else {
result = .InvocationError(NSError(domain: "kocomojo.kit", code: -2, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON", "data": dict]))
}
} else {
result = .InvocationError(NSError(domain: "kocomojo.kit", code: -3, userInfo: [NSLocalizedDescriptionKey: "Empty response"]))
}
}
}
callback(result)
}
}
private func fillHeaders(inout headers: [String:String]) {
// Set common headers, if any
}
private func encodeFromJsonDict(jsonDict: JsonDictionary?) -> (String?, NSData?) {
var jsonString: String?
var jsonData: NSData?
var error: NSError?
if let jsonDict = jsonDict {
jsonData = NSJSONSerialization.dataWithJSONObject(jsonDict, options: nil, error: &error)
switch (jsonData, error) {
case (.Some(let jsonData), .None):
jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
break
case (_, let .Some(error)):
break
case (.None, .None):
break;
}
}
return (jsonString, jsonData)
}
} | 37.589147 | 191 | 0.547948 |
22c2c3962b8913d14d74882ba51cafbe1eb29d34 | 4,261 | //
// PersonsModel.swift
// DataFlow
//
// Created by Sarah Reichelt on 14/09/2019.
// Copyright © 2019 TrozWare. All rights reserved.
//
import Foundation
class PersonListModel: ObservableObject {
// Main list view model
// ObservableObject so that updates are detected
@Published var ids: [UUID] = []
@Published var persons: [UUID : PersonViewModel] = [:]
func fetchData() {
// avoid too many calls to the API
if ids.count > 0 { return }
let address = "https://next.json-generator.com/api/json/get/VyQroKB8P?indent=2"
guard let url = URL(string: address) else {
fatalError("Bad data URL!")
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data, error == nil else {
print("Error fetching data")
return
}
do {
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601
let dataArray = try jsonDecoder.decode([PersonModel].self, from: data)
DispatchQueue.main.async {
let personViewModels = dataArray.map { PersonViewModel(with: $0) }.sorted() {
$0.last + $0.first < $1.last + $1.first
}
self.ids = personViewModels.map { $0.id }
self.persons = Dictionary(
uniqueKeysWithValues: personViewModels.map { ($0.id, $0) }
)
}
} catch {
print(error)
}
}.resume()
}
func refreshData() {
ids = []
persons = [:]
fetchData()
}
}
class PersonViewModel: Identifiable, ObservableObject {
// Main model for use as ObservableObject
// Derived from JSON via basic model
// Even though this is not observed directly,
// it must be an ObservableObject for the data flow to work
var id = UUID()
@Published var first: String = ""
@Published var last: String = ""
@Published var phone: String = ""
@Published var address: String = ""
@Published var city: String = ""
@Published var state: String = ""
@Published var zip: String = ""
@Published var registered: Date = Date()
init(with person: PersonModel) {
self.id = person.id
self.first = person.first
self.last = person.last
self.phone = person.phone
self.address = person.address
self.city = person.city
self.state = person.state
self.zip = person.zip
self.registered = person.registered
}
init() { }
}
struct PersonModel: Codable {
// Basic model for decoding from JSON
let id: UUID
let first: String
let last: String
let phone: String
let address: String
let city: String
let state: String
let zip: String
let registered: Date
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(UUID.self, forKey: .id)
first = try values.decode(String.self, forKey: .first)
last = try values.decode(String.self, forKey: .last)
phone = try values.decode(String.self, forKey: .phone)
registered = try values.decode(Date.self, forKey: .registered)
// split up address into separate lines for easier editing
let addressData = try values.decode(String.self, forKey: .address)
let addressComponents = addressData.components(separatedBy: ", ")
address = addressComponents[0]
city = addressComponents[1]
state = addressComponents[2]
zip = addressComponents[3]
}
}
// Extension to force un-wrap a Dictionary value which is normally an optional.
// This is so it can be used to create a Binding.
extension Dictionary where Key == UUID, Value == PersonViewModel {
subscript(unchecked key: Key) -> Value {
get {
guard let result = self[key] else {
fatalError("This person does not exist.")
}
return result
}
set {
self[key] = newValue
}
}
}
| 30.435714 | 97 | 0.578503 |
7ac11442da252842ec4f7e0e30a231aa0fbcc511 | 11,123 | /*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import GRPC
import NIO
import XCTest
// These tests demonstrate how to use gRPC to create a service provider using your own payload type,
// or alternatively, how to avoid deserialization and just extract the raw bytes from a payload.
class GRPCCustomPayloadTests: GRPCTestCase {
var group: EventLoopGroup!
var server: Server!
var client: AnyServiceClient!
override func setUp() {
super.setUp()
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.server = try! Server.insecure(group: self.group)
.withServiceProviders([CustomPayloadProvider()])
.bind(host: "localhost", port: 0)
.wait()
let channel = ClientConnection.insecure(group: self.group)
.connect(host: "localhost", port: server.channel.localAddress!.port!)
self.client = AnyServiceClient(channel: channel)
}
override func tearDown() {
XCTAssertNoThrow(try self.server.close().wait())
XCTAssertNoThrow(try self.client.channel.close().wait())
XCTAssertNoThrow(try self.group.syncShutdownGracefully())
}
func testCustomPayload() throws {
// This test demonstrates how to call a manually created bidirectional RPC with custom payloads.
let statusExpectation = self.expectation(description: "status received")
var responses: [CustomPayload] = []
// Make a bidirectional stream using `CustomPayload` as the request and response type.
// The service defined below is called "CustomPayload", and the method we call on it
// is "AddOneAndReverseMessage"
let rpc: BidirectionalStreamingCall<CustomPayload, CustomPayload> = self.client.makeBidirectionalStreamingCall(
path: "/CustomPayload/AddOneAndReverseMessage",
handler: { responses.append($0) }
)
// Make and send some requests:
let requests: [CustomPayload] = [
CustomPayload(message: "one", number: .random(in: Int64.min..<Int64.max)),
CustomPayload(message: "two", number: .random(in: Int64.min..<Int64.max)),
CustomPayload(message: "three", number: .random(in: Int64.min..<Int64.max))
]
rpc.sendMessages(requests, promise: nil)
rpc.sendEnd(promise: nil)
// Wait for the RPC to finish before comparing responses.
rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
self.wait(for: [statusExpectation], timeout: 1.0)
// Are the responses as expected?
let expected = requests.map { request in
CustomPayload(message: String(request.message.reversed()), number: request.number + 1)
}
XCTAssertEqual(responses, expected)
}
func testNoDeserializationOnTheClient() throws {
// This test demonstrates how to skip the deserialization step on the client. It isn't necessary
// to use a custom service provider to do this, although we do here.
let statusExpectation = self.expectation(description: "status received")
var responses: [IdentityPayload] = []
// Here we use `IdentityPayload` for our response type: we define it below such that it does
// not deserialize the bytes provided to it by gRPC.
let rpc: BidirectionalStreamingCall<CustomPayload, IdentityPayload> = self.client.makeBidirectionalStreamingCall(
path: "/CustomPayload/AddOneAndReverseMessage",
handler: { responses.append($0) }
)
let request = CustomPayload(message: "message", number: 42)
rpc.sendMessage(request, promise: nil)
rpc.sendEnd(promise: nil)
// Wait for the RPC to finish before comparing responses.
rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
self.wait(for: [statusExpectation], timeout: 1.0)
guard var response = responses.first?.buffer else {
XCTFail("RPC completed without a response")
return
}
// We just took the raw bytes from the payload: we can still decode it because we know the
// server returned a serialized `CustomPayload`.
let actual = try CustomPayload(serializedByteBuffer: &response)
XCTAssertEqual(actual.message, "egassem")
XCTAssertEqual(actual.number, 43)
}
func testCustomPayloadUnary() throws {
let rpc: UnaryCall<StringPayload, StringPayload> = self.client.makeUnaryCall(
path: "/CustomPayload/Reverse",
request: StringPayload(message: "foobarbaz")
)
XCTAssertEqual(try rpc.response.map { $0.message }.wait(), "zabraboof")
XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
}
func testCustomPayloadClientStreaming() throws {
let rpc: ClientStreamingCall<StringPayload, StringPayload> = self.client.makeClientStreamingCall(path: "/CustomPayload/ReverseThenJoin")
rpc.sendMessages(["foo", "bar", "baz"].map(StringPayload.init(message:)), promise: nil)
rpc.sendEnd(promise: nil)
XCTAssertEqual(try rpc.response.map { $0.message }.wait(), "baz bar foo")
XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
}
func testCustomPayloadServerStreaming() throws {
let message = "abc"
var expectedIterator = message.reversed().makeIterator()
let rpc: ServerStreamingCall<StringPayload, StringPayload> = self.client.makeServerStreamingCall(
path: "/CustomPayload/ReverseThenSplit",
request: StringPayload(message: message)
) { response in
if let next = expectedIterator.next() {
XCTAssertEqual(String(next), response.message)
} else {
XCTFail("Unexpected message: \(response.message)")
}
}
XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
}
}
// MARK: Custom Payload Service
fileprivate class CustomPayloadProvider: CallHandlerProvider {
var serviceName: String = "CustomPayload"
fileprivate func reverseString(
request: StringPayload,
context: UnaryResponseCallContext<StringPayload>
) -> EventLoopFuture<StringPayload> {
let reversed = StringPayload(message: String(request.message.reversed()))
return context.eventLoop.makeSucceededFuture(reversed)
}
fileprivate func reverseThenJoin(
context: UnaryResponseCallContext<StringPayload>
) -> EventLoopFuture<(StreamEvent<StringPayload>) -> Void> {
var messages: [String] = []
return context.eventLoop.makeSucceededFuture({ event in
switch event {
case .message(let request):
messages.append(request.message)
case .end:
let response = messages.reversed().joined(separator: " ")
context.responsePromise.succeed(StringPayload(message: response))
}
})
}
fileprivate func reverseThenSplit(
request: StringPayload,
context: StreamingResponseCallContext<StringPayload>
) -> EventLoopFuture<GRPCStatus> {
let responses = request.message.reversed().map {
context.sendResponse(StringPayload(message: String($0)))
}
return EventLoopFuture.andAllSucceed(responses, on: context.eventLoop).map { .ok }
}
// Bidirectional RPC which returns a new `CustomPayload` for each `CustomPayload` received.
// The returned payloads have their `message` reversed and their `number` incremented by one.
fileprivate func addOneAndReverseMessage(
context: StreamingResponseCallContext<CustomPayload>
) -> EventLoopFuture<(StreamEvent<CustomPayload>) -> Void> {
return context.eventLoop.makeSucceededFuture({ event in
switch event {
case .message(let payload):
let response = CustomPayload(
message: String(payload.message.reversed()),
number: payload.number + 1
)
_ = context.sendResponse(response)
case .end:
context.statusPromise.succeed(.ok)
}
})
}
func handleMethod(_ methodName: String, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName {
case "Reverse":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in
return self.reverseString(request: request, context: context)
}
}
case "ReverseThenJoin":
return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in
return self.reverseThenJoin(context: context)
}
case "ReverseThenSplit":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in
return self.reverseThenSplit(request: request, context: context)
}
}
case "AddOneAndReverseMessage":
return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in
return self.addOneAndReverseMessage(context: context)
}
default:
return nil
}
}
}
fileprivate struct IdentityPayload: GRPCPayload {
var buffer: ByteBuffer
init(serializedByteBuffer: inout ByteBuffer) throws {
self.buffer = serializedByteBuffer
}
func serialize(into buffer: inout ByteBuffer) throws {
// This will never be called, however, it could be implemented as a direct copy of the bytes
// we hold, e.g.:
//
// var copy = self.buffer
// buffer.writeBuffer(©)
fatalError("Unimplemented")
}
}
/// A toy custom payload which holds a `String` and an `Int64`.
///
/// The payload is serialized as:
/// - the `UInt32` encoded length of the message,
/// - the UTF-8 encoded bytes of the message, and
/// - the `Int64` bytes of the number.
fileprivate struct CustomPayload: GRPCPayload, Equatable {
var message: String
var number: Int64
init(message: String, number: Int64) {
self.message = message
self.number = number
}
init(serializedByteBuffer: inout ByteBuffer) throws {
guard let messageLength = serializedByteBuffer.readInteger(as: UInt32.self),
let message = serializedByteBuffer.readString(length: Int(messageLength)),
let number = serializedByteBuffer.readInteger(as: Int64.self) else {
throw GRPCError.DeserializationFailure()
}
self.message = message
self.number = number
}
func serialize(into buffer: inout ByteBuffer) throws {
buffer.writeInteger(UInt32(self.message.count))
buffer.writeString(self.message)
buffer.writeInteger(self.number)
}
}
fileprivate struct StringPayload: GRPCPayload {
var message: String
init(message: String) {
self.message = message
}
init(serializedByteBuffer: inout ByteBuffer) throws {
self.message = serializedByteBuffer.readString(length: serializedByteBuffer.readableBytes)!
}
func serialize(into buffer: inout ByteBuffer) throws {
buffer.writeString(self.message)
}
}
| 35.765273 | 140 | 0.711948 |
504cedc2ad68193b837825bf967b55f9e6aa4bf9 | 16,686 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import LanguageServerProtocol
import SKCore
import SKSupport
import IndexStoreDB
import Basic
import SPMUtility
import Dispatch
import Foundation
import SPMLibc
public typealias URL = Foundation.URL
/// The SourceKit language server.
///
/// This is the client-facing language server implementation, providing indexing, multiple-toolchain
/// and cross-language support. Requests may be dispatched to language-specific services or handled
/// centrally, but this is transparent to the client.
public final class SourceKitServer: LanguageServer {
struct LanguageServiceKey: Hashable {
var toolchain: String
var language: Language
}
let buildSetup: BuildSetup
let toolchainRegistry: ToolchainRegistry
var languageService: [LanguageServiceKey: Connection] = [:]
var workspace: Workspace?
let fs: FileSystem
let onExit: () -> Void
/// Creates a language server for the given client.
public init(client: Connection, fileSystem: FileSystem = localFileSystem, buildSetup: BuildSetup, onExit: @escaping () -> Void = {}) {
self.fs = fileSystem
self.toolchainRegistry = ToolchainRegistry.shared
self.buildSetup = buildSetup
self.onExit = onExit
super.init(client: client)
}
public override func _registerBuiltinHandlers() {
_register(SourceKitServer.initialize)
_register(SourceKitServer.clientInitialized)
_register(SourceKitServer.cancelRequest)
_register(SourceKitServer.shutdown)
_register(SourceKitServer.exit)
registerWorkspaceNotfication(SourceKitServer.openDocument)
registerWorkspaceNotfication(SourceKitServer.closeDocument)
registerWorkspaceNotfication(SourceKitServer.changeDocument)
registerWorkspaceNotfication(SourceKitServer.willSaveDocument)
registerWorkspaceNotfication(SourceKitServer.didSaveDocument)
registerWorkspaceRequest(SourceKitServer.completion)
registerWorkspaceRequest(SourceKitServer.hover)
registerWorkspaceRequest(SourceKitServer.definition)
registerWorkspaceRequest(SourceKitServer.references)
registerWorkspaceRequest(SourceKitServer.documentSymbolHighlight)
registerWorkspaceRequest(SourceKitServer.foldingRange)
registerWorkspaceRequest(SourceKitServer.symbolInfo)
registerWorkspaceRequest(SourceKitServer.documentSymbol)
}
func registerWorkspaceRequest<R>(
_ requestHandler: @escaping (SourceKitServer) -> (Request<R>, Workspace) -> Void)
{
_register { [unowned self] (req: Request<R>) in
guard let workspace = self.workspace else {
return req.reply(.failure(.serverNotInitialized))
}
requestHandler(self)(req, workspace)
}
}
func registerWorkspaceNotfication<N>(
_ noteHandler: @escaping (SourceKitServer) -> (Notification<N>, Workspace) -> Void)
{
_register { [unowned self] (note: Notification<N>) in
guard let workspace = self.workspace else {
log("received notification before \"initialize\", ignoring...", level: .error)
return
}
noteHandler(self)(note, workspace)
}
}
public override func _handleUnknown<R>(_ req: Request<R>) {
if req.clientID == ObjectIdentifier(client) {
return super._handleUnknown(req)
}
// Unknown requests from a language server are passed on to the client.
let id = client.send(req.params, queue: queue) { result in
req.reply(result)
}
req.cancellationToken.addCancellationHandler {
self.client.send(CancelRequest(id: id))
}
}
/// Handle an unknown notification.
public override func _handleUnknown<N>(_ note: Notification<N>) {
if note.clientID == ObjectIdentifier(client) {
return super._handleUnknown(note)
}
// Unknown notifications from a language server are passed on to the client.
client.send(note.params)
}
func toolchain(for url: URL, _ language: Language) -> Toolchain? {
if let toolchain = workspace?.buildSettings.settings(for: url, language)?.preferredToolchain {
return toolchain
}
let supportsLang = { (toolchain: Toolchain) -> Bool in
// FIXME: the fact that we're looking at clangd/sourcekitd instead of the compiler indicates this method needs a parameter stating what kind of tool we're looking for.
switch language {
case .swift:
return toolchain.sourcekitd != nil
case .c, .cpp, .objective_c, .objective_cpp:
return toolchain.clangd != nil
default:
return false
}
}
if let toolchain = toolchainRegistry.default, supportsLang(toolchain) {
return toolchain
}
for toolchain in toolchainRegistry.toolchains {
if supportsLang(toolchain) {
return toolchain
}
}
return nil
}
func languageService(for toolchain: Toolchain, _ language: Language) -> Connection? {
let key = LanguageServiceKey(toolchain: toolchain.identifier, language: language)
if let service = languageService[key] {
return service
}
// Start a new service.
return orLog("failed to start language service", level: .error) {
guard let service = try SourceKit.languageService(for: toolchain, language, client: self) else {
return nil
}
let pid = Int(ProcessInfo.processInfo.processIdentifier)
let resp = try service.sendSync(InitializeRequest(
processId: pid,
rootPath: nil,
rootURL: (workspace?.rootPath).map { URL(fileURLWithPath: $0.pathString) },
initializationOptions: InitializationOptions(),
capabilities: workspace?.clientCapabilities ?? ClientCapabilities(workspace: nil, textDocument: nil),
trace: .off,
workspaceFolders: nil))
// FIXME: store the server capabilities.
guard case .incremental? = resp.capabilities.textDocumentSync?.change else {
fatalError("non-incremental update not implemented")
}
service.send(InitializedNotification())
languageService[key] = service
return service
}
}
func languageService(for url: URL, _ language: Language, in workspace: Workspace) -> Connection? {
if let service = workspace.documentService[url] {
return service
}
guard let toolchain = toolchain(for: url, language),
let service = languageService(for: toolchain, language)
else {
return nil
}
log("Using toolchain \(toolchain.displayName) (\(toolchain.identifier)) for \(url)")
workspace.documentService[url] = service
return service
}
}
// MARK: - Request and notification handling
extension SourceKitServer {
// MARK: - General
func initialize(_ req: Request<InitializeRequest>) {
if let url = req.params.rootURL {
self.workspace = try? Workspace(
url: url,
clientCapabilities: req.params.capabilities,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.buildSetup)
} else if let path = req.params.rootPath {
self.workspace = try? Workspace(
url: URL(fileURLWithPath: path),
clientCapabilities: req.params.capabilities,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.buildSetup)
}
if self.workspace == nil {
log("no workspace found", level: .warning)
self.workspace = Workspace(
rootPath: nil,
clientCapabilities: req.params.capabilities,
buildSettings: BuildSystemList(),
index: nil,
buildSetup: self.buildSetup
)
}
req.reply(InitializeResult(capabilities: ServerCapabilities(
textDocumentSync: TextDocumentSyncOptions(
openClose: true,
change: .incremental,
willSave: true,
willSaveWaitUntil: false,
save: TextDocumentSyncOptions.SaveOptions(includeText: false)
),
completionProvider: CompletionOptions(
resolveProvider: false,
triggerCharacters: ["."]
),
hoverProvider: true,
definitionProvider: true,
referencesProvider: true,
documentHighlightProvider: true,
foldingRangeProvider: true,
documentSymbolProvider: true
)))
}
func clientInitialized(_: Notification<InitializedNotification>) {
// Nothing to do.
}
func cancelRequest(_ notification: Notification<CancelRequest>) {
let key = RequestCancelKey(client: notification.clientID, request: notification.params.id)
requestCancellation[key]?.cancel()
}
func shutdown(_ request: Request<Shutdown>) {
// Nothing to do yet.
request.reply(VoidResponse())
}
func exit(_ notification: Notification<Exit>) {
onExit()
}
// MARK: - Text synchronization
func openDocument(_ note: Notification<DidOpenTextDocument>, workspace: Workspace) {
workspace.documentManager.open(note)
if let service = languageService(for: note.params.textDocument.url, note.params.textDocument.language, in: workspace) {
service.send(note.params)
}
}
func closeDocument(_ note: Notification<DidCloseTextDocument>, workspace: Workspace) {
workspace.documentManager.close(note)
if let service = workspace.documentService[note.params.textDocument.url] {
service.send(note.params)
}
}
func changeDocument(_ note: Notification<DidChangeTextDocument>, workspace: Workspace) {
workspace.documentManager.edit(note)
if let service = workspace.documentService[note.params.textDocument.url] {
service.send(note.params)
}
}
func willSaveDocument(_ note: Notification<WillSaveTextDocument>, workspace: Workspace) {
}
func didSaveDocument(_ note: Notification<DidSaveTextDocument>, workspace: Workspace) {
}
// MARK: - Language features
func completion(_ req: Request<CompletionRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(
req,
workspace: workspace,
fallback: CompletionList(isIncomplete: false, items: []))
}
func hover(_ req: Request<HoverRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(req, workspace: workspace, fallback: nil)
}
/// Forwards a SymbolInfoRequest to the appropriate toolchain service for this document.
func symbolInfo(_ req: Request<SymbolInfoRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(req, workspace: workspace, fallback: [])
}
func documentSymbolHighlight(_ req: Request<DocumentHighlightRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(req, workspace: workspace, fallback: nil)
}
func foldingRange(_ req: Request<FoldingRangeRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(req, workspace: workspace, fallback: nil)
}
func documentSymbol(_ req: Request<DocumentSymbolRequest>, workspace: Workspace) {
toolchainTextDocumentRequest(req, workspace: workspace, fallback: nil)
}
func definition(_ req: Request<DefinitionRequest>, workspace: Workspace) {
// FIXME: sending yourself a request isn't very convenient
guard let service = workspace.documentService[req.params.textDocument.url] else {
req.reply([])
return
}
let id = service.send(SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position), queue: queue) { result in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
if let error = result.failure {
req.reply(.failure(error))
} else {
req.reply([])
}
return
}
let fallbackLocation = [symbol.bestLocalDeclaration].compactMap { $0 }
guard let usr = symbol.usr, let index = workspace.index else {
return req.reply(fallbackLocation)
}
log("performing indexed jump-to-def with usr \(usr)")
var occurs = index.occurrences(ofUSR: usr, roles: [.definition])
if occurs.isEmpty {
occurs = index.occurrences(ofUSR: usr, roles: [.declaration])
}
// FIXME: overrided method logic
let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
url: URL(fileURLWithPath: occur.location.path),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}
req.reply(locations.isEmpty ? fallbackLocation : locations)
}
req.cancellationToken.addCancellationHandler { [weak service] in
service?.send(CancelRequest(id: id))
}
}
// FIXME: a lot of duplication with definition request
func references(_ req: Request<ReferencesRequest>, workspace: Workspace) {
// FIXME: sending yourself a request isn't very convenient
guard let service = workspace.documentService[req.params.textDocument.url] else {
req.reply([])
return
}
let id = service.send(SymbolInfoRequest(textDocument: req.params.textDocument, position: req.params.position), queue: queue) { result in
guard let symbols: [SymbolDetails] = result.success ?? nil, let symbol = symbols.first else {
if let error = result.failure {
req.reply(.failure(error))
} else {
req.reply([])
}
return
}
guard let usr = symbol.usr, let index = workspace.index else {
req.reply([])
return
}
log("performing indexed jump-to-def with usr \(usr)")
var roles: SymbolRole = [.reference]
if req.params.includeDeclaration != false {
roles.formUnion([.declaration, .definition])
}
let occurs = index.occurrences(ofUSR: usr, roles: roles)
let locations = occurs.compactMap { occur -> Location? in
if occur.location.path.isEmpty {
return nil
}
return Location(
url: URL(fileURLWithPath: occur.location.path),
range: Range(Position(
line: occur.location.line - 1, // 1-based -> 0-based
// FIXME: we need to convert the utf8/utf16 column, which may require reading the file!
utf16index: occur.location.utf8Column - 1
))
)
}
req.reply(locations)
}
req.cancellationToken.addCancellationHandler { [weak service] in
service?.send(CancelRequest(id: id))
}
}
func toolchainTextDocumentRequest<PositionRequest>(
_ req: Request<PositionRequest>,
workspace: Workspace,
fallback: @autoclosure () -> PositionRequest.Response)
where PositionRequest: TextDocumentRequest
{
guard let service = workspace.documentService[req.params.textDocument.url] else {
req.reply(fallback())
return
}
let id = service.send(req.params, queue: DispatchQueue.global()) { result in
req.reply(result)
}
req.cancellationToken.addCancellationHandler { [weak service] in
service?.send(CancelRequest(id: id))
}
}
}
/// Creates a new connection from `client` to a service for `language` if available, and launches
/// the service. Does *not* send the initialization request.
///
/// - returns: The connection, if a suitable language service is available; otherwise nil.
/// - throws: If there is a suitable service but it fails to launch, throws an error.
public func languageService(
for toolchain: Toolchain,
_ language: Language,
client: MessageHandler) throws -> Connection?
{
switch language {
case .c, .cpp, .objective_c, .objective_cpp:
guard let clangd = toolchain.clangd else { return nil }
return try makeJSONRPCClangServer(client: client, clangd: clangd, buildSettings: (client as? SourceKitServer)?.workspace?.buildSettings)
case .swift:
guard let sourcekitd = toolchain.sourcekitd else { return nil }
return try makeLocalSwiftServer(client: client, sourcekitd: sourcekitd, buildSettings: (client as? SourceKitServer)?.workspace?.buildSettings, clientCapabilities: (client as? SourceKitServer)?.workspace?.clientCapabilities)
default:
return nil
}
}
public typealias Notification = LanguageServerProtocol.Notification
public typealias Diagnostic = LanguageServerProtocol.Diagnostic
| 33.041584 | 227 | 0.68926 |
39dd5d43c4ca5dd3ebff3d16312848e9590cb64d | 1,655 | //
// AlbumCell.swift
// ColectionView
//
// Created by d182_raul_j on 21/04/18.
// Copyright © 2018 d182_raul_j. All rights reserved.
//
import UIKit
class AlbumCell: UICollectionViewCell{
var album: Album?{
didSet{
if let name = album?.name{
titleLabel.text = name
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "cover1")
iv.layer.cornerRadius = 15
iv.layer.masksToBounds = true
iv.contentMode = .scaleAspectFill
return iv
}()
let titleLabel: UILabel = {
let label = UILabel()
label.text = "Queen"
label.font = UIFont.systemFont(ofSize: 13)
label.numberOfLines = 2
return label
}()
let categoryLabel: UILabel = {
let label = UILabel()
label.text = "ROCK y ya"
label.font = UIFont.systemFont(ofSize: 11)
label.numberOfLines = 2
return label
}()
func setupLayout(){
addSubview(imageView)
addSubview(titleLabel)
addSubview(categoryLabel)
imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.width)
titleLabel.frame = CGRect(x: 0, y: frame.width, width: frame.width, height: 40)
categoryLabel.frame = CGRect(x: 0, y: frame.width+40, width: frame.width, height: 40)
}
}
| 25.075758 | 93 | 0.571601 |
48914cdd5779d39cab5e967d103dd95ce400c52b | 17,227 | //
// AtomicValueTests.swift
// Futures
//
// Copyright © 2019 Akis Kesoglou. Licensed under the MIT license.
//
import FuturesSync
import FuturesTestSupport
import XCTest
final class AtomicValueTests: XCTestCase {
func testConsistency() {
let PARTITIONS = 128
let ITERATIONS = 10_000
let total = (PARTITIONS * (PARTITIONS + 1) / 2) * ITERATIONS
let q = DispatchQueue(label: "futures.test-atomic", attributes: .concurrent)
let g = DispatchGroup()
let counter = AtomicInt(0)
for p in 1...PARTITIONS {
q.async(group: g, flags: .detached) {
for _ in 0..<ITERATIONS {
counter.fetchAdd(p)
}
}
}
g.wait()
XCTAssertEqual(counter.load(), total)
}
func testBool() {
let i = AtomicBool(false)
XCTAssert(i.load() == false)
i.store(false)
XCTAssert(i.load() == false)
i.store(true)
XCTAssert(i.load() == true)
i.store(true)
i.fetchOr(true)
XCTAssert(i.load() == true)
i.fetchOr(false)
XCTAssert(i.load() == true)
i.store(false)
i.fetchOr(false)
XCTAssert(i.load() == false)
i.fetchOr(true)
XCTAssert(i.load() == true)
i.fetchAnd(false)
XCTAssert(i.load() == false)
i.fetchAnd(true)
XCTAssert(i.load() == false)
i.fetchXor(false)
XCTAssert(i.load() == false)
i.fetchXor(true)
XCTAssert(i.load() == true)
var old = i.exchange(false)
XCTAssert(old == true)
XCTAssert(i.exchange(true) == false)
i.store(false)
XCTAssert(i.compareExchange(false, true) == false)
XCTAssert(i.compareExchange(true, false) == true)
XCTAssert(i.compareExchange(&old, false) == false)
XCTAssert(i.compareExchange(old, true) == old)
old = i.exchange(false)
XCTAssert(old == true)
XCTAssert(i.exchange(true) == false)
i.store(false)
XCTAssert(i.compareExchangeWeak(false, true) == false)
XCTAssert(i.compareExchangeWeak(true, false) == true)
XCTAssert(i.compareExchangeWeak(&old, false) == false)
XCTAssert(i.compareExchangeWeak(old, true) == old)
}
func testInt() {
let i = AtomicInt(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: Int.self)
let r2 = randomInteger(ofType: Int.self)
let r3 = randomInteger(ofType: Int.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testInt8() {
let i = AtomicInt8(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: Int8.self)
let r2 = randomInteger(ofType: Int8.self)
let r3 = randomInteger(ofType: Int8.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testInt16() {
let i = AtomicInt16(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: Int16.self)
let r2 = randomInteger(ofType: Int16.self)
let r3 = randomInteger(ofType: Int16.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testInt32() {
let i = AtomicInt32(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: Int32.self)
let r2 = randomInteger(ofType: Int32.self)
let r3 = randomInteger(ofType: Int32.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testInt64() {
let i = AtomicInt64(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: Int64.self)
let r2 = randomInteger(ofType: Int64.self)
let r3 = randomInteger(ofType: Int64.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testUInt() {
let i = AtomicUInt(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: UInt.self)
let r2 = randomInteger(ofType: UInt.self)
let r3 = randomInteger(ofType: UInt.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testUInt8() {
let i = AtomicUInt8(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: UInt8.self)
let r2 = randomInteger(ofType: UInt8.self)
let r3 = randomInteger(ofType: UInt8.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testUInt16() {
let i = AtomicUInt16(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: UInt16.self)
let r2 = randomInteger(ofType: UInt16.self)
let r3 = randomInteger(ofType: UInt16.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testUInt32() {
let i = AtomicUInt32(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: UInt32.self)
let r2 = randomInteger(ofType: UInt32.self)
let r3 = randomInteger(ofType: UInt32.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
func testUInt64() {
let i = AtomicUInt64(0)
XCTAssert(i.load() == 0)
let r1 = randomInteger(ofType: UInt64.self)
let r2 = randomInteger(ofType: UInt64.self)
let r3 = randomInteger(ofType: UInt64.self)
i.store(r1)
XCTAssert(r1 == i.load())
var j = i.exchange(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load())
j = i.fetchAdd(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load())
j = i.fetchSub(r2)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load())
i.store(r1)
j = i.fetchOr(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load())
i.store(r2)
j = i.fetchXor(r1)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load())
i.store(r1)
j = i.fetchAnd(r2)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchange(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchange(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
i.store(r1)
XCTAssertTrue(i.compareExchangeWeak(r1, r2) == r1)
XCTAssertEqual(r2, i.load())
j = r2
i.store(r1)
while !i.compareExchangeWeak(&j, r3) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load())
}
}
| 25.446086 | 84 | 0.531433 |
cc6f9209565adbaf7d18337c423d33e5701cb5d6 | 310 | //
// RefreshControlView.swift
// RefreshControlKit
//
// Created by hirotaka on 2020/09/04.
// Copyright © 2020 hiro. All rights reserved.
//
import UIKit
public protocol RefreshControlView: UIView {
func willRefresh()
func didRefresh()
func didScroll(_ progress: RefreshControl.Progress)
}
| 19.375 | 55 | 0.719355 |
50247e186aa92639c24c6dbfe0c8a9e04c15193a | 1,511 | //
// ViewController.swift
// 025-rxswift
//
// Created by moma on 2018/3/5.
// Copyright © 2018年 yifans. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
// from http://www.hangge.com/blog/cache/detail_1918.html
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let cellName = "cellName"
//歌曲列表数据源
let musicListViewModel = MusicListViewModel()
//负责对象销毁
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// 这里我们不再需要实现数据源和委托协议了。而是写一些响应式代码,让它们将数据和 UITableView 建立绑定关系。
/*
代码的简单说明:
DisposeBag:作用是 Rx 在视图控制器或者其持有者将要销毁的时候,自动释法掉绑定在它上面的资源。它是通过类似“订阅处置机制”方式实现(类似于 NotificationCenter 的 removeObserver)。
rx.items(cellIdentifier:):这是 Rx 基于 cellForRowAt 数据源方法的一个封装。传统方式中我们还要有个 numberOfRowsInSection 方法,使用 Rx 后就不再需要了(Rx 已经帮我们完成了相关工作)。
rx.modelSelected: 这是 Rx 基于 UITableView 委托回调方法 didSelectRowAt 的一个封装。
*/
// 将数据源数据绑定到tableView上
musicListViewModel.data.bind(to: tableView.rx.items(cellIdentifier: cellName)) { _, music, cell in
cell.textLabel?.text = music.name
cell.detailTextLabel?.text = music.singer
}.disposed(by: disposeBag)
// tableView点击响应
tableView.rx.modelSelected(Music.self).subscribe(onNext: { music in
print("你选中的歌曲信息【\(music)】")
}).disposed(by: disposeBag)
}
}
| 29.057692 | 136 | 0.647915 |
dee9f7bf8cf180e4f48b2caac223054ccd429665 | 2,130 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Declarations to enable ease-of-testing
public // @testable
struct _StringRepresentation {
public var _isASCII: Bool
public var _count: Int
public var _capacity: Int
public enum _Form {
case _small
case _cocoa(object: AnyObject)
case _native(object: AnyObject)
case _immortal(address: UInt)
// TODO: shared native
}
public var _form: _Form
public var _objectIdentifier: ObjectIdentifier? {
switch _form {
case ._cocoa(let object): return ObjectIdentifier(object)
case ._native(let object): return ObjectIdentifier(object)
default: return nil
}
}
}
extension String {
public // @testable
func _classify() -> _StringRepresentation { return _guts._classify() }
}
extension _StringGuts {
internal func _classify() -> _StringRepresentation {
var result = _StringRepresentation(
_isASCII: self.isASCII,
_count: self.count,
_capacity: nativeCapacity ?? 0,
_form: ._small
)
if self.isSmall {
result._capacity = _SmallString.capacity
return result
}
if _object.largeIsCocoa {
result._form = ._cocoa(object: _object.cocoaObject)
return result
}
// TODO: shared native
_internalInvariant(_object.providesFastUTF8)
if _object.isImmortal {
result._form = ._immortal(
address: UInt(bitPattern: _object.nativeUTF8Start))
return result
}
if _object.hasNativeStorage {
_internalInvariant(_object.largeFastIsTailAllocated)
result._form = ._native(object: _object.nativeStorage)
return result
}
fatalError()
}
}
| 27.662338 | 80 | 0.642254 |
fe02e985b0ab4479ad807a4d366d76a37da479b9 | 272 | /// A convenient "instance" of `Void` to make it more ergonomic to write instead of `()` where appropriate.
///
/// Example:
///
/// let subject = PassthroughSubject<Void, Never>()
/// subject.send(void) // instead of `subject.send(())`
public let void: Void = ()
| 34 | 107 | 0.639706 |
e9b610c64fb7caaaab17930bf1ae44fdda94fe2e | 28,289 | import Foundation
import CoreFoundation
#if os(Linux)
import SwiftGlibc
import Glibc
#else
import Darwin.C
#endif
let unescapeMapping: [UnicodeScalar: UnicodeScalar] = [
"t": "\t",
"r": "\r",
"n": "\n"
]
let escapeMapping: [Character: String] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
"\r\n": "\\r\\n"
]
let hexMapping: [UnicodeScalar: UInt32] = [
"0": 0x0,
"1": 0x1,
"2": 0x2,
"3": 0x3,
"4": 0x4,
"5": 0x5,
"6": 0x6,
"7": 0x7,
"8": 0x8,
"9": 0x9,
"a": 0xA, "A": 0xA,
"b": 0xB, "B": 0xB,
"c": 0xC, "C": 0xC,
"d": 0xD, "D": 0xD,
"e": 0xE, "E": 0xE,
"f": 0xF, "F": 0xF
]
let digitMapping: [UnicodeScalar:Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
]
public func escapeAsJSONString(source : String) -> String {
var s = "\""
for c in source.characters {
if let escapedSymbol = escapeMapping[c] {
s.appendContentsOf(escapedSymbol)
} else {
s.append(c)
}
}
s.appendContentsOf("\"")
return s
}
func digitToInt(byte: UInt8) -> Int? {
return digitMapping[UnicodeScalar(byte)]
}
func hexToDigit(byte: UInt8) -> UInt32? {
return hexMapping[UnicodeScalar(byte)]
}
public protocol JSONSerializer {
func serialize(JSONValue: JSON) -> String
}
public class DefaultJSONSerializer: JSONSerializer {
public init() {}
public func serialize(JSONValue: JSON) -> String {
switch JSONValue {
case .NullValue: return "null"
case .BooleanValue(let b): return b ? "true" : "false"
case .NumberValue(let n): return serializeNumber(n)
case .StringValue(let s): return escapeAsJSONString(s)
case .ArrayValue(let a): return serializeArray(a)
case .ObjectValue(let o): return serializeObject(o)
}
}
func serializeNumber(n: Double) -> String {
if n == Double(Int64(n)) {
return Int64(n).description
} else {
return n.description
}
}
func serializeArray(a: [JSON]) -> String {
var s = "["
for (i, _) in a.enumerate() {
// for var i = 0; i < a.count; i += 1 {
s += a[i].serialize(self)
if i != (a.count - 1) {
s += ","
}
}
return s + "]"
}
func serializeObject(o: [String: JSON]) -> String {
var s = "{"
var i = 0
for entry in o {
s += "\(escapeAsJSONString(entry.0)):\(entry.1.serialize(self))"
i += 1
if i != (o.count - 1) {
s += ","
}
}
return s + "}"
}
}
public final class PrettyJSONSerializer: DefaultJSONSerializer {
var indentLevel = 0
override public func serializeArray(a: [JSON]) -> String {
var s = "["
indentLevel += 1
for (i, _) in a.enumerate() {
// for var i = 0; i < a.count; i += 1 {
s += "\n"
s += indent()
s += a[i].serialize(self)
if i != (a.count - 1) {
s += ","
}
}
indentLevel -= 1
return s + "\n" + indent() + "]"
}
override public func serializeObject(o: [String: JSON]) -> String {
var s = "{"
indentLevel += 1
var i = 0
var keys = Array(o.keys)
keys.sortInPlace()
for key in keys {
s += "\n"
s += indent()
s += "\(escapeAsJSONString(key)): \(o[key]!.serialize(self))"
i += 1
if i != (o.count - 1) {
s += ","
}
}
indentLevel -= 1
return s + "\n" + indent() + "}"
}
func indent() -> String {
var s = ""
var i = 0
while i < indentLevel {
// for var i = 0; i < indentLevel; i += 1 {
s += " "
i += 1
}
return s
}
}
public enum JSON {
case NullValue
case BooleanValue(Bool)
case NumberValue(Double)
case StringValue(String)
case ArrayValue([JSON])
case ObjectValue([String: JSON])
public static func from(value: Bool) -> JSON {
return .BooleanValue(value)
}
public static func from(value: Double) -> JSON {
return .NumberValue(value)
}
public static func from(value: String) -> JSON {
return .StringValue(value)
}
public static func from(value: [JSON]) -> JSON {
return .ArrayValue(value)
}
public static func from(value: [String: JSON]) -> JSON {
return .ObjectValue(value)
}
public static func from(values: [Any]) -> JSON {
var jsonArray: [JSON] = []
for value in values {
if let value = value as? Bool {
jsonArray.append(JSON.from(value))
}
else if let value = value as? Double {
jsonArray.append(JSON.from(value))
}
else if let value = value as? Int {
jsonArray.append(JSON.from(Double(value)))
}
else if let value = value as? String {
jsonArray.append(JSON.from(value))
}
// Covariance hacks for arrays
else if let arr = value as? [String] {
jsonArray.append(JSON.from(arr.map { $0 as Any }))
}
else if let arr = value as? [Double] {
jsonArray.append(JSON.from(arr.map { $0 as Any }))
}
else if let arr = value as? [Int] {
jsonArray.append(JSON.from(arr.map { $0 as Any }))
}
else if let arr = value as? [Bool] {
jsonArray.append(JSON.from(arr.map { $0 as Any }))
}
else if let value = value as? [Any] {
jsonArray.append(JSON.from(value))
}
// Covariance hacks for dictionaries
else if let dict = value as? [String: NSObject] {
var rebuild: [String: Any] = [:]
_ = dict.map { rebuild[$0] = $1 as Any}
jsonArray.append(JSON.from(rebuild))
}
else if let value = value as? [String: Any] {
jsonArray.append(JSON.from(value))
}
else {
print("WARN: Cant json value: \(value) of type: \(value.dynamicType)")
}
}
return JSON.from(jsonArray)
}
public static func from(value: [String: Any]) -> JSON {
var jsonDictionary: [String: JSON] = [:]
for (key, value) in value {
if let value = value as? Bool {
jsonDictionary[key] = JSON.from(value)
}
if let value = value as? Double {
jsonDictionary[key] = JSON.from(value)
}
if let value = value as? Float {
jsonDictionary[key] = JSON.from(Double(value))
}
if let value = value as? Int {
jsonDictionary[key] = JSON.from(Double(value))
}
if let value = value as? String {
jsonDictionary[key] = JSON.from(value)
}
if let value = value as? [Any] {
jsonDictionary[key] = JSON.from(value)
}
if let value = value as? [String: Any] {
jsonDictionary[key] = JSON.from(value)
}
}
return JSON.from(jsonDictionary)
}
public var isBoolean: Bool {
switch self {
case .BooleanValue: return true
default: return false
}
}
public var isNumber: Bool {
switch self {
case .NumberValue: return true
default: return false
}
}
public var isString: Bool {
switch self {
case .StringValue: return true
default: return false
}
}
public var isArray: Bool {
switch self {
case .ArrayValue: return true
default: return false
}
}
public var isObject: Bool {
switch self {
case .ObjectValue: return true
default: return false
}
}
public var boolValue: Bool? {
switch self {
case .BooleanValue(let b): return b
default: return nil
}
}
public var doubleValue: Double? {
switch self {
case .NumberValue(let n): return n
default: return nil
}
}
public var intValue: Int? {
if let v = doubleValue {
return Int(v)
}
return nil
}
public var value: Any {
switch self {
case .NumberValue: return Int(doubleValue!)
case .StringValue(let s): return s
default:
print("JSON WARN: Unable to extract any value!")
return 0
}
}
public var uintValue: UInt? {
if let v = doubleValue {
return UInt(v)
}
return nil
}
public var stringValue: String? {
switch self {
case .StringValue(let s): return s
default: return nil
}
}
public var arrayValue: [JSON]? {
switch self {
case .ArrayValue(let array): return array
default: return nil
}
}
public var dictionaryValue: [String: JSON]? {
switch self {
case .ObjectValue(let dictionary): return dictionary
default: return nil
}
}
public subscript(index: UInt) -> JSON? {
set {
switch self {
case .ArrayValue(let a):
var a = a
if Int(index) < a.count {
if let json = newValue {
a[Int(index)] = json
} else {
a[Int(index)] = .NullValue
}
self = .ArrayValue(a)
}
default: break
}
}
get {
switch self {
case .ArrayValue(let a):
return Int(index) < a.count ? a[Int(index)] : nil
default: return nil
}
}
}
public subscript(key: String) -> JSON? {
set {
switch self {
case .ObjectValue(let o):
var o = o
o[key] = newValue
self = .ObjectValue(o)
default: break
}
}
get {
switch self {
case .ObjectValue(let o):
return o[key]
default: return nil
}
}
}
public func serialize(serializer: JSONSerializer) -> String {
return serializer.serialize(self)
}
}
extension JSON: CustomStringConvertible {
public var description: String {
return serialize(DefaultJSONSerializer())
}
}
extension JSON: CustomDebugStringConvertible {
public var debugDescription: String {
return serialize(PrettyJSONSerializer())
}
}
extension JSON: Equatable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch lhs {
case .NullValue:
switch rhs {
case .NullValue: return true
default: return false
}
case .BooleanValue(let lhsValue):
switch rhs {
case .BooleanValue(let rhsValue): return lhsValue == rhsValue
default: return false
}
case .StringValue(let lhsValue):
switch rhs {
case .StringValue(let rhsValue): return lhsValue == rhsValue
default: return false
}
case .NumberValue(let lhsValue):
switch rhs {
case .NumberValue(let rhsValue): return lhsValue == rhsValue
default: return false
}
case .ArrayValue(let lhsValue):
switch rhs {
case .ArrayValue(let rhsValue): return lhsValue == rhsValue
default: return false
}
case .ObjectValue(let lhsValue):
switch rhs {
case .ObjectValue(let rhsValue): return lhsValue == rhsValue
default: return false
}
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral value: Void) {
self = .NullValue
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self = .BooleanValue(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self = .NumberValue(Double(value))
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self = .NumberValue(Double(value))
}
}
extension JSON: StringLiteralConvertible {
public typealias UnicodeScalarLiteralType = String
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self = .StringValue(value)
}
public typealias ExtendedGraphemeClusterLiteralType = String
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterType) {
self = .StringValue(value)
}
public init(stringLiteral value: StringLiteralType) {
self = .StringValue(value)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: JSON...) {
self = .ArrayValue(elements)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, JSON)...) {
var dictionary = [String: JSON](minimumCapacity: elements.count)
for pair in elements {
dictionary[pair.0] = pair.1
}
self = .ObjectValue(dictionary)
}
}
enum JSONParseError: ErrorType, CustomStringConvertible {
case UnexpectedTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case InsufficientTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case ExtraTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case NonStringKeyError(reason: String, lineNumber: Int, columnNumber: Int)
case InvalidStringError(reason: String, lineNumber: Int, columnNumber: Int)
case InvalidNumberError(reason: String, lineNumber: Int, columnNumber: Int)
var description: String {
switch self {
case UnexpectedTokenError(let r, let l, let c):
return "UnexpectedTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case InsufficientTokenError(let r, let l, let c):
return "InsufficientTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case ExtraTokenError(let r, let l, let c):
return "ExtraTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case NonStringKeyError(let r, let l, let c):
return "NonStringKeyError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case InvalidStringError(let r, let l, let c):
return "InvalidStringError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case InvalidNumberError(let r, let l, let c):
return "InvalidNumberError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
}
}
}
public struct JSONParser {
public static func parse(source: String) throws -> Any {
return try GenericJSONParser(source.utf8).parse()
}
public static func parse(source: [UInt8]) throws -> Any {
return try GenericJSONParser(source).parse()
}
public static func parse(source: [Int8]) throws -> Any {
return try parse(source.map({UInt8($0)}))
}
}
public class GenericJSONParser<ByteSequence: CollectionType where ByteSequence.Generator.Element == UInt8> {
public typealias Source = ByteSequence
typealias Char = Source.Generator.Element
let source: Source
var cur: Source.Index
let end: Source.Index
public var lineNumber = 1
public var columnNumber = 1
public init(_ source: Source) {
self.source = source
self.cur = source.startIndex
self.end = source.endIndex
}
public func parse() throws -> Any {
let JSON = try parseValue()
skipWhitespaces()
if (cur == end) {
return JSON
} else {
throw JSONParseError.ExtraTokenError(
reason: "extra tokens foundd",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
}
extension GenericJSONParser {
private func parseValue() throws -> Any {
skipWhitespaces()
if cur == end {
throw JSONParseError.InsufficientTokenError(
reason: "unexpected end of tokens",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
switch currentChar {
case Char(ascii: "n"): return try parseSymbol("null", NSNull())
case Char(ascii: "t"): return try parseSymbol("true", true)
case Char(ascii: "f"): return try parseSymbol("false", false)
case Char(ascii: "-"), Char(ascii: "0") ... Char(ascii: "9"): return try parseNumber()
case Char(ascii: "\""): return try parseString()
case Char(ascii: "{"): return try parseObject()
case Char(ascii: "["): return try parseArray()
case (let c): throw JSONParseError.UnexpectedTokenError(
reason: "unexpected token: \(c)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private var currentChar: Char {
return source[cur]
}
private var nextChar: Char {
return source[cur.successor()]
}
private var currentSymbol: Character {
return Character(UnicodeScalar(currentChar))
}
private func parseSymbol(target: StaticString, @autoclosure _ iftrue: Void -> Any) throws -> Any {
if expect(target) {
return iftrue()
} else {
throw JSONParseError.UnexpectedTokenError(
reason: "expected \"\(target)\" but \(currentSymbol)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private func parseString() throws -> Any {
assert(currentChar == Char(ascii: "\""), "points a double quote")
advance()
var buffer: [CChar] = []
while cur != end {
// LOOP: for ; cur != end; advance() {
var breakLoop = false
switch currentChar {
case Char(ascii: "\\"):
advance()
if (cur == end) {
throw JSONParseError.InvalidStringError(
reason: "unexpected end of a string literal",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
if let c = parseEscapedChar() {
for u in String(c).utf8 {
buffer.append(CChar(bitPattern: u))
}
} else {
throw JSONParseError.InvalidStringError(
reason: "invalid escape sequence",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
case Char(ascii: "\""):
breakLoop = true
// break LOOP
default: buffer.append(CChar(bitPattern: currentChar))
}
if breakLoop {
break
}
advance()
}
if !expect("\"") {
throw JSONParseError.InvalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
buffer.append(0)
let s = String.fromCString(buffer)!
return s
}
private func parseEscapedChar() -> UnicodeScalar? {
let c = UnicodeScalar(currentChar)
if c == "u" {
var length = 0
var value: UInt32 = 0
while let d = hexToDigit(nextChar) {
advance()
length += 1
if length > 8 {
break
}
value = (value << 4) | d
}
if length < 2 {
return nil
}
return UnicodeScalar(value)
} else {
let c = UnicodeScalar(currentChar)
return unescapeMapping[c] ?? c
}
}
private func parseNumber() throws -> Any {
let sign = expect("-") ? -1.0 : 1.0
var integer: Int64 = 0
switch currentChar {
case Char(ascii: "0"): advance()
case Char(ascii: "1") ... Char(ascii: "9"):
while cur != end {
if let value = digitToInt(currentChar) {
integer = (integer * 10) + Int64(value)
} else {
break
}
advance()
}
default:
throw JSONParseError.InvalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
if integer != Int64(Double(integer)) {
throw JSONParseError.InvalidNumberError(
reason: "too large number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
var fraction: Double = 0.0
if expect(".") {
var factor = 0.1
var fractionLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
fraction += (Double(value) * factor)
factor /= 10
fractionLength += 1
} else {
break
}
advance()
}
if fractionLength == 0 {
throw JSONParseError.InvalidNumberError(
reason: "insufficient fraction part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
var exponent: Int64 = 0
if expect("e") || expect("E") {
var expSign: Int64 = 1
if expect("-") {
expSign = -1
} else if expect("+") {}
exponent = 0
var exponentLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
exponent = (exponent * 10) + Int64(value)
exponentLength += 1
} else {
break
}
advance()
}
if exponentLength == 0 {
throw JSONParseError.InvalidNumberError(
reason: "insufficient exponent part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
exponent *= expSign
}
return sign * (Double(integer) + fraction) * pow(10, Double(exponent))
}
private func parseObject() throws -> Any {
assert(currentChar == Char(ascii: "{"), "points \"{\"")
advance()
skipWhitespaces()
var object: [String: Any] = [:]
LOOP: while cur != end && !expect("}") {
let keyValue = try parseValue()
if let key = keyValue as? String {
skipWhitespaces()
if !expect(":") {
throw JSONParseError.UnexpectedTokenError(
reason: "missing colon (:)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
skipWhitespaces()
let value = try parseValue()
object[key] = value
skipWhitespaces()
if expect(",") {
continue
} else if expect("}") {
break LOOP
} else {
throw JSONParseError.UnexpectedTokenError(
reason: "missing comma (,)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
} else {
throw JSONParseError.NonStringKeyError(
reason: "unexpected value for object key",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return object
}
private func parseArray() throws -> Any {
assert(currentChar == Char(ascii: "["), "points \"[\"")
advance()
skipWhitespaces()
var array: [Any] = []
// Another example of the loop break
LOOP: while cur != end && !expect("]") {
let JSON = try parseValue()
skipWhitespaces()
array.append(JSON)
if expect(",") {
continue
} else if expect("]") {
break LOOP
} else {
throw JSONParseError.UnexpectedTokenError(
reason: "missing comma (,) (token: \(currentSymbol))",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return array
}
private func expect(target: StaticString) -> Bool {
if cur == end {
return false
}
if !isIdentifier(target.utf8Start.memory) {
if target.utf8Start.memory == currentChar {
advance()
return true
} else {
return false
}
}
let start = cur
let l = lineNumber
let c = columnNumber
var p = target.utf8Start
let endp = p.advancedBy(Int(target.byteSize))
while p != endp {
if p.memory != currentChar {
cur = start
lineNumber = l
columnNumber = c
return false
}
p += 1
advance()
}
return true
}
// only "true", "false", "null" are identifiers
private func isIdentifier(char: Char) -> Bool {
switch char {
case Char(ascii: "a") ... Char(ascii: "z"):
return true
default:
return false
}
}
private func advance() {
assert(cur != end, "out of range")
cur++
if cur != end {
switch currentChar {
case Char(ascii: "\n"):
lineNumber += 1
columnNumber = 1
default:
columnNumber += 1
}
}
}
private func skipWhitespaces() {
while cur != end {
switch currentChar {
case Char(ascii: " "), Char(ascii: "\t"), Char(ascii: "\r"), Char(ascii: "\n"):
break
default:
return
}
advance()
}
}
}
// Convert parsed JSON to Any, because why the hell do you think everyone wants to manually query their json?
func anynize(from: JSON) -> Any {
switch from {
case .NullValue:
return NSNull()
case .BooleanValue:
return from.boolValue!
case .StringValue:
return from.stringValue!
case .NumberValue:
return from.doubleValue!
case .ArrayValue:
return from.arrayValue!.map { anynize($0) }
case .ObjectValue:
var ret: [String: Any] = [:]
for (k, v) in from.dictionaryValue! {
ret[k] = anynize(v)
}
return ret
}
}
| 26.865147 | 109 | 0.494857 |
9b7276e1af0084a0df0eeb1c40a7df1f148a4bfb | 7,518 | //
// ContentView.swift
// SwiftUIExample
//
// Created by Jovins on 2021/7/19.
//
import SwiftUI
import UIKit
import Bursts
struct ContentView: View {
@State var title: String = "Hello Burst"
@State var subtitle: String = "Use Bursts show alerts"
@State var position: Int = 0
@State var duration: TimeInterval = 2.0 // default
@State var hasIcon: Bool = false
@State var hasActionIcon: Bool = false
@State var colorRed: Double = 0.2
@State var colorGreen: Double = 0.4
@State var colorBlue: Double = 0.25
var body: some View {
ZStack {
Color(.secondarySystemBackground).ignoresSafeArea(.all)
VStack(alignment: .center, spacing: 20) {
VStack {
HStack {
Text("Title").font(.caption)
Spacer()
}
TextField("Title", text: $title).textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Subtitle").font(.caption)
Spacer()
}
TextField("Subtitle", text: $subtitle).textFieldStyle(RoundedBorderTextFieldStyle())
}
VStack {
HStack {
Text("Select Action").font(.caption)
Spacer()
}
HStack(spacing: 60) {
Toggle("Icon", isOn: $hasIcon)
.frame(width: 100, alignment: .leading)
Spacer()
}
}
VStack {
HStack {
Text("Position").font(.caption)
Spacer()
}
Picker(selection: $position, label: Text("Position")) {
Text("Top").tag(0)
Text("Bottom").tag(1)
}
.pickerStyle(SegmentedPickerStyle())
}
VStack {
HStack {
Text("Duration (\(String(format: "%.1f", duration)) s)").font(.caption)
Spacer()
}
Slider(value: $duration, in: 0.1...10).accentColor(Color(hex: 0x66ccff))
}
ZStack {
// 背景矩形
Rectangle()
.foregroundColor(.white)
.cornerRadius(16)
.shadow(color: Color(red: 1.0 - max(colorRed, max(colorGreen, colorBlue)), green: 1.0 - max(colorRed, max(colorGreen, colorBlue)), blue: 1.0 - max(colorRed, max(colorGreen, colorBlue)), opacity: 0.25), radius: 16, x: 0, y: 8)
VStack {
HStack {
Image(systemName: "r.circle")
.foregroundColor(Color.red.opacity(0.5))
.font(.system(size: 20))
Slider(value: $colorRed, in: 0.0 ... 1.0)
.accentColor(Color.red.opacity(colorRed))
Image(systemName: "r.circle.fill")
.foregroundColor(Color.red)
.font(.system(size: 24))
}
.padding(.top, 4)
.padding()
HStack {
Image(systemName: "g.circle")
.foregroundColor(Color.green.opacity(0.5))
.font(.system(size: 20))
Slider(value: $colorGreen, in: 0.0 ... 1.0)
.accentColor(Color.green.opacity(colorGreen))
Image(systemName: "g.circle.fill")
.foregroundColor(Color.green)
.font(.system(size: 25))
.accentColor(Color.blue.opacity(colorBlue))
}
.padding(.top, 2)
.padding(.bottom, 2)
.padding()
HStack {
Image(systemName: "b.circle")
.foregroundColor(Color.blue.opacity(0.5))
.font(.system(size: 20))
Slider(value: $colorBlue, in: 0.0 ... 1.0)
Image(systemName: "b.circle.fill")
.foregroundColor(Color.blue)
.font(.system(size: 25))
}
.padding(.bottom, 4)
.padding()
}
}
.padding(.all, 8)
.frame(height: 240)
Button(action: {
showBursts()
}, label: {
Text("Show Bursts")
.foregroundColor(.white)
.frame(maxWidth: .infinity)
.padding(10)
})
.frame(maxWidth: .infinity)
.background(Color(red: colorRed, green: colorGreen, blue: colorBlue, opacity: 1.0))
.cornerRadius(7.5)
.padding(.bottom, 44)
}
.padding()
.padding(.top, 64)
}
.ignoresSafeArea(.keyboard)
.onTapGesture {
UIApplication.shared.endEditing()
}
}
private func showBursts() {
UIApplication.shared.endEditing()
let title = self.title.trimmingCharacters(in: .whitespacesAndNewlines)
let subtitle = self.subtitle.trimmingCharacters(in: .whitespacesAndNewlines)
let iposition: Burst.Position = self.position == 0 ? .top : .bottom
let icon = self.hasIcon ? UIImage(named: "mute") : nil
let btnIcon = self.hasActionIcon ? UIImage(systemName: "arrowshape.turn.up.left") : nil
// setting
var setting = BurstSetting()
setting.isDefault = false
setting.backgroundColor = UIColor(red: CGFloat(colorRed), green: CGFloat(colorGreen), blue: CGFloat(colorBlue), alpha: 1.0)
//setting.shadowColor = .black
setting.titleColor = .white
setting.subtitleColor = UIColor(hex: 0xEFEFEF)
setting.shadowColor = UIColor(red: CGFloat(colorRed), green: CGFloat(colorGreen), blue: CGFloat(colorBlue), alpha: 1.0)
setting.shadowOpacity = 0.8
setting.shadowRadius = 8
let burst = Burst(
title: title,
subtitle: subtitle,
icon: icon,
action: .init(icon: btnIcon, handler: {
Bursts.hide()
}),
position: iposition,
duration: .seconds(duration),
setting: setting
)
Bursts.show(burst)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
private extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
| 38.953368 | 249 | 0.437616 |
ab2a94f3eb27c85eab2bb0454a6bca4a4b690e60 | 2,633 | import ArgumentParser
import Foundation
import Base
struct Main: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "png-fuzzy-compare",
abstract: "Tool for generationg CoreGraphics code from vector images in pdf format",
version: "0.1"
)
@Option var firstImage: String
@Option var secondImage: String
@Option var outputImageDiff: String?
@Option var outputAsciiDiff: String?
func run() throws {
let img1 = try! readImage(filePath: firstImage)
let img2 = try! readImage(filePath: secondImage)
if let diffOutputImage = outputImageDiff {
let url = URL(fileURLWithPath: diffOutputImage) as CFURL
try! CGImage.diff(lhs: img1, rhs: img2).write(fileURL: url)
}
let buffer1 = RGBABuffer(image: img1)
let buffer2 = RGBABuffer(image: img2)
if let diffOutputAscii = outputAsciiDiff {
let url = URL(fileURLWithPath: diffOutputAscii)
try! asciiDiff(buffer1: buffer1, buffer2: buffer2)
.data(using: .utf8)!
.write(to: url)
}
let rw1 = buffer1.pixels
.flatMap { $0 }
.flatMap { $0.normComponents }
let rw2 = buffer2.pixels
.flatMap { $0 }
.flatMap { $0.normComponents }
let ziped = zip(rw1, rw2).lazy.map(-)
print(ziped.rootMeanSquare())
}
}
enum ReadImageError: Error {
case failedToCreateDataProvider
case failedToCreateImage
}
func readImage(filePath: String) throws -> CGImage {
let url = URL(fileURLWithPath: filePath) as CFURL
guard let dataProvider = CGDataProvider(url: url)
else { throw ReadImageError.failedToCreateDataProvider }
guard let img = CGImage(
pngDataProviderSource: dataProvider,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent
)
else { throw ReadImageError.failedToCreateImage }
return img
}
func symbolForRelativeDeviation(_ deviation: Double) -> String {
precondition(0...1 ~= deviation)
switch deviation {
case ..<0.001:
return " "
case ..<0.01:
return "·"
case ..<0.1:
return "•"
case ..<0.2:
return "✜"
case ..<0.3:
return "✖"
default:
return "@"
}
}
extension RGBAPixel {
var normComponents: [Double] {
norm().components
}
}
func asciiDiff(buffer1: RGBABuffer, buffer2: RGBABuffer) -> String {
zip(buffer1.pixels, buffer2.pixels)
.concurrentMap { l1, l2 in zip(l1, l2)
.map { p1, p2 in
let deviation = zip(p1.normComponents, p2.normComponents)
.map(-)
.rootMeanSquare()
return symbolForRelativeDeviation(deviation)
}
.joined()
}
.joined(separator: "\n")
}
Main.main()
| 24.37963 | 88 | 0.664261 |
8f921c5c0699da5727ff6fb4b14f71ebfb4fdc2c | 4,555 | import SpriteKit
class ArkonEmbryo {
var arkonBuilder: ArkonBuilder?
var fishday: Fishday?
var metabolism: Metabolism?
var name: ArkonName?
var net: Net?
var netDisplay: NetDisplay?
var netStructure: NetStructure?
var newborn: Stepper?
var noseSprite: SKSpriteNode?
weak var parentArkon: Stepper?
var sensorPad: SensorPad?
var spindle: Spindle?
var spindleTarget: GridCell?
let spindleTargetIsPreLocked: Bool
var thoraxSprite: SKSpriteNode?
var toothSprite: SKSpriteNode?
init(
_ parentArkon: Stepper?, _ spindleTarget: GridCell,
spindleTargetIsPreLocked: Bool
) {
self.spindleTargetIsPreLocked = spindleTargetIsPreLocked
self.arkonBuilder = ArkonBuilder(embryo: self)
self.spindleTarget = spindleTarget
self.parentArkon = parentArkon
}
func beginLife(_ onOffspringReadyToSeparate: (() -> Void)?) {
buildArkon(onOffspringReadyToSeparate)
}
}
extension ArkonEmbryo {
func buildArkon(_ onOffspringReadyToSeparate: (() -> Void)?) {
Debug.log(level: 209) { "buildArkon" }
var worldClock = 0
var cNeurons = 0
Clock.dispatchQueue.async { buildArkon_0() }
func buildArkon_0() { worldClock = Int(Clock.shared.worldClock); buildArkon_1() }
func buildArkon_1() { mainDispatch(buildArkon_A) }
func buildArkon_A() { buildNetStructure(); buildArkon_B() }
func buildArkon_B() { Census.dispatchQueue.async(execute: buildArkon_C) }
func buildArkon_C() {
cNeurons = Census.shared.registerBirth(netStructure!, parentArkon)
self.fishday = Fishday(currentTime: worldClock, cNeurons: cNeurons)
buildArkon_D()
}
func buildArkon_D() { mainDispatch(buildArkon_E) }
func buildArkon_E() { arkonBuilder!.buildGuts(buildArkon_F) }
func buildArkon_F() { SceneDispatch.shared.schedule(buildArkon_G) }
func buildArkon_G() { arkonBuilder!.buildSprites(buildArkon_H) }
func buildArkon_H() { SceneDispatch.shared.schedule(buildArkon_I) }
func buildArkon_I() { arkonBuilder!.setupNetDisplay(buildArkon_J) }
func buildArkon_J() { mainDispatch(buildArkon_K) }
func buildArkon_K() { self.launch(onOffspringReadyToSeparate) }
}
func buildNetStructure() {
self.netStructure = NetStructure(
parentArkon?.net.netStructure.cSenseRings,
parentArkon?.net.netStructure.layerDescriptors
)
}
func launch(_ onOffspringReadyToSeparate: (() -> Void)?) {
self.newborn = Stepper(self)
self.newborn!.spindle.postInit(self.newborn!)
if let oof = onOffspringReadyToSeparate {
Debug.log(level: 212) { "separate \(self.newborn!.name) from parent" }
mainDispatch(oof)
}
Debug.log(level: 214) {
"launch newborn \(self.newborn!.name) child of \(AKName(parentArkon?.name))"
+ " at spindle target \(self.spindleTarget!.properties)"
}
func launch_A() { SceneDispatch.shared.schedule(launch_B) }
func launch_B() {
SpriteFactory.shared.arkonsPool.attachSprite(newborn!.thorax)
let birthDance = SKAction.rotate(byAngle: -2 * CGFloat.tau, duration: 0.5)
newborn!.thorax.run(birthDance)
// let deathDance = SKAction.rotate(byAngle: -2 * CGFloat.tau, duration: 1)
// let forever = SKAction.repeatForever(deathDance)
// newborn!.tooth.run(forever)
// Parent will have relinquished its hold on the live connection
newborn!.spindle.attachToGrid(iHaveTheLiveConnection: spindleTargetIsPreLocked, launch_C)
}
func launch_C() {
// Should do this long before, during the build process when we have
// the census lock already, but it's ugly and I don't feel like
// fixing it right now
Census.dispatchQueue.async {
Census.shared.censusAgent.insert(self.newborn!)
launch_D()
}
}
func launch_D() {
// Away we go. If I'm supernatural, I might have to wait for my
// birth cell to become available, if someone else is in it, or
// looking at it. If I'm a natural birth, an offspring from an
// arkon, the cell is locked and waiting just for me
newborn!.spindle.sensorPad.engageSensors(newborn!.tickLife)
}
launch_A()
}
}
| 35.038462 | 101 | 0.638639 |
e6bc934148193e015f8e29d97fb818001b2bdbe2 | 10,575 | //
// HomeView.swift
// AsiKarnesiMobil
//
// Created by Elif Basak Yildirim on 5.04.2021.
//
import SwiftUI
import FirebaseAuth
import UIKit
import UserNotifications
struct HomeView: View {
let timer = Timer.publish(every: 60, on: .main, in: .common).autoconnect()
/// Gerekli tüm ViewModel'leri bağlıyorum:
@StateObject var viewModel = HomeViewModel()
@StateObject var asilarimViewModel = MyVaccinesViewModel()
@StateObject var friendsViewModel = FriendsViewModel()
@StateObject var requestViewModel = FriendRequestViewModel()
@StateObject var userViewModel = UserViewModel()
@StateObject var googleViewModel = GoogleContactsViewModel()
/// App Delegate'te kullanıcı giriş yaptıktan sonra UserDefaults'a kaydettiğimiz kullanıcı ID Token ve GoogleID bu değişkenler sayesinde alabiliyorum. (@AppStorage)
@AppStorage("idToken") var idToken = ""
@AppStorage("userID") var userID = ""
@AppStorage("email") var email = ""
@AppStorage("name") var name = ""
@AppStorage("accessToken") var accessToken = ""
/// Arkadaşlık isteklerini görünütülemek için Bool değişkeni
@State var show = false
/// Çıkış yapınca LoginView()'a gitmek için FullScreen modal değişkeni
@State var isPresented = false
// Button Titles:
@State var asilarimButtonTittle = "Aşılarım"
@State var arkadalarimButtonTittle = "Arkadaşlarım"
@State var QRscanButtonTittle = "QR Scan"
@State var QRgenerateButtonTittle = "QR Generate"
/// Profile:
@State var showProfile = false
/// Google Contacts:
@State var showContacts = false
var body: some View {
/// NavigationView olmadan görünümler arası geçiş yapamayız. UIKit teki karşığı NavController ve Segue
NavigationView{
/*
ZStack -> ZStack bloğu içerisine konulan her şey üst üste gelir. En yukarıdaki satır en arkada en alttaki satır en üste.
VStack -> Vertical Stack içerisindeki her şeyi alt alta koyar.
HStack -> Horizontal Stack içerisindeki her şeyi yan yana koyar.
NOT: ZStack içerisindeki herhangi bir görünümün üstte mi altta mı olacağına .zIndex(Int) ile belirleyebiliriz.
*/
ZStack{
NavigationLink("", destination: AsilarimView(homeViewModel : viewModel, viewModel: asilarimViewModel), isActive: $viewModel.nav1)
NavigationLink("", destination: ArkadaslarimView(homeViewModel : viewModel, viewModel: friendsViewModel, requestModel: requestViewModel), isActive: $viewModel.nav2)
NavigationLink("", destination: ScannerView(homeViewModel: viewModel), isActive: $viewModel.nav3)
NavigationLink("", destination: QRGenerateView(homeViewModel : viewModel, vaccinesModel: asilarimViewModel), isActive: $viewModel.nav4)
NavigationLink("", destination: LoginView(), isActive: $isPresented)
NavigationLink("", destination: ProfileView(viewModel: userViewModel), isActive: $showProfile)
NavigationLink("", destination: GoogleContactsView(viewModel: googleViewModel), isActive: $showContacts)
VStack(spacing:25){
VStack(alignment: .leading){
if let data = self.userViewModel.userData?.info {
HStack(spacing:0){
Text("Merhaba ")
.foregroundColor(.white)
.font(.system(size: 24, weight: .medium, design: .default))
Text("\(data.name)!")
.foregroundColor(.white)
.font(.system(size: 24, weight: .bold, design: .default))
}
.padding(.top, 25)
}
}
.frame(maxWidth: UIScreen.main.bounds.width, alignment: .leading)
HStack(spacing: 25){
/// Aşılarım Butonu
Button(action: {
self.viewModel.asilarButton()
}, label: {
HomeViewButtonsView(title: self.asilarimButtonTittle)
})
/// Arkadaşlarım Butonu
Button(action: {
self.viewModel.arkadaslarimButton()
}, label: {
HomeViewButtonsView(title: self.arkadalarimButtonTittle)
})
}
HStack(spacing:25){
/// QR Okuyucu Butonu
Button(action: {
self.viewModel.qrScanButton()
}, label: {
HomeViewButtonsView(title: self.QRscanButtonTittle)
})
/// QR Yaratma Butonu
Button(action: {
self.viewModel.qrGenerateButton()
}, label: {
HomeViewButtonsView(title: self.QRgenerateButtonTittle)
})
}
Button {
self.showContacts = true
} label: {
ZStack{
Color.purple
.cornerRadius(15)
.frame(height: 100, alignment: .center)
Text("Google Contacts")
.foregroundColor(.black)
.font(.system(size: 18, weight: .semibold, design: .rounded))
}
}
Spacer()
Button {
self.showProfile = true
} label: {
VStack(spacing:0){
Image(systemName: "person.crop.circle.fill")
.foregroundColor(.black)
.font(.system(size: 18, weight: .semibold, design: .rounded))
Text("Profil")
.foregroundColor(.black)
.font(.system(size: 18, weight: .semibold, design: .rounded))
}
.padding(.vertical,10)
.padding(.horizontal, 30)
.background(Color.purple.cornerRadius(15))
}
}
.padding(.horizontal, 15)
}
.navigationBarTitle("")
.navigationBarTitleDisplayMode(.inline)
/// Bu görünüm her göründüğünde çağırılacak fonksiyonlar
.onAppear(perform: {
self.asilarimViewModel.fetchJSON(googleID: self.userID)
self.friendsViewModel.fetchJSON(googleID: self.userID)
self.requestViewModel.fetchJSON(googleID: self.userID)
self.userViewModel.fetchJSON(googleID: self.userID)
self.googleViewModel.fetchJSON(googleID: self.userID)
print("Current User: \(self.email)")
print(self.userID)
})
/// Çıkış yapma butonu:
.navigationBarItems(leading:
Button(action: {
self.show = true
}, label: {
Text("Arkadaş istekleri")
}), trailing:
Button(action: {
self.viewModel.signOutButton { (result) in
if result == true {
self.idToken = ""
self.userID = ""
self.email = ""
self.name = ""
self.accessToken = ""
self.isPresented = true
}
}
}, label: {
Text("Çıkış")
}))
.sheet(isPresented: $show){
FriendRequestView(viewModel: self.requestViewModel, friendModel: friendsViewModel)
}
.onReceive(timer) { input in
self.requestViewModel.fetchJSON(googleID: self.userID)
if self.requestViewModel.friendModel.isEmpty == true {
print("Arakdaşlık isteği Yok")
} else {
print("İSTEK GELDİ!!!!!!!!!!--------!!!!!!!!!!!!!!!!!!!!!")
var name = ""
let label = "Sana arkadaşlık isteği gönderdi"
for data in self.requestViewModel.friendModel {
name = data.requester_name
}
// second
let content = UNMutableNotificationContent()
content.title = "\(name) \(label)"
content.sound = UNNotificationSound.default
// show this notification five seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// add our notification request
UNUserNotificationCenter.current().add(request)
}
}
}
}
}
| 46.179039 | 180 | 0.456265 |
1eae50fffa5273134ac8ede1d5afca8acf514372 | 2,605 | //
// SSQMUIViewController.swift
// SwiftStudy
//
// Created by Zhu ChaoJun on 2020/6/2.
// Copyright © 2020 Zhu ChaoJun. All rights reserved.
//
import UIKit
/*
类的继承关系。
NSObject基类->UIResponder(接受事件,内部有touchxxx点击事件、motionxxx加速计、remoteControlReceivedWithEvent远程控制)->UIView(显示)->UIControl(addTarge等方法)->UIButton。
继承自UIResponse的有UIIVew、UIVIewController、UIApplication、AppDelegate。
CALayer直接继承NSObject所以不能接受事件。
QMUI是实现的逻辑,1、当QMUITheme.shareInstance.setThemeIdentify的时候,会调用notificyName方法,然后会调用UIview层的quuiThemeDidChangexxxx方法。
然后在UIView的分类中,会重写获取view的一些属性进行赋值。
*/
class SSQMUIViewController: QMUICommonViewController {
lazy var datas = ["QMUIDispalyLinkAnimation","QMUIAsset", ""]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
navigationItem.title = "ThirdFramework"
let tabV = UITableView()
tabV.delegate = self
tabV.dataSource = self
tabV.tableFooterView = UIView()
view.addSubview(tabV)
tabV.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
}
extension SSQMUIViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "cellID"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellId)
}
cell?.textLabel?.text = datas[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
navigationController?.pushViewController(SSDisplayLinkAnimationVC(), animated: true)
}else if indexPath.row == 1 {
navigationController?.pushViewController(SSAssetLibVC(), animated: true)
}else {
}
}
}
// runtime 增加属性。
extension SSQMUIViewController {
private struct AssociatedKey {
static var nameKey: String = ""
}
var name: String {
set {
objc_setAssociatedObject(self, &AssociatedKey.nameKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &AssociatedKey.nameKey) as! String
}
}
}
| 26.313131 | 141 | 0.659117 |
3365428ba008190165944b52462e0ad06e4c5899 | 8,851 | import CoreData
import LlamaKit
public enum StoreType {
case Sqlite
case Binary
case Memory
func toString() -> NSString {
switch self {
case .Sqlite:
return NSSQLiteStoreType
case .Binary:
return NSBinaryStoreType
case .Memory:
return NSInMemoryStoreType
}
}
}
public class CoreDataStorage: NSObject {
private let modelName: String
private let storeType: StoreType
private let storeOptions: [NSObject : AnyObject]?
let managedObjectModel: NSManagedObjectModel = NSManagedObjectModel()
let persistentStoreCoordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel())
let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext()
public init(modelName name: String, storeType type: StoreType, storeOptions options: [NSObject : AnyObject]?) {
modelName = name
storeType = type
super.init()
if type == StoreType.Memory {
storeOptions = nil
}
else {
if let _storeOptions = options {
storeOptions = _storeOptions
}
else {
storeOptions = defaultStoreOptions(storeType)
}
}
managedObjectModel = managedObjectModel(managedObjectModelPath(modelName))
persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
let persistancePath = storePathForFilename(persistentFilePath(persistentStoreDirectory(directoryPath()), fileName: sqliteFileName(modelName)))
addPersistanceStoreWithPath(persistentStoreCoordinator, storePath: persistancePath, options: storeOptions)
managedObjectContext = managedObjectContext(persistentStoreCoordinator)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "managedObjectContextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext)
}
private func sqliteFileName(filePath: String) -> String {
if filePath.pathExtension == "sqlite" {
return filePath
}
if let path = filePath.stringByDeletingPathExtension.stringByAppendingPathExtension("sqlite") {
return path
}
return filePath
}
private func defaultStoreOptions(storeType: StoreType) -> [NSObject : AnyObject]? {
if (storeType != StoreType.Memory) {
return [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
}
return nil
}
private func directoryPath() -> String {
if let displayName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as String? {
return displayName
}
return "CoreDataStorage"
}
private func persistentStoreDirectory(directoryPath: String) -> String {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let basePath = (paths.count > 0) ? paths[0] as String : NSTemporaryDirectory()
let fullPath = basePath.stringByAppendingPathComponent(directoryPath)
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(fullPath) {
fileManager.createDirectoryAtPath(fullPath, withIntermediateDirectories: true, attributes: nil, error: nil)
}
return fullPath
}
private func persistentFilePath(directory: String, fileName: String) -> String {
return directory.stringByAppendingPathComponent(fileName)
}
private func addPersistanceStoreWithPath(persistentStoreCoordinator: NSPersistentStoreCoordinator, storePath: NSURL?, options: [NSObject : AnyObject]?) -> NSPersistentStore? {
if let aStorePath = storePath {
return persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: aStorePath, options: options, error: nil);
}
else {
return persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: nil)
}
}
private func managedObjectModelPath(name: String) -> String? {
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "mom") {
return path
}
if let path = NSBundle.mainBundle().pathForResource(name, ofType: "momd") {
return path
}
return nil
}
private func managedObjectModel(path: String?) -> NSManagedObjectModel {
if let momPath = path {
if let momURL = NSURL(fileURLWithPath: momPath) {
if let managedObject = NSManagedObjectModel(contentsOfURL: momURL) {
return managedObject
}
}
}
return NSManagedObjectModel()
}
private func storePathForFilename(filePath: String?) -> NSURL? {
if let _filePath = filePath {
if let storePath = NSURL(fileURLWithPath: _filePath) {
return storePath
}
}
return nil
}
private func managedObjectContext(persistentStoreCoordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext {
//TODO: check for queue
let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator;
managedObjectContext.undoManager = nil;
return managedObjectContext
}
private func managedObjectContextDidSave(notification: NSNotification) {
//TODO: check for queue
let sender = notification.object as NSManagedObjectContext;
if sender != managedObjectContext && sender.persistentStoreCoordinator == managedObjectContext.persistentStoreCoordinator {
if let dictionary = notification.userInfo as [NSObject : AnyObject]? {
if let array = dictionary[NSUpdatedObjectsKey] as [NSManagedObject]? {
for object:NSManagedObject in array {
managedObjectContext.objectWithID(object.objectID)
}
}
}
managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
extension NSManagedObject {
convenience public init(name: String, context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context)
self.init(entity: entity!, insertIntoManagedObjectContext: context)
}
}
extension NSManagedObjectContext {
public func save() -> Result<Void> {
if persistentStoreCoordinator?.persistentStores.count <= 0 {
return failure(CoreDataStorage.noPersistentStoresError())
}
var error: NSError?
save(&error)
if let _error = error {
return failure(_error)
}
else {
return success()
}
}
}
extension NSFetchedResultsController {
public func performFetch() -> Result<Void> {
var error: NSError?
performFetch(&error)
if let _error = error {
return failure(_error)
}
else {
return success()
}
}
}
extension CoreDataStorage {
public class func noPersistentStoresError() -> NSError {
return NSError(domain: "CoreDataStorage", code: 1, userInfo: [NSLocalizedDescriptionKey: "This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation."])
}
} | 32.421245 | 196 | 0.620721 |
f7b80e7385db97953841faac9721f6b1932e0572 | 1,503 | //
// Dictionary+String.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2018 Stanwood GmbH (www.stanwood.io)
//
// 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
extension Dictionary where Key == String {
var prettyString: String {
var headers = String()
headers += "[\n"
forEach({
headers += " \($0.key) : \($0.value)\n"
})
headers += "]"
return headers
}
}
| 36.658537 | 81 | 0.692615 |
f79f0e4897d57f65ad214c036e051ac7563f88ac | 9,220 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import Foundation
import NIOCore
import NIOFoundationCompat
import NIOConcurrencyHelpers
import Dispatch
import Network
/// An object that conforms to this protocol represents the substate of a channel in the
/// active state. This can be used to provide more fine-grained tracking of states
/// within the active state of a channel. Example uses include for tracking TCP half-closure
/// state in a TCP stream channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
internal protocol ActiveChannelSubstate {
/// Create the substate in its default initial state.
init()
}
/// A state machine enum that tracks the state of the connection channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
internal enum ChannelState<ActiveSubstate: ActiveChannelSubstate> {
case idle
case registered
case activating
case active(ActiveSubstate)
case inactive
/// Unlike every other one of these methods, this one has a side-effect. This is because
/// it's impossible to correctly be in the reigstered state without verifying that
/// registration has occurred.
fileprivate mutating func register(eventLoop: NIOTSEventLoop, channel: Channel) throws {
guard case .idle = self else {
throw NIOTSErrors.InvalidChannelStateTransition()
}
try eventLoop.register(channel)
self = .registered
}
fileprivate mutating func beginActivating() throws {
guard case .registered = self else {
throw NIOTSErrors.InvalidChannelStateTransition()
}
self = .activating
}
fileprivate mutating func becomeActive() throws {
guard case .activating = self else {
throw NIOTSErrors.InvalidChannelStateTransition()
}
self = .active(ActiveSubstate())
}
fileprivate mutating func becomeInactive() throws -> ChannelState {
let oldState = self
switch self {
case .idle, .registered, .activating, .active:
self = .inactive
case .inactive:
// In this state we're already closed.
throw ChannelError.alreadyClosed
}
return oldState
}
}
/// The kinds of activation that a channel may support.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
internal enum ActivationType {
case connect
case bind
}
/// A protocol for `Channel` implementations with a simple Network.framework
/// state management layer.
///
/// This protocol provides default hooks for managing state appropriately for a
/// given channel. It also provides some default implementations of `Channel` methods
/// for simple behaviours.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
internal protocol StateManagedChannel: Channel, ChannelCore {
associatedtype ActiveSubstate: ActiveChannelSubstate
var state: ChannelState<ActiveSubstate> { get set }
var isActive0: NIOAtomic<Bool> { get set }
var tsEventLoop: NIOTSEventLoop { get }
var closePromise: EventLoopPromise<Void> { get }
var supportedActivationType: ActivationType { get }
func beginActivating0(to: NWEndpoint, promise: EventLoopPromise<Void>?) -> Void
func becomeActive0(promise: EventLoopPromise<Void>?) -> Void
func alreadyConfigured0(promise: EventLoopPromise<Void>?) -> Void
func doClose0(error: Error) -> Void
func doHalfClose0(error: Error, promise: EventLoopPromise<Void>?) -> Void
func readIfNeeded0() -> Void
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
extension StateManagedChannel {
public var eventLoop: EventLoop {
return self.tsEventLoop
}
/// Whether this channel is currently active.
public var isActive: Bool {
return self.isActive0.load()
}
/// Whether this channel is currently closed. This is not necessary for the public
/// API, it's just a convenient helper.
internal var closed: Bool {
switch self.state {
case .inactive:
return true
case .idle, .registered, .activating, .active:
return false
}
}
public func register0(promise: EventLoopPromise<Void>?) {
// TODO: does this need to do anything more than this?
do {
try self.state.register(eventLoop: self.tsEventLoop, channel: self)
self.pipeline.fireChannelRegistered()
promise?.succeed(())
} catch {
promise?.fail(error)
self.close0(error: error, mode: .all, promise: nil)
}
}
public func registerAlreadyConfigured0(promise: EventLoopPromise<Void>?) {
do {
try self.state.register(eventLoop: self.tsEventLoop, channel: self)
self.pipeline.fireChannelRegistered()
try self.state.beginActivating()
promise?.succeed(())
} catch {
promise?.fail(error)
self.close0(error: error, mode: .all, promise: nil)
return
}
// Ok, we are registered and ready to begin activating. Tell the channel: it must
// call becomeActive0 directly.
self.alreadyConfigured0(promise: promise)
}
public func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
self.activateWithType(type: .connect, to: NWEndpoint(fromSocketAddress: address), promise: promise)
}
public func connect0(to endpoint: NWEndpoint, promise: EventLoopPromise<Void>?) {
self.activateWithType(type: .connect, to: endpoint, promise: promise)
}
public func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
self.activateWithType(type: .bind, to: NWEndpoint(fromSocketAddress: address), promise: promise)
}
public func bind0(to endpoint: NWEndpoint, promise: EventLoopPromise<Void>?) {
self.activateWithType(type: .bind, to: endpoint, promise: promise)
}
public func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) {
switch mode {
case .all:
let oldState: ChannelState<ActiveSubstate>
do {
oldState = try self.state.becomeInactive()
} catch let thrownError {
promise?.fail(thrownError)
return
}
self.isActive0.store(false)
self.doClose0(error: error)
switch oldState {
case .active:
self.pipeline.fireChannelInactive()
fallthrough
case .registered, .activating:
self.tsEventLoop.deregister(self)
self.pipeline.fireChannelUnregistered()
case .idle:
// If this was already idle we don't have anything to do.
break
case .inactive:
preconditionFailure("Should be prevented by state machine")
}
// Next we fire the promise passed to this method.
promise?.succeed(())
// Now we schedule our final cleanup. We need to keep the channel pipeline alive for at least one more event
// loop tick, as more work might be using it.
self.eventLoop.execute {
self.removeHandlers(pipeline: self.pipeline)
self.closePromise.succeed(())
}
case .input:
promise?.fail(ChannelError.operationUnsupported)
case .output:
self.doHalfClose0(error: error, promise: promise)
}
}
public func becomeActive0(promise: EventLoopPromise<Void>?) {
// Here we crash if we cannot transition our state. That's because my understanding is that we
// should not be able to hit this.
do {
try self.state.becomeActive()
} catch {
self.close0(error: error, mode: .all, promise: promise)
return
}
self.isActive0.store(true)
promise?.succeed(())
self.pipeline.fireChannelActive()
self.readIfNeeded0()
}
/// A helper to handle the fact that activation is mostly common across connect and bind, and that both are
/// not supported by a single channel type.
private func activateWithType(type: ActivationType, to endpoint: NWEndpoint, promise: EventLoopPromise<Void>?) {
guard type == self.supportedActivationType else {
promise?.fail(ChannelError.operationUnsupported)
return
}
do {
try self.state.beginActivating()
} catch {
promise?.fail(error)
return
}
self.beginActivating0(to: endpoint, promise: promise)
}
}
#endif
| 33.527273 | 120 | 0.632972 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.