repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EugeneTrapeznikov/ETCollapsableTable
|
Source/ETCollapsableTable.swift
|
1
|
3444
|
//
// ETCollapsableTable.swift
// ETCollapsableTable
//
// Created by Eugene Trapeznikov on 9/2/16.
// Copyright © 2016 Evgenii Trapeznikov. All rights reserved.
//
import Foundation
import UIKit
open class ETCollapsableTable: UIViewController {
fileprivate var items : [ETCollapsableTableItem] = []
override open func viewDidLoad() {
super.viewDidLoad()
items = buildItems()
}
// MARK: - Public methods
open func buildItems() -> [ETCollapsableTableItem] {
// override in subclass
return []
}
open func singleOpenSelectionOnly() -> Bool {
// could be overridden, but not necessary
return true
}
open func itemAtIndexPath(_ indexPath: IndexPath) -> ETCollapsableTableItem {
var item = items[indexPath.section]
if indexPath.row != 0 {
item = item.items[indexPath.row - 1]
}
return item
}
// MARK: - Public table view methods
open func numberOfSections() -> Int {
return items.count
}
open func numberOfRowsInSection(_ section: Int) -> Int {
let item = items[section]
var count = 0
if item.isOpen {
count = item.items.count + 1
}
else {
count = 1
}
return count
}
open func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
let item = items[indexPath.section]
if indexPath.row == 0 && item.items.count > 0 {
toogleMenuForItem(item, inTableView: tableView, atIndexPath: indexPath)
}
}
// MARK: - Private methods
fileprivate func toogleMenuForItem(_ item: ETCollapsableTableItem, inTableView tableView: UITableView, atIndexPath indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ETCollapsableTableCell
tableView.beginUpdates()
var foundOpenUnchosenMenuSection = false
for (index, sectionItem) in items.enumerated() {
let isChosenMenuSection = sectionItem == item
let isOpen = sectionItem.isOpen
if (isChosenMenuSection && isOpen) {
sectionItem.isOpen = false
cell.closeAnimated(true)
let indexPaths = indexPathsForSection(indexPath.section,
andItem: sectionItem)
tableView.deleteRows(at: indexPaths,
with: foundOpenUnchosenMenuSection ? .bottom : .top)
}
else if (!isOpen && isChosenMenuSection) {
sectionItem.isOpen = true
cell.openAnimated(true)
let indexPaths = indexPathsForSection(indexPath.section,
andItem: sectionItem)
tableView.insertRows(at: indexPaths,
with: foundOpenUnchosenMenuSection ? .bottom : .top)
}
else if (isOpen && !isChosenMenuSection && singleOpenSelectionOnly()) {
foundOpenUnchosenMenuSection = true
sectionItem.isOpen = false
let cell = tableView.cellForRow(at: IndexPath(row: 0, section: index)) as! ETCollapsableTableCell
cell.closeAnimated(true)
let indexPaths = indexPathsForSection(index,
andItem: sectionItem)
tableView.deleteRows(at: indexPaths, with: indexPath.section > index ? .top : .bottom)
}
}
tableView.endUpdates()
}
fileprivate func indexPathsForSection(_ section: Int, andItem item: ETCollapsableTableItem) -> [IndexPath] {
var collector: [IndexPath] = []
let count = item.items.count
for i in 1...count {
let indexPath = IndexPath(row: i, section: section)
collector.append(indexPath)
}
return collector
}
}
|
mit
|
4ba625b7c97e38ef59d20d6470932fd1
| 22.582192 | 139 | 0.67325 | 3.881623 | false | false | false | false |
bigtreenono/NSPTools
|
RayWenderlich/Introduction to Swift/1 . Variables and Constants/DemoVariables.playground/section-1.swift
|
1
|
401
|
// Playground - noun: a place where people can play
import UIKit
let str = "Hello, playground"
var myInt = 1
var myDouble = 3.14
var myBool = true
var myString = "Kermit"
var myString2: String = "Kermit2"
// str = "Goodbye, playground"
var view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.greenColor()
view
var j = 2
for i in 1 ..< 10 {
j *= i
}
|
mit
|
de9b704699d4363448425620faafbc7a
| 18.095238 | 69 | 0.670823 | 2.97037 | false | false | false | false |
avidas/CameraSwift
|
CameraSwift/ViewController.swift
|
1
|
3333
|
//
// ViewController.swift
// CameraSwift
//
// Created by Das, Ananya on 9/17/14.
// Copyright (c) 2014 Das, Ananya. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UIAlertViewDelegate, UITableViewDataSource {
var imagePicker : UIImagePickerController? = nil
var actionSheet : UIActionSheet? = nil
var imagesList : [UIImage] = []
@IBOutlet weak var tbView: UITableView!
@IBAction func captureImage(sender: AnyObject) {
actionSheet = UIActionSheet(title: "UploadImage", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Library Image","Camera Image")
actionSheet?.showInView(self.view)
}
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
//why 1 and not 0 as in objective C
if (buttonIndex==1) {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) {
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
imagePicker?.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
// need to guarantee that never nil
self.presentViewController(imagePicker!, animated:true, completion: nil)
}
}
else if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
imagePicker?.sourceType = UIImagePickerControllerSourceType.Camera
// need to guarantee that never nil
self.presentViewController(imagePicker!, animated:true, completion: nil)
}
else {
println("\(buttonIndex)")
var alert : UIAlertView = UIAlertView(title: "Error accessing Camera", message: "Device does not support camera", delegate: self, cancelButtonTitle: "Dismiss")
alert.show()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var image : UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
imagesList.append(image)
tbView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imagesList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "photocell"
var cell: CustomPhotoTableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier) as CustomPhotoTableViewCell
if (imagesList.count > 0) {
cell.backgroundImageView.image = imagesList[indexPath.row]
}
return cell
}
}
|
mit
|
ce456040794909315b5a16c453765996
| 37.310345 | 182 | 0.674767 | 5.983842 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxSwift/RxSwift/Traits/Completable.swift
|
20
|
11485
|
//
// Completable.swift
// RxSwift
//
// Created by sergdort on 19/08/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
#if DEBUG
import Foundation
#endif
/// Sequence containing 0 elements
public enum CompletableTrait { }
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> Void
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<Trait, Element> {
let source = Observable<Element>.create { observer in
return subscribe { event in
switch event {
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> Void) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
#if DEBUG
let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : []
#else
let callStack = [String]()
#endif
return self.primitiveSequence.subscribe { event in
switch event {
case .error(let error):
if let onError = onError {
onError(error)
} else {
Hooks.defaultErrorHandler(callStack, error)
}
case .completed:
onCompleted?()
}
}
}
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> Completable {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> Completable {
return PrimitiveSequence(raw: Observable.never())
}
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> Completable {
return Completable(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where Trait == CompletableTrait, Element == Swift.Never {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter afterError: Action to invoke after errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onError: ((Swift.Error) throws -> Void)? = nil,
afterError: ((Swift.Error) throws -> Void)? = nil,
onCompleted: (() throws -> Void)? = nil,
afterCompleted: (() throws -> Void)? = nil,
onSubscribe: (() -> Void)? = nil,
onSubscribed: (() -> Void)? = nil,
onDispose: (() -> Void)? = nil)
-> Completable {
return Completable(raw: self.primitiveSequence.source.do(
onError: onError,
afterError: afterError,
onCompleted: onCompleted,
afterCompleted: afterCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat(_ second: Completable) -> Completable {
return Completable.concat(self.primitiveSequence, second)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Completable
where Sequence.Element == Completable {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Completable
where Collection.Element == Completable {
let source = Observable.concat(collection.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Completable ...) -> Completable {
let source = Observable.concat(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables from a collection into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Collection of Completables to merge.
- returns: A Completable that merges the completion of all Completables.
*/
public static func zip<Collection: Swift.Collection>(_ sources: Collection) -> Completable
where Collection.Element == Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables from an array into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Array of observable sequences to merge.
- returns: A Completable that merges the completion of all Completables.
*/
public static func zip(_ sources: [Completable]) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
/**
Merges the completion of all Completables into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- note: For `Completable`, `zip` is an alias for `merge`.
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func zip(_ sources: Completable...) -> Completable {
let source = Observable.merge(sources.map { $0.asObservable() })
return Completable(raw: source)
}
}
|
mit
|
9e41c1524157eac83afde29ad792aa67
| 41.850746 | 220 | 0.661964 | 5.22 | false | false | false | false |
seraphjiang/JHUIKit
|
JHUIKit/Classes/JHRingView.swift
|
1
|
1239
|
//
// JHRingView.swift
// Pods
//
// Created by Huan Jiang on 5/7/16.
//
//
import UIKit
/// A simple ring view
//https://developer.apple.com/videos/play/wwdc2014/411/
@IBDesignable
public class JHRingView: UIView {
let lineWidth: CGFloat = 10.0
var backgroundRingLayer: CAShapeLayer!
var ringLayer: CAShapeLayer!
/**
layout subviews to add ring
*/
override public func layoutSubviews() {
super.layoutSubviews()
if (backgroundRingLayer == nil) {
backgroundRingLayer = CAShapeLayer()
layer.addSublayer(backgroundRingLayer)
// stroke will have half out side border , half inside border, use inset to make sure
// we are drawing inside area we want.
let rect = CGRectInset(bounds, lineWidth/2.0, lineWidth/2.0)
let path = UIBezierPath(ovalInRect: rect)
backgroundRingLayer.path = path.CGPath
backgroundRingLayer.fillColor = nil
backgroundRingLayer.lineWidth = lineWidth
backgroundRingLayer.strokeColor = UIColor(white: 0.5, alpha: 0.3).CGColor
}
backgroundRingLayer.frame = layer.bounds
}
}
|
mit
|
ded03e279a3943dd967adf789a39e892
| 27.813953 | 98 | 0.614205 | 4.858824 | false | false | false | false |
carabina/ActionSwift3
|
ActionSwift3/UIColor.swift
|
1
|
2317
|
//
// UIColor.swift
// ActionSwift
//
// Created by Craig on 5/08/2015.
// Copyright (c) 2015 Interactive Coconut. All rights reserved.
//
import Foundation
import UIKit
/**
Add hex initializer, eg `UIColor(hex:"#FFFFFF")
*/
extension UIColor {
/** initialize with hex string.
Use format eg. "#FFFFFF"
*/
convenience public init(var hex: String) {
var alpha: Float = 100
let hexLength = count(hex)
if !(hexLength == 7 || hexLength == 9) {
// A hex must be either 7 or 9 characters (#GGRRBBAA)
println("improper call to 'colorFromHex', hex length must be 7 or 9 chars (#GGRRBBAA). You've called \(hex)")
self.init(white: 0, alpha: 1)
return
}
if hexLength == 9 {
var temp = hex[7...8]
alpha = temp.floatValue
hex = hex[0...6]
}
// Establishing the rgb color
var rgb: UInt32 = 0
var s: NSScanner = NSScanner(string: hex)
// Setting the scan location to ignore the leading `#`
s.scanLocation = 1
// Scanning the int into the rgb colors
s.scanHexInt(&rgb)
// Creating the UIColor from hex int
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alpha / 100)
)
}
}
/**
Add subscripts to String
*/
extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
get {
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(startIndex, r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
func lastCharacter()->String {
return self[self.length()-1]
}
var floatValue: Float {
return (self as NSString).floatValue
}
func length()->Int {
return count(self)
}
func getFirstWord()->String {
return( split(self) {$0 == " "}[0])
}
}
|
mit
|
7e7ea14b32f9bfcf24fd8788b6d8ebce
| 25.94186 | 121 | 0.542512 | 4.015598 | false | false | false | false |
lbkchen/cvicu-app
|
complicationsapp/Pods/Eureka/Source/Core/Row.swift
|
1
|
5508
|
// Row.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 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
public class RowOf<T: Equatable>: BaseRow {
/// The typed value of this row.
public var value : T?{
didSet {
guard value != oldValue else { return }
guard let form = section?.form else { return }
if let delegate = form.delegate {
delegate.rowValueHasBeenChanged(self, oldValue: oldValue, newValue: value)
callbackOnChange?()
}
guard let t = tag else { return }
form.tagToValues[t] = value as? AnyObject ?? NSNull()
if let rowObservers = form.rowObservers[t]?[.Hidden]{
for rowObserver in rowObservers {
(rowObserver as? Hidable)?.evaluateHidden()
}
}
if let rowObservers = form.rowObservers[t]?[.Disabled]{
for rowObserver in rowObservers {
(rowObserver as? Disableable)?.evaluateDisabled()
}
}
}
}
/// The untyped value of this row.
public override var baseValue: Any? {
get { return value }
set { value = newValue as? T }
}
/// Variable used in rows with options that serves to generate the options for that row.
public var dataProvider: DataProvider<T>?
/// Block variable used to get the String that should be displayed for the value of this row.
public var displayValueFor : (T? -> String?)? = {
if let t = $0 {
return String(t)
}
return nil
}
public required init(tag: String?){
super.init(tag: tag)
}
}
/// Generic class that represents an Eureka row.
public class Row<T: Equatable, Cell: CellType where Cell: TypedCellType, Cell: BaseCell, Cell.Value == T>: RowOf<T>, TypedRowType {
/// Responsible for creating the cell for this row.
public var cellProvider = CellProvider<Cell>()
/// The type of the cell associated to this row.
public let cellType: Cell.Type! = Cell.self
private var _cell: Cell! {
didSet {
RowDefaults.cellSetup["\(self.dynamicType)"]?(_cell, self)
(callbackCellSetup as? (Cell -> ()))?(_cell)
}
}
/// The cell associated to this row.
public var cell : Cell! {
return _cell ?? {
let result = cellProvider.createCell(self.cellStyle)
result.row = self
result.setup()
_cell = result
return _cell
}()
}
/// The untyped cell associated to this row
public override var baseCell: BaseCell { return cell }
public required init(tag: String?) {
super.init(tag: tag)
}
/**
Method that reloads the cell
*/
override public func updateCell() {
super.updateCell()
cell.update()
customUpdateCell()
RowDefaults.cellUpdate["\(self.dynamicType)"]?(cell, self)
callbackCellUpdate?()
}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
public override func didSelect() {
super.didSelect()
if !isDisabled {
cell?.didSelect()
}
customDidSelect()
callbackCellOnSelection?()
}
/**
Method that is responsible for highlighting the cell.
*/
override public func hightlightCell() {
super.hightlightCell()
cell.highlight()
RowDefaults.onCellHighlight["\(self.dynamicType)"]?(cell, self)
callbackOnCellHighlight?()
}
/**
Method that is responsible for unhighlighting the cell.
*/
public override func unhighlightCell() {
super.unhighlightCell()
cell.unhighlight()
RowDefaults.onCellUnHighlight["\(self.dynamicType)"]?(cell, self)
callbackOnCellUnHighlight?()
}
/**
Will be called inside `didSelect` method of the row. Can be used to customize row selection from the definition of the row.
*/
public func customDidSelect(){}
/**
Will be called inside `updateCell` method of the row. Can be used to customize reloading a row from its definition.
*/
public func customUpdateCell(){}
}
|
mit
|
e312086500d60b2c028544ad8aca301e
| 32.381818 | 132 | 0.616376 | 4.900356 | false | false | false | false |
SomaticLabs/SwiftyBluetooth
|
SwiftyBluetooth/Source/PeripheralProxy.swift
|
1
|
44245
|
//
// PeripheralProxy.swift
//
// Copyright (c) 2016 Jordane Belanger
//
// 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 CoreBluetooth
final class PeripheralProxy: NSObject {
static let defaultTimeoutInS: TimeInterval = 10
fileprivate lazy var readRSSIRequests: [ReadRSSIRequest] = []
fileprivate lazy var serviceRequests: [ServiceRequest] = []
fileprivate lazy var includedServicesRequests: [IncludedServicesRequest] = []
fileprivate lazy var characteristicRequests: [CharacteristicRequest] = []
fileprivate lazy var descriptorRequests: [DescriptorRequest] = []
fileprivate lazy var readCharacteristicRequests: [CBUUIDPath: [ReadCharacteristicRequest]] = [:]
fileprivate lazy var readDescriptorRequests: [CBUUIDPath: [ReadDescriptorRequest]] = [:]
fileprivate lazy var writeCharacteristicValueRequests: [CBUUIDPath: [WriteCharacteristicValueRequest]] = [:]
fileprivate lazy var writeDescriptorValueRequests: [CBUUIDPath: [WriteDescriptorValueRequest]] = [:]
fileprivate lazy var updateNotificationStateRequests: [CBUUIDPath: [UpdateNotificationStateRequest]] = [:]
fileprivate weak var peripheral: Peripheral?
let cbPeripheral: CBPeripheral
// Peripheral that are no longer valid must be rediscovered again (happens when for example the Bluetooth is turned off
// from a user's phone and turned back on
var valid: Bool = true
init(cbPeripheral: CBPeripheral, peripheral: Peripheral) {
self.cbPeripheral = cbPeripheral
self.peripheral = peripheral
super.init()
cbPeripheral.delegate = self
NotificationCenter.default.addObserver(forName: Central.CentralStateChange,
object: Central.sharedInstance,
queue: nil)
{ [weak self] (notification) in
if let state = notification.userInfo?["state"] as? CBCentralManagerState, state == .poweredOff {
self?.valid = false
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
fileprivate func postPeripheralEvent(_ event: Notification.Name, userInfo: [AnyHashable: Any]?) {
guard let peripheral = self.peripheral else {
return
}
NotificationCenter.default.post(
name: event,
object: peripheral,
userInfo: userInfo)
}
}
// MARK: Connect/Disconnect Requests
extension PeripheralProxy {
func connect(timeout: TimeInterval = 10, _ completion: @escaping ConnectPeripheralCallback) {
if self.valid {
Central.sharedInstance.connect(peripheral: self.cbPeripheral, timeout: timeout, completion: completion)
} else {
completion(.failure(SBError.invalidPeripheral))
}
}
func disconnect(_ completion: @escaping DisconnectPeripheralCallback) {
Central.sharedInstance.disconnect(peripheral: self.cbPeripheral, completion: completion)
}
}
// MARK: RSSI Requests
private final class ReadRSSIRequest {
let callback: ReadRSSIRequestCallback
init(callback: @escaping ReadRSSIRequestCallback) {
self.callback = callback
}
}
extension PeripheralProxy {
func readRSSI(_ completion: @escaping ReadRSSIRequestCallback) {
self.connect { (result) in
if let error = result.error {
completion(.failure(error))
return
}
let request = ReadRSSIRequest(callback: completion)
self.readRSSIRequests.append(request)
if self.readRSSIRequests.count == 1 {
self.runRSSIRequest()
}
}
}
fileprivate func runRSSIRequest() {
guard let request = self.readRSSIRequests.first else {
return
}
self.cbPeripheral.readRSSI()
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onReadRSSIOperationTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onReadRSSIOperationTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<ReadRSSIRequest>
guard let request = weakRequest.value else {
return
}
self.readRSSIRequests.removeFirst()
request.callback(.failure(SBError.operationTimedOut(operation: .readRSSI)))
self.runRSSIRequest()
}
}
// MARK: Service requests
private final class ServiceRequest {
let serviceUUIDs: [CBUUID]?
let callback: ServiceRequestCallback
init(serviceUUIDs: [CBUUID]?, callback: @escaping ServiceRequestCallback) {
self.callback = callback
if let serviceUUIDs = serviceUUIDs {
self.serviceUUIDs = serviceUUIDs
} else {
self.serviceUUIDs = nil
}
}
}
extension PeripheralProxy {
func discoverServices(_ serviceUUIDs: [CBUUID]?, completion: @escaping ServiceRequestCallback) {
self.connect { (result) in
if let error = result.error {
completion(.failure(error))
return
}
// Checking if the peripheral has already discovered the services requested
if let serviceUUIDs = serviceUUIDs {
let servicesTuple = self.cbPeripheral.servicesWithUUIDs(serviceUUIDs)
if servicesTuple.missingServicesUUIDs.count == 0 {
completion(.success(servicesTuple.foundServices))
return
}
}
let request = ServiceRequest(serviceUUIDs: serviceUUIDs) { result in
completion(result)
}
self.serviceRequests.append(request)
if self.serviceRequests.count == 1 {
self.runServiceRequest()
}
}
}
fileprivate func runServiceRequest() {
guard let request = self.serviceRequests.first else {
return
}
self.cbPeripheral.discoverServices(request.serviceUUIDs)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onServiceRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onServiceRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<ServiceRequest>
// If the original rssi read operation callback is still there, this should mean the operation went
// through and this timer can be ignored
guard let request = weakRequest.value else {
return
}
self.serviceRequests.removeFirst()
request.callback(.failure(SBError.operationTimedOut(operation: .discoverServices)))
self.runServiceRequest()
}
}
// MARK: Included services Request
private final class IncludedServicesRequest {
let serviceUUIDs: [CBUUID]?
let parentService: CBService
let callback: ServiceRequestCallback
init(serviceUUIDs: [CBUUID]?, forService service: CBService, callback: @escaping ServiceRequestCallback) {
self.callback = callback
if let serviceUUIDs = serviceUUIDs {
self.serviceUUIDs = serviceUUIDs
} else {
self.serviceUUIDs = nil
}
self.parentService = service
}
}
extension PeripheralProxy {
func discoverIncludedServices(_ serviceUUIDs: [CBUUID]?, forService serviceUUID: CBUUID, completion: @escaping ServiceRequestCallback) {
self.discoverServices([serviceUUID]) { result in
if let error = result.error {
completion(.failure(error))
return
}
let parentService = result.value!.first!
let request = IncludedServicesRequest(serviceUUIDs: serviceUUIDs, forService: parentService) { result in
completion(result)
}
self.includedServicesRequests.append(request)
if self.includedServicesRequests.count == 1 {
self.runIncludedServicesRequest()
}
}
}
fileprivate func runIncludedServicesRequest() {
guard let request = self.includedServicesRequests.first else {
return
}
self.cbPeripheral.discoverIncludedServices(request.serviceUUIDs, for: request.parentService)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onIncludedServicesRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onIncludedServicesRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<IncludedServicesRequest>
// If the original discover included services callback is still there, this means the operation went
// through and this timer can be ignored
guard let request = weakRequest.value else {
return
}
self.includedServicesRequests.removeFirst()
request.callback(.failure(SBError.operationTimedOut(operation: .discoverIncludedServices)))
self.runIncludedServicesRequest()
}
}
// MARK: Discover Characteristic requests
private final class CharacteristicRequest{
let service: CBService
let characteristicUUIDs: [CBUUID]?
let callback: CharacteristicRequestCallback
init(service: CBService,
characteristicUUIDs: [CBUUID]?,
callback: @escaping CharacteristicRequestCallback)
{
self.callback = callback
self.service = service
if let characteristicUUIDs = characteristicUUIDs {
self.characteristicUUIDs = characteristicUUIDs
} else {
self.characteristicUUIDs = nil
}
}
}
extension PeripheralProxy {
func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?,
forService serviceUUID: CBUUID,
completion: @escaping CharacteristicRequestCallback)
{
self.discoverServices([serviceUUID]) { result in
if let error = result.error {
completion(.failure(error))
return
}
// It would be a bug if we received an empty service array without an error from the discoverServices function
// when asking for a specific service
let service = result.value!.first!
// Checking if this service already has the characteristic requested
if let characteristicUUIDs = characteristicUUIDs {
let characTuple = service.characteristicsWithUUIDs(characteristicUUIDs)
if (characTuple.missingCharacteristicsUUIDs.count == 0) {
completion(.success(characTuple.foundCharacteristics))
return
}
}
let request = CharacteristicRequest(service: service,
characteristicUUIDs: characteristicUUIDs) { result in
completion(result)
}
self.characteristicRequests.append(request)
if self.characteristicRequests.count == 1 {
self.runCharacteristicRequest()
}
}
}
fileprivate func runCharacteristicRequest() {
guard let request = self.characteristicRequests.first else {
return
}
self.cbPeripheral.discoverCharacteristics(request.characteristicUUIDs, for: request.service)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onCharacteristicRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onCharacteristicRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<CharacteristicRequest>
// If the original rssi read operation callback is still there, this should mean the operation went
// through and this timer can be ignored
guard let request = weakRequest.value else {
return
}
self.characteristicRequests.removeFirst()
request.callback(.failure(SBError.operationTimedOut(operation: .discoverCharacteristics)))
self.runCharacteristicRequest()
}
}
// MARK: Discover Descriptors requets
private final class DescriptorRequest {
let service: CBService
let characteristic: CBCharacteristic
let callback: DescriptorRequestCallback
init(characteristic: CBCharacteristic, callback: @escaping DescriptorRequestCallback) {
self.callback = callback
self.service = characteristic.service
self.characteristic = characteristic
}
}
extension PeripheralProxy {
func discoverDescriptorsForCharacteristic(_ characteristicUUID: CBUUID, serviceUUID: CBUUID, completion: @escaping DescriptorRequestCallback) {
self.discoverCharacteristics([characteristicUUID], forService: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
// It would be a terrible bug in the first place if the discover characteristic returned an empty array
// with no error message when searching for a specific characteristic, I want to crash if it happens :)
let characteristic = result.value!.first!
let request = DescriptorRequest(characteristic: characteristic) { result in
completion(result)
}
self.descriptorRequests.append(request)
if self.descriptorRequests.count == 1 {
self.runDescriptorRequest()
}
}
}
fileprivate func runDescriptorRequest() {
guard let request = self.descriptorRequests.first else {
return
}
self.cbPeripheral.discoverDescriptors(for: request.characteristic)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onDescriptorRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onDescriptorRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<DescriptorRequest>
guard let request = weakRequest.value else {
return
}
self.descriptorRequests.removeFirst()
request.callback(.failure(SBError.operationTimedOut(operation: .discoverDescriptors)))
self.runDescriptorRequest()
}
}
// MARK: Read Characteristic value requests
private final class ReadCharacteristicRequest {
let service: CBService
let characteristic: CBCharacteristic
let callback: ReadCharacRequestCallback
init(characteristic: CBCharacteristic, callback: @escaping ReadCharacRequestCallback) {
self.callback = callback
self.service = characteristic.service
self.characteristic = characteristic
}
}
extension PeripheralProxy {
func readCharacteristic(_ characteristicUUID: CBUUID,
serviceUUID: CBUUID,
completion: @escaping ReadCharacRequestCallback) {
self.discoverCharacteristics([characteristicUUID], forService: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
// Having no error yet not having the characteristic should never happen and would be considered a bug,
// I'd rather crash here than not notice the bug
let characteristic = result.value!.first!
let request = ReadCharacteristicRequest(characteristic: characteristic) { result in
completion(result)
}
let readPath = characteristic.uuidPath
if var currentPathRequests = self.readCharacteristicRequests[readPath] {
currentPathRequests.append(request)
self.readCharacteristicRequests[readPath] = currentPathRequests
} else {
self.readCharacteristicRequests[readPath] = [request]
self.runReadCharacteristicRequest(readPath)
}
}
}
fileprivate func runReadCharacteristicRequest(_ readPath: CBUUIDPath) {
guard let request = self.readCharacteristicRequests[readPath]?.first else {
return
}
self.cbPeripheral.readValue(for: request.characteristic)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onReadCharacteristicTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onReadCharacteristicTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<ReadCharacteristicRequest>
guard let request = weakRequest.value else {
return
}
let readPath = request.characteristic.uuidPath
self.readCharacteristicRequests[readPath]?.removeFirst()
if self.readCharacteristicRequests[readPath]?.count == 0 {
self.readCharacteristicRequests[readPath] = nil
}
request.callback(.failure(SBError.operationTimedOut(operation: .readCharacteristic)))
self.runReadCharacteristicRequest(readPath)
}
}
// MARK: Read Descriptor value requests
private final class ReadDescriptorRequest {
let service: CBService
let characteristic: CBCharacteristic
let descriptor: CBDescriptor
let callback: ReadDescriptorRequestCallback
init(descriptor: CBDescriptor, callback: @escaping ReadDescriptorRequestCallback) {
self.callback = callback
self.descriptor = descriptor
self.characteristic = descriptor.characteristic
self.service = descriptor.characteristic.service
}
}
extension PeripheralProxy {
func readDescriptor(_ descriptorUUID: CBUUID,
characteristicUUID: CBUUID,
serviceUUID: CBUUID,
completion: @escaping ReadDescriptorRequestCallback)
{
self.discoverDescriptorsForCharacteristic(characteristicUUID, serviceUUID: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
guard let descriptor = result.value?.first else {
completion(.failure(SBError.peripheralDescriptorsNotFound(missingDescriptorsUUIDs: [descriptorUUID])))
return
}
let request = ReadDescriptorRequest(descriptor: descriptor, callback: completion)
let readPath = descriptor.uuidPath
if var currentPathRequests = self.readDescriptorRequests[readPath] {
currentPathRequests.append(request)
self.readDescriptorRequests[readPath] = currentPathRequests
} else {
self.readDescriptorRequests[readPath] = [request]
self.runReadDescriptorRequest(readPath)
}
}
}
fileprivate func runReadDescriptorRequest(_ readPath: CBUUIDPath) {
guard let request = self.readDescriptorRequests[readPath]?.first else {
return
}
self.cbPeripheral.readValue(for: request.descriptor)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onReadDescriptorTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onReadDescriptorTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<ReadDescriptorRequest>
guard let request = weakRequest.value else {
return
}
let readPath = request.descriptor.uuidPath
self.readDescriptorRequests[readPath]?.removeFirst()
if self.readDescriptorRequests[readPath]?.count == 0 {
self.readDescriptorRequests[readPath] = nil
}
request.callback(.failure(SBError.operationTimedOut(operation: .readDescriptor)))
self.runReadDescriptorRequest(readPath)
}
}
// MARK: Write Characteristic value requests
private final class WriteCharacteristicValueRequest {
let service: CBService
let characteristic: CBCharacteristic
let value: Data
let type: CBCharacteristicWriteType
let callback: WriteRequestCallback
init(characteristic: CBCharacteristic, value: Data, type: CBCharacteristicWriteType, callback: @escaping WriteRequestCallback) {
self.callback = callback
self.value = value
self.type = type
self.characteristic = characteristic
self.service = characteristic.service
}
}
extension PeripheralProxy {
func writeCharacteristicValue(_ characteristicUUID: CBUUID,
serviceUUID: CBUUID,
value: Data,
type: CBCharacteristicWriteType,
completion: @escaping WriteRequestCallback)
{
self.discoverCharacteristics([characteristicUUID], forService: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
// Having no error yet not having the characteristic should never happen and would be considered a bug,
// I'd rather crash here than not notice the bug hence the forced unwrap
let characteristic = result.value!.first!
let request = WriteCharacteristicValueRequest(characteristic: characteristic,
value: value,
type: type) { result in
completion(result)
}
let writePath = characteristic.uuidPath
if var currentPathRequests = self.writeCharacteristicValueRequests[writePath] {
currentPathRequests.append(request)
self.writeCharacteristicValueRequests[writePath] = currentPathRequests
} else {
self.writeCharacteristicValueRequests[writePath] = [request]
self.runWriteCharacteristicValueRequest(writePath)
}
}
}
fileprivate func runWriteCharacteristicValueRequest(_ writePath: CBUUIDPath) {
guard let request = self.writeCharacteristicValueRequests[writePath]?.first else {
return
}
self.cbPeripheral.writeValue(request.value, for: request.characteristic, type: request.type)
if request.type == CBCharacteristicWriteType.withResponse {
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onWriteCharacteristicValueRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
} else {
// If no response is expected, we execute the callback and clear the request right away
self.writeCharacteristicValueRequests[writePath]?.removeFirst()
if self.writeCharacteristicValueRequests[writePath]?.count == 0 {
self.writeCharacteristicValueRequests[writePath] = nil
}
request.callback(.success(()))
self.runWriteCharacteristicValueRequest(writePath)
}
}
@objc fileprivate func onWriteCharacteristicValueRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<WriteCharacteristicValueRequest>
guard let request = weakRequest.value else {
return
}
let writePath = request.characteristic.uuidPath
self.writeCharacteristicValueRequests[writePath]?.removeFirst()
if self.writeCharacteristicValueRequests[writePath]?.count == 0 {
self.writeCharacteristicValueRequests[writePath] = nil
}
request.callback(.failure(SBError.operationTimedOut(operation: .writeCharacteristic)))
self.runWriteCharacteristicValueRequest(writePath)
}
}
// MARK: Write Descriptor value requests
private final class WriteDescriptorValueRequest {
let service: CBService
let characteristic: CBCharacteristic
let descriptor: CBDescriptor
let value: Data
let callback: WriteRequestCallback
init(descriptor: CBDescriptor, value: Data, callback: @escaping WriteRequestCallback) {
self.callback = callback
self.value = value
self.descriptor = descriptor
self.characteristic = descriptor.characteristic
self.service = descriptor.characteristic.service
}
}
extension PeripheralProxy {
func writeDescriptorValue(_ descriptorUUID: CBUUID,
characteristicUUID: CBUUID,
serviceUUID: CBUUID,
value: Data,
completion: @escaping WriteRequestCallback)
{
self.discoverDescriptorsForCharacteristic(characteristicUUID, serviceUUID: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
guard let descriptor = result.value?.filter({ $0.uuid == descriptorUUID }).first else {
completion(.failure(SBError.peripheralDescriptorsNotFound(missingDescriptorsUUIDs: [descriptorUUID])))
return
}
let request = WriteDescriptorValueRequest(descriptor: descriptor, value: value) { result in
completion(result)
}
let writePath = descriptor.uuidPath
if var currentPathRequests = self.writeDescriptorValueRequests[writePath] {
currentPathRequests.append(request)
self.writeDescriptorValueRequests[writePath] = currentPathRequests
} else {
self.writeDescriptorValueRequests[writePath] = [request]
self.runWriteDescriptorValueRequest(writePath)
}
}
}
fileprivate func runWriteDescriptorValueRequest(_ writePath: CBUUIDPath) {
guard let request = self.writeDescriptorValueRequests[writePath]?.first else {
return
}
self.cbPeripheral.writeValue(request.value, for: request.descriptor)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onWriteDescriptorValueRequestTimerTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onWriteDescriptorValueRequestTimerTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<WriteDescriptorValueRequest>
guard let request = weakRequest.value else {
return
}
let writePath = request.descriptor.uuidPath
self.writeDescriptorValueRequests[writePath]?.removeFirst()
if self.writeDescriptorValueRequests[writePath]?.count == 0 {
self.writeDescriptorValueRequests[writePath] = nil
}
request.callback(.failure(SBError.operationTimedOut(operation: .writeDescriptor)))
self.runWriteDescriptorValueRequest(writePath)
}
}
// MARK: Update Characteristic Notification State requests
private final class UpdateNotificationStateRequest {
let service: CBService
let characteristic: CBCharacteristic
let enabled: Bool
let callback: UpdateNotificationStateCallback
init(enabled: Bool, characteristic: CBCharacteristic, callback: @escaping UpdateNotificationStateCallback) {
self.enabled = enabled
self.characteristic = characteristic
self.service = characteristic.service
self.callback = callback
}
}
extension PeripheralProxy {
func setNotifyValueForCharacteristic(_ enabled: Bool, characteristicUUID: CBUUID, serviceUUID: CBUUID, completion: @escaping UpdateNotificationStateCallback) {
self.discoverCharacteristics([characteristicUUID], forService: serviceUUID) { result in
if let error = result.error {
completion(.failure(error))
return
}
// Having no error yet not having the characteristic should never happen and would be considered a bug,
// I'd rather crash here than not notice the bug hence the forced unwrap
let characteristic = result.value!.first!
let request = UpdateNotificationStateRequest(enabled: enabled,
characteristic: characteristic) { result in
completion(result)
}
let path = characteristic.uuidPath
if var currentPathRequests = self.updateNotificationStateRequests[path] {
currentPathRequests.append(request)
self.updateNotificationStateRequests[path] = currentPathRequests
} else {
self.updateNotificationStateRequests[path] = [request]
self.runUpdateNotificationStateRequest(path)
}
}
}
fileprivate func runUpdateNotificationStateRequest(_ path: CBUUIDPath) {
guard let request = self.updateNotificationStateRequests[path]?.first else {
return
}
self.cbPeripheral.setNotifyValue(request.enabled, for: request.characteristic)
Timer.scheduledTimer(
timeInterval: PeripheralProxy.defaultTimeoutInS,
target: self,
selector: #selector(self.onUpdateNotificationStateRequestTick),
userInfo: Weak(value: request),
repeats: false)
}
@objc fileprivate func onUpdateNotificationStateRequestTick(_ timer: Timer) {
defer {
if timer.isValid { timer.invalidate() }
}
let weakRequest = timer.userInfo as! Weak<UpdateNotificationStateRequest>
guard let request = weakRequest.value else {
return
}
let path = request.characteristic.uuidPath
self.updateNotificationStateRequests[path]?.removeFirst()
if self.updateNotificationStateRequests[path]?.count == 0 {
self.updateNotificationStateRequests[path] = nil
}
request.callback(.failure(SBError.operationTimedOut(operation: .updateNotificationStatus)))
self.runUpdateNotificationStateRequest(path)
}
}
// MARK: CBPeripheralDelegate
extension PeripheralProxy: CBPeripheralDelegate {
@objc func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
guard let readRSSIRequest = self.readRSSIRequests.first else {
return
}
self.readRSSIRequests.removeFirst()
let result: SwiftyBluetooth.Result<Int> = {
if let error = error {
return .failure(error)
} else {
return .success(RSSI.intValue)
}
}()
readRSSIRequest.callback(result)
self.runRSSIRequest()
}
@objc func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
var userInfo: [AnyHashable: Any]?
if let name = peripheral.name {
userInfo = ["name": name]
}
self.postPeripheralEvent(Peripheral.PeripheralNameUpdate, userInfo: userInfo)
}
@objc func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
self.postPeripheralEvent(Peripheral.PeripheralModifedServices, userInfo: ["invalidatedServices": invalidatedServices])
}
@objc func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {
guard let includedServicesRequest = self.includedServicesRequests.first else {
return
}
defer {
self.runIncludedServicesRequest()
}
self.includedServicesRequests.removeFirst()
if let error = error {
includedServicesRequest.callback(.failure(error))
return
}
if let serviceUUIDs = includedServicesRequest.serviceUUIDs {
let servicesTuple = peripheral.servicesWithUUIDs(serviceUUIDs)
if servicesTuple.missingServicesUUIDs.count > 0 {
includedServicesRequest.callback(.failure(SBError.peripheralServiceNotFound(missingServicesUUIDs: servicesTuple.missingServicesUUIDs)))
} else { // This implies that all the services we're found through Set logic in the servicesWithUUIDs function
includedServicesRequest.callback(.success(servicesTuple.foundServices))
}
} else {
includedServicesRequest.callback(.success(service.includedServices ?? []))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let serviceRequest = self.serviceRequests.first else {
return
}
defer {
self.runServiceRequest()
}
self.serviceRequests.removeFirst()
if let error = error {
serviceRequest.callback(.failure(error))
return
}
if let serviceUUIDs = serviceRequest.serviceUUIDs {
let servicesTuple = peripheral.servicesWithUUIDs(serviceUUIDs)
if servicesTuple.missingServicesUUIDs.count > 0 {
serviceRequest.callback(.failure(SBError.peripheralServiceNotFound(missingServicesUUIDs: servicesTuple.missingServicesUUIDs)))
} else { // This implies that all the services we're found through Set logic in the servicesWithUUIDs function
serviceRequest.callback(.success(servicesTuple.foundServices))
}
} else {
serviceRequest.callback(.success(peripheral.services ?? []))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristicRequest = self.characteristicRequests.first else {
return
}
defer {
self.runCharacteristicRequest()
}
self.characteristicRequests.removeFirst()
if let error = error {
characteristicRequest.callback(.failure(error))
return
}
if let characteristicUUIDs = characteristicRequest.characteristicUUIDs {
let characteristicsTuple = service.characteristicsWithUUIDs(characteristicUUIDs)
if characteristicsTuple.missingCharacteristicsUUIDs.count > 0 {
characteristicRequest.callback(.failure(SBError.peripheralCharacteristicNotFound(missingCharacteristicsUUIDs: characteristicsTuple.missingCharacteristicsUUIDs)))
} else {
characteristicRequest.callback(.success(characteristicsTuple.foundCharacteristics))
}
} else {
characteristicRequest.callback(.success(service.characteristics ?? []))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
guard let descriptorRequest = self.descriptorRequests.first else {
return
}
defer {
self.runDescriptorRequest()
}
self.descriptorRequests.removeFirst()
if let error = error {
descriptorRequest.callback(.failure(error))
} else {
descriptorRequest.callback(.success(characteristic.descriptors ?? []))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let readPath = characteristic.uuidPath
guard let request = self.readCharacteristicRequests[readPath]?.first else {
if characteristic.isNotifying {
var userInfo: [AnyHashable: Any] = ["characteristic": characteristic]
if let error = error {
userInfo["error"] = error
}
self.postPeripheralEvent(Peripheral.PeripheralCharacteristicValueUpdate, userInfo: userInfo)
}
return
}
defer {
self.runReadCharacteristicRequest(readPath)
}
self.readCharacteristicRequests[readPath]?.removeFirst()
if self.readCharacteristicRequests[readPath]?.count == 0 {
self.readCharacteristicRequests[readPath] = nil
}
if let error = error {
request.callback(.failure(error))
} else {
request.callback(.success(characteristic.value!))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
let writePath = characteristic.uuidPath
guard let request = self.writeCharacteristicValueRequests[writePath]?.first else {
return
}
defer {
self.runWriteCharacteristicValueRequest(writePath)
}
self.writeCharacteristicValueRequests[writePath]?.removeFirst()
if self.writeCharacteristicValueRequests[writePath]?.count == 0 {
self.writeCharacteristicValueRequests[writePath] = nil
}
if let error = error {
request.callback(.failure(error))
} else {
request.callback(.success(()))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
let path = characteristic.uuidPath
guard let request = self.updateNotificationStateRequests[path]?.first else {
return
}
defer {
self.runUpdateNotificationStateRequest(path)
}
self.updateNotificationStateRequests[path]?.removeFirst()
if self.updateNotificationStateRequests[path]?.count == 0 {
self.updateNotificationStateRequests[path] = nil
}
if let error = error {
request.callback(.failure(error))
} else {
request.callback(.success(characteristic.isNotifying))
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
let readPath = descriptor.uuidPath
guard let request = self.readDescriptorRequests[readPath]?.first else {
return
}
defer {
self.runReadCharacteristicRequest(readPath)
}
self.readDescriptorRequests[readPath]?.removeFirst()
if self.readDescriptorRequests[readPath]?.count == 0 {
self.readDescriptorRequests[readPath] = nil
}
if let error = error {
request.callback(.failure(error))
} else {
do {
let value = try DescriptorValue(descriptor: descriptor)
request.callback(.success(value))
} catch let error {
request.callback(.failure(error))
}
}
}
@objc func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
let writePath = descriptor.uuidPath
guard let request = self.writeDescriptorValueRequests[writePath]?.first else {
return
}
defer {
self.runWriteDescriptorValueRequest(writePath)
}
self.writeDescriptorValueRequests[writePath]?.removeFirst()
if self.writeDescriptorValueRequests[writePath]?.count == 0 {
self.writeDescriptorValueRequests[writePath] = nil
}
if let error = error {
request.callback(.failure(error))
} else {
request.callback(.success(()))
}
}
}
|
mit
|
43c4d5455f8a78a83794fc9b70a4e8d8
| 35.236691 | 177 | 0.611482 | 5.762568 | false | false | false | false |
rplankenhorn/BowieUtilityKnife
|
Pods/BrightFutures/BrightFutures/Errors.swift
|
6
|
2648
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// 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
/// Can be used as the value type of a `Future` or `Result` to indicate it can never fail.
/// This is guaranteed by the type system, because `NoError` has no possible values and thus cannot be created.
public enum NoError {}
extension NoError: Equatable { }
public func ==(lhs: NoError, rhs: NoError) -> Bool {
return true
}
/// Extends `NoError` to conform to `ErrorType`
extension NoError: ErrorType {}
/// An enum representing every possible error for errors returned by BrightFutures
/// A `BrightFuturesError` can also wrap an external error (e.g. coming from a user defined future)
/// in its `External` case. `BrightFuturesError` has the type of the external error as its generic parameter.
public enum BrightFuturesError<E: ErrorType>: ErrorType {
case NoSuchElement
case InvalidationTokenInvalidated
case IllegalState
case External(E)
/// Constructs a BrightFutures.External with the given external error
public init(external: E) {
self = .External(external)
}
}
/// Returns `true` if `left` and `right` are both of the same case ignoring .External associated value
public func ==<E: Equatable>(lhs: BrightFuturesError<E>, rhs: BrightFuturesError<E>) -> Bool {
switch (lhs, rhs) {
case (.NoSuchElement, .NoSuchElement): return true
case (.InvalidationTokenInvalidated, .InvalidationTokenInvalidated): return true
case (.External(let lhs), .External(let rhs)): return lhs == rhs
default: return false
}
}
|
mit
|
ff95ef7de0f5ab9cde9df4bec5f23e38
| 41.709677 | 111 | 0.738293 | 4.480541 | false | false | false | false |
tzef/BunbunuCustom
|
BunbunuCustom/BunbunuCustom/Extension/UIViewControllerExtension.swift
|
1
|
1800
|
//
// UIViewControllerExtension.swift
// BunbunuCustom
//
// Created by LEE ZHE YU on 2016/7/13.
// Copyright © 2016年 LEE ZHE YU. All rights reserved.
//
import UIKit
extension UIViewController {
private static func findBestViewController(vc:UIViewController) -> UIViewController! {
if ((vc.presentedViewController) != nil) {
return UIViewController.findBestViewController(vc.presentedViewController!)
}
else if (vc.isKindOfClass(UISplitViewController.classForCoder())) {
let splite = vc as! UISplitViewController
if (splite.viewControllers.count > 0) {
return UIViewController.findBestViewController(splite.viewControllers.last!)
}
else {
return vc
}
}
else if(vc.isKindOfClass(UINavigationController.classForCoder())) {
let svc = vc as! UINavigationController
if (svc.viewControllers.count > 0) {
return UIViewController.findBestViewController(svc.topViewController!)
}
else {
return vc
}
}
else if (vc.isKindOfClass(UITabBarController.classForCoder())) {
let svc = vc as! UITabBarController
if (svc.viewControllers?.count > 0) {
return UIViewController.findBestViewController(svc.selectedViewController!)
}
else {
return vc
}
}
else {
return vc
}
}
static func currentViewController() -> UIViewController {
let vc:UIViewController! = UIApplication.sharedApplication().keyWindow?.rootViewController
return UIViewController.findBestViewController(vc)
}
}
|
mit
|
96079875984d709f8176cf0df00949a0
| 32.277778 | 98 | 0.598219 | 5.66877 | false | false | false | false |
elpassion/el-space-ios
|
ELSpace/Screens/Hub/Activity/Views/ActivityView.swift
|
1
|
2025
|
import UIKit
import Anchorage
class ActivityView: UIView {
init() {
super.init(frame: .zero)
addSubviews()
setupLayout()
backgroundColor = .white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addView(_ view: UIView ) {
let arrangedView = Factory.shadowedView(with: view)
stackView.addArrangedSubview(arrangedView)
}
let scrollView = Factory.scrollView()
// MARK: - Private
private let stackView = Factory.stackView()
private func addSubviews() {
addSubview(scrollView)
scrollView.addSubview(stackView)
}
private func setupLayout() {
scrollView.edgeAnchors == edgeAnchors
stackView.edgeAnchors == scrollView.edgeAnchors + 16
stackView.widthAnchor == scrollView.widthAnchor - 32
}
}
private extension ActivityView {
struct Factory {
static func shadowedView(with contentView: UIView) -> UIView {
let view = UIView(frame: .zero)
view.addSubview(contentView)
contentView.edgeAnchors == view.edgeAnchors + 8
view.backgroundColor = .white
view.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor
view.layer.shadowOffset = CGSize(width: 0, height: 4)
view.layer.shadowOpacity = 1
view.layer.shadowRadius = 7
view.layer.cornerRadius = 6
return view
}
static func scrollView() -> UIScrollView {
let scrollView = UIScrollView(frame: .zero)
scrollView.keyboardDismissMode = .interactive
scrollView.showsVerticalScrollIndicator = false
return scrollView
}
static func stackView() -> UIStackView {
let view = UIStackView(frame: .zero)
view.axis = .vertical
view.distribution = .fill
view.spacing = 16
return view
}
}
}
|
gpl-3.0
|
3c8ce72770caf380ae1ed8bca9e5fafe
| 26.364865 | 82 | 0.607407 | 5.219072 | false | false | false | false |
DannyvanSwieten/SwiftSignals
|
SwiftAudio/Scheduler.swift
|
1
|
882
|
//
// Scheduler.swift
// SwiftEngine
//
// Created by Danny van Swieten on 2/5/16.
// Copyright © 2016 Danny van Swieten. All rights reserved.
//
import Foundation
struct Task {
var timestamp = 0
typealias Function = (Void) -> Void
var taskToBeDone: Function = {_ in return}
func perform() {
taskToBeDone()
}
}
class Scheduler {
var time = 0
var tasks = [Task]()
func addTask(t: Task) {
for index in 0..<tasks.count {
if t.timestamp > tasks[index].timestamp && t.timestamp < tasks[index + 1].timestamp {
tasks.insert(t, atIndex: index)
}
}
}
func update(timestamp: Int) {
time = timestamp
for task in tasks {
if task.timestamp <= timestamp {
task.perform()
}
}
}
}
|
gpl-3.0
|
3735b451ceae950fb50995e285758f61
| 19.045455 | 97 | 0.519864 | 4.097674 | false | false | false | false |
sdduursma/Scenic
|
Scenic/Scene.swift
|
1
|
3676
|
import UIKit
public protocol SceneFactory {
func makeScene(for sceneName: String) -> Scene?
}
public protocol Scene: class {
var viewController: UIViewController { get }
var eventDelegate: EventDelegate? { get set }
func embed(_ children: [Scene], customData: [AnyHashable: AnyHashable]?)
}
extension Scene {
public var eventDelegate: EventDelegate? {
get {
return nil
}
set { }
}
public func embed(_ children: [Scene], customData: [AnyHashable: AnyHashable]?) { }
}
public protocol EventDelegate: class {
func sendEvent(_ event: NavigationEvent)
}
public class StackScene: NSObject, Scene, UINavigationControllerDelegate {
static let didPopEventName = "StackScene.didPop".scenicNamespacedName
private let navigationController: UINavigationController
private var children: [Scene] = []
public var viewController: UIViewController {
return navigationController
}
public weak var eventDelegate: EventDelegate?
public init(navigationController: UINavigationController = UINavigationController()) {
self.navigationController = navigationController
super.init()
navigationController.delegate = self
}
public func embed(_ children: [Scene], customData: [AnyHashable: AnyHashable]?) {
self.children = children
let childViewControllers = children.map { $0.viewController }
navigationController.setViewControllers(childViewControllers, animated: false)
}
public func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController, animated: Bool) {
let childViewControllers = children.map { $0.viewController }
if navigationController.viewControllers == Array(childViewControllers.dropLast()) {
let toIndex = navigationController.viewControllers.count - 1
eventDelegate?.sendEvent(NavigationEvent(eventName: StackScene.didPopEventName,
customData: ["toIndex": toIndex]))
}
}
}
public class TabBarScene: NSObject, Scene, UITabBarControllerDelegate {
public static let didSelectIndexEventName = "TabBarScene.didSelectIndexEvent".scenicNamespacedName
private let tabBarController: UITabBarController
public var viewController: UIViewController {
return tabBarController
}
public weak var eventDelegate: EventDelegate?
public init(tabBarController: UITabBarController = UITabBarController()) {
self.tabBarController = tabBarController
super.init()
tabBarController.delegate = self
}
public func embed(_ children: [Scene], customData: [AnyHashable: AnyHashable]?) {
let childViewControllers = children.map { $0.viewController }
tabBarController.setViewControllers(childViewControllers, animated: true)
tabBarController.selectedIndex = customData?["selectedIndex"] as? Int ?? 0
}
public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let selectedIndex = tabBarController.viewControllers?.index(of: viewController) else { return false }
eventDelegate?.sendEvent(NavigationEvent(eventName: TabBarScene.didSelectIndexEventName, customData: ["selectedIndex": selectedIndex]))
return false
}
}
public class SingleScene: Scene {
public let viewController: UIViewController
public init(viewController: UIViewController = UIViewController()) {
self.viewController = viewController
}
}
|
mit
|
d11a43d60c68c6998318682c7625a4b0
| 31.530973 | 143 | 0.70593 | 5.853503 | false | false | false | false |
ello/ello-ios
|
Sources/Controllers/Profile/Badge/ProfileBadgeViewController.swift
|
1
|
1726
|
////
/// ProfileBadgeViewController.swift
//
final class ProfileBadgeViewController: BaseElloViewController {
let badge: Badge
init(badge: Badge) {
self.badge = badge
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var _mockScreen: ProfileBadgeScreenProtocol?
var screen: ProfileBadgeScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
override func loadView() {
let screen = ProfileBadgeScreen(title: badge.name, caption: badge.caption)
screen.delegate = self
view = screen
}
}
extension ProfileBadgeViewController: UIViewControllerTransitioningDelegate {
func presentationController(
forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController
) -> UIPresentationController? {
guard presented == self
else { return .none }
return DarkModalPresentationController(
presentedViewController: presented,
presentingViewController: presenting,
backgroundColor: .dimmedModalBackground
)
}
}
extension ProfileBadgeViewController: ProfileBadgeScreenDelegate {
func learnMoreTapped() {
let badge = self.badge
Tracker.shared.badgeLearnMore(badge.slug)
self.dismiss(animated: true) {
if let url = badge.url {
postNotification(ExternalWebNotification, value: url.absoluteString)
}
}
}
func dismiss() {
self.dismiss(animated: true, completion: nil)
}
}
|
mit
|
5fd4560314e3cd5f3b7fba5ccbc0e4ae
| 25.96875 | 84 | 0.651217 | 5.167665 | false | false | false | false |
nnianhou-/M-Vapor
|
Sources/App/Models/Friend.swift
|
1
|
5851
|
//
// Friend.swift
// M-Vapor
//
// Created by N年後 on 2017/9/3.
//
//
import Vapor
import FluentProvider
import HTTP
final class Friend:Model{
static let idKey = "id"
static let usernameKey = "username"
static let mobilePhoneKey = "mobilePhone"
static let sexKey = "sex"
static let headimgurlKey = "headimgurl"
static let rcuseridKey = "rcuserid"
static let devicenoKey = "deviceno"
static let wayKey = "way"
static let accountKey = "account"
static let pwdKey = "pwd"
var username: String // 姓名
var mobilePhone: String // 姓名
var sex: String // 性别
var headimgurl: String // 用户图像
var rcuserid: String //
var deviceno: String
var way: String // 登录方式
var account: String // 账号
var pwd: String // 密码
let storage = Storage()
/// 常规的构造器
init(username:String,mobilePhone:String,sex:String,headimgurl:String,rcuserid:String,deviceno:String,way:String,account:String,pwd:String) {
self.username = username
self.mobilePhone = mobilePhone
self.sex = sex
self.headimgurl = headimgurl
self.rcuserid = rcuserid
self.deviceno = deviceno
self.way = way
self.account = account
self.pwd = pwd
}
// MARK: Fluent 序列化构造器
/// 通过这个构造器你可以使用数据库中的一行生成一个对应的对象
init(row: Row) throws {
username = try row.get(Friend.usernameKey)
mobilePhone = try row.get(Friend.mobilePhoneKey)
sex = try row.get(Friend.sexKey)
headimgurl = try row.get(Friend.headimgurlKey)
rcuserid = try row.get(Friend.rcuseridKey)
deviceno = try row.get(Friend.devicenoKey)
way = try row.get(Friend.wayKey)
account = try row.get(Friend.accountKey)
pwd = try row.get(Friend.pwdKey)
}
// 把一个对象存储到数据库当中
func makeRow() throws -> Row {
var row = Row()
try row.set(Friend.usernameKey, username)
try row.set(Friend.mobilePhoneKey, mobilePhone)
try row.set(Friend.sexKey, sex)
try row.set(Friend.headimgurlKey, headimgurl)
try row.set(Friend.rcuseridKey, rcuserid)
try row.set(Friend.devicenoKey, deviceno)
try row.set(Friend.wayKey, way)
try row.set(Friend.accountKey, account)
try row.set(Friend.pwdKey, pwd)
return row
}
}
extension Friend:Preparation {
static func prepare(_ database: Database) throws {
try database.create(self, closure: { Friends in
Friends.id()
Friends.string(Friend.usernameKey)
Friends.string(Friend.mobilePhoneKey)
Friends.string(Friend.sexKey)
Friends.string(Friend.headimgurlKey)
Friends.string(Friend.rcuseridKey)
Friends.string(Friend.devicenoKey)
Friends.string(Friend.wayKey)
Friends.string(Friend.accountKey)
Friends.string(Friend.pwdKey)
})
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Friend: JSONRepresentable {
convenience init(json: JSON) throws {
try self.init(
username:json.get(Friend.usernameKey),
mobilePhone:json.get(Friend.mobilePhoneKey),
sex:json.get(Friend.sexKey),
headimgurl:json.get(Friend.headimgurlKey),
rcuserid:json.get(Friend.rcuseridKey),
deviceno:json.get(Friend.devicenoKey),
way:json.get(Friend.wayKey),
account:json.get(Friend.accountKey),
pwd:json.get(Friend.pwdKey)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Friend.idKey, id)
try json.set(Friend.usernameKey, username)
try json.set(Friend.mobilePhoneKey, mobilePhone)
try json.set(Friend.sexKey, sex)
try json.set(Friend.headimgurlKey, headimgurl)
try json.set(Friend.rcuseridKey, rcuserid)
try json.set(Friend.devicenoKey, deviceno)
try json.set(Friend.wayKey, way)
try json.set(Friend.accountKey, account)
try json.set(Friend.pwdKey, pwd)
return json
}
}
extension Friend: Updateable {
public static var updateableKeys: [UpdateableKey<Friend>] {
return [
UpdateableKey(Friend.usernameKey, String.self) { Friend, username in
Friend.username = username
},
UpdateableKey(Friend.mobilePhoneKey, String.self) { Friend, mobilePhone in
Friend.mobilePhone = mobilePhone
},
UpdateableKey(Friend.sexKey, String.self) { Friend, sex in
Friend.sex = sex
},
UpdateableKey(Friend.headimgurlKey, String.self) { Friend, headimgurl in
Friend.headimgurl = headimgurl
},
UpdateableKey(Friend.rcuseridKey, String.self) { Friend, rcuserid in
Friend.rcuserid = rcuserid
},
UpdateableKey(Friend.devicenoKey, String.self) { Friend, deviceno in
Friend.deviceno = deviceno
},
UpdateableKey(Friend.wayKey, String.self) { Friend, way in
Friend.way = way
},
UpdateableKey(Friend.accountKey, String.self) { Friend, account in
Friend.account = account
},
UpdateableKey(Friend.pwdKey, String.self) { Friend, pwd in
Friend.pwd = pwd
}
]
}
}
extension Friend: ResponseRepresentable { }
|
mit
|
78ef0671dd7cfd7be92690fb4d676ce4
| 27.668342 | 144 | 0.592989 | 4.046099 | false | false | false | false |
ByteriX/BxObjC
|
iBXTest/iBXTest/Sources/Controllers/UIViewController.swift
|
1
|
811
|
//
// UIViewController.swift
// iBXTest
//
// Created by Sergey Balalaev on 12/04/2019.
// Copyright © 2019 ByteriX. All rights reserved.
//
import UIKit
@objc
extension UIViewController {
func tablePositionLayout(_ tableView: UITableView, topMagrin: CGFloat) {
let topY = self.topExtendedEdges() + topMagrin
let bottomY = self.bottomExtendedEdges()
let contentOffsetY = tableView.contentOffset.y - (topY - tableView.contentInset.top)
tableView.contentInset = UIEdgeInsets(top: topY, left: 0, bottom: bottomY, right: 0)
tableView.scrollIndicatorInsets = UIEdgeInsets(top: topY, left: 0, bottom: bottomY, right: 0)
tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: contentOffsetY), animated: false)
}
}
|
mit
|
d87360779e8dae91cffd44446ff16587
| 31.4 | 109 | 0.685185 | 4.21875 | false | false | false | false |
roana0229/PullAndInfiniteTableView
|
PullAndInfiniteTableView/PullAndInfiniteTableView.swift
|
1
|
5484
|
//
// PullAndInfiniteTableView.swift
// PullAndInfiniteTableView
//
// Created by Kaoru Tsutsumishita on 2015/10/27.
// Copyright © 2015年 roana0229. All rights reserved.
//
import UIKit
public class PullAndInfiniteTableView: UITableView {
private let TOP_ATTRIBUTE = "TopAttribute"
private var refreshControl: UIRefreshControl!
private var footerHeight: CGFloat = 0
private var footerIndicator: UIActivityIndicatorView!
private var pullToRefreshHandler: (() -> ())?
private var infiniteScrollHandler: (() -> ())?
private var nowLoading: Bool = false
public var showPullToRefresh: Bool = false {
didSet {
if oldValue != showPullToRefresh {
if showPullToRefresh {
showPullToRefreshView()
} else {
hidePullToRefreshView()
}
}
}
}
public var showInfiniteScroll: Bool = false {
didSet {
if oldValue != showInfiniteScroll {
if showInfiniteScroll {
showInfiniteScrollRefreshView()
} else {
hideInfiniteScrollRefreshView()
}
}
}
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: footerHeight))
footerView.hidden = true
return footerView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return showInfiniteScroll ? footerHeight : 0.1
}
private func showPullToRefreshView() {
if refreshControl == nil {
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "pullToRefresh", forControlEvents: .ValueChanged)
}
addSubview(refreshControl)
}
private func hidePullToRefreshView() {
refreshControl.removeFromSuperview()
}
private func showInfiniteScrollRefreshView() {
if footerIndicator == nil {
footerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
footerHeight = footerIndicator.bounds.height * 3
}
footerIndicator.startAnimating()
addSubview(footerIndicator)
footerIndicator.translatesAutoresizingMaskIntoConstraints = false
let topAttribute = NSLayoutConstraint(item: footerIndicator, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0)
topAttribute.identifier = TOP_ATTRIBUTE
addConstraints([
topAttribute,
NSLayoutConstraint(item: footerIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: footerIndicator, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 56),
NSLayoutConstraint(item: footerIndicator, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1.0, constant: 56)
])
}
private func hideInfiniteScrollRefreshView() {
footerIndicator.removeFromSuperview()
}
public func addPullToRefreshHandler(handler: () -> ()) {
pullToRefreshHandler = handler
}
public func addInfiniteScrollHandler(handler: () -> ()) {
infiniteScrollHandler = handler
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if contentSize.height <= footerHeight || !showInfiniteScroll || nowLoading {
return
}
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
let o = maximumOffset - currentOffset
if o <= footerHeight {
if !scrollView.dragging {
executeHandler(.INFINITE_SCROLL_REFRESH)
}
}
}
func pullToRefresh() {
if nowLoading {
return
}
executeHandler(.PULL_TO_REFRESH)
}
private func executeHandler(state: RefreshState) {
nowLoading = true
switch state {
case .PULL_TO_REFRESH:
pullToRefreshHandler?()
break
case .INFINITE_SCROLL_REFRESH:
infiniteScrollHandler?()
break
default:
break
}
}
public func refresh(state: RefreshState) {
switch state {
case .PULL_TO_REFRESH:
refreshControl.endRefreshing()
reloadData()
break
case .INFINITE_SCROLL_REFRESH:
UIView.animateWithDuration(0.3, animations: {
self.reloadData()
})
break
case .INIT_REFRESH:
reloadData()
break
}
nowLoading = false
layoutFooterIndicatorTopConstraint()
}
private func layoutFooterIndicatorTopConstraint() {
if !showInfiniteScroll {
return
}
for constraint in constraints {
if let id = constraint.identifier where id == TOP_ATTRIBUTE {
constraint.constant = contentSize.height - footerHeight
footerIndicator.layoutIfNeeded()
}
}
}
}
|
mit
|
2021878c705c969e8a412d7e1ee11a70
| 31.820359 | 165 | 0.599526 | 5.47006 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications
|
final-project/Appa/NewGeocacheViewController.swift
|
1
|
3114
|
/*
* @authors Tyler Brockett, Shikha Mehta, Tam Le
* @course ASU CSE 394
* @project Group Project
* @version April 15, 2016
* @project-description Allows users to track Geocaches
* @class-name NewGeocacheViewController.swift
* @class-description Allows user to create a new Geocache and add it to Core Data
*/
import Foundation
import UIKit
import CoreData
import MapKit
import CoreLocation
class NewGeocacheViewController: UIViewController, MKMapViewDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate {
@IBOutlet weak var nam: UITextField!
@IBOutlet weak var descriptio: UITextField!
@IBOutlet weak var longitude: UITextField!
@IBOutlet weak var latitude: UITextField!
@IBOutlet weak var mapView: MKMapView!
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
mapView.setUserTrackingMode(.Follow, animated: true)
locationManager.startUpdatingLocation()
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,
longitude: userLocation.coordinate.longitude)
let width = 1000.0 // meters
let height = 1000.0
let region = MKCoordinateRegionMakeWithDistance(center, width, height)
mapView.setRegion(region, animated: true)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error:NSError) {
print("Errors" + error.localizedDescription)
}
@IBAction func presentLocation(sender: UIButton) {
let annotation = MKPointAnnotation()
annotation.coordinate = mapView.userLocation.coordinate
annotation.title = "Your Location"
self.mapView.addAnnotation(annotation)
latitude.text = String(format:"%.3f", mapView.userLocation.coordinate.latitude)
longitude.text = String(format:"%.3f", mapView.userLocation.coordinate.longitude)
}
@IBAction func saveData(sender: UIButton) {
let ent = NSEntityDescription.entityForName("Geocache", inManagedObjectContext: context)
let nItem = Geocache(entity: ent!, insertIntoManagedObjectContext: context)
nItem.name = nam.text!
nItem.desc = descriptio.text!
nItem.latitude = Double(latitude.text!)
nItem.longitude = Double(longitude.text!)
do {
try context.save()
} catch _ {
}
navigationController!.popViewControllerAnimated(true)
}
}
|
mit
|
131aa04dc9a5acf06fff42439e55fb1d
| 38.417722 | 129 | 0.699743 | 5.295918 | false | false | false | false |
brentdax/swift
|
test/Inputs/resilient_protocol.swift
|
5
|
841
|
public protocol OtherResilientProtocol {
}
var x: Int = 0
extension OtherResilientProtocol {
public var propertyInExtension: Int {
get { return x }
set { x = newValue }
}
public static var staticPropertyInExtension: Int {
get { return x }
set { x = newValue }
}
}
public protocol ResilientBaseProtocol {
func requirement() -> Int
}
public protocol ResilientDerivedProtocol : ResilientBaseProtocol {}
public protocol ProtocolWithRequirements {
associatedtype T
func first()
func second()
}
public struct Wrapper<T>: OtherResilientProtocol { }
public protocol ProtocolWithAssocTypeDefaults {
associatedtype T1 = Self
associatedtype T2: OtherResilientProtocol = Wrapper<T1>
}
public protocol ResilientSelfDefault : ResilientBaseProtocol {
associatedtype AssocType: ResilientBaseProtocol = Self
}
|
apache-2.0
|
b92e7e5b75cd143f42d22f0debd2c432
| 20.025 | 67 | 0.751486 | 4.778409 | false | false | false | false |
Raiden9000/Sonarus
|
ChatViewFirebase.swift
|
1
|
2636
|
//
// ChatViewFirebase.swift
// Sonarus
//
// Created by Christopher Arciniega on 5/12/17.
// Copyright © 2017 HQZenithLabs. All rights reserved.
//
import Foundation
extension ChatViewController{
func fireGetRooms(){
//let groupRef:FIRDatabaseReference = FIRDatabase.database().reference().child("Roombase")
}
func fireListenForMessages(){
let room = UserVariables.activeRoom
print("listening to room \(room)")
let refRoom = FIRDatabase.database().reference().child("Roombase/\(room)/5Messages/")
refRoom.queryLimited(toLast: 1).observe(.value, with: {snapshot in
for msg in snapshot.children.allObjects as! [FIRDataSnapshot]{
let msgObject = msg.value as? [String: AnyObject]
let msgText = msgObject?["msg"]
let msgSender = msgObject?["from"]
//let timeStamp = msgObject?["time"]
//Create Sonarus message object to display
var m:Message
if msgSender != nil{
//print(msgText as! String)
if msgSender as! String == UserVariables.userID{
m = Message(Message: msgText as! String, Sender: msgSender as! String, incoming: false)
}
else{
m = Message(Message: msgText as! String, Sender: msgSender as! String, incoming: true)
}
self.messages.append(m)
}
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "FIRMessageAdded"), object: nil)
})
}
func fireSendMessage(message:String, room:String){
//Generate key
print("sending message to room \(room)" )
let refMessages = FIRDatabase.database().reference().child("Roombase/\(room)/5Messages/")
let key = refMessages.childByAutoId().key
let timestamp = "\(0 - (NSDate().timeIntervalSince1970))"
//Create message
var name = ""
if UserVariables.userName == ""{
name = UserVariables.userID
}
else{
name = UserVariables.userName
}
let m = ["from":name, "msg":message, "time": timestamp]
print(m)
print(UserVariables.userName)
//self.messages.append(Message.init(Message: message, Sender: username, incoming: false))
//Add message to generated key
refMessages.child(key).setValue(m)
print("Message sent")
}
func fireFollowGroup(){
}
}
|
mit
|
ac12bce646d310185906420336d28b6c
| 34.608108 | 111 | 0.564326 | 4.69697 | false | false | false | false |
cxpyear/cc
|
spdbapp/spdbapp/MainViewController.swift
|
1
|
2110
|
//
// ViewController.swift
// spdbapp
//
// Created by tommy on 15/5/7.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Foundation
class MainViewController: UIViewController {
@IBOutlet weak var btnConf: UIButton!
@IBOutlet weak var lbConfName: UILabel!
var current = GBMeeting()
var builder = Builder()
var appManager = AppManager()
var poller = Poller()
override func viewDidLoad() {
super.viewDidLoad()
var box = GBBox()
var style = NSMutableParagraphStyle()
style.lineSpacing = 20
style.alignment = NSTextAlignment.Center
var attr = [NSParagraphStyleAttributeName : style]
//上海浦东发展银行股份有限公司第二届董事会第一次会议
var name = "暂无会议"
lbConfName.attributedText = NSAttributedString(string: name, attributes : attr)
//初始化时候btnconf背景颜色为灰色,点击无效
btnConf.layer.cornerRadius = 8
btnConf.backgroundColor = UIColor.grayColor()
btnConf.enabled = false
appManager.addObserver(self, forKeyPath: "current", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil)
}
private var myContext = 1
//显示当前会议名
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "current"{
self.lbConfName.text = object.current.name
self.btnConf.enabled = true
btnConf.backgroundColor = UIColor(red: 123/255, green: 0/255, blue: 31/255, alpha: 1.0)
}
}
deinit{
appManager.removeObserver(self, forKeyPath: "current", context: &myContext)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
bsd-3-clause
|
85ee18f0685d0d4b3af7531a3d503476
| 25.693333 | 156 | 0.61988 | 4.623557 | false | false | false | false |
pawel-sp/PSZRingView
|
PSZRingView/RingView.swift
|
1
|
2607
|
//
// RingView.swift
// PSZRingView
//
// Created by Paweł Sporysz on 19.10.2014.
// Copyright (c) 2014 Paweł Sporysz. All rights reserved.
//
import UIKit
@IBDesignable
public class RingView: UIView {
// MARK: - Oval image
private lazy var ovalImageView:UIImageView = {
let imageView = UIImageView(frame: self.bounds)
imageView.addOvalMask()
self.addSubview(imageView)
return imageView
}()
/// Image for imageView added inside current view with the oval mask
@IBInspectable
public var ovalImage:UIImage? {
didSet {
if let _ovalImage = ovalImage {
ovalImageView.image = _ovalImage
}
}
}
/// Distance between view bounds and image ones
@IBInspectable
public var ovalImageOffset:Float = 0.0 {
didSet {
ovalImageView.frame = ovalImageView.frame.insetBy(dx: CGFloat(ovalImageOffset), dy: CGFloat(ovalImageOffset))
ovalImageView.addOvalMask()
}
}
// MARK: - Oval background
/// Circled background color. It is over regular background color.If You want to hide square background color You need to set it to clear color and turn off opaque.
@IBInspectable
public var ovalBackgroundColor:UIColor = UIColor.clearColor() {
didSet {
setNeedsDisplay()
}
}
private func setOvalBackround(color color:UIColor) {
let path = UIBezierPath(ovalInRect: bounds)
path.addClip()
color.setFill()
UIRectFill(bounds)
}
// MARK: - Rings
/**
It adds single ring to view.
:param: ring Instance of PSSRing class to provides information about ring.
*/
public func addRing(ring:Ring) {
let circleLayer = CAShapeLayer()
circleLayer.path = UIBezierPath(ovalInRect: CGRectInset(bounds, CGFloat(ring.offset), CGFloat(ring.offset))).CGPath
circleLayer.strokeColor = ring.color.CGColor
circleLayer.lineWidth = CGFloat(ring.width)
circleLayer.fillColor = ring.background.CGColor
self.layer.addSublayer(circleLayer)
}
/**
It adds multiple rings to view
:param: rings Array of PSSRing instances to provides information about rings.
*/
public func addRing(rings:[Ring]) {
for ring in rings {
addRing(ring)
}
}
// MARK: - Overrides
override public func drawRect(rect: CGRect) {
setOvalBackround(color: ovalBackgroundColor)
}
}
|
mit
|
321b9a5ae858bb1e02268d31577bd756
| 27.010753 | 168 | 0.616891 | 4.660107 | false | false | false | false |
hooman/swift
|
test/attr/attr_specialize.swift
|
3
|
16609
|
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}},
@_specialize(where T == T1) // expected-error{{cannot find type 'T1' in scope}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-warning{{redundant same-type constraint 'T' == 'T'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == S<T>) // expected-error{{same-type constraint 'T' == 'S<T>' is recursive}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note {{missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // FIXME e/xpected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}}
// expected-note@-1 {{same-type constraint 'T' == 'NonSub' implied here}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected type}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{cannot find type 'Z' in scope}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{cannot find type 'MyClass' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}}
// expected-note@-2{{same-type constraint 'X' == 'Int' written here}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{cannot find type 'X1' in scope}} expected-error{{cannot find type 'Y1' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{cannot find type 'exported' in scope}} expected-error{{cannot find type 'kind' in scope}} expected-error{{cannot find type 'partial' in scope}} expected-error{{expected type}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} expected-note {{use 'T == Int' to require 'T' to be 'Int'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: S1) // expected-error{{type 'T' constrained to non-protocol, non-class type 'S1'}} expected-note {{use 'T == S1' to require 'T' to be 'S1'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: C1) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-note{{missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject)
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}}
// expected-error@-2{{type 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}}
// expected-warning@-3{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-4 {{constraint 'T' : '_Trivial' implied here}}
// expected-note@-5 2{{constraint conflicts with 'T' : '_Trivial(32)'}}
@_specialize(where T: _Trivial, T: _Trivial(64))
// expected-warning@-1{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-2 1{{constraint 'T' : '_Trivial' implied here}}
@_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject)
// expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}}
// expected-note@-2 1{{constraint 'T' : '_RefCountedObject' implied here}}
@_specialize(where Array<T> == Int) // expected-error{{generic signature requires types 'Array<T>' and 'Int' to be the same}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T.Element == Int) // expected-error{{only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public protocol Proto: class {
}
@_specialize(where T: _RefCountedObject)
// expected-warning@-1 {{redundant constraint 'T' : '_RefCountedObject'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial)
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial' and '_NativeClass'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial(64))
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 {
return 44444
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@_specialize(exported: true, where S: _NativeRefCountedObject)
@_specialize(exported: true, where S: _Class)
@_specialize(exported: true, where S: _NativeClass)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-note{{missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
public func targetFun<T>(_ t: T) {}
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) {
}
public struct Container {
public func targetFun<T>(_ t: T) {}
}
extension Container {
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) { }
@_specialize(exported: true, target: targetFun2(_:), where T == Int) // expected-error{{target function 'targetFun2' could not be found}}
public func specifyTargetFunc2<T>(_ t: T) { }
}
// Make sure we don't complain that 'E' is not explicitly specialized here.
// E becomes concrete via the combination of 'S == Set<String>' and
// 'E == S.Element'.
@_specialize(where S == Set<String>)
public func takesSequenceAndElement<S, E>(_: S, _: E)
where S : Sequence, E == S.Element {}
|
apache-2.0
|
b00dc050639bd043d316c9be5bfc9c91
| 50.107692 | 393 | 0.692938 | 3.659982 | false | false | false | false |
braintree/braintree_ios
|
UnitTests/BraintreeCoreTests/BTPreferredPaymentMethods_Tests.swift
|
1
|
9621
|
import XCTest
import BraintreeTestShared
class BTPreferredPaymentMethods_Tests: XCTestCase {
var mockAPIClient = MockAPIClient(authorization: "development_client_key")!
var fakeApplication = FakeApplication()
override func setUp() {
fakeApplication.cannedCanOpenURL = false
}
func testFetchPreferredPaymentMethods_sendsQueryToGraphQL() {
let expectation = self.expectation(description: "Sends query to GraphQL")
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
guard let lastRequestParameters = self.mockAPIClient.lastPOSTParameters as? [String: String] else { XCTFail(); return }
XCTAssertEqual(lastRequestParameters["query"], "query PreferredPaymentMethods { preferredPaymentMethods { paypalPreferred } }")
XCTAssertEqual(self.mockAPIClient.lastPOSTAPIClientHTTPType, .graphQLAPI)
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenBothPayPalAndVenmoAppsAreInstalled_callsCompletionWithTrueForBoth() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let expectation = self.expectation(description: "Calls completion with result")
// allowlist paypal and venmo urls
fakeApplication.canOpenURLWhitelist = [
URL(string: "paypal://")!,
URL(string: "com.venmo.touch.v2://")!
]
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertTrue(result.isPayPalPreferred)
XCTAssertTrue(result.isVenmoPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.paypal.app-installed.true"))
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.venmo.app-installed.true"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenVenmoAppIsNotInstalled_callsCompletionWithFalseForVenmo() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isVenmoPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.venmo.app-installed.false"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenAPIDetectsPayPalPreferred_callsCompletionWithTrueForPayPal() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let jsonString =
"""
{
"data": {
"preferredPaymentMethods": {
"paypalPreferred": true
}
}
}
"""
mockAPIClient.cannedResponseBody = BTJSON(data: jsonString.data(using: String.Encoding.utf8)!)
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertTrue(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.paypal.api-detected.true"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenAPIDetectsPayPalNotPreferred_callsCompletionWithFalseForPayPal() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let jsonString =
"""
{
"data": {
"preferredPaymentMethods": {
"paypalPreferred": false
}
}
}
"""
mockAPIClient.cannedResponseBody = BTJSON(data: jsonString.data(using: String.Encoding.utf8)!)
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.paypal.api-detected.false"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenGraphQLResponseIsNull_callsCompletionWithFalseForPayPal() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
mockAPIClient.cannedResponseBody = nil
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.api-error"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenGraphQLReturnsError_callsCompletionWithFalseForPayPal() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
mockAPIClient.cannedResponseError = NSError(domain: "domain", code: 1, userInfo: nil)
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.api-error"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenGraphQLIsDisabled_callsCompletionWithFalseForPayPal() {
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": nil ]])
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.api-disabled"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenFetchingConfigurationReturnsAnError_callsCompletionWithFalseForPayPal() {
mockAPIClient.cannedConfigurationResponseError = NSError(domain: "com.braintreepayments.UnitTest", code: 0, userInfo: nil)
let expectation = self.expectation(description: "Calls completion with result")
let sut = BTPreferredPaymentMethods(apiClient: mockAPIClient)
sut.application = fakeApplication
sut.fetch { result in
XCTAssertFalse(result.isPayPalPreferred)
XCTAssertTrue(self.mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.api-error"))
expectation.fulfill()
}
waitForExpectations(timeout: 1.0, handler: nil)
}
func testFetchPreferredPaymentMethods_whenNetworkConnectionLost_sendsAnalytics() {
mockAPIClient.cannedResponseError = NSError(domain: NSURLErrorDomain, code: -1005, userInfo: [NSLocalizedDescriptionKey: "The network connection was lost."])
mockAPIClient.cannedConfigurationResponseBody = BTJSON(value: ["graphQL": ["url": "https://graphql.com"]])
let preferredPaymentMethods = BTPreferredPaymentMethods(apiClient: mockAPIClient)
preferredPaymentMethods.application = fakeApplication
let expectation = self.expectation(description: "Callback invoked")
preferredPaymentMethods.fetch { result in
expectation.fulfill()
}
waitForExpectations(timeout: 2)
XCTAssertTrue(mockAPIClient.postedAnalyticsEvents.contains("ios.preferred-payment-methods.network-connection.failure"))
}
}
|
mit
|
7b3864fba8452d20045d0db037f483fc
| 41.950893 | 165 | 0.663756 | 5.444822 | false | true | false | false |
haitran2011/Rocket.Chat.iOS
|
Rocket.Chat/Views/Avatar/AvatarView.swift
|
1
|
3515
|
//
// AvatarView.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 10/09/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
let avatarColors: [UInt] = [
0xF44336, 0xE91E63, 0x9C27B0, 0x673AB7, 0x3F51B5,
0x2196F3, 0x03A9F4, 0x00BCD4, 0x009688, 0x4CAF50,
0x8BC34A, 0xCDDC39, 0xFFC107, 0xFF9800, 0xFF5722,
0x795548, 0x9E9E9E, 0x607D8B]
final class AvatarView: UIView {
var imageURL: URL? {
didSet {
updateAvatar()
}
}
var user: User? {
didSet {
updateAvatar()
}
}
@IBOutlet weak var labelInitials: UILabel!
var labelInitialsFontSize: CGFloat? {
didSet {
labelInitials?.font = UIFont.systemFont(ofSize: labelInitialsFontSize ?? 0)
}
}
@IBOutlet weak var imageView: UIImageView!
private func userAvatarURL() -> URL? {
guard let username = user?.username else { return nil }
guard let auth = AuthManager.isAuthenticated() else { return nil }
guard let baseURL = auth.baseURL() else { return nil }
guard let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil }
return URL(string: "\(baseURL)/avatar/\(encodedUsername).jpg")
}
private func updateAvatar() {
setAvatarWithInitials()
var imageURL: URL?
if let avatar = self.imageURL {
imageURL = avatar
} else {
imageURL = userAvatarURL()
}
if let imageURL = imageURL {
imageView?.sd_setImage(with: imageURL, completed: { [weak self] _, error, _, _ in
guard error != nil else {
self?.labelInitials.text = ""
self?.backgroundColor = UIColor.clear
return
}
self?.setAvatarWithInitials()
})
}
}
internal func initialsFor(_ username: String) -> String {
guard username.characters.count > 0 else {
return "?"
}
let strings = username.components(separatedBy: ".")
if let first = strings.first, let last = strings.last {
let lastOffset = strings.count > 1 ? 1 : 2
let indexFirst = first.index(first.startIndex, offsetBy: 1)
let firstString = first.substring(to: indexFirst)
var lastString = ""
if last.characters.count >= lastOffset {
let indexLast = last.index(last.startIndex, offsetBy: lastOffset)
lastString = last.substring(to: indexLast)
if lastOffset == 2 {
let endIndex = lastString.index(lastString.startIndex, offsetBy: 1)
lastString = lastString.substring(from: endIndex)
}
}
return "\(firstString)\(lastString)".uppercased()
}
return ""
}
private func setAvatarWithInitials() {
let username = user?.username ?? "?"
var initials = ""
var color: UInt = 0x000000
if username == "?" {
initials = username
color = 0x000000
} else {
let position = username.characters.count % avatarColors.count
color = avatarColors[position]
initials = initialsFor(username)
}
labelInitials?.text = initials.uppercased()
backgroundColor = UIColor(rgb: color, alphaVal: 1)
}
}
|
mit
|
7d6b3450a06e8fcd198f300b9fc4ed07
| 28.529412 | 139 | 0.569721 | 4.414573 | false | false | false | false |
AnneBlair/YYGRegular
|
YYGRegular/SwitchSegue.swift
|
1
|
1156
|
//
// SwitchSegue.swift
// Aplan
//
// Created by 区块国际-yin on 2017/5/4.
// Copyright © 2017年 blog.aiyinyu.com. All rights reserved.
//
import UIKit
protocol SegueHandelr {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandelr where Self: UIViewController, SegueIdentifier.RawValue == String {
func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("UnKnown segue: \(segue)") }
return segueIdentifier
}
func performSegue(withIdentifier segueIdentifier: SegueIdentifier) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: nil)
}
}
//
//func viewController(forStoryboardName: String) -> UIViewController {
// return UIStoryboard(name: forStoryboardName, bundle: nil).instantiateInitialViewController()!
//}
//
//class TemplateImageView: UIImageView {
// @IBInspectable var templateImage: UIImage? {
// didSet {
// image = templateImage?.withRenderingMode(.alwaysTemplate)
// }
// }
//}
|
mit
|
824feea5a6d5e062821cdba6f1845115
| 30.75 | 155 | 0.713036 | 4.608871 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit
|
Sources/BSWInterfaceKit/ViewControllers/ContainerViewController.swift
|
1
|
4338
|
//
// RootViewController.swift
// Created by Pierluigi Cifani on 15/09/2018.
//
#if canImport(UIKit)
import UIKit
@objc(BSWRootViewController)
final public class RootViewController: ContainerViewController {}
@objc(BSWContainerViewController)
open class ContainerViewController: UIViewController {
public enum LayoutMode {
case pinToSuperview
case pinToSafeArea
}
public enum Appereance {
static public var BackgroundColor: UIColor = .clear
}
private(set) public var containedViewController: UIViewController
private let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeInOut)
public var layoutMode = LayoutMode.pinToSuperview
public convenience init() {
self.init(containedViewController: UIViewController())
}
public init(containedViewController: UIViewController) {
self.containedViewController = containedViewController
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Appereance.BackgroundColor
containViewController(containedViewController)
}
open override var childForStatusBarStyle: UIViewController? { containedViewController }
open override var childForStatusBarHidden: UIViewController? { containedViewController }
open override var childForHomeIndicatorAutoHidden: UIViewController? { containedViewController }
open override var childForScreenEdgesDeferringSystemGestures: UIViewController? { containedViewController }
open override var navigationItem: UINavigationItem {
return containedViewController.navigationItem
}
@available(iOS 13.0, *)
open override var isModalInPresentation: Bool {
get {
containedViewController.isModalInPresentation
} set {
containedViewController.isModalInPresentation = newValue
}
}
open func updateContainedViewController(_ newVC: UIViewController) {
guard newVC != containedViewController else { return }
/// Make sure that if a user calls `updateContainedViewController:`
/// before the animation is completed, the view hierarchy is in sync with
/// what the user's trying to achieve, even with a crappy animation
if animator.isRunning {
animator.stopAnimation(false)
animator.finishAnimation(at: .end)
}
// Notify current VC that time is up
let oldVC = self.containedViewController
oldVC.willMove(toParent: nil)
/// Store a reference to the new guy in town
self.containedViewController = newVC
// Add new VC
self.addChild(newVC)
self.view.insertSubview(newVC.view, belowSubview: oldVC.view)
switch layoutMode {
case .pinToSuperview:
newVC.view.pinToSuperview()
case .pinToSafeArea:
newVC.view.pinToSuperviewSafeLayoutEdges()
}
newVC.didMove(toParent: self)
newVC.view.alpha = 0
animator.addAnimations {
oldVC.view.alpha = 0
newVC.view.alpha = 1
}
animator.addCompletion { (_) in
oldVC.view.removeFromSuperview()
oldVC.removeFromParent()
self.setNeedsStatusBarAppearanceUpdate()
self.setNeedsUpdateOfHomeIndicatorAutoHidden()
self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
}
animator.startAnimation()
/// This is a workaround for an issue where the `containedViewController`'s navigationItem wasn't
/// being correctly synced with the contents of the navigation bar. This will make sure to force an update to
/// it, making the contents of the navigationBar correct after every `updateContainedViewController`.
if let navBarHidden = self.navigationController?.isNavigationBarHidden {
self.navigationController?.setNavigationBarHidden(!navBarHidden, animated: false)
self.navigationController?.setNavigationBarHidden(navBarHidden, animated: false)
}
}
}
#endif
|
mit
|
0921fd81fab50cb28616c816b4e7f1dc
| 36.721739 | 117 | 0.68142 | 5.619171 | false | false | false | false |
crazypoo/PTools
|
Pods/JXSegmentedView/Sources/Indicator/JXSegmentedIndicatorDoubleLineView.swift
|
1
|
4601
|
//
// JXSegmentedIndicatorDoubleLineView.swift
// JXSegmentedView
//
// Created by jiaxin on 2019/1/16.
// Copyright © 2019 jiaxin. All rights reserved.
//
import UIKit
open class JXSegmentedIndicatorDoubleLineView: JXSegmentedIndicatorBaseView {
/// 线收缩到最小的百分比
open var minLineWidthPercent: CGFloat = 0.2
public let selectedLineView: UIView = UIView()
public let otherLineView: UIView = UIView()
open override func commonInit() {
super.commonInit()
indicatorHeight = 3
addSubview(selectedLineView)
otherLineView.alpha = 0
addSubview(otherLineView)
}
open override func refreshIndicatorState(model: JXSegmentedIndicatorSelectedParams) {
super.refreshIndicatorState(model: model)
selectedLineView.backgroundColor = indicatorColor
otherLineView.backgroundColor = indicatorColor
selectedLineView.layer.cornerRadius = getIndicatorCornerRadius(itemFrame: model.currentSelectedItemFrame)
otherLineView.layer.cornerRadius = getIndicatorCornerRadius(itemFrame: model.currentSelectedItemFrame)
let width = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame, itemContentWidth: model.currentItemContentWidth)
let height = getIndicatorHeight(itemFrame: model.currentSelectedItemFrame)
let x = model.currentSelectedItemFrame.origin.x + (model.currentSelectedItemFrame.size.width - width)/2
var y: CGFloat = 0
switch indicatorPosition {
case .top:
y = verticalOffset
case .bottom:
y = model.currentSelectedItemFrame.size.height - height - verticalOffset
case .center:
y = (model.currentSelectedItemFrame.size.height - height)/2 + verticalOffset
}
selectedLineView.frame = CGRect(x: x, y: y, width: width, height: height)
otherLineView.frame = selectedLineView.frame
}
open override func contentScrollViewDidScroll(model: JXSegmentedIndicatorTransitionParams) {
super.contentScrollViewDidScroll(model: model)
guard canHandleTransition(model: model) else {
return
}
let rightItemFrame = model.rightItemFrame
let leftItemFrame = model.leftItemFrame
let percent = model.percent
let leftCenter = getCenter(in: leftItemFrame)
let rightCenter = getCenter(in: rightItemFrame)
let leftMaxWidth = getIndicatorWidth(itemFrame: leftItemFrame, itemContentWidth: model.leftItemContentWidth)
let rightMaxWidth = getIndicatorWidth(itemFrame: rightItemFrame, itemContentWidth: model.rightItemContentWidth)
let leftMinWidth = leftMaxWidth*minLineWidthPercent
let rightMinWidth = rightMaxWidth*minLineWidthPercent
let leftWidth: CGFloat = JXSegmentedViewTool.interpolate(from: leftMaxWidth, to: leftMinWidth, percent: CGFloat(percent))
let rightWidth: CGFloat = JXSegmentedViewTool.interpolate(from: rightMinWidth, to: rightMaxWidth, percent: CGFloat(percent))
let leftAlpha: CGFloat = JXSegmentedViewTool.interpolate(from: 1, to: 0, percent: CGFloat(percent))
let rightAlpha: CGFloat = JXSegmentedViewTool.interpolate(from: 0, to: 1, percent: CGFloat(percent))
if model.currentSelectedIndex == model.leftIndex {
selectedLineView.bounds.size.width = leftWidth
selectedLineView.center = leftCenter
selectedLineView.alpha = leftAlpha
otherLineView.bounds.size.width = rightWidth
otherLineView.center = rightCenter
otherLineView.alpha = rightAlpha
}else {
otherLineView.bounds.size.width = leftWidth
otherLineView.center = leftCenter
otherLineView.alpha = leftAlpha
selectedLineView.bounds.size.width = rightWidth
selectedLineView.center = rightCenter
selectedLineView.alpha = rightAlpha
}
}
open override func selectItem(model: JXSegmentedIndicatorSelectedParams) {
super.selectItem(model: model)
let targetWidth = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame, itemContentWidth: model.currentItemContentWidth)
let targetCenter = getCenter(in: model.currentSelectedItemFrame)
selectedLineView.bounds.size.width = targetWidth
selectedLineView.center = targetCenter
selectedLineView.alpha = 1
otherLineView.alpha = 0
}
private func getCenter(in frame: CGRect) -> CGPoint {
return CGPoint(x: frame.midX, y: selectedLineView.center.y)
}
}
|
mit
|
e323748cf710d1455d6e64550835c055
| 41.018349 | 135 | 0.710699 | 4.994547 | false | false | false | false |
mdpianelli/ios-shopfinder
|
ShopFinder/ShopFinder/UIView+VisualEffects.swift
|
1
|
3605
|
//
// UIView+VisualEffects.swift
// ShopFinder
//
// Created by Marcos Pianelli on 18/07/15.
// Copyright (c) 2015 Barkala Studios. All rights reserved.
//
import UIKit
extension UIView {
func addLightBlur(){
self.backgroundColor = UIColor.clearColor()
let lightBlur = UIBlurEffect(style: .Light)
let lightBlurView = UIVisualEffectView(effect: lightBlur)
let lightVibrancyView = vibrancyEffectView(forBlurEffectView: lightBlurView)
lightBlurView.contentView.addSubview(lightVibrancyView)
lightBlurView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
self.insertSubview(lightBlurView, atIndex: 0)
}
func addExtraLightBlur(){
self.backgroundColor = UIColor.clearColor()
let extraLightBlur = UIBlurEffect(style: .ExtraLight)
let lightBlurView = UIVisualEffectView(effect: extraLightBlur)
let lightVibrancyView = vibrancyEffectView(forBlurEffectView: lightBlurView)
lightBlurView.contentView.addSubview(lightVibrancyView)
lightBlurView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
self.insertSubview(lightBlurView, atIndex: 0)
}
func addDarkBlur(){
self.backgroundColor = UIColor.clearColor()
let darkBlur = UIBlurEffect(style: .Dark)
let lightBlurView = UIVisualEffectView(effect:darkBlur)
let lightVibrancyView = vibrancyEffectView(forBlurEffectView: lightBlurView)
lightBlurView.contentView.addSubview(lightVibrancyView)
lightBlurView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
self.insertSubview(lightBlurView, atIndex: 0)
}
private func vibrancyEffectView(forBlurEffectView blurEffectView:UIVisualEffectView) -> UIVisualEffectView {
let vibrancy = UIVibrancyEffect(forBlurEffect: blurEffectView.effect as! UIBlurEffect)
let vibrancyView = UIVisualEffectView(effect: vibrancy)
vibrancyView.frame = blurEffectView.bounds
vibrancyView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
return vibrancyView
}
func addVibrantStatusBarBackground(effect: UIBlurEffect) {
let statusBarBlurView = UIVisualEffectView(effect: effect)
statusBarBlurView.frame = UIApplication.sharedApplication().statusBarFrame
statusBarBlurView.autoresizingMask = .FlexibleWidth
let statusBarVibrancyView = vibrancyEffectView(forBlurEffectView: statusBarBlurView)
statusBarBlurView.contentView.addSubview(statusBarVibrancyView)
let statusBar = UIApplication.sharedApplication().valueForKey("statusBar") as! UIView
statusBar.superview!.insertSubview(statusBarBlurView, belowSubview: statusBar)
self.addSubview(statusBarBlurView)
let statusBarBackgroundImage = UIImage(named: "MaskPixel")!.imageWithRenderingMode(.AlwaysTemplate)
let statusBarBackgroundView = UIImageView(image: statusBarBackgroundImage)
statusBarBackgroundView.frame = statusBarVibrancyView.bounds
statusBarBackgroundView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
statusBarVibrancyView.contentView.addSubview(statusBarBackgroundView)
statusBarBlurView.tag = 1
}
func removeVibrantStatusBarBackground(){
self.viewWithTag(1)?.removeFromSuperview()
}
}
|
mit
|
e62ca89f199362a1fab330e4ba7b69d3
| 34.70297 | 112 | 0.694036 | 5.546154 | false | false | false | false |
Adorkable/Eunomia
|
Source/Core/UtilityExtensions/Views/UIScrollView+Utility.swift
|
1
|
1999
|
//
// UIScrollView+Utility.swift
// Eunomia
//
// Created by Ian Grossberg on 10/5/15.
// Copyright © 2015 Adorkable. All rights reserved.
//
#if os(iOS)
import UIKit
extension UIScrollView {
fileprivate var filteredScrollLastContentOffsetKey : String {
return "Eunomia_UIScrollView_filteredScrollLastContentOffsetKey"
}
fileprivate var filteredScrollLastContentOffset : CGFloat {
get {
return self.getAssociatedProperty(self.filteredScrollLastContentOffsetKey, fallback: 0)
}
set {
self.setAssociatedRetainProperty(self.filteredScrollLastContentOffsetKey, value: newValue as AnyObject)
}
}
public func applyFilteredScrollForScrollingBar(_ bar : UIView, barTopAlignment : NSLayoutConstraint, minimumDelta : CGFloat = 20) {
let scrollDistance : CGFloat = self.contentOffset.y - self.filteredScrollLastContentOffset
self.filteredScrollLastContentOffset = self.contentOffset.y
// Minimum delta scroll before bar is effected, ie: only adjust past a minimum scroll speed. We allow even small amounts to pass if we're in the middle of hiding or showing the bar.
guard abs(scrollDistance) > abs(minimumDelta) || (barTopAlignment.constant != 0 && barTopAlignment.constant != -bar.frame.height) else {
return
}
// Only allow the topbar to move into and out of the area it's in and above
guard barTopAlignment.constant - scrollDistance <= 0 else {
barTopAlignment.constant = 0
return
}
// Only move the topbar enough to hide it
guard abs(barTopAlignment.constant - scrollDistance) <= bar.frame.height else {
barTopAlignment.constant = -bar.frame.height
return
}
barTopAlignment.constant -= scrollDistance / 2
bar.superview?.setNeedsLayout()
}
}
#endif
|
mit
|
59a2e7bbe924e5c683fa39c8448209f6
| 35.327273 | 189 | 0.652653 | 4.802885 | false | false | false | false |
SkyOldLee/iOS-Study-Demo
|
Swift用Storyboard的学习/StoryBoard教程第一季/StoryBoard教程第一季/PlayersViewController.swift
|
15
|
4021
|
//
// PlayersViewController.swift
// StoryBoard教程第一季
//
// Created by aiteyuan on 15/1/29.
// Copyright (c) 2015年 黄成都. All rights reserved.
//
import UIKit
class PlayersViewController: UITableViewController {
var players: [Player] = playersData
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return players.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerCell", forIndexPath: indexPath)
as PlayerCell
let player = players[indexPath.row] as Player
cell.nameLabel.text = player.name
cell.gameLabel.text = player.game
cell.ratingImageView.image = imageForRating(player.rating)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func imageForRating(rating:Int) -> UIImage? {
switch rating {
case 1:
return UIImage(named: "1StarSmall")
case 2:
return UIImage(named: "2StarsSmall")
case 3:
return UIImage(named: "3StarsSmall")
case 4:
return UIImage(named: "4StarsSmall")
case 5:
return UIImage(named: "5StarsSmall")
default:
return nil
}
}
}
|
apache-2.0
|
28d29c04a3b6a023de0e70fc1ae6828d
| 32.923729 | 157 | 0.662503 | 5.294974 | false | false | false | false |
digipost/ios
|
Digipost/POSAppointment.swift
|
1
|
1178
|
//
// Copyright (C) Posten Norge AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class POSAppointment : POSMetadataObject {
var title = ""
var creatorName = ""
var startTime = Date()
var endTime = Date()
var arrivalTimeDate = Date()
var arrivalTime = ""
var place = ""
var streetAddress = ""
var streetAddress2 = ""
var postalCode = ""
var city = ""
var country = ""
var address = ""
var subTitle = ""
var infoTitle1 = ""
var infoText1 = ""
var infoTitle2 = ""
var infoText2 = ""
init() {
super.init(type: POSMetadata.TYPE.APPOINTMENT)
}
}
|
apache-2.0
|
2301942e16c35ef5c1cb9b7fa63d3ce6
| 26.395349 | 75 | 0.648557 | 4.10453 | false | false | false | false |
airspeedswift/swift
|
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift
|
3
|
13305
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main3Box[[UNIQUE_ID_1:[A-Za-z0-9_]+]]LLCyAA5InnerACLLCySiGGMf" =
// CHECK: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMf" = linkonce_odr hidden
// CHECK-apple-SAME: global
// CHECK-unknown-SAME: constant
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }> <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD
// CHECK-SAME: $sBoWV
// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMM
// CHECK-unknown-SAME: [[INT]] 0,
// CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject
// CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-apple-SAME: %swift.opaque* null,
// CHECK-apple-SAME: [[INT]] add (
// CHECK-apple-SAME: [[INT]] ptrtoint (
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// : i32,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: [
// CHECK-apple-SAME: 1 x {
// CHECK-apple-SAME: [[INT]]*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32
// CHECK-apple-SAME: }
// CHECK-apple-SAME: ]
// CHECK-apple-SAME: }*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*
// CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_1]]5Value to [[INT]]
// CHECK-apple-SAME: ),
// CHECK-apple-SAME: [[INT]] 2
// CHECK-apple-SAME: ),
// CHECK-SAME: i32 26,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{(24|12)}},
// CHECK-SAME: i16 {{(7|3)}},
// CHECK-SAME: i16 0,
// CHECK-apple-SAME: i32 {{(120|72)}},
// CHECK-unknown-SAME: i32 96,
// CHECK-SAME: i32 {{(16|8)}},
// : %swift.type_descriptor* bitcast (
// : <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i16,
// : i16,
// : i8,
// : i8,
// : i8,
// : i8,
// : i32,
// : i32,
// : %swift.method_descriptor
// : }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCMn" to %swift.type_descriptor*
// : ),
// CHECK-SAME: i8* null,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main3Box[[UNIQUE_ID_1:[a-zA-Z0-9_]+]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main3Box[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main3Box[[UNIQUE_ID_1]]LLCyAA5InnerACLLCySiGGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] {{(16|8)}},
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
fileprivate class Value<First> {
let first_Value: First
init(first: First) {
self.first_Value = first
}
}
fileprivate class Box<Value> {
let value: Value
init(value: Value) {
self.value = value
}
}
fileprivate class Inner<Value> {
let value: Value
init(value: Value) {
self.value = value
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] 0)
// CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( Value(first: Box(value: Inner(value: 13))) )
}
doit()
// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main3Box[[UNIQUE_ID_2]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main3Box[[UNIQUE_ID_2]]LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// : }>*
// CHECK-SAME: @"$s4main3Box[[UNIQUE_ID_1]]LLCyAA5InnerACLLCySiGGMf"
// : to %swift.full_heapmetadata*
// : ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ) to i8*
// CHECK-SAME: ),
// CHECK-SAME: [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_3:[0-9A-Z_]+]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] [[METADATA_REQUEST]])
// CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0
// CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1
// CHECK: ret %swift.metadata_response [[RESULT_METADATA]]
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK: [[INT]] [[METADATA_REQUEST]],
// CHECK: i8* [[ERASED_TYPE]],
// CHECK: i8* undef,
// CHECK: i8* undef,
// CHECK: %swift.type_descriptor* bitcast (
// : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>*
// CHECK: $s4main5Value[[UNIQUE_ID_1]]LLCMn
// CHECK: to %swift.type_descriptor*
// CHECK: )
// CHECK: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {
// CHECK: entry:
// CHECK-unknown: ret
// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self(
// : %objc_class* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMf"
// : to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to %objc_class*
// : )
// : )
// CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type*
// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0
// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1
// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]]
// CHECK: }
|
apache-2.0
|
dcc01087398be07a70fe33aa78df5f9a
| 41.372611 | 214 | 0.447351 | 3.245914 | false | false | false | false |
shvets/WebAPI
|
Sources/WebAPI/KinoKongAPI.swift
|
1
|
16283
|
import Foundation
import SwiftSoup
import Alamofire
//import Networking
open class KinoKongAPI: HttpService {
public static let SiteUrl = "https://kinokong.se"
let UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
public func getDocument(_ url: String) throws -> Document? {
return try fetchDocument(url, headers: getHeaders(), encoding: .windowsCP1251)
}
public func searchDocument(_ url: String, parameters: [String: String]) throws -> Document? {
return try fetchDocument(url, headers: getHeaders(), parameters: parameters, method: .post, encoding: .windowsCP1251)
}
// public override func fetchDocument(_ url: String,
// headers: HTTPHeaders = [:],
// parameters: Parameters = [:],
// method: HTTPMethod = .get,
// encoding: String.Encoding = .utf8) throws -> Document? {
// var document: Document?
//
//// if let dataResponse = fetchDataResponse(url, headers: headers, parameters: parameters, method: method),
//// let data = dataResponse.data,
//// let html = String(data: data, encoding: encoding) {
//// document = try SwiftSoup.parse(html)
//// }
//
//// let networking = Networking(baseURL: url)
////
//// networking.get("/", headers: headers, parameters: parameters) { result in
//// switch result {
//// case .success(let response):
//// let json = response.dictionaryBody
//// // Do something with JSON, you can also get arrayBody
//// case .failure(let response):
//// print(response)
//// // Handle error
//// }
//// }
//
// return document
// }
public func available() throws -> Bool {
if let document = try getDocument(KinoKongAPI.SiteUrl) {
return try document.select("div[id=container]").size() > 0
}
else {
return false
}
}
func getPagePath(_ path: String, page: Int=1) -> String {
if page == 1 {
return path
}
else {
return "\(path)page/\(page)/"
}
}
public func getAllMovies(page: Int=1) throws -> [String: Any] {
return try getMovies("/film/", page: page)
}
public func getNewMovies(page: Int=1) throws -> [String: Any] {
return try getMovies("/film/2019", page: page)
}
public func getAllSeries(page: Int=1) throws -> [String: Any] {
return try getMovies("/series/", page: page)
}
public func getAnimations(page: Int=1) throws -> [String: Any] {
return try getMovies("/cartoons/", page: page)
}
public func getAnime(page: Int=1) throws -> [String: Any] {
return try getMovies("/animes/", page: page)
}
public func getTvShows(page: Int=1) throws -> [String: Any] {
return try getMovies("/documentary/", page: page)
}
public func getMovies(_ path: String, page: Int=1) throws -> [String: Any] {
var data = [Any]()
var paginationData: ItemsList = [:]
let pagePath = getPagePath(path, page: page)
if let document = try getDocument(KinoKongAPI.SiteUrl + pagePath) {
let items = try document.select("div[class=owl-item]")
for item: Element in items.array() {
var href = try item.select("div[class=item] span[class=main-sliders-bg] a").attr("href")
let name = try item.select("h2[class=main-sliders-title] a").text()
let thumb = try KinoKongAPI.SiteUrl +
item.select("div[class=main-sliders-shadow] span[class=main-sliders-bg] ~ img").attr("src")
let seasonNode = try item.select("div[class=main-sliders-shadow] div[class=main-sliders-season]").text()
if href.find(KinoKongAPI.SiteUrl) != nil {
let index = href.index(href.startIndex, offsetBy: KinoKongAPI.SiteUrl.count)
href = String(href[index ..< href.endIndex])
}
let type = seasonNode.isEmpty ? "movie" : "serie"
data.append(["id": href, "name": name, "thumb": thumb, "type": type])
}
if items.size() > 0 {
paginationData = try extractPaginationData(document, page: page)
}
}
return ["movies": data, "pagination": paginationData]
}
func getMoviesByRating(page: Int=1) throws -> [String: Any] {
return try getMoviesByCriteriaPaginated("/?do=top&mode=rating", page: page)
}
func getMoviesByViews(page: Int=1) throws -> [String: Any] {
return try getMoviesByCriteriaPaginated("/?do=top&mode=views", page: page)
}
func getMoviesByComments(page: Int=1) throws -> [String: Any] {
return try getMoviesByCriteriaPaginated("/?do=top&mode=comments", page: page)
}
func getMoviesByCriteria(_ path: String) throws -> [Any] {
var data = [Any]()
if let document = try getDocument(KinoKongAPI.SiteUrl + path) {
let items = try document.select("div[id=dle-content] div div table tr")
for item: Element in items.array() {
let link = try item.select("td a")
if !link.array().isEmpty {
var href = try link.attr("href")
let index = href.index(href.startIndex, offsetBy: KinoKongAPI.SiteUrl.count)
href = String(href[index ..< href.endIndex])
let name = try link.text().trim()
let tds = try item.select("td").array()
let rating = try tds[tds.count-1].text()
data.append(["id": href, "name": name, "rating": rating, "type": "rating"])
}
}
}
return data
}
public func getMoviesByCriteriaPaginated(_ path: String, page: Int=1, perPage: Int=25) throws -> [String: Any] {
let data = try getMoviesByCriteria(path)
var items: [Any] = []
for (index, item) in data.enumerated() {
if index >= (page-1)*perPage && index < page*perPage {
items.append(item)
}
}
let pagination = buildPaginationData(data, page: page, perPage: perPage)
return ["movies": items, "pagination": pagination]
}
public func getTags() throws -> [Any] {
var data = [Any]()
if let document = try getDocument(KinoKongAPI.SiteUrl + "/kino-podborka.html") {
let items = try document.select("div[class=podborki-item-block]")
for item: Element in items.array() {
let link = try item.select("a")
let img = try item.select("a span img")
let title = try item.select("a span[class=podborki-title]")
let href = try link.attr("href")
var thumb = try img.attr("src")
if thumb.find(KinoKongAPI.SiteUrl) == nil {
thumb = KinoKongAPI.SiteUrl + thumb
}
let name = try title.text()
data.append(["id": href, "name": name, "thumb": thumb, "type": "movie"])
}
}
return data
}
func buildPaginationData(_ data: [Any], page: Int, perPage: Int) -> [String: Any] {
let pages = data.count / perPage
return [
"page": page,
"pages": pages,
"has_next": page < pages,
"has_previous": page > 1
]
}
func getSeries(_ path: String, page: Int=1) throws -> [String: Any] {
return try getMovies(path, page: page)
}
public func getUrls(_ path: String) throws -> [String] {
var urls: [String] = []
if let document = try getDocument(KinoKongAPI.SiteUrl + path) {
let items = try document.select("script")
for item: Element in items.array() {
let text0 = try item.html()
let text = text0.replacingOccurrences(of: ",file:", with: ", file:")
if !text.isEmpty {
let index1 = text.find("\", file:\"")
let index2 = text.find("\"});")
if let startIndex = index1, let endIndex = index2 {
urls = text[text.index(startIndex, offsetBy: 8) ..< endIndex].components(separatedBy: ",")
break
}
else {
let index1 = text.find("\", file:\"")
let index2 = text.find("\",st:")
if let startIndex = index1, let endIndex = index2 {
urls = text[text.index(startIndex, offsetBy: 8) ..< endIndex].components(separatedBy: ",")
break
}
}
}
}
}
var newUrls: [String] = []
for url in urls {
if !url.hasPrefix("cuid:") {
let newUrl = url.replacingOccurrences(of: "\"", with: "")
.replacingOccurrences(of: "[720]", with: "")
.replacingOccurrences(of: "[480]", with: "")
newUrls.append(newUrl)
}
}
return newUrls.reversed()
}
public func getSeriePlaylistUrl(_ path: String) throws -> String {
var url = ""
if let document = try getDocument(KinoKongAPI.SiteUrl + path) {
let items = try document.select("script")
for item: Element in items.array() {
let text = try item.html()
if !text.isEmpty {
let index1 = text.find("pl:")
if let startIndex = index1 {
let text2 = String(String(text[startIndex ..< text.endIndex]))
let index2 = text2.find("\",")
if let endIndex = index2 {
url = String(text2[text2.index(text2.startIndex, offsetBy:4) ..< endIndex])
break
}
}
}
}
}
return url
}
public func getMetadata(_ url: String) -> [String: String] {
var data = [String: String]()
let groups = url.components(separatedBy: ".")
if (groups.count > 1) {
let text = groups[groups.count-2]
let pattern = "(\\d+)p_(\\d+)"
do {
let regex = try NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.count))
if let width = getMatched(text, matches: matches, index: 1) {
data["width"] = width
}
if let height = getMatched(text, matches: matches, index: 2) {
data["height"] = height
}
}
catch {
print("Error in regular expression.")
}
}
return data
}
func getMatched(_ link: String, matches: [NSTextCheckingResult], index: Int) -> String? {
var matched: String?
let match = matches.first
if let match = match, index < match.numberOfRanges {
let capturedGroupIndex = match.range(at: index)
let index1 = link.index(link.startIndex, offsetBy: capturedGroupIndex.location)
let index2 = link.index(index1, offsetBy: capturedGroupIndex.length-1)
matched = String(link[index1 ... index2])
}
return matched
}
public func getGroupedGenres() throws -> [String: [Any]] {
var data = [String: [Any]]()
if let document = try getDocument(KinoKongAPI.SiteUrl) {
let items = try document.select("div[id=header] div div div ul li")
for item: Element in items.array() {
let hrefLink = try item.select("a")
let genresNode1 = try item.select("span em a")
let genresNode2 = try item.select("span a")
var href = try hrefLink.attr("href")
if href == "#" {
href = "top"
}
else {
href = String(href[href.index(href.startIndex, offsetBy: 1) ..< href.index(href.endIndex, offsetBy: -1)])
}
var genresNode: Elements?
if !genresNode1.array().isEmpty {
genresNode = genresNode1
}
else {
genresNode = genresNode2
}
if let genresNode = genresNode, !genresNode.array().isEmpty {
data[href] = []
for genre in genresNode {
let path = try genre.attr("href")
let name = try genre.text()
if !["/kino-recenzii/", "/news-kino/"].contains(path) {
data[href]!.append(["id": path, "name": name])
}
}
}
}
}
return data
}
public func search(_ query: String, page: Int=1, perPage: Int=15) throws -> [String: Any] {
var data = [Any]()
var paginationData: ItemsList = [:]
var searchData = [
//"do": "search",
"subaction": "search",
"search_start": "\(page)",
"full_search": "0",
"result_from": "1",
"story": query.windowsCyrillicPercentEscapes()
]
if page > 1 {
searchData["result_from"] = "\(page * perPage + 1)"
}
let path = "/index.php?do=search"
if let document = try searchDocument(KinoKongAPI.SiteUrl + path, parameters: searchData) {
let items = try document.select("div[class=owl-item]")
for item: Element in items.array() {
var href = try item.select("div[class=item] span[class=main-sliders-bg] a").attr("href")
let name = try item.select("div[class=main-sliders-title] a").text()
let thumb = try item.select("div[class=item] span[class=main-sliders-bg] img").attr("src")
//try item.select("div[class=main-sliders-shadow] span[class=main-sliders-bg] ~ img").attr("src")
let seasonNode = try item.select("div[class=main-sliders-shadow] span[class=main-sliders-season]").text()
if href.find(KinoKongAPI.SiteUrl) != nil {
let index = href.index(href.startIndex, offsetBy: KinoKongAPI.SiteUrl.count)
href = String(href[index ..< href.endIndex])
}
var type = seasonNode.isEmpty ? "movie" : "serie"
if name.contains("Сезон") || name.contains("сезон") {
type = "serie"
}
data.append(["id": href, "name": name, "thumb": thumb, "type": type])
}
if items.size() > 0 {
paginationData = try extractPaginationData(document, page: page)
}
}
return ["movies": data, "pagination": paginationData]
}
func extractPaginationData(_ document: Document, page: Int) throws -> [String: Any] {
var pages = 1
let paginationRoot = try document.select("div[class=basenavi] div[class=navigation]")
if !paginationRoot.array().isEmpty {
let paginationNode = paginationRoot.get(0)
let links = try paginationNode.select("a").array()
if let number = Int(try links[links.count-1].text()) {
pages = number
}
}
return [
"page": page,
"pages": pages,
"has_previous": page > 1,
"has_next": page < pages
]
}
public func getSeasons(_ playlistUrl: String, path: String) throws -> [Season] {
var list: [Season] = []
if let data = fetchData(playlistUrl, headers: getHeaders(KinoKongAPI.SiteUrl + path)),
let content = String(data: data, encoding: .windowsCP1251) {
if !content.isEmpty {
if let index = content.find("{\"playlist\":") {
let playlistContent = content[index ..< content.endIndex]
if let localizedData = playlistContent.data(using: .windowsCP1251) {
if let result = try? localizedData.decoded() as PlayList {
for item in result.playlist {
list.append(Season(comment: item.comment, playlist: buildEpisodes(item.playlist)))
}
}
else if let result = try? localizedData.decoded() as SingleSeasonPlayList {
list.append(Season(comment: "Сезон 1", playlist: buildEpisodes(result.playlist)))
}
}
}
}
}
return list
}
func buildEpisodes(_ playlist: [Episode]) -> [Episode] {
var episodes: [Episode] = []
for item in playlist {
let filesStr = item.file.components(separatedBy: ",")
var files: [String] = []
for item in filesStr {
if !item.isEmpty {
files.append(item)
}
}
episodes.append(Episode(comment: item.comment, file: item.file, files: files))
}
return episodes
}
func getEpisodeUrl(url: String, season: String, episode: String) -> String {
var episodeUrl = url
if !season.isEmpty {
episodeUrl = "\(url)?season=\(season)&episode=\(episode)"
}
return episodeUrl
}
func getHeaders(_ referer: String="") -> [String: String] {
var headers: [String: String] = [
"User-Agent": UserAgent,
"Host": KinoKongAPI.SiteUrl.replacingOccurrences(of: "https://", with: ""),
"Referer": KinoKongAPI.SiteUrl,
"Upgrade-Insecure-Requests": "1"
];
if !referer.isEmpty {
headers["Referer"] = referer
}
return headers
}
}
|
mit
|
439a70569f1aa4e12a0c98dc76661066
| 28.686131 | 140 | 0.584891 | 3.863215 | false | false | false | false |
MA806P/SwiftDemo
|
SwiftAlgorithm/0-Foundation.playground/Contents.swift
|
1
|
1634
|
import UIKit
var str = "Hello, playground"
var text = """
hello this line multiply
"""
var a = [4,1,2,6,3,5]
a.sort() //1,2,3,4,5,6
a.sort(by: >) //6,5,4,3,2,1
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("celery")
case let x where x.hasSuffix("pepper"):
print("pepper")
default:
print("nothing")
}
//pepper
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides"
}
}
var tmpShape = NamedShape(name: "suqare")
tmpShape.numberOfSides = 6
print("shape: \(tmpShape.simpleDescription())")
//shape: A shape with 6 sides
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
//self.name = name //'self' used in property access 'name' before 'super.init' call
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "square with sides of length \(sideLength)"
}
var perimeter: Double {
get {
return 4 * sideLength
}
set {
sideLength = newValue / 4.0
}
}
}
let tmpSquare = Square(sideLength: 3.0, name: "test square")
tmpSquare.area() //9
tmpSquare.simpleDescription()
print("suqare side length \(tmpSquare.sideLength)") //3.0
tmpSquare.perimeter = 20
print("suqare side length \(tmpSquare.sideLength)") //5.0
|
apache-2.0
|
b44a57004b463c1a0c02396450abcabb
| 20.786667 | 91 | 0.616279 | 3.631111 | false | false | false | false |
shubham01/StyleGuide
|
StyleGuide/Classes/Utils.swift
|
1
|
3066
|
//
// Utils.swift
// StyleGuide
//
// Created by Shubham Agrawal on 28/10/17.
//
import Foundation
import SwiftyJSON
class Utils {
class func parseVariableName(fromString string: String) -> String? {
let string = string.trimmingCharacters(in: .whitespaces)
if string.first == "@" {
let fromIndex = string.index(string.startIndex, offsetBy: 1)
return string.substring(from: fromIndex)
}
return nil
}
/**
Parse font from string to UIFont object
- parameter from: The input font string in format -> "size,fontName"
- returns: UIFont object if successful, nil otherwise. If font name is not specified, system font of asked size is returned.
*/
class func parseFont(from string: String?) -> UIFont? {
guard let values = string?.components(separatedBy: ","), values.count > 0 else {
return nil
}
var properties: [String: String] = [:]
for value in values {
let components = value.components(separatedBy: ":")
if components.count == 2 {
properties[components[0].trimmingCharacters(in: .whitespaces)] = components[1].trimmingCharacters(in: .whitespaces)
}
}
guard let fontSize = cgFloatFrom(string: properties["size"]) else {
return nil
}
let fontWeight = fontWeightFrom(string: properties["weight"])
if let family = properties["family"] {
let traits = [UIFontDescriptor.TraitKey.weight: fontWeight]
let fontDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptor.AttributeName.family: family,
UIFontDescriptor.AttributeName.traits: traits])
return UIFont(descriptor: fontDescriptor, size: fontSize)
} else {
return UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
}
}
class func cgFloatFrom(string: String?) -> CGFloat? {
guard let string = string else {
return nil
}
if let number = NumberFormatter().number(from: string) {
return CGFloat(number)
}
return nil
}
class func fontWeightFrom(string: String?) -> UIFont.Weight {
guard let string = string else {
return UIFont.Weight.regular
}
switch string {
case "ultraLight":
return UIFont.Weight.ultraLight
case "thin":
return UIFont.Weight.thin
case "light":
return UIFont.Weight.light
case "regular":
return UIFont.Weight.regular
case "medium":
return UIFont.Weight.medium
case "semiBold":
return UIFont.Weight.semibold
case "bold":
return UIFont.Weight.bold
case "heavy":
return UIFont.Weight.heavy
case "black":
return UIFont.Weight.black
default:
return UIFont.Weight.regular
}
}
}
|
mit
|
e339a57a76391d2ddd1992ff3b6cacf2
| 28.76699 | 131 | 0.581539 | 5.034483 | false | false | false | false |
kristoferdoman/stormy-treehouse-weather-app
|
Stormy/ForecastService.swift
|
2
|
943
|
//
// ForecastService.swift
// Stormy
//
// Created by Kristofer Doman on 2015-06-17.
// Copyright (c) 2015 Kristofer Doman. All rights reserved.
//
import Foundation
struct ForecastService {
let APIKey: String
let baseURL: NSURL?
init(APIKey: String) {
self.APIKey = APIKey
self.baseURL = NSURL(string: "https://api.forecast.io/forecast/\(APIKey)/")
}
func getForecast(lat: Double, long: Double, completion: (Forecast? -> Void)) {
if let url = NSURL(string: "\(lat),\(long)", relativeToURL: baseURL) {
let networkOperation = NetworkOperation(url: url)
networkOperation.downloadJSONFromURL { (let JSONDictionary) in
let forecast = Forecast(weatherDictionary: JSONDictionary)
completion(forecast)
}
} else {
println("Could not construct a valid URL.")
}
}
}
|
mit
|
3e7273e81e92e16235a934eb36c38276
| 26.764706 | 83 | 0.592789 | 4.42723 | false | false | false | false |
russbishop/swift
|
stdlib/public/SDK/SceneKit/SceneKit.swift
|
1
|
7604
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import SceneKit // Clang module
import CoreGraphics
import simd
// MARK: Exposing SCNFloat
#if os(OSX)
public typealias SCNFloat = CGFloat
#elseif os(iOS) || os(tvOS) || os(watchOS)
public typealias SCNFloat = Float
#endif
// MARK: Working with SCNVector3
extension SCNVector3 {
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = SCNFloat(x)
self.y = SCNFloat(y)
self.z = SCNFloat(z)
}
public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat) {
self.x = SCNFloat(x)
self.y = SCNFloat(y)
self.z = SCNFloat(z)
}
public init(_ x: Double, _ y: Double, _ z: Double) {
self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z))
}
public init(_ x: Int, _ y: Int, _ z: Int) {
self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z))
}
public init(_ v: float3) {
self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z))
}
public init(_ v: double3) {
self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z))
}
}
extension float3 {
public init(_ v: SCNVector3) {
self.init(Float(v.x), Float(v.y), Float(v.z))
}
}
extension double3 {
public init(_ v: SCNVector3) {
self.init(Double(v.x), Double(v.y), Double(v.z))
}
}
// MARK: Working with SCNVector4
extension SCNVector4 {
public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) {
self.x = SCNFloat(x)
self.y = SCNFloat(y)
self.z = SCNFloat(z)
self.w = SCNFloat(w)
}
public init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat, _ w: CGFloat) {
self.x = SCNFloat(x)
self.y = SCNFloat(y)
self.z = SCNFloat(z)
self.w = SCNFloat(w)
}
public init(_ x: Double, _ y: Double, _ z: Double, _ w: Double) {
self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w))
}
public init(_ x: Int, _ y: Int, _ z: Int, _ w: Int) {
self.init(SCNFloat(x), SCNFloat(y), SCNFloat(z), SCNFloat(w))
}
public init(_ v: float4) {
self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w))
}
public init(_ v: double4) {
self.init(SCNFloat(v.x), SCNFloat(v.y), SCNFloat(v.z), SCNFloat(v.w))
}
}
extension float4 {
public init(_ v: SCNVector4) {
self.init(Float(v.x), Float(v.y), Float(v.z), Float(v.w))
}
}
extension double4 {
public init(_ v: SCNVector4) {
self.init(Double(v.x), Double(v.y), Double(v.z), Double(v.w))
}
}
// MARK: Working with SCNMatrix4
extension SCNMatrix4 {
public init(_ m: float4x4) {
self.init(
m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]),
m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]),
m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]),
m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3]))
}
public init(_ m: double4x4) {
self.init(
m11: SCNFloat(m[0,0]), m12: SCNFloat(m[0,1]), m13: SCNFloat(m[0,2]), m14: SCNFloat(m[0,3]),
m21: SCNFloat(m[1,0]), m22: SCNFloat(m[1,1]), m23: SCNFloat(m[1,2]), m24: SCNFloat(m[1,3]),
m31: SCNFloat(m[2,0]), m32: SCNFloat(m[2,1]), m33: SCNFloat(m[2,2]), m34: SCNFloat(m[2,3]),
m41: SCNFloat(m[3,0]), m42: SCNFloat(m[3,1]), m43: SCNFloat(m[3,2]), m44: SCNFloat(m[3,3]))
}
}
extension float4x4 {
public init(_ m: SCNMatrix4) {
self.init([
float4(Float(m.m11), Float(m.m12), Float(m.m13), Float(m.m14)),
float4(Float(m.m21), Float(m.m22), Float(m.m23), Float(m.m24)),
float4(Float(m.m31), Float(m.m32), Float(m.m33), Float(m.m34)),
float4(Float(m.m41), Float(m.m42), Float(m.m43), Float(m.m44))
])
}
}
extension double4x4 {
public init(_ m: SCNMatrix4) {
self.init([
double4(Double(m.m11), Double(m.m12), Double(m.m13), Double(m.m14)),
double4(Double(m.m21), Double(m.m22), Double(m.m23), Double(m.m24)),
double4(Double(m.m31), Double(m.m32), Double(m.m33), Double(m.m34)),
double4(Double(m.m41), Double(m.m42), Double(m.m43), Double(m.m44))
])
}
}
// MARK: Swift Extensions
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.8)
extension SCNGeometryElement {
/// Creates an instance from `indices` for a `primitiveType`
/// that has a constant number of indices per primitive
/// - Precondition: the `primitiveType` must be `.triangles`, `.triangleStrip`, `.line` or `.point`
public convenience init<IndexType : Integer>(
indices: [IndexType], primitiveType: SCNGeometryPrimitiveType
) {
precondition(primitiveType == .triangles || primitiveType == .triangleStrip || primitiveType == .line || primitiveType == .point, "Expected constant number of indices per primitive")
let indexCount = indices.count
let primitiveCount: Int
switch primitiveType {
case .triangles:
primitiveCount = indexCount / 3
case .triangleStrip:
primitiveCount = indexCount - 2
case .line:
primitiveCount = indexCount / 2
case .point:
primitiveCount = indexCount
case .polygon:
fatalError("Expected constant number of indices per primitive")
}
self.init(
data: Data(bytes: UnsafePointer<UInt8>(indices), count: indexCount * sizeof(IndexType.self)),
primitiveType: primitiveType,
primitiveCount: primitiveCount,
bytesPerIndex: sizeof(IndexType.self))
_fixLifetime(indices)
}
}
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.8)
extension SCNGeometrySource {
public convenience init(vertices: [SCNVector3]) {
self.init(vertices: UnsafePointer(vertices), count: vertices.count)
}
public convenience init(normals: [SCNVector3]) {
self.init(normals: UnsafePointer(normals), count: normals.count)
}
public convenience init(textureCoordinates: [CGPoint]) {
self.init(textureCoordinates: UnsafePointer(textureCoordinates), count: textureCoordinates.count)
}
}
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.10)
extension SCNBoundingVolume {
public var boundingBox: (min: SCNVector3, max: SCNVector3) {
get {
var min = SCNVector3Zero
var max = SCNVector3Zero
getBoundingBoxMin(&min, max: &max)
return (min: min, max: max)
}
set {
var min = newValue.min
var max = newValue.max
setBoundingBoxMin(&min, max: &max)
}
}
public var boundingSphere: (center: SCNVector3, radius: Float) {
var center = SCNVector3Zero
var radius = CGFloat(0.0)
getBoundingSphereCenter(¢er, radius: &radius)
return (center: center, radius: Float(radius))
}
}
// MARK: APIs refined for Swift
@_silgen_name("SCN_Swift_SCNSceneSource_entryWithIdentifier")
internal func SCN_Swift_SCNSceneSource_entryWithIdentifier(
_ self_: AnyObject,
_ uid: NSString,
_ entryClass: AnyObject) -> AnyObject?
@available(iOS, introduced: 8.0)
@available(OSX, introduced: 10.8)
extension SCNSceneSource {
public func entryWithIdentifier<T>(_ uid: String, withClass entryClass: T.Type) -> T? {
return SCN_Swift_SCNSceneSource_entryWithIdentifier(
self, uid as NSString, entryClass as! AnyObject) as! T?
}
}
|
apache-2.0
|
2abf29e8c1dbf5ea93328112d542b111
| 31.357447 | 186 | 0.634797 | 3.078543 | false | false | false | false |
burhanaksendir/SwiftVideoPlayer
|
SwiftVideoPlayerDemo/SwiftVideoPlayerDemo/ViewController.swift
|
2
|
2088
|
//
// ViewController.swift
// SwiftVideoPlayer
//
// Created by Benjamin Horner on 08/09/2015.
// Copyright (c) 2015 Qanda. All rights reserved.
//
import UIKit
import SwiftVideoPlayer
class ViewController: UIViewController, VideoPlayerDelegate {
var player: VideoPlayer!
let videoURLString = "https://v.cdn.vine.co/r/videos/87DFC77702972658601489752064_1bdfc8e7016.3.1_5IH3bEUktlF4Q2jauHL0q3dPAXtmMAmsQJhJOZnIW.Cl9EPTgMj46EaM0c1PjHiO.mp4"
let videoRect = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.player = VideoPlayer(frame: videoRect, parentView: self.view, file: videoURLString)
self.player.delegate = self
self.player.scrubberMaximumTrackTintColor = UIColor.clearColor()
self.player.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: delegates
func playerReady(player: VideoPlayer) {
println("playerReady")
}
func playerPlaybackStateDidChange(player: VideoPlayer) {
println("playerPlaybackStateDidChange")
}
func playerBufferingStateDidChange(player: VideoPlayer) {
println("playerBufferingStateDidChange")
}
func playerPlaybackDidEnd(player: VideoPlayer) {
println("playerPlaybackDidEnd")
}
func playerPlaybackWillStartFromBeginning(player: VideoPlayer) {
println("playerPlaybackWillStartFromBeginning")
}
@IBAction func playPause(sender: UITapGestureRecognizer) {
if self.player.playbackState == .Playing {
self.player.pause()
}
else {
self.player.play()
}
}
}
|
mit
|
1f19a17b230f89a5f5fd74699c770c42
| 24.463415 | 171 | 0.62931 | 4.660714 | false | false | false | false |
dankogai/swift-complex
|
macOS.playground/Pages/Types.xcplaygroundpage/Contents.swift
|
1
|
2307
|
//: [Previous](@previous)
//:## Types
/*:
`Complex` offers two `Struct`s. `GaussianInt` is for integers and `Complex` is for floating-point numbers.
*/
import Complex
let gi = 1 + 1.i // gi is GaussianInt<Int>
let cd = 1.0 + 1.0.i // cd is Complex<Double>
/*:
Both are generic so any integral types can be an element of `GaussianInt` and any floating-point types can be an element of `Complex`.
*/
//:### struct GaussianInt<I:GaussianIntElement> : ComplexInt
/*:
`GaussianInt` accepts any integral types that conform to `GaussianIntElement` protocol. All built-in integers already do.
*/
let gi8 = Int8(0x7f) + Int8(-0x80).i
let gi16 = Int16(0x7fff) + Int16(-0x8000).i
let gi32 = Int32(0x7fff_ffff) + Int32(-0x80000000).i
let gi64 = Int64(0x7fff_ffff_ffff_ffff) + Int64(-0x8000_0000_0000_0000).i
/*:
`GaussianIntElement` is simply `SignedInteger` so if your custom integer conforms to that, you can use it with no extension. For instance, [attaswift/BigInt] does conform so:
[attaswift/BigInt]: https://github.com/attaswift/BigInt
```
import BigInt
import Complex
func factorial(_ n: Int) -> BigInt {
return (1 ... n).map { BigInt($0) }.reduce(BigInt(1), *)
}
let bgi = factorial(100)+factorial(100).i
print(bgi)
```
does simply work if you add it to your package dependency.
*/
//:### struct Complex<R:ComplexElement> : ComplexFloat
/*:
`GaussianInt` accepts any floating-point types that conform to `ComplexElement` protocol. `Float` and `Double` already do.
*/
let cf32 = Float32.pi + Float32.pi.i
let cf64 = Float64.pi + Float64.pi.i
/*:
`ComplexElement` is `FloatingPoint & FloatingPointMath. Meaning it is a bit trikier to comply. Unlike built-in `FloatingPoint`, [FloatingPointMath] is externaly defined to ensure necessary math functions exist. But if your type is already `FloatingPoint`, Complying to `FloatingPointMath` should be relatively easy. All you need is:
[FloatingPointMath]: https://github.com/dankogai/swift-floatingpointmath
```
extension YourFloat: FloatingPointMath {
init(_:Double) {
// convert from Double
}
var asDouble:Double {
// convert to Double
}
}
```
*/
//: [Next](@next)
|
mit
|
2fe92e74f54ffd0f773d56535010b99a
| 26.795181 | 336 | 0.665366 | 3.495455 | false | false | false | false |
Eitot/vienna-rss
|
Vienna/Sources/Main window/PopUpButtonToolbarItem.swift
|
1
|
1871
|
//
// PopUpButtonToolbarItem.swift
// Vienna
//
// Copyright 2017
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
/// A toolbar item with a pop-up button as its view.
class PopUpButtonToolbarItem: NSToolbarItem {
override func awakeFromNib() {
super.awakeFromNib()
// The toolbar item's width is too wide on older systems.
if #available(macOS 11, *) {
// Do nothing
} else {
minSize = NSSize(width: 41, height: 25)
maxSize = NSSize(width: 41, height: 28)
}
}
// Assign the pop-up button's menu to the menu-form representation.
override var view: NSView? {
didSet {
if let popupButton = view as? NSPopUpButton {
menuFormRepresentation?.submenu = popupButton.menu
// Unsetting target and action will ascertain that the menu is
// always enabled.
menuFormRepresentation?.target = nil
menuFormRepresentation?.action = nil
}
}
}
// Permanently enable the menu-form representation. The submenu's items are
// validated separately by their target.
override func validate() {
super.validate()
if view is NSPopUpButton {
menuFormRepresentation?.isEnabled = true
}
}
}
|
apache-2.0
|
ef79121ecdd75d4a60dfa5f166c1e580
| 29.672131 | 79 | 0.63442 | 4.552311 | false | false | false | false |
jfrowies/coolblue
|
coolblue/Models/Models+SwiftyJSON/Image+SwiftyJSON.swift
|
1
|
704
|
//
// Image+SwiftyJSON.swift
// coolblue
//
// Created by Fer Rowies on 3/24/16.
// Copyright © 2016 Fernando Rowies. All rights reserved.
//
import Foundation
import SwiftyJSON
extension Image {
init(fromJSON json : JSON) {
orderNumber = json["orderNumber"].intValue
type = json["type"].stringValue
thumbnailHdUrl = json["thumbnailHdUrl"].stringValue
smallUrl = json["smallUrl"].stringValue
smallHdUrl = json["smallHdUrl"].stringValue
mediumUrl = json["mediumUrl"].stringValue
mediumHdUrl = json["mediumHdUrl"].stringValue
largeUrl = json["largeUrl"].stringValue
largeHdUrl = json["largeHdUrl"].stringValue
}
}
|
mit
|
cc985df6dc71b40daacdbae3e8da620f
| 27.12 | 59 | 0.661451 | 4.23494 | false | false | false | false |
sachin004/firefox-ios
|
Utils/Functions.swift
|
3
|
5185
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Pipelining.
infix operator |> { associativity left }
public func |> <T, U>(x: T, f: T -> U) -> U {
return f(x)
}
// Basic currying.
public func curry<A, B>(f: (A) -> B) -> A -> B {
return { a in
return f(a)
}
}
public func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C {
return { a in
return { b in
return f(a, b)
}
}
}
public func curry<A, B, C, D>(f: (A, B, C) -> D) -> A -> B -> C -> D {
return { a in
return { b in
return { c in
return f(a, b, c)
}
}
}
}
public func curry<A, B, C, D, E>(f: (A, B, C, D) -> E) -> (A, B, C) -> D -> E {
return { (a, b, c) in
return { d in
return f(a, b, c, d)
}
}
}
// Function composition.
infix operator • {}
public func •<T, U, V>(f: T -> U, g: U -> V) -> T -> V {
return { t in
return g(f(t))
}
}
public func •<T, V>(f: T -> (), g: () -> V) -> T -> V {
return { t in
f(t)
return g()
}
}
public func •<V>(f: () -> (), g: () -> V) -> () -> V {
return {
f()
return g()
}
}
// Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse.
// This is enough to catch arrays, which Swift will delegate to element-==.
public func optArrayEqual<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {
switch (lhs, rhs) {
case (.None, .None):
return true
case (.None, _):
return false
case (_, .None):
return false
default:
// This delegates to Swift's own array '==', which calls T's == on each element.
return lhs! == rhs!
}
}
/**
* Given an array, return an array of slices of size `by` (possibly excepting the last slice).
*
* If `by` is longer than the input, returns a single chunk.
* If `by` is less than 1, acts as if `by` is 1.
* If the length of the array isn't a multiple of `by`, the final slice will
* be smaller than `by`, but never empty.
*
* If the input array is empty, returns an empty array.
*/
public func chunk<T>(arr: [T], by: Int) -> [ArraySlice<T>] {
let count = arr.count
let step = max(1, by) // Handle out-of-range 'by'.
let s = 0.stride(to: count, by: step)
return s.map {
arr[$0..<$0.advancedBy(step, limit: count)]
}
}
public func optDictionaryEqual<K: Equatable, V: Equatable>(lhs: [K: V]?, rhs: [K: V]?) -> Bool {
switch (lhs, rhs) {
case (.None, .None):
return true
case (.None, _):
return false
case (_, .None):
return false
default:
return lhs! == rhs!
}
}
/**
* Return members of `a` that aren't nil, changing the type of the sequence accordingly.
*/
public func optFilter<T>(a: [T?]) -> [T] {
return a.flatMap { $0 }
}
/**
* Return a new map with only key-value pairs that have a non-nil value.
*/
public func optFilter<K, V>(source: [K: V?]) -> [K: V] {
var m = [K: V]()
for (k, v) in source {
if let v = v {
m[k] = v
}
}
return m
}
/**
* Map a function over the values of a map.
*/
public func mapValues<K, T, U>(source: [K: T], f: (T -> U)) -> [K: U] {
var m = [K: U]()
for (k, v) in source {
m[k] = f(v)
}
return m
}
/**
* Find the first matching item in the array and return it.
* Unlike map/filter approaches, this is lazy.
*/
public func find<T>(arr: [T], f: T -> Bool) -> T? {
for x in arr {
if f(x) {
return x
}
}
return nil
}
public func findOneValue<K, V>(map: [K: V], f: V -> Bool) -> V? {
for v in map.values {
if f(v) {
return v
}
}
return nil
}
/**
* Take a JSON array, returning the String elements as an array.
* It's usually convenient for this to accept an optional.
*/
public func jsonsToStrings(arr: [JSON]?) -> [String]? {
if let arr = arr {
return optFilter(arr.map { j in
return j.asString
})
}
return nil
}
// Encapsulate a callback in a way that we can use it with NSTimer.
private class Callback {
private let handler:()->()
init(handler:()->()) {
self.handler = handler
}
@objc
func go() {
handler()
}
}
/**
* Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call
* Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires.
**/
public func debounce(delay:NSTimeInterval, action:()->()) -> ()->() {
let callback = Callback(handler: action)
var timer: NSTimer?
return {
// If calling again, invalidate the last timer.
if let timer = timer {
timer.invalidate()
}
timer = NSTimer(timeInterval: delay, target: callback, selector: "go", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)
}
}
|
mpl-2.0
|
e3736b153ebd84d7d024f11a797f2f49
| 23.652381 | 115 | 0.536025 | 3.305875 | false | false | false | false |
BareFeetWare/BFWControls
|
BFWControls/Modules/Styled/Model/StyledText.swift
|
1
|
4956
|
//
// StyledText.swift
//
// Created by Tom Brodhurst-Hill on 9/04/2016.
// Copyright © 2016 BareFeetWare. Free to use and modify, without warranty.
//
import UIKit
//TODO: Refactor to not use strings.
open class StyledText {
// MARK: - Constants
public struct Section {
public static let level = "level"
public static let emphasis = "emphasis"
public static let style = "style"
}
struct Key {
static let fontName = "fontName"
static let familyName = "familyName"
static let fontSize = "fontSize"
static let textColor = "textColor"
static let weight = "weight"
}
fileprivate static let styledTextPlist = "StyledText"
fileprivate static var plistDict: [String : AnyObject]? = {
guard let path = Bundle.path(forFirstResource: styledTextPlist, ofType: "plist"),
let plistDict = NSDictionary(contentsOfFile: path) as? [String : AnyObject]
else {
debugPrint("StyledText: plistDict: failed")
return nil
}
return plistDict
}()
// MARK: - Functions
open class func attributes(for style: String) -> TextAttributes? {
return attributes(forSection: Section.style, key: style)
}
open class func attributes(for styles: [String]) -> TextAttributes? {
var textAttributes: TextAttributes?
for style in styles {
if let extraAttributes = attributes(for: style) {
if textAttributes == nil {
textAttributes = TextAttributes()
}
textAttributes!.update(with: extraAttributes)
}
}
return textAttributes
}
open class func attributes(forLevel level: Int) -> TextAttributes? {
return attributes(forSection: Section.level, key: String(level))
}
open class func attributes(for lookupDict: [String : AnyObject]) -> TextAttributes? {
var attributes = TextAttributes()
let flatDict = flatLookup(dict: lookupDict)
if let familyName = flatDict[Key.familyName] as? String,
let fontSize = flatDict[Key.fontSize] as? CGFloat
{
var fontAttributes = [UIFontDescriptor.AttributeName : Any]()
fontAttributes[.family] = familyName
if let weight = flatDict[Key.weight] as? CGFloat {
let fontWeight = FontWeight(approximateWeight: weight)
let validWeight = fontWeight.rawValue
let traits = [UIFontDescriptor.TraitKey.weight: validWeight]
fontAttributes[.traits] = traits
}
let fontDescriptor = UIFontDescriptor(fontAttributes: fontAttributes)
attributes[.font] = UIFont(descriptor: fontDescriptor, size: fontSize)
} else if let fontName = flatDict[Key.fontName] as? String,
let fontSize = flatDict[Key.fontSize] as? CGFloat,
let font = UIFont(name: fontName, size: fontSize)
{
attributes[.font] = font
} else if let fontName = flatDict[Key.fontName] as? String {
debugPrint("**** error: Couldn't load UIFont(name: \(fontName)")
} else {
debugPrint("**** error: No value for key: \(Key.fontName)")
}
if let textColorString = flatDict[Key.textColor] as? String,
// TODO: Facilitate alpha ≠ 1.0
let textColor = UIColor(hexString: textColorString, alpha: 1.0)
{
attributes[.foregroundColor] = textColor
}
return attributes
}
// MARK: - Private variables and functions
fileprivate class var sections: [String] {
return [Section.style, Section.level, Section.emphasis]
}
// TODO: Make this private by providing alternative func.
open class func attributes(forSection section: String, key: String) -> TextAttributes? {
guard let sectionDict = plistDict?[section] as? [String : AnyObject],
let lookupDict = sectionDict[key] as? [String : AnyObject]
else { return nil }
return attributes(for: lookupDict)
}
fileprivate class func flatLookup(dict lookupDict: [String : AnyObject]) -> [String : AnyObject] {
guard let plistDict = plistDict
else { return [:] }
var combined = [String : AnyObject]()
for section in sections {
if let key = lookupDict[section],
let sectionDict = plistDict[section] as? [String : AnyObject],
let dict = sectionDict[String(describing: key)] as? [String : AnyObject]
{
combined.update(with: flatLookup(dict: dict))
}
}
for (key, value) in lookupDict {
if !sections.contains(key) {
combined[key] = value
}
}
return combined
}
}
|
mit
|
19b1001d34f3c719bd30bcb7a51879f1
| 35.962687 | 102 | 0.59257 | 4.957958 | false | false | false | false |
OscarSwanros/swift
|
stdlib/public/SDK/MetalKit/MetalKit.swift
|
2
|
1811
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import MetalKit // Clang module
@available(swift 4)
@available(macOS 10.11, iOS 9.0, tvOS 9.0, *)
extension MTKMesh {
public class func newMeshes(asset: MDLAsset, device: MTLDevice) throws -> (modelIOMeshes: [MDLMesh], metalKitMeshes: [MTKMesh]) {
var modelIOMeshes: NSArray?
var metalKitMeshes = try MTKMesh.newMeshes(from: asset, device: device, sourceMeshes: &modelIOMeshes)
return (modelIOMeshes: modelIOMeshes as! [MDLMesh], metalKitMeshes: metalKitMeshes)
}
}
@available(swift 4)
@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
public func MTKModelIOVertexDescriptorFromMetalWithError(_ metalDescriptor: MTLVertexDescriptor) throws -> MDLVertexDescriptor {
var error: NSError? = nil
let result = MTKModelIOVertexDescriptorFromMetalWithError(metalDescriptor, &error)
if let error = error {
throw error
}
return result
}
@available(swift 4)
@available(macOS 10.12, iOS 10.0, tvOS 10.0, *)
public func MTKMetalVertexDescriptorFromModelIOWithError(_ modelIODescriptor: MDLVertexDescriptor) throws -> MTLVertexDescriptor? {
var error: NSError? = nil
let result = MTKMetalVertexDescriptorFromModelIOWithError(modelIODescriptor, &error)
if let error = error {
throw error
}
return result
}
|
apache-2.0
|
7776f537a1384d80da00d6c376053737
| 39.244444 | 133 | 0.668139 | 4.363855 | false | false | false | false |
IBM-Swift/BluePic
|
BluePic-CloudFunctions/actions/Weather.swift
|
1
|
2374
|
/**
* fetch current weather observation from weather service
*/
import KituraNet
import Dispatch
import Foundation
import RestKit
import SwiftyJSON
func main(args: [String:Any]) -> [String:Any] {
var str = ""
var result: [String:Any] = [
"weather": str
]
guard let username = args["weatherUsername"] as? String,
let password = args["weatherPassword"] as? String,
let latitude = args["latitude"] as? String,
let longitude = args["longitude"] as? String else {
str = "Error: missing a required parameter for retrieving weather data."
return result
}
let language = args["language"] as? String ?? "en-US"
let units = args["units"] as? String ?? "e"
let requestOptions: [ClientRequest.Options] = [ .method("GET"),
.schema("https://"),
.hostname("twcservice.mybluemix.net"),
.username(username),
.password(password),
.path("/api/weather/v1/geocode/\(latitude)/\(longitude)/observations.json?language=\(language)")
]
let req = HTTP.request(requestOptions) { response in
do {
guard let response = response else {
str = "No response was received from Weather Insights"
return
}
var data = Data()
_ = try response.read(into: &data)
let json = SwiftyJSON.JSON(data: data)
guard let icon_code = json["observation"]["wx_icon"].int,
let sky_cover = json["observation"]["wx_phrase"].string else {
str = "Unable to resolve sky cover and icon code weather response data"
return
}
let temp = json["observation"]["temp"].int ?? 0
str = "{ \"observation\":{" +
"\"icon_code\":\(icon_code)," +
"\"sky_cover\":\"\(sky_cover)\"," +
"\"imperial\":{\"temp\":\(temp)}" +
"}}"
} catch {
str = "Error \(error)"
}
}
req.end()
result = [
"weather": "\(str)"
]
return result
}
|
apache-2.0
|
9d7d114263813fdfdaf85b7c58a0f5c7
| 30.653333 | 148 | 0.475569 | 4.987395 | false | false | false | false |
KevinChouRafael/UICollectionViewFreezeLayout
|
ZKCollectionViewFreezeLayout/ZKCollectionViewFreezeLayout/Classes/ZKCollectionViewFreezeLayout.swift
|
1
|
10103
|
//
// ZKCollectionViewFreezeLayout.swift
//
// Created by rafael on 5/6/16.
// Copyright © 2016 Rafael. All rights reserved.
//
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc public protocol ZKCollectionViewFreezeLayoutDelegate : UICollectionViewDelegate {
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize
@objc optional func contentSize(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout) -> CGSize
}
@objc open class ZKCollectionViewFreezeLayout: UICollectionViewLayout {
// default Size of the cell
open var itemSize:CGSize = CGSize(width: 50, height: 50)
fileprivate var cellAttrsDictionary = Dictionary<IndexPath, UICollectionViewLayoutAttributes>()
fileprivate var cellAttrsDictionaryConst = Dictionary<IndexPath, UICollectionViewLayoutAttributes>()
open var freezeColum:Int = 1
open var freezeRow:Int = 1
// Defines the size of the area the user can move around in
// within the collection view.
var contentSize = CGSize.zero
// Used to determine if a data source update has occured.
// Note: The data source would be responsible for updating
// this value if an update was performed.
var dataSourceDidUpdate = true
open weak var delegate:ZKCollectionViewFreezeLayoutDelegate?
override open var collectionViewContentSize : CGSize {
return self.contentSize
}
override open func prepare() {
// Only update header cells.
if !dataSourceDidUpdate {
// Determine current content offsets.
let xOffset = collectionView!.contentOffset.x
let yOffset = collectionView!.contentOffset.y
if collectionView?.numberOfSections > 0 {
for section in 0...collectionView!.numberOfSections-1 {
if collectionView?.numberOfItems(inSection: section) > 0 {
// Update all items with freeze
for item in 0...collectionView!.numberOfItems(inSection: section)-1 {
if section < freezeRow && item < freezeColum {
let indexPath = IndexPath(item: item, section: section)
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.x = xOffset + cellAttrsDictionaryConst[indexPath]!.frame.origin.x
frame.origin.y = yOffset + cellAttrsDictionaryConst[indexPath]!.frame.origin.y
attrs.frame = frame
}
}else if section < freezeRow {
// Build indexPath to get attributes from dictionary.
let indexPath = IndexPath(item: item, section: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.y = yOffset + cellAttrsDictionaryConst[indexPath]!.frame.origin.y
attrs.frame = frame
}
}else if item < freezeColum {
// Build indexPath to get attributes from dictionary.
let indexPath = IndexPath(item: item, section: section)
// Update x-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.x = xOffset + cellAttrsDictionaryConst[indexPath]!.frame.origin.x
attrs.frame = frame
}
}
} //// Update all items with freeze
}
}
}
// Do not run attribute generation code
// unless data source has been updated.
updateContentSize()
return
}
// Acknowledge data source change, and disable for next time.
dataSourceDidUpdate = false
// Cycle through each section of the data source.
if collectionView?.numberOfSections > 0 {
for section in 0...collectionView!.numberOfSections-1 {
// Cycle through each item in the section.
if collectionView?.numberOfItems(inSection: section) > 0 {
var xPos:CGFloat = 0
var yPos:CGFloat = 0
for item in 0...collectionView!.numberOfItems(inSection: section)-1 {
// Build the UICollectionVieLayoutAttributes for the cell.
let cellIndex = IndexPath(item: item, section: section)
// let xPos = CGFloat(item) * getItemSize(cellIndex).width
// let yPos = CGFloat(section) * getItemSize(cellIndex).height
yPos = CGFloat(section) * getItemSize(cellIndex).height
let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: cellIndex)
cellAttributes.frame = CGRect(x: xPos, y: yPos, width: getItemSize(cellIndex).width, height: getItemSize(cellIndex).height)
// Determine zIndex based on cell type.
if section < freezeRow && item < freezeColum {
cellAttributes.zIndex = 4
} else if section < freezeRow{
cellAttributes.zIndex = 3
} else if item < freezeColum {
cellAttributes.zIndex = 2
} else {
cellAttributes.zIndex = 1
}
// Save the attributes.
cellAttrsDictionary[cellIndex] = cellAttributes
cellAttrsDictionaryConst[cellIndex] = cellAttributes.copy() as? UICollectionViewLayoutAttributes
xPos += getItemSize(cellIndex).width
}
}
}
}
// Update content size.
updateContentSize()
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Create an array to hold all elements found in our current view.
var attributesInRect = [UICollectionViewLayoutAttributes]()
// Check each element to see if it should be returned.
for cellAttributes in cellAttrsDictionary.values {
if rect.intersects(cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}
// Return list of elements.
return attributesInRect
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cellAttrsDictionary[indexPath]!
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
func getItemSize(_ indexPath:IndexPath)->CGSize{
if delegate != nil && (delegate!.responds(to: #selector(ZKCollectionViewFreezeLayoutDelegate.collectionView(_:layout:sizeForItemAtIndexPath:)))) {
return (delegate!.collectionView!(collectionView!, layout: self, sizeForItemAtIndexPath: indexPath))
}else{
return itemSize
}
}
func updateContentSize(){
if delegate != nil && (delegate!.responds(to: #selector(ZKCollectionViewFreezeLayoutDelegate.contentSize(_:layout:)))) {
self.contentSize = delegate!.contentSize!(collectionView!, layout: self)
}else{
let contentHeight = CGFloat(collectionView!.numberOfSections) * itemSize.height
var contentWidth:CGFloat = 0.0
if collectionView!.numberOfSections > 0 {
contentWidth = CGFloat(collectionView!.numberOfItems(inSection: 0)) * itemSize.width
}
self.contentSize = CGSize(width: contentWidth, height: contentHeight)
}
}
}
|
mit
|
358436a8eb706c754ec3550a4ac92500
| 41.445378 | 182 | 0.524748 | 6.564003 | false | false | false | false |
velvetroom/columbus
|
Source/View/Global/Plan/VPlanStop.swift
|
1
|
1198
|
import UIKit
struct VPlanStop
{
//MARK: private
private static func travelMap() -> [DPlanTravelMode:UIImage]
{
let map:[DPlanTravelMode:UIImage] = [
DPlanTravelMode.walking : #imageLiteral(resourceName: "assetGenericStopWalking"),
DPlanTravelMode.cycling : #imageLiteral(resourceName: "assetGenericStopCycling"),
DPlanTravelMode.transit : #imageLiteral(resourceName: "assetGenericStopTransit"),
DPlanTravelMode.driving : #imageLiteral(resourceName: "assetGenericStopDriving")]
return map
}
private static func factoryIcon(travel:DPlanTravel) -> UIImage?
{
let map:[DPlanTravelMode:UIImage] = travelMap()
let image:UIImage? = map[travel.mode]
return image
}
//MARK: internal
static func factoryIcon(stop:DPlanStop) -> UIImage?
{
let icon:UIImage?
if let travel:DPlanTravel = stop.destinationTravel
{
icon = factoryIcon(travel:travel)
}
else
{
icon = #imageLiteral(resourceName: "assetGenericStopOrigin")
}
return icon
}
}
|
mit
|
f8005f566413f87644025921bb16f3c4
| 26.860465 | 93 | 0.606845 | 4.792 | false | false | false | false |
nicolastinkl/swift
|
ListerAProductivityAppBuiltinSwift/ListerTodayOSX/TodayViewController.swift
|
1
|
5553
|
/*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Handles display of the Today view. It leverages iCloud for seamless interaction between devices.
*/
import Cocoa
import NotificationCenter
import ListerKitOSX
@objc(TodayViewController) class TodayViewController: NSViewController, NCWidgetProviding, NCWidgetListViewDelegate, ListRowViewControllerDelegate, ListDocumentDelegate {
// MARK: Types
struct TableViewConstants {
static let openListRow = 0
}
// MARK: Properties
@IBOutlet var listViewController: NCWidgetListViewController
var document: ListDocument!
var list: List {
return document.list
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
updateWidgetContents()
}
override func viewWillAppear() {
super.viewWillAppear()
listViewController.delegate = self
listViewController.hasDividerLines = false
listViewController.showsAddButtonWhenEditing = false
listViewController.contents = []
updateWidgetContents()
}
// MARK: NCWidgetProviding
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
updateWidgetContents(completionHandler)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInset: NSEdgeInsets) -> NSEdgeInsets {
return NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func widgetAllowsEditing() -> Bool {
return true
}
func widgetDidBeginEditing() {
listViewController.editing = true
}
func widgetDidEndEditing() {
listViewController.editing = false
}
// MARK: NCWidgetListViewDelegate
func widgetList(_: NCWidgetListViewController, viewControllerForRow row: Int) -> NSViewController {
if row == TableViewConstants.openListRow {
return OpenListerRowViewController()
}
else if list.isEmpty {
return NoItemsRowViewController()
}
let listRowViewController = ListRowViewController()
listRowViewController.representedObject = listViewController.contents[row]
listRowViewController.delegate = self
return listRowViewController
}
func widgetList(_: NCWidgetListViewController, shouldRemoveRow row: Int) -> Bool {
return row != TableViewConstants.openListRow
}
func widgetList(_: NCWidgetListViewController, didRemoveRow row: Int) {
let item = list[row - 1]
list.removeItems([item])
document.updateChangeCount(.ChangeDone)
}
// MARK: ListRowViewControllerDelegate
func listRowViewControllerDidChangeRepresentedObjectState(listRowViewController: ListRowViewController) {
let indexOfListRowViewController = listViewController.rowForViewController(listRowViewController)
let item = list[indexOfListRowViewController - 1]
list.toggleItem(item)
document.updateChangeCount(.ChangeDone)
// Make sure the rows are reordered appropriately.
listViewController.contents = listRowRepresentedObjectsForList(list)
}
// MARK: ListDocumentDelegate
func listDocumentDidChangeContents(document: ListDocument) {
listViewController.contents = listRowRepresentedObjectsForList(list)
}
// MARK: Convenience
func listRowRepresentedObjectsForList(aList: List) -> AnyObject[] {
var representedObjects = AnyObject[]()
let listColor = list.color.colorValue
// The "Open in Lister" has a representedObject as an NSColor, representing the text color.
representedObjects += listColor
for item in aList.items {
representedObjects += ListRowRepresentedObject(item: item, color: listColor)
}
// Add a sentinel NSNull value to represent the "No Items" represented object.
if (list.isEmpty) {
// No items in the list.
representedObjects += NSNull()
}
return representedObjects
}
func updateWidgetContents(completionHandler: ((NCUpdateResult) -> Void)? = nil) {
TodayListManager.fetchTodayDocumentURLWithCompletionHandler { todayDocumentURL in
if !todayDocumentURL {
completionHandler?(.Failed)
return
}
dispatch_async(dispatch_get_main_queue()) {
var error: NSError?
let newDocument = ListDocument(contentsOfURL: todayDocumentURL!, makesCustomWindowControllers: false, error: &error)
if error {
completionHandler?(.Failed)
}
else {
if self.document?.list == newDocument.list {
completionHandler?(.NoData)
}
else {
self.document = newDocument
self.document.delegate = self
self.listViewController.contents = self.listRowRepresentedObjectsForList(newDocument.list)
completionHandler?(.NewData)
}
}
}
}
}
}
|
mit
|
4157014dbc544a3dcc156dae0ecc59b9
| 30.539773 | 170 | 0.62223 | 5.924226 | false | false | false | false |
iOS-mamu/SS
|
P/Library/Eureka/Source/Rows/FieldsRow.swift
|
1
|
13066
|
//
// FieldsRow.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
open class TextCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .default
textField.autocapitalizationType = .sentences
textField.keyboardType = .default
}
}
open class IntCell : _FieldCell<Int>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .default
textField.autocapitalizationType = .none
textField.keyboardType = .numberPad
}
}
open class PhoneCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.keyboardType = .phonePad
}
}
open class NameCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .words
textField.keyboardType = .asciiCapable
}
}
open class EmailCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .emailAddress
}
}
open class PasswordCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .asciiCapable
textField.isSecureTextEntry = true
}
}
open class DecimalCell : _FieldCell<Double>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.keyboardType = .decimalPad
}
}
open class URLCell : _FieldCell<URL>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .URL
}
}
open class TwitterCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .twitter
}
}
open class AccountCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.keyboardType = .asciiCapable
}
}
open class ZipCodeCell : _FieldCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func update() {
super.update()
textField.autocorrectionType = .no
textField.autocapitalizationType = .allCharacters
textField.keyboardType = .numbersAndPunctuation
}
}
open class _TextRow: FieldRow<String, TextCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _IntRow: FieldRow<Int, IntCell> {
public required init(tag: String?) {
super.init(tag: tag)
let numberFormatter = NumberFormatter()
numberFormatter.locale = .current
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 0
formatter = numberFormatter
}
}
open class _PhoneRow: FieldRow<String, PhoneCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _NameRow: FieldRow<String, NameCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _EmailRow: FieldRow<String, EmailCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _PasswordRow: FieldRow<String, PasswordCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _DecimalRow: FieldRow<Double, DecimalCell> {
public required init(tag: String?) {
super.init(tag: tag)
let numberFormatter = NumberFormatter()
numberFormatter.locale = .current
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 2
formatter = numberFormatter
}
}
open class _URLRow: FieldRow<URL, URLCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _TwitterRow: FieldRow<String, TwitterCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _AccountRow: FieldRow<String, AccountCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
open class _ZipCodeRow: FieldRow<String, ZipCodeCell> {
public required init(tag: String?) {
super.init(tag: tag)
}
}
/// A String valued row where the user can enter arbitrary text.
public final class TextRow: _TextRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter names. Biggest difference to TextRow is that it autocapitalization is set to Words.
public final class NameRow: _NameRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter secure text.
public final class PasswordRow: _PasswordRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter an email address.
public final class EmailRow: _EmailRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter a twitter username.
public final class TwitterRow: _TwitterRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter a simple account username.
public final class AccountRow: _AccountRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter a zip code.
public final class ZipCodeRow: _ZipCodeRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A row where the user can enter an integer number.
public final class IntRow: _IntRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A row where the user can enter a decimal number.
public final class DecimalRow: _DecimalRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A row where the user can enter an URL. The value of this row will be a NSURL.
public final class URLRow: _URLRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
/// A String valued row where the user can enter a phone number.
public final class PhoneRow: _PhoneRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
onCellHighlight { cell, row in
let color = cell.textLabel?.textColor
row.onCellUnHighlight { cell, _ in
cell.textLabel?.textColor = color
}
cell.textLabel?.textColor = cell.tintColor
}
}
}
|
mit
|
e17fa431a6bec5006e367f4e85341876
| 28.828767 | 132 | 0.632836 | 4.681118 | false | false | false | false |
davidolesch/CurrentWeather
|
Current Weather/CurrentWeatherViewController.swift
|
1
|
1452
|
import UIKit
import CoreLocation
class CurrentWeatherViewController: UIViewController {
@IBOutlet weak var locationNameLabel: UILabel!
@IBOutlet weak var currentTemperatureLabel: UILabel!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var locationManger: LocationManager!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
locationManger = LocationManager.init { location in
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
self.updateWeatherLabel(latitude, lon: longitude)
}
}
override func viewDidLoad() {
super.viewDidLoad()
locationNameLabel.text = "Finding Weather"
currentTemperatureLabel.text = ""
loadingIndicator.startAnimating()
}
func updateWeatherLabel(lat:CLLocationDegrees, lon:CLLocationDegrees) -> () {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let currentObservation = currentObservationAtLat(lat, lon: lon)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.locationNameLabel.text = currentObservation.locationName
self.currentTemperatureLabel.text = currentObservation.currentTemperature
self.loadingIndicator.stopAnimating()
})
}
}
}
|
mit
|
f8ab5e3f5c9a29d399326fbc0cf3e1d9
| 34.414634 | 89 | 0.665978 | 5.563218 | false | false | false | false |
jiankaiwang/codein
|
examples/oop.swift
|
1
|
1126
|
/*
* desc : structure and class definition
* docv : 0.1.0
* plat : CodeIn
* swif : 5.1.3
*/
struct Car {
var weight = 0
var horsepower = 0
var name = ""
}
class CarPhysicalProperty {
var carInfo = Car()
var acceleration : Double = 0.0
// private void function
private func calAccelerate() {
self.acceleration =
Double(self.carInfo.horsepower) / Double(self.carInfo.weight)
}
// constructor
init(carWeight : Int, carHorsepower : Int, carName : String) {
self.carInfo = Car(
weight : carWeight,
horsepower : carHorsepower,
name : carName
)
self.calAccelerate()
}
// public Double function
public func getCarAcc() -> Double {
return(self.acceleration)
}
// public String function
public func getCarName() -> String {
return(self.carInfo.name)
}
}
var firstCar = CarPhysicalProperty(
carWeight : 100, carHorsepower : 200, carName : "FCar"
)
print("The accelerate of \(firstCar.getCarName()) is \(firstCar.getCarAcc()).")
|
mit
|
86b91eb217d037fc10b657640afdbd2a
| 21.979592 | 80 | 0.586146 | 3.856164 | false | false | false | false |
ephread/Instructions
|
Sources/Instructions/Instructions.swift
|
2
|
3051
|
// Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
struct Constants {
static let overlayFadeAnimationDuration: TimeInterval = 0.3
static let coachMarkFadeAnimationDuration: TimeInterval = 0.3
}
struct InstructionsColor {
static let overlay: UIColor = {
let defaultColor = #colorLiteral(red: 0.9098039216, green: 0.9098039216, blue: 0.9098039216, alpha: 0.65)
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
if traits.userInterfaceStyle == .dark {
return #colorLiteral(red: 0.1960784314, green: 0.1960784314, blue: 0.1960784314, alpha: 0.75)
} else {
return defaultColor
}
}
} else {
return defaultColor
}
}()
static let coachMarkInner: UIColor = {
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
if traits.userInterfaceStyle == .dark {
let lightTraits = UITraitCollection(userInterfaceStyle: .light)
return UIColor.systemGray4.resolvedColor(with: lightTraits)
} else {
return .white
}
}
} else {
return .white
}
}()
static let coachMarkHighlightedInner: UIColor = {
let defaultColor = #colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9490196078, alpha: 1)
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
if traits.userInterfaceStyle == .dark {
let lightTraits = UITraitCollection(userInterfaceStyle: .light)
return UIColor.systemGray2.resolvedColor(with: lightTraits)
} else {
return defaultColor
}
}
} else {
return defaultColor
}
}()
static let coachMarkOuter: UIColor = {
let defaultColor = #colorLiteral(red: 0.8901960784, green: 0.8901960784, blue: 0.8901960784, alpha: 1)
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
if traits.userInterfaceStyle == .dark {
return .systemGray
} else {
return defaultColor
}
}
} else {
return defaultColor
}
}()
static let coachMarkLabel: UIColor = {
let defaultColor = #colorLiteral(red: 0.1333333333, green: 0.1333333333, blue: 0.1333333333, alpha: 1)
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
if traits.userInterfaceStyle == .dark {
return .black
} else {
return defaultColor
}
}
} else {
return defaultColor
}
}()
}
|
mit
|
ace1e32447a9176be9e6456594f1d473
| 32.505495 | 113 | 0.528698 | 4.941653 | false | false | false | false |
mrdepth/Neocom
|
Neocom/Neocom/Utility/DataLoaders/AccountInfo.swift
|
2
|
3258
|
//
// AccountInfo.swift
// Neocom
//
// Created by Artem Shimanski on 11/29/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import Alamofire
import Expressible
import Combine
import CoreData
class AccountInfo: ObservableObject {
@Published var isLoading = false
@Published var skillQueue: Result<[ESI.SkillQueueItem], AFError>?
@Published var ship: Result<ESI.Ship, AFError>?
@Published var location: Result<SDEMapSolarSystem, AFError>?
@Published var skills: Result<ESI.CharacterSkills, AFError>?
@Published var balance: Result<Double, AFError>?
private var esi: ESI
private var characterID: Int64
private var managedObjectContext: NSManagedObjectContext
init(esi: ESI, characterID: Int64, managedObjectContext: NSManagedObjectContext) {
self.esi = esi
self.characterID = characterID
self.managedObjectContext = managedObjectContext
update(cachePolicy: .useProtocolCachePolicy)
}
func update(cachePolicy: URLRequest.CachePolicy) {
let esi = self.esi
let managedObjectContext = self.managedObjectContext
subscriptions.removeAll()
isLoading = true
let character = esi.characters.characterID(Int(characterID))
let ship = character.ship().get()
.map{$0.value}
.receive(on: RunLoop.main)
.share()
ship.asResult().sink { [weak self] result in
self?.ship = result
}.store(in: &subscriptions)
let skills = character.skills().get()
.map{$0.value}
.receive(on: RunLoop.main)
.share()
skills.asResult().sink { [weak self] result in
self?.skills = result
}.store(in: &subscriptions)
let wallet = character.wallet().get()
.map{$0.value}
.receive(on: RunLoop.main)
.share()
wallet.asResult().sink { [weak self] result in
self?.balance = result
}.store(in: &subscriptions)
let location = character.location().get()
.map{$0.value}
.receive(on: RunLoop.main)
.share()
location.compactMap { location in
try? managedObjectContext.from(SDEMapSolarSystem.self).filter(/\SDEMapSolarSystem.solarSystemID == Int32(location.solarSystemID)).first()
}
.asResult()
.sink { [weak self] result in
self?.location = result
}.store(in: &subscriptions)
let skillQueue = character.skillqueue().get()
.map{$0.value}
.receive(on: RunLoop.main)
.share()
skillQueue.map{$0.filter{$0.finishDate.map{$0 > Date()} == true}}
.asResult()
.sink { [weak self] result in
self?.skillQueue = result
}.store(in: &subscriptions)
ship.zip(skills).zip(wallet).zip(location).zip(skillQueue).sink(receiveCompletion: {[weak self] _ in
self?.isLoading = false
}, receiveValue: {_ in})
.store(in: &subscriptions)
}
private var subscriptions = Set<AnyCancellable>()
}
|
lgpl-2.1
|
0ac70eb358d347b368ad8271b3e80a56
| 31.247525 | 149 | 0.596868 | 4.686331 | false | false | false | false |
dsoisson/SwiftLearningExercises
|
Exercise8_1.playground/Contents.swift
|
1
|
6639
|
import Foundation
/*:
**Exercise:** Create two classes `Dog` and `Cat`. Each will have properties of `breed`, `color`, `age` and `name`. They also have methods of `barking` (dog's) only, `meowing` (cats only), `eating`, `sleeping`, `playing`, and `chase`.
*/
/*:
**Constraints:** You must also have:
* Initializer & Deinitializer
* Computed Properties
* Property Observers
* Method body is up to you, but your method signatures need parameter(s)
*/
enum DogFoes {
case cat
case squirrel
case intruder
}
enum MeowReasons {
case wantsFood
case wantsOutside
case wantsInside
case wantsAttention
}
class Dog {
var breed: String = ""
var color: String = ""
var name: String? = ""
var birthday: NSDate?
var alive: Bool = true
var eating: Bool = false
var sleeping: Bool = false
var playing: Bool = false
var barking: Bool = false
var age: Int {//read only computed property using birthday and current date
guard birthday != nil && alive else{
return 0
}
return DateUtils.yearSpan(birthday!, to: NSDate())
}
init(breed: String, color: String) {
self.breed = breed
self.color = color
}
var energy: Int = 100 {
willSet {
print("About to set energy to \(newValue)%")
}
didSet {
print("You had \(oldValue)% energy, now you have \(energy)%")
if energy <= 0 {
print("Too tired. Time to rest.")
}
}
}
func bark(kind: DogFoes) -> (String, Bool) {
barking = true
switch kind {
case .cat:
return ("Bark, Bark, Bark", barking)
case .squirrel:
return ("arf", barking)
case .intruder:
return ("grrrr", barking)
}
}
func eat(inout energy: Int) -> String {
switch energy{
case 0..<25:
energy = 100
return "Really hungry. Ate 4 cups of food."
case 25..<75:
energy = 100
return "Sort of hungry. Ate 2 cups of food."
case 75..<100:
energy = 100
return "Not very hungry but ate anyway."
default:
sleep()
return "Feeling stuffed. Didn't eat."
}
}
func sleep() -> String{
return "Very sleepy. Need to close eyes."
}
func play() -> (String, Int) {
energy = 50
while energy > 10 {
chase()
energy -= 5
bark(DogFoes.cat)
energy -= 10
}
return ("I'm tired now", energy)
}
func chase() -> String{
return "I'm gonna get that cat!!"
}
deinit {
print("no more dog")
}
}
class Cat{
var breed: String = ""
var color: String = ""
var name: String? = ""
var birthday: NSDate?
var alive: Bool = true
var eating: Bool = false
var sleeping: Bool = false
var playing: Bool = false
var meowing: Bool = false
var age: Int {//read only computed property using birthday and current date
guard birthday != nil && alive else{
return 0
}
return DateUtils.yearSpan(birthday!, to: NSDate())
}
init(breed: String, color: String) {
self.breed = breed
self.color = color
}
var energy: Int = 100 {
willSet {
print("About to set energy to \(newValue)%")
}
didSet {
print("You had \(oldValue)% energy, now you have \(energy)%")
if energy <= 0 {
print("Too tired. Time to rest.")
}
}
}
func meow(kind: MeowReasons) -> (String, Bool) {
meowing = true
switch kind {
case .wantsAttention:
return ("MEOW!", meowing)
case .wantsFood:
return ("meow", meowing)
case .wantsInside:
return ("Meow", meowing)
case .wantsOutside:
return ("meOWt", meowing)
}
}
func eat(inout energy: Int) -> String {
switch energy{
case 0..<25:
energy = 100
return "Really hungry. Ate the entire can."
case 25..<75:
energy = 100
return "Sort of hungry. Ate half the can."
case 75..<100:
energy = 100
return "Not very hungry. Ate only one bite."
default:
sleep()
return "Feeling stuffed. Didn't eat."
}
}
func sleep() -> String{
return "Very sleepy. Need to close eyes."
}
func play() -> (String, Int) {
energy = 50
while energy > 10 {
chase()
energy -= 5
}
return ("I'm tired now", energy)
}
func chase() -> String{
return "I'm gonna get that dog!!"
}
deinit {
print("no more cat")
}
}
class Toy {
var dogToy: Set = [
"Red Guy", "Rubber Ball", "Chew Bone", "String"
]
var catToy: Set = [
"Rubber Ball", "Cat Nip", "String", "Mousy"
]
}
var activities = [
1: "Sleeping",
2: "Playing",
3: "Eating",
4: "Chasing",
5: "Barking"
]
var myCat = Cat(breed: "Hemmingway", color: "Gray")
myCat.name = "Polly"
print("My cat \(myCat.name!) has five toes.")
myCat.energy = 90
var dogTwo: Dog? = Dog(breed: "Dauchsund", color: "Gray")
dogTwo!.name = "Kaycee"
dogTwo!.barking = true
var myDog = Dog(breed: "Dauchsund", color: "Black")
myDog.birthday = DateUtils.createDate(year: 2008, month: 11, day: 18)
myDog.name = "Frannie"
print("I love my \(myDog.color) \(myDog.breed), \(myDog.name!). She is \(myDog.age) years old.")
myDog.energy = 50
if myCat.energy < myDog.energy {
myDog.chase()
} else {
myCat.chase()
}
myDog.play()
print("Energy Level is \(myDog.energy)")
myDog.eat(&myDog.energy)
print("Energy Level is \(myDog.energy)")
print(myDog.bark(DogFoes.cat).1)
dogTwo!.barking
myDog.barking
if dogTwo!.barking {
activities[5]
} else {
print("\(dogTwo!.name!) is not barking.")
}
if myDog.barking {
"Stop that incessant barking!"
myDog.barking = false
}
if myDog.play().1 < 50 {
var energyLevel = myDog.play().1
myDog.eat(&energyLevel)
}
dogTwo = nil
|
mit
|
8937d014cfbdb63a11586dbdb5f213a5
| 20.278846 | 233 | 0.508962 | 3.930728 | false | false | false | false |
joerocca/GitHawk
|
Pods/Tabman/Sources/Tabman/TabmanBar/Components/Separator/SeparatorView.swift
|
1
|
1816
|
//
// SeparatorView.swift
// Tabman
//
// Created by Merrick Sapsford on 21/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import PureLayout
internal class SeparatorView: UIView {
//
// MARK: Properties
//
private var leftPinConstraint: NSLayoutConstraint?
private var rightPinConstraint: NSLayoutConstraint?
override var intrinsicContentSize: CGSize {
return CGSize(width: 0.0, height: 0.5)
}
override var tintColor: UIColor! {
didSet {
self.color = tintColor
}
}
/// The color of the separator.
var color: UIColor = .clear {
didSet {
self.backgroundColor = color
}
}
/// The distance to inset the separator from it's superview (X-axis only).
var edgeInsets: UIEdgeInsets = .zero {
didSet {
leftPinConstraint?.constant = edgeInsets.left
rightPinConstraint?.constant = -edgeInsets.right
superview?.layoutIfNeeded()
}
}
//
// MARK: Init
//
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initSeparator()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.initSeparator()
}
public convenience init() {
self.init(frame: .zero)
}
private func initSeparator() {
self.backgroundColor = self.color
}
// MARK: Layout
func addAsSubview(to parent: UIView) {
parent.addSubview(self)
autoPinEdge(toSuperviewEdge: .bottom)
leftPinConstraint = autoPinEdge(toSuperviewEdge: .leading)
rightPinConstraint = autoPinEdge(toSuperviewEdge: .trailing)
}
}
|
mit
|
733c3f95a75d9f35f3807cbd6226f176
| 22.571429 | 78 | 0.595592 | 4.714286 | false | false | false | false |
rddmw/DYZBJHY
|
DYZBJHY/DYZBJHY/Classes/Main/PageTitleView.swift
|
1
|
2885
|
//
// PageTitleView.swift
// DYZBJHY
//
// Created by hugh.jia on 2016/12/22.
// Copyright © 2016年 Mac. All rights reserved.
//
import UIKit
fileprivate let kScrollLineH : CGFloat = 2
class PageTitleView: UIView {
fileprivate var titles:[String]
fileprivate lazy var titlesLabels :[UILabel] = [UILabel]()
fileprivate lazy var scrollView : UIScrollView = {
let scrView = UIScrollView()
scrView.showsVerticalScrollIndicator = false
scrView.scrollsToTop = false
scrView.bounces = false
return scrView
}()
fileprivate lazy var scrollLine :UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
init(frame: CGRect , titles:[String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
fileprivate func setupUI() {
//添加scrollView
addSubview(scrollView)
scrollView.frame = bounds
setupTitleLabels()
//设置底线 和底部滑块
setupScrollViewBottomLine()
}
fileprivate func setupTitleLabels() {
let labelW :CGFloat = frame.width / CGFloat(titles.count)
let labelH :CGFloat = frame.height - kScrollLineH
let labelY :CGFloat = 0
for (index,title) in titles.enumerated(){
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.darkGray
label.textAlignment = .center
let labelX :CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titlesLabels.append(label)
}
}
fileprivate func setupScrollViewBottomLine () {
let bottomLine = UIView()
bottomLine.frame = CGRect(x: 0, y: self.frame.height - 0.5, width: self.frame.width, height: 0.5)
bottomLine.backgroundColor = UIColor.lightGray
addSubview(bottomLine)
scrollView.addSubview(scrollLine)
guard let firstLabels = titlesLabels.first
else{
return
}
firstLabels.textColor = UIColor.orange
scrollLine.frame = CGRect(x: firstLabels.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabels.frame.width, height: kScrollLineH)
}
}
|
mit
|
50a2cb283757d462cf531c53cce1c3b9
| 23.655172 | 150 | 0.563636 | 5.116279 | false | false | false | false |
DoubleSha/BitcoinSwift
|
BitcoinSwift/CoreDataBlockChainStore.swift
|
1
|
8617
|
//
// CoreDataBlockChainStore.swift
// BitcoinSwift
//
// Created by Kevin Greene on 2/10/15.
// Copyright (c) 2015 DoubleSha. All rights reserved.
//
import CoreData
import Foundation
/// Stores the blockchain using CoreData.
public class CoreDataBlockChainStore: BlockChainStore {
private var context: NSManagedObjectContext!
private let blockChainHeaderEntityName = "BlockChainHeader"
private let blockChainHeadEntityName = "BlockChainHead"
private let blockChainHeightEntityName = "BlockChainHeight"
public init() {}
public var isSetUp: Bool {
return context != nil
}
/// Helper for setUpWithURL() that uses the default directory location, and the blockStoreFileName
/// provided by params.
/// One of the setUp functions MUST be called before using the store, and can only be called once.
/// If setup fails, throws the error.
public func setUpWithParams(params: BlockChainStoreParameters) throws {
try setUpWithParams(params, dir: defaultDir)
}
/// Helper for setUpWithURL() that uses the provided |dir|, and the blockStoreFileName
/// provided by params.
/// One of the setUp functions MUST be called before using the store, and can only be called once.
/// If setup fails, throws the error.
public func setUpWithParams(params: BlockChainStoreParameters, dir: NSURL) throws {
try setUpWithURL(dir.URLByAppendingPathComponent(params.blockChainStoreFileName + ".sqlite"))
}
/// Sets up the SQLite file a the path specified by |url|, and the CoreData managed object.
/// This MUST be called before using the store, and can only be called once.
/// If setup fails, throws the error.
/// In most cases, you should just use setUpWithParams() rather than calling this directly.
public func setUpWithURL(url: NSURL) throws {
try setUpContextWithType(NSSQLiteStoreType, URL: url)
}
/// Sets up an in-memory persistent store, and the CoreData managed object.
/// If setup fails, throws the error.
/// This is only used for unit tests. If you want to store the blockchain in memory in your
/// app, use the InMemoryBlockChainStore instead.
public func setUpInMemory() throws {
try setUpContextWithType(NSInMemoryStoreType)
}
public var defaultDir: NSURL {
return NSFileManager.defaultManager().URLsForDirectory(.LibraryDirectory,
inDomains: .UserDomainMask)[0]
}
/// Returns the full path of the sqlite file backing the persistent store.
/// This is only valid after calling one of the setUp functions.
public var URL: NSURL {
precondition(context != nil)
let persistentStore = context.persistentStoreCoordinator!.persistentStores[0]
return persistentStore.URL!
}
/// Deletes the sqlite file backing the persistent store.
/// After calling this function, one of the setUp functions must be called again in order to
/// continue to use the same object.
public func deletePersistentStore() throws {
try NSFileManager.defaultManager().removeItemAtURL(URL)
// NOTE: context won't be set to nil if an exception is thrown in the line above.
context = nil
}
// MARK: - BlockChainStore
public func height() throws -> UInt32? {
precondition(context != nil)
return try head()?.height
}
public func head() throws -> BlockChainHeader? {
precondition(context != nil)
var blockChainHeader: BlockChainHeader? = nil
try context.performBlockAndWaitOrThrow() {
if let headerEntity = try self.fetchBlockChainHeadEntity() {
blockChainHeader = headerEntity.blockChainHeader
}
}
return blockChainHeader
}
public func addBlockChainHeaderAsNewHead(blockChainHeader: BlockChainHeader) throws {
precondition(context != nil)
try context.performBlockAndWaitOrThrow() {
// Add the block to the block store if it's not already present.
let hash = blockChainHeader.blockHeader.hash
if try self.fetchBlockChainHeaderEntityWithHash(hash) != nil {
// The blockChainHeader already exists, so there's nothing to do.
} else {
// The blockChainHeader doesn't exist, so create a new entity for it.
let headerEntity =
NSEntityDescription.insertNewObjectForEntityForName(self.blockChainHeaderEntityName,
inManagedObjectContext: self.context) as! BlockChainHeaderEntity
headerEntity.setBlockChainHeader(blockChainHeader)
}
// Update the head entity as the new block.
do {
if let headEntity = try self.fetchBlockChainHeadEntity() {
if blockChainHeader == headEntity.blockChainHeader {
// The head is already the correct value, so there is nothing more to do.
try self.attemptToSave()
return
} else {
// Delete the old head entity so we can replace it (below) with the new head entity.
self.context.deleteObject(headEntity)
}
}
} catch let innerError as NSError {
self.context.undo()
throw innerError
}
let headEntity =
NSEntityDescription.insertNewObjectForEntityForName(self.blockChainHeadEntityName,
inManagedObjectContext: self.context) as! BlockChainHeaderEntity
headEntity.setBlockChainHeader(blockChainHeader)
try self.attemptToSave()
}
}
public func deleteBlockChainHeaderWithHash(hash: SHA256Hash) throws {
precondition(context != nil)
try context.performBlockAndWaitOrThrow() {
if let headerEntity = try self.fetchBlockChainHeaderEntityWithHash(hash) {
self.context.deleteObject(headerEntity)
try self.attemptToSave()
}
}
}
public func blockChainHeaderWithHash(hash: SHA256Hash) throws -> BlockChainHeader? {
precondition(context != nil)
var blockChainHeader: BlockChainHeader? = nil
try context.performBlockAndWaitOrThrow() {
if let headerEntity = try self.fetchBlockChainHeaderEntityWithHash(hash) {
blockChainHeader = headerEntity.blockChainHeader
}
}
return blockChainHeader
}
// MARK: - Private Methods
/// Sets up the context ivar with the provided type and URL.
/// URL can be nil if the type is NSInMemoryStoreType.
private func setUpContextWithType(type: NSString, URL: NSURL? = nil) throws {
precondition(context == nil)
let bundle = NSBundle(forClass: self.dynamicType)
let model = NSManagedObjectModel.mergedModelFromBundles([bundle])!
context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
do {
try context.persistentStoreCoordinator!.addPersistentStoreWithType(type as String,
configuration: nil,
URL: URL,
options: nil)
} catch let error as NSError {
Logger.error("Failed to setup CoreDataBlockChainStore \(error)")
context = nil
throw error
}
}
/// Returns the BlockChainHeaderEntity keyed by the given hash, or nil if not found.
/// This MUST be called from within context.performBlock().
private func fetchBlockChainHeaderEntityWithHash(hash: SHA256Hash) throws
-> BlockChainHeaderEntity? {
let request = NSFetchRequest(entityName: blockChainHeaderEntityName)
request.predicate = NSPredicate(format: "blockHash == %@", hash.data)
let results = try self.context.executeFetchRequest(request)
assert(results.count <= 1)
if results.count > 0 {
return (results[0] as! BlockChainHeaderEntity)
}
return nil
}
/// Returns the BlockChainHeaderEntity that is currently the head of the blockchain, or nil if
/// not found. This MUST be called from within context.performBlock().
private func fetchBlockChainHeadEntity() throws -> BlockChainHeaderEntity? {
let request = NSFetchRequest(entityName: blockChainHeadEntityName)
let results = try self.context.executeFetchRequest(request)
assert(results.count <= 1)
if results.count > 0 {
return (results[0] as! BlockChainHeaderEntity)
}
return nil
}
/// Attempts to save changes to context. If there is an error, all changes to context are undone
/// and the error is thrown.
private func attemptToSave() throws {
do {
try context.save()
} catch let error as NSError {
self.context.undo()
throw error
}
}
}
|
apache-2.0
|
464da250708f96d208e6804bcf9812e0
| 38.709677 | 100 | 0.692584 | 4.838293 | false | false | false | false |
DoubleSha/BitcoinSwift
|
BitcoinSwift/Models/TransactionOutput.swift
|
1
|
1880
|
//
// TransactionOutput.swift
// BitcoinSwift
//
// Created by Kevin Greene on 9/27/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: Transaction.Output, right: Transaction.Output) -> Bool {
return left.value == right.value && left.script == right.script
}
public extension Transaction {
/// An Output represents the bitcoin being received in a Transaction. It can then later be spent
/// by an Input in another transaction.
/// https://en.bitcoin.it/wiki/Protocol_specification#tx
public struct Output: Equatable {
/// The value being sent in this output, in satoshi.
public let value: Int64
/// The script defines the conditions that must be met in order to spend the output.
/// https://en.bitcoin.it/wiki/Script
public let script: NSData
public init(value: Int64, script: NSData) {
// TODO: Validate script.
self.value = value
self.script = script
}
}
}
extension Transaction.Output: BitcoinSerializable {
public var bitcoinData: NSData {
let data = NSMutableData()
data.appendInt64(value)
data.appendVarInt(script.length)
data.appendData(script)
return data
}
public static func fromBitcoinStream(stream: NSInputStream) -> Transaction.Output? {
let value = stream.readInt64()
if value == nil {
Logger.warn("Failed to parse value from Transaction.Output")
return nil
}
let scriptLength = stream.readVarInt()
if scriptLength == nil {
Logger.warn("Failed to parse scriptLength from Transaction.Output")
return nil
}
let script = stream.readData(Int(scriptLength!))
if script == nil {
Logger.warn("Failed to parse script from Transaction.Output")
return nil
}
// TODO: Validate script.
return Transaction.Output(value: value!, script: script!)
}
}
|
apache-2.0
|
a1612cfbebc6d52f1ce1dc9f3e80cf26
| 27.484848 | 98 | 0.682447 | 4.205817 | false | false | false | false |
fantast1k/Swiftent
|
Swiftent/Swiftent/Source/UIKit/UITextView+Contentable.swift
|
1
|
609
|
//
// UITextView+Contentable.swift
// Swiftent
//
// Created by Dmitry Fa[n]tastik on 26/08/2016.
// Copyright © 2016 Fantastik Solution. All rights reserved.
//
import UIKit
extension UITextView : Contentable {
public typealias Content = UITextViewContent
public func installContent(_ content: UITextViewContent) {
switch content.text {
case .Raw(let txt):
if let txt = txt {
self.text = txt
}
case .Attributed(let txt):
if let txt = txt {
self.attributedText = txt
}
}
}
}
|
gpl-3.0
|
13d85c90e56f82c9c28c57aa69ebd871
| 20.714286 | 62 | 0.570724 | 4.222222 | false | false | false | false |
Foild/SugarRecord
|
spec/CoreData/RestkitCDStackTests.swift
|
1
|
2496
|
//
// RestkitCDStackTests.swift
// SugarRecord
//
// Created by Pedro Piñera Buendía on 28/09/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import XCTest
import CoreData
class RestkitCDStackTests: XCTestCase
{
func testIfInitializeGetContextsFromRestkit()
{
class MockRKStore: RKManagedObjectStore
{
var addSQliteCalled: Bool = false
var createManagedObjectContextsCalled: Bool = false
override func addSQLitePersistentStoreAtPath(storePath: String!, fromSeedDatabaseAtPath seedPath: String!, withConfiguration nilOrConfigurationName: String!, options nilOrOptions: [NSObject : AnyObject]!) throws -> NSPersistentStore {
addSQliteCalled = true
return try super.addSQLitePersistentStoreAtPath(storePath, fromSeedDatabaseAtPath: seedPath, withConfiguration: nilOrConfigurationName, options: nilOrOptions)
}
override func createManagedObjectContexts()
{
super.createManagedObjectContexts()
createManagedObjectContextsCalled = true
}
}
class MockReskitCDStack: RestkitCDStack
{
var rkStore: MockRKStore?
override func createRKManagedObjectStore() -> RKManagedObjectStore {
rkStore = MockRKStore(managedObjectModel: self.managedObjectModel!)
return rkStore!
}
}
let bundle: NSBundle = NSBundle(forClass: CoreDataObjectTests.classForCoder())
let modelPath: NSString = bundle.pathForResource("TestsDataModel", ofType: "momd")!
let model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: modelPath as String))!
let stack: MockReskitCDStack = MockReskitCDStack(databaseName: "Restkit.sqlite", model: model, automigrating: true)
stack.initialize()
XCTAssertTrue(stack.rkStore!.addSQliteCalled, "The stack should initialize SQLite from RestKit")
XCTAssertTrue(stack.rkStore!.createManagedObjectContextsCalled, "The stack should create contexts using RestKit")
XCTAssertNotNil(stack.persistentStoreCoordinator, "The persistent store coordinator should be not nil")
XCTAssertNotNil(stack.rootSavingContext, "The root saving context should be not nil")
XCTAssertNotNil(stack.mainContext, "The main context should be not nil")
stack.removeDatabase()
}
}
|
mit
|
d0859a12a312360c2e0275cc7260fa62
| 46.075472 | 246 | 0.698877 | 5.206681 | false | true | false | false |
whiteshadow-gr/HatForIOS
|
HAT/Objects/Profile/Employement Status/HATEmployementStatus.swift
|
1
|
3615
|
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATEmployementStatus: HatApiType, Comparable {
// MARK: - Comparable protocol
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: HATEmployementStatus, rhs: HATEmployementStatus) -> Bool {
return (lhs.recordID == rhs.recordID)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: HATEmployementStatus, rhs: HATEmployementStatus) -> Bool {
return lhs.recordID < rhs.recordID
}
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `status` in JSON is `status`
* `recordID` in JSON is `recordId`
*/
private enum CodingKeys: String, CodingKey {
case status = "status"
case recordID = "recordId"
}
// MARK: - Variables
/// Employment status
public var status: String = ""
/// The record ID
public var recordID: String = "-1"
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
status = ""
recordID = "-1"
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(from dict: JSON) {
if let data: [String: JSON] = (dict["data"].dictionary) {
if let tempStatus: String = (data[CodingKeys.status.rawValue]?.stringValue) {
status = tempStatus
}
}
recordID = (dict[CodingKeys.recordID.rawValue].stringValue)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
if let tempStatus: Any = fromCache[CodingKeys.status.rawValue] {
self.status = String(describing: tempStatus)
}
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.status.rawValue: self.status,
"unixTimeStamp": Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)!
]
}
}
|
mpl-2.0
|
e0e58bb606e16cf32b1af645cbd74f6a
| 27.023256 | 90 | 0.581189 | 4.564394 | false | false | false | false |
wojteklu/logo
|
Logo/IDE/Utils.swift
|
1
|
782
|
import Cocoa
extension NSColor {
convenience init(hexString: String) {
var hex = hexString.hasPrefix("#") ? String(hexString.dropFirst()) : hexString
guard hex.count == 3 || hex.count == 6 else {
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)
return
}
if hex.count == 3 {
for (index, char) in hex.enumerated() {
hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2))
}
}
let number = Int(hex, radix: 16)!
let red = CGFloat((number >> 16) & 0xFF) / 255.0
let green = CGFloat((number >> 8) & 0xFF) / 255.0
let blue = CGFloat(number & 0xFF) / 255.0
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
|
mit
|
36bf5b62f1853a801e2f1f7ccb706c7e
| 31.583333 | 86 | 0.529412 | 3.62037 | false | false | false | false |
jinseokpark6/u-team
|
Code/Controllers/CVCalendarRenderer.swift
|
1
|
1732
|
//
// CVCalendarRenderer.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVCalendarRenderer {
private unowned let calendarView: CalendarView
private var appearance: Appearance {
get {
return calendarView.appearance
}
}
init(calendarView: CalendarView) {
self.calendarView = calendarView
}
// MARK: - Rendering
func renderWeekFrameForRect(rect: CGRect) -> CGRect {
let width = rect.width
let space = self.appearance.spaceBetweenWeekViews!
let height = CGFloat((rect.height / CGFloat(4)) - space) + space / 0.5
let y: CGFloat = (height + space)
let x: CGFloat = 0
return CGRectMake(x, y, width, height)
}
func renderWeekFrameForMonthView(monthView: MonthView, weekIndex: Int) -> CGRect {
let width = monthView.frame.width
let space = self.appearance.spaceBetweenWeekViews!
let height = CGFloat((monthView.frame.height / CGFloat(monthView.numberOfWeeks!)) - space) + space / 0.5
let y: CGFloat = CGFloat(weekIndex) * (height + space)
let x: CGFloat = 0
return CGRectMake(x, y, width, height)
}
func renderDayFrameForMonthView(weekView: WeekView, dayIndex: Int) -> CGRect {
let space = self.appearance.spaceBetweenDayViews!
let width = CGFloat((weekView.frame.width / 7) - space)
let height = weekView.frame.height
let x = CGFloat(dayIndex) * (width + space) + space / 2
let y = CGFloat(0)
return CGRectMake(x, y, width, height)
}
}
|
apache-2.0
|
a808d0828017440f0cd5747f8795aeab
| 28.355932 | 112 | 0.610277 | 4.418367 | false | false | false | false |
liuxuan30/ios-charts
|
Source/Charts/Charts/BarLineChartViewBase.swift
|
3
|
69393
|
//
// BarLineChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if canImport(UIKit)
import UIKit
#endif
#if canImport(Cocoa)
import Cocoa
#endif
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
open class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, NSUIGestureRecognizerDelegate
{
/// the maximum number of entries to which values will be drawn
/// (entry numbers greater than this value will cause value-labels to disappear)
internal var _maxVisibleCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragXEnabled = true
private var _dragYEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
@objc open var gridBackgroundColor = NSUIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
@objc open var borderColor = NSUIColor.black
@objc open var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
@objc open var drawGridBackgroundEnabled = false
/// When enabled, the borders rectangle will be rendered.
/// If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
@objc open var drawBordersEnabled = false
/// When enabled, the values will be clipped to contentRect, otherwise they can bleed outside the content rect.
@objc open var clipValuesToContentEnabled: Bool = false
/// When disabled, the data and/or highlights will not be clipped to contentRect. Disabling this option can
/// be useful, when the data lies fully within the content rect, but is drawn in such a way (such as thick lines)
/// that there is unwanted clipping.
@objc open var clipDataToContentEnabled: Bool = true
/// Sets the minimum offset (padding) around the chart, defaults to 10
@objc open var minOffset = CGFloat(10.0)
/// Sets whether the chart should keep its position (zoom / scroll) after a rotation (orientation change)
/// **default**: false
@objc open var keepPositionOnRotation: Bool = false
/// The left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
@objc open internal(set) var leftAxis = YAxis(position: .left)
/// The right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
@objc open internal(set) var rightAxis = YAxis(position: .right)
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var leftYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: leftAxis, transformer: _leftAxisTransformer)
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of YAxisRenderer
@objc open lazy var rightYAxisRenderer = YAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: rightAxis, transformer: _rightAxisTransformer)
internal var _leftAxisTransformer: Transformer!
internal var _rightAxisTransformer: Transformer!
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// **default**: An instance of XAxisRenderer
@objc open lazy var xAxisRenderer = XAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
internal var _tapGestureRecognizer: NSUITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: NSUITapGestureRecognizer!
#if !os(tvOS)
internal var _pinchGestureRecognizer: NSUIPinchGestureRecognizer!
#endif
internal var _panGestureRecognizer: NSUIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = Transformer(viewPortHandler: _viewPortHandler)
self.highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
_doubleTapGestureRecognizer = NSUITapGestureRecognizer(target: self, action: #selector(doubleTapGestureRecognized(_:)))
_doubleTapGestureRecognizer.nsuiNumberOfTapsRequired = 2
_panGestureRecognizer = NSUIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized(_:)))
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
_panGestureRecognizer.isEnabled = _dragXEnabled || _dragYEnabled
#if !os(tvOS)
_pinchGestureRecognizer = NSUIPinchGestureRecognizer(target: self, action: #selector(BarLineChartViewBase.pinchGestureRecognized(_:)))
_pinchGestureRecognizer.delegate = self
self.addGestureRecognizer(_pinchGestureRecognizer)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
// Saving current position of chart.
var oldPoint: CGPoint?
if (keepPositionOnRotation && (keyPath == "frame" || keyPath == "bounds"))
{
oldPoint = viewPortHandler.contentRect.origin
getTransformer(forAxis: .left).pixelToValues(&oldPoint!)
}
// Superclass transforms chart.
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
// Restoring old position of chart
if var newPoint = oldPoint , keepPositionOnRotation
{
getTransformer(forAxis: .left).pointValueToPixel(&newPoint)
viewPortHandler.centerViewPort(pt: newPoint, chart: self)
}
else
{
viewPortHandler.refresh(newMatrix: viewPortHandler.touchMatrix, chart: self, invalidate: true)
}
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
guard data != nil, let renderer = renderer else { return }
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
// execute all drawing commands
drawGridBackground(context: context)
if _autoScaleMinMaxEnabled
{
autoScale()
}
if leftAxis.isEnabled
{
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
}
if rightAxis.isEnabled
{
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
}
if _xAxis.isEnabled
{
xAxisRenderer.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false)
}
xAxisRenderer.renderAxisLine(context: context)
leftYAxisRenderer.renderAxisLine(context: context)
rightYAxisRenderer.renderAxisLine(context: context)
// The renderers are responsible for clipping, to account for line-width center etc.
if xAxis.drawGridLinesBehindDataEnabled
{
xAxisRenderer.renderGridLines(context: context)
leftYAxisRenderer.renderGridLines(context: context)
rightYAxisRenderer.renderGridLines(context: context)
}
if _xAxis.isEnabled && _xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
context.saveGState()
// make sure the data cannot be drawn outside the content-rect
if clipDataToContentEnabled {
context.clip(to: _viewPortHandler.contentRect)
}
renderer.drawData(context: context)
// The renderers are responsible for clipping, to account for line-width center etc.
if !xAxis.drawGridLinesBehindDataEnabled
{
xAxisRenderer.renderGridLines(context: context)
leftYAxisRenderer.renderGridLines(context: context)
rightYAxisRenderer.renderGridLines(context: context)
}
// if highlighting is enabled
if (valuesToHighlight())
{
renderer.drawHighlighted(context: context, indices: _indicesToHighlight)
}
context.restoreGState()
renderer.drawExtras(context: context)
if _xAxis.isEnabled && !_xAxis.isDrawLimitLinesBehindDataEnabled
{
xAxisRenderer.renderLimitLines(context: context)
}
if leftAxis.isEnabled && !leftAxis.isDrawLimitLinesBehindDataEnabled
{
leftYAxisRenderer.renderLimitLines(context: context)
}
if rightAxis.isEnabled && !rightAxis.isDrawLimitLinesBehindDataEnabled
{
rightYAxisRenderer.renderLimitLines(context: context)
}
xAxisRenderer.renderAxisLabels(context: context)
leftYAxisRenderer.renderAxisLabels(context: context)
rightYAxisRenderer.renderAxisLabels(context: context)
if clipValuesToContentEnabled
{
context.saveGState()
context.clip(to: _viewPortHandler.contentRect)
renderer.drawValues(context: context)
context.restoreGState()
}
else
{
renderer.drawValues(context: context)
}
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
private var _autoScaleLastLowestVisibleX: Double?
private var _autoScaleLastHighestVisibleX: Double?
/// Performs auto scaling of the axis by recalculating the minimum and maximum y-values based on the entries currently in view.
internal func autoScale()
{
guard let data = _data
else { return }
data.calcMinMaxY(fromX: self.lowestVisibleX, toX: self.highestVisibleX)
_xAxis.calculate(min: data.xMin, max: data.xMax)
// calculate axis range (min / max) according to provided data
if leftAxis.isEnabled
{
leftAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left))
}
if rightAxis.isEnabled
{
rightAxis.calculate(min: data.getYMin(axis: .right), max: data.getYMax(axis: .right))
}
calculateOffsets()
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(rightAxis.axisRange), chartYMin: rightAxis._axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: xAxis._axisMinimum, deltaX: CGFloat(xAxis.axisRange), deltaY: CGFloat(leftAxis.axisRange), chartYMin: leftAxis._axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(inverted: rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(inverted: leftAxis.isInverted)
}
open override func notifyDataSetChanged()
{
renderer?.initBuffers()
calcMinMax()
leftYAxisRenderer.computeAxis(min: leftAxis._axisMinimum, max: leftAxis._axisMaximum, inverted: leftAxis.isInverted)
rightYAxisRenderer.computeAxis(min: rightAxis._axisMinimum, max: rightAxis._axisMaximum, inverted: rightAxis.isInverted)
if let data = _data
{
xAxisRenderer.computeAxis(
min: _xAxis._axisMinimum,
max: _xAxis._axisMaximum,
inverted: false)
if _legend !== nil
{
legendRenderer?.computeLegend(data: data)
}
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
// calculate / set x-axis range
_xAxis.calculate(min: _data?.xMin ?? 0.0, max: _data?.xMax ?? 0.0)
// calculate axis range (min / max) according to provided data
leftAxis.calculate(min: _data?.getYMin(axis: .left) ?? 0.0, max: _data?.getYMax(axis: .left) ?? 0.0)
rightAxis.calculate(min: _data?.getYMin(axis: .right) ?? 0.0, max: _data?.getYMax(axis: .right) ?? 0.0)
}
internal func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat)
{
// setup offsets for legend
if _legend !== nil && _legend.isEnabled && !_legend.drawInside
{
switch _legend.orientation
{
case .vertical:
switch _legend.horizontalAlignment
{
case .left:
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .right:
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset
case .center:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
default:
break
}
}
case .horizontal:
switch _legend.verticalAlignment
{
case .top:
offsetTop += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
case .bottom:
offsetBottom += min(_legend.neededHeight, _viewPortHandler.chartHeight * _legend.maxSizePercent) + _legend.yOffset
default:
break
}
}
}
}
internal override func calculateOffsets()
{
if !_customViewPortEnabled
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
calculateLegendOffsets(offsetLeft: &offsetLeft,
offsetTop: &offsetTop,
offsetRight: &offsetRight,
offsetBottom: &offsetBottom)
// offsets for y-labels
if leftAxis.needsOffset
{
offsetLeft += leftAxis.requiredSize().width
}
if rightAxis.needsOffset
{
offsetRight += rightAxis.requiredSize().width
}
if xAxis.isEnabled && xAxis.isDrawLabelsEnabled
{
let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset
// offsets for x-labels
if xAxis.labelPosition == .bottom
{
offsetBottom += xlabelheight
}
else if xAxis.labelPosition == .top
{
offsetTop += xlabelheight
}
else if xAxis.labelPosition == .bothSided
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// draws the grid background
internal func drawGridBackground(context: CGContext)
{
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.saveGState()
}
if drawGridBackgroundEnabled
{
// draw the grid background
context.setFillColor(gridBackgroundColor.cgColor)
context.fill(_viewPortHandler.contentRect)
}
if drawBordersEnabled
{
context.setLineWidth(borderLineWidth)
context.setStrokeColor(borderColor.cgColor)
context.stroke(_viewPortHandler.contentRect)
}
if drawGridBackgroundEnabled || drawBordersEnabled
{
context.restoreGState()
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case both
case x
case y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.both
private var _closestDataSetToTouch: IChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: NSUIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: TimeInterval = 0.0
private var _decelerationDisplayLink: NSUIDisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if !isHighLightPerTapEnabled { return }
let h = getHighlightByTouchPoint(recognizer.location(in: self))
if h === nil || h == self.lastHighlighted
{
lastHighlighted = nil
highlightValue(nil, callDelegate: true)
}
else
{
lastHighlighted = h
highlightValue(h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(_ recognizer: NSUITapGestureRecognizer)
{
if _data === nil
{
return
}
if recognizer.state == NSUIGestureRecognizerState.ended
{
if _data !== nil && _doubleTapToZoomEnabled && (data?.entryCount ?? 0) > 0
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
let scaleX: CGFloat = isScaleXEnabled ? 1.4 : 1.0
let scaleY: CGFloat = isScaleYEnabled ? 1.4 : 1.0
self.zoom(scaleX: scaleX, scaleY: scaleY, x: location.x, y: location.y)
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
}
#if !os(tvOS)
@objc private func pinchGestureRecognized(_ recognizer: NSUIPinchGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began
{
stopDeceleration()
if _data !== nil &&
(_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)
{
_isScaling = true
if _pinchZoomEnabled
{
_gestureScaleAxis = .both
}
else
{
let x = abs(recognizer.location(in: self).x - recognizer.nsuiLocationOfTouch(1, inView: self).x)
let y = abs(recognizer.location(in: self).y - recognizer.nsuiLocationOfTouch(1, inView: self).y)
if _scaleXEnabled != _scaleYEnabled
{
_gestureScaleAxis = _scaleXEnabled ? .x : .y
}
else
{
_gestureScaleAxis = x > y ? .x : .y
}
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended ||
recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isScaling
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
let isZoomingOut = (recognizer.nsuiScale < 1)
var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY
if _isScaling
{
canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .x)
canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .both || _gestureScaleAxis == .y)
if canZoomMoreX || canZoomMoreY
{
var location = recognizer.location(in: self)
location.x = location.x - _viewPortHandler.offsetLeft
if isTouchInverted()
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
let scaleX = canZoomMoreX ? recognizer.nsuiScale : 1.0
let scaleY = canZoomMoreY ? recognizer.nsuiScale : 1.0
var matrix = CGAffineTransform(translationX: location.x, y: location.y)
matrix = matrix.scaledBy(x: scaleX, y: scaleY)
matrix = matrix.translatedBy(x: -location.x, y: -location.y)
matrix = _viewPortHandler.touchMatrix.concatenating(matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if delegate !== nil
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.nsuiScale = 1.0
}
}
}
#endif
@objc private func panGestureRecognized(_ recognizer: NSUIPanGestureRecognizer)
{
if recognizer.state == NSUIGestureRecognizerState.began && recognizer.nsuiNumberOfTouches() > 0
{
stopDeceleration()
if _data === nil || !self.isDragEnabled
{ // If we have no data, we have nothing to pan and no data to highlight
return
}
// If drag is enabled and we are in a position where there's something to drag:
// * If we're zoomed in, then obviously we have something to drag.
// * If we have a drag offset - we always have something to drag
if !self.hasNoDragOffset || !self.isFullyZoomedOut
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(point: recognizer.nsuiLocationOfTouch(0, inView: self))
var translation = recognizer.translation(in: self)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let didUserDrag = translation.x != 0.0 || translation.y != 0.0
// Check to see if user dragged at all and if so, can the chart be dragged by the given amount
if didUserDrag && !performPanChange(translation: translation)
{
if _outerScrollView !== nil
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if _outerScrollView !== nil
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.nsuiIsScrollEnabled = false
}
}
_lastPanPoint = recognizer.translation(in: self)
}
else if self.isHighlightPerDragEnabled
{
// We will only handle highlights on NSUIGestureRecognizerState.Changed
_isDragging = false
}
}
else if recognizer.state == NSUIGestureRecognizerState.changed
{
if _isDragging
{
let originalTranslation = recognizer.translation(in: self)
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
if !self.dragXEnabled
{
translation.x = 0.0
}
else if !self.dragYEnabled
{
translation.y = 0.0
}
let _ = performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if isHighlightPerDragEnabled
{
let h = getHighlightByTouchPoint(recognizer.location(in: self))
let lastHighlighted = self.lastHighlighted
if h != lastHighlighted
{
self.lastHighlighted = h
self.highlightValue(h, callDelegate: true)
}
}
}
else if recognizer.state == NSUIGestureRecognizerState.ended || recognizer.state == NSUIGestureRecognizerState.cancelled
{
if _isDragging
{
if recognizer.state == NSUIGestureRecognizerState.ended && isDragDecelerationEnabled
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocity(in: self)
_decelerationDisplayLink = NSUIDisplayLink(target: self, selector: #selector(BarLineChartViewBase.decelerationLoop))
_decelerationDisplayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
}
_isDragging = false
delegate?.chartViewDidEndPanning?(self)
}
if _outerScrollView !== nil
{
_outerScrollView?.nsuiIsScrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(translation: CGPoint) -> Bool
{
var translation = translation
if isTouchInverted()
{
if self is HorizontalBarChartView
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
let originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransform(translationX: translation.x, y: translation.y)
matrix = originalMatrix.concatenating(matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if matrix != originalMatrix
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
private func isTouchInverted() -> Bool
{
return isAnyAxisInverted &&
_closestDataSetToTouch !== nil &&
getAxis(_closestDataSetToTouch.axisDependency).isInverted
}
@objc open func stopDeceleration()
{
if _decelerationDisplayLink !== nil
{
_decelerationDisplayLink.remove(from: RunLoop.main, forMode: RunLoop.Mode.common)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
let currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
let timeInterval = CGFloat(currentTime - _decelerationLastTime)
let distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if !performPanChange(translation: distance)
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
private func nsuiGestureRecognizerShouldBegin(_ gestureRecognizer: NSUIGestureRecognizer) -> Bool
{
if gestureRecognizer == _panGestureRecognizer
{
let velocity = _panGestureRecognizer.velocity(in: self)
if _data === nil || !isDragEnabled ||
(self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) ||
(!_dragYEnabled && abs(velocity.y) > abs(velocity.x)) ||
(!_dragXEnabled && abs(velocity.y) < abs(velocity.x))
{
return false
}
}
else
{
#if !os(tvOS)
if gestureRecognizer == _pinchGestureRecognizer
{
if _data === nil || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)
{
return false
}
}
#endif
}
return true
}
#if !os(OSX)
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
{
if !super.gestureRecognizerShouldBegin(gestureRecognizer)
{
return false
}
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
#if os(OSX)
public func gestureRecognizerShouldBegin(gestureRecognizer: NSGestureRecognizer) -> Bool
{
return nsuiGestureRecognizerShouldBegin(gestureRecognizer)
}
#endif
open func gestureRecognizer(_ gestureRecognizer: NSUIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: NSUIGestureRecognizer) -> Bool
{
#if !os(tvOS)
if ((gestureRecognizer is NSUIPinchGestureRecognizer && otherGestureRecognizer is NSUIPanGestureRecognizer) ||
(gestureRecognizer is NSUIPanGestureRecognizer && otherGestureRecognizer is NSUIPinchGestureRecognizer))
{
return true
}
#endif
if gestureRecognizer is NSUIPanGestureRecognizer,
otherGestureRecognizer is NSUIPanGestureRecognizer,
gestureRecognizer == _panGestureRecognizer
{
var scrollView = self.superview
while scrollView != nil && !(scrollView is NSUIScrollView)
{
scrollView = scrollView?.superview
}
// If there is two scrollview together, we pick the superview of the inner scrollview.
// In the case of UITableViewWrepperView, the superview will be UITableView
if let superViewOfScrollView = scrollView?.superview,
superViewOfScrollView is NSUIScrollView
{
scrollView = superViewOfScrollView
}
var foundScrollView = scrollView as? NSUIScrollView
if !(foundScrollView?.nsuiIsScrollEnabled ?? true)
{
foundScrollView = nil
}
let scrollViewPanGestureRecognizer = foundScrollView?.nsuiGestureRecognizers?.first {
$0 is NSUIPanGestureRecognizer
}
if otherGestureRecognizer === scrollViewPanGestureRecognizer
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center.
@objc open func zoomIn()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomIn(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center.
@objc open func zoomOut()
{
let center = _viewPortHandler.contentCenter
let matrix = _viewPortHandler.zoomOut(x: center.x, y: -center.y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out to original size.
@objc open func resetZoom()
{
let matrix = _viewPortHandler.resetZoom()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// - Parameters:
/// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - x:
/// - y:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
x: CGFloat,
y: CGFloat)
{
let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor.
/// x and y are the values (**not pixels**) of the zoom center.
///
/// - Parameters:
/// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - xValue:
/// - yValue:
/// - axis:
@objc open func zoom(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let job = ZoomViewJob(
viewPortHandler: viewPortHandler,
scaleX: scaleX,
scaleY: scaleY,
xValue: xValue,
yValue: yValue,
transformer: getTransformer(forAxis: axis),
axis: axis,
view: self)
addViewportJob(job)
}
/// Zooms to the center of the chart with the given scale factor.
///
/// - Parameters:
/// - scaleX: if < 1 --> zoom out, if > 1 --> zoom in
/// - scaleY: if < 1 --> zoom out, if > 1 --> zoom in
/// - xValue:
/// - yValue:
/// - axis:
@objc open func zoomToCenter(
scaleX: CGFloat,
scaleY: CGFloat)
{
let center = centerOffsets
let matrix = viewPortHandler.zoom(
scaleX: scaleX,
scaleY: scaleY,
x: center.x,
y: -center.y)
viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - Parameters:
/// - scaleX:
/// - scaleY:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let origin = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let job = AnimatedZoomViewJob(
viewPortHandler: viewPortHandler,
transformer: getTransformer(forAxis: axis),
view: self,
yAxis: getAxis(axis),
xAxisRange: _xAxis.axisRange,
scaleX: scaleX,
scaleY: scaleY,
xOrigin: viewPortHandler.scaleX,
yOrigin: viewPortHandler.scaleY,
zoomCenterX: CGFloat(xValue),
zoomCenterY: CGFloat(yValue),
zoomOriginX: origin.x,
zoomOriginY: origin.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - Parameters:
/// - scaleX:
/// - scaleY:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// Zooms by the specified scale factor to the specified values on the specified axis.
///
/// - Parameters:
/// - scaleX:
/// - scaleY:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func zoomAndCenterViewAnimated(
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
zoomAndCenterViewAnimated(scaleX: scaleX, scaleY: scaleY, xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
@objc open func fitScreen()
{
let matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
@objc open func setScaleMinima(_ scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
@objc open var visibleXRange: Double
{
return abs(highestVisibleX - lowestVisibleX)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zooming out allowed).
///
/// If this is e.g. set to 10, no more than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMaximum(_ maxXRange: Double)
{
let xScale = _xAxis.axisRange / maxXRange
_viewPortHandler.setMinimumScaleX(CGFloat(xScale))
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
///
/// If this is e.g. set to 10, no less than a range of 10 values on the x-axis can be viewed at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRangeMinimum(_ minXRange: Double)
{
let xScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMaximumScaleX(CGFloat(xScale))
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
///
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling.
///
/// If you call this method, chart must have data or it has no effect.
@objc open func setVisibleXRange(minXRange: Double, maxXRange: Double)
{
let minScale = _xAxis.axisRange / maxXRange
let maxScale = _xAxis.axisRange / minXRange
_viewPortHandler.setMinMaxScaleX(
minScaleX: CGFloat(minScale),
maxScaleX: CGFloat(maxScale))
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// - Parameters:
/// - yRange:
/// - axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMaximum(_ maxYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinimumScaleY(CGFloat(yScale))
}
/// Sets the size of the area (range on the y-axis) that should be minimum visible at once, no further zooming in possible.
///
/// - Parameters:
/// - yRange:
/// - axis: - the axis for which this limit should apply
@objc open func setVisibleYRangeMinimum(_ minYRange: Double, axis: YAxis.AxisDependency)
{
let yScale = getAxisRange(axis: axis) / minYRange
_viewPortHandler.setMaximumScaleY(CGFloat(yScale))
}
/// Limits the maximum and minimum y range that can be visible by pinching and zooming.
///
/// - Parameters:
/// - minYRange:
/// - maxYRange:
/// - axis:
@objc open func setVisibleYRange(minYRange: Double, maxYRange: Double, axis: YAxis.AxisDependency)
{
let minScale = getAxisRange(axis: axis) / minYRange
let maxScale = getAxisRange(axis: axis) / maxYRange
_viewPortHandler.setMinMaxScaleY(minScaleY: CGFloat(minScale), maxScaleY: CGFloat(maxScale))
}
/// Moves the left side of the current viewport to the specified x-value.
/// This also refreshes the chart by calling setNeedsDisplay().
@objc open func moveViewToX(_ xValue: Double)
{
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: 0.0,
transformer: getTransformer(forAxis: .left),
view: self)
addViewportJob(job)
}
/// Centers the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - yValue:
/// - axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewToY(_ yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: 0.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-value on the x-axis, and center the viewport to the specified y-value on the y-axis.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: - which axis should be used as a reference for the y-axis
@objc open func moveViewTo(xValue: Double, yValue: Double, axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the left side of the current viewport to the specified x-position and center the viewport to the specified y-position animated.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func moveViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
moveViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// This will move the center of the current viewport to the specified x-value and y-value.
/// This also refreshes the chart by calling setNeedsDisplay().
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: - which axis should be used as a reference for the y-axis
@objc open func centerViewTo(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency)
{
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = MoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easing: ChartEasingFunctionBlock?)
{
let bounds = valueForTouchPoint(
point: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop),
axis: axis)
let yInView = getAxisRange(axis: axis) / Double(_viewPortHandler.scaleY)
let xInView = xAxis.axisRange / Double(_viewPortHandler.scaleX)
let job = AnimatedMoveViewJob(
viewPortHandler: viewPortHandler,
xValue: xValue - xInView / 2.0,
yValue: yValue + yInView / 2.0,
transformer: getTransformer(forAxis: axis),
view: self,
xOrigin: bounds.x,
yOrigin: bounds.y,
duration: duration,
easing: easing)
addViewportJob(job)
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval,
easingOption: ChartEasingOption)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easing: easingFunctionFromOption(easingOption))
}
/// This will move the center of the current viewport to the specified x-value and y-value animated.
///
/// - Parameters:
/// - xValue:
/// - yValue:
/// - axis: which axis should be used as a reference for the y-axis
/// - duration: the duration of the animation in seconds
/// - easing:
@objc open func centerViewToAnimated(
xValue: Double,
yValue: Double,
axis: YAxis.AxisDependency,
duration: TimeInterval)
{
centerViewToAnimated(xValue: xValue, yValue: yValue, axis: axis, duration: duration, easingOption: .easeInOutSine)
}
/// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`.
@objc open func setViewPortOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if Thread.isMainThread
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
DispatchQueue.main.async(execute: {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically.
@objc open func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// - Returns: The range of the specified axis.
@objc open func getAxisRange(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
return leftAxis.axisRange
}
else
{
return rightAxis.axisRange
}
}
/// - Returns: The position (in pixels) the provided Entry has inside the chart view
@objc open func getPosition(entry e: ChartDataEntry, axis: YAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y))
getTransformer(forAxis: axis).pointValueToPixel(&vals)
return vals
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var dragEnabled: Bool
{
get
{
return _dragXEnabled || _dragYEnabled
}
set
{
_dragYEnabled = newValue
_dragXEnabled = newValue
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
@objc open var isDragEnabled: Bool
{
return dragEnabled
}
/// is dragging on the X axis enabled?
@objc open var dragXEnabled: Bool
{
get
{
return _dragXEnabled
}
set
{
_dragXEnabled = newValue
}
}
/// is dragging on the Y axis enabled?
@objc open var dragYEnabled: Bool
{
get
{
return _dragYEnabled
}
set
{
_dragYEnabled = newValue
}
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
@objc open func setScaleEnabled(_ enabled: Bool)
{
if _scaleXEnabled != enabled || _scaleYEnabled != enabled
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
@objc open var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if _scaleXEnabled != newValue
{
_scaleXEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if _scaleYEnabled != newValue
{
_scaleYEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
@objc open var isScaleXEnabled: Bool { return scaleXEnabled }
@objc open var isScaleYEnabled: Bool { return scaleYEnabled }
/// flag that indicates if double tap zoom is enabled or not
@objc open var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if _doubleTapToZoomEnabled != newValue
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.isEnabled = _doubleTapToZoomEnabled
}
}
}
/// **default**: true
/// `true` if zooming via double-tap is enabled `false` ifnot.
@objc open var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
@objc open var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a `NSUIScrollView`
///
/// **default**: true
@objc open var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// **default**: true
/// `true` if drawing the grid background is enabled, `false` ifnot.
@objc open var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// **default**: false
/// `true` if drawing the borders rectangle is enabled, `false` ifnot.
@objc open var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// - Returns: The x and y values in the chart at the given touch point
/// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// `getPixelsForValues(...)`.
@objc open func valueForTouchPoint(point pt: CGPoint, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).valueForTouchPoint(pt)
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to `valueForTouchPoint(...)`.
@objc open func pixelForValues(x: Double, y: Double, axis: YAxis.AxisDependency) -> CGPoint
{
return getTransformer(forAxis: axis).pixelForValues(x: x, y: y)
}
/// - Returns: The Entry object displayed at the touched position of the chart
@objc open func getEntryByTouchPoint(point pt: CGPoint) -> ChartDataEntry!
{
if let h = getHighlightByTouchPoint(pt)
{
return _data!.entryForHighlight(h)
}
return nil
}
/// - Returns: The DataSet object displayed at the touched position of the chart
@objc open func getDataSetByTouchPoint(point pt: CGPoint) -> IBarLineScatterCandleBubbleChartDataSet?
{
let h = getHighlightByTouchPoint(pt)
if h !== nil
{
return _data?.getDataSetByIndex(h!.dataSetIndex) as? IBarLineScatterCandleBubbleChartDataSet
}
return nil
}
/// The current x-scale factor
@objc open var scaleX: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// The current y-scale factor
@objc open var scaleY: CGFloat
{
if _viewPortHandler === nil
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
@objc open var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut }
/// - Returns: The y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
@objc open func getAxis(_ axis: YAxis.AxisDependency) -> YAxis
{
if axis == .left
{
return leftAxis
}
else
{
return rightAxis
}
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately
@objc open var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if _pinchZoomEnabled != newValue
{
_pinchZoomEnabled = newValue
#if !os(tvOS)
_pinchGestureRecognizer.isEnabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
#endif
}
}
}
/// **default**: false
/// `true` if pinch-zoom is enabled, `false` ifnot
@objc open var isPinchZoomEnabled: Bool { return pinchZoomEnabled }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
@objc open func setDragOffsetX(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
@objc open func setDragOffsetY(_ offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// `true` if both drag offsets (x and y) are zero or smaller.
@objc open var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset }
open override var chartYMax: Double
{
return max(leftAxis._axisMaximum, rightAxis._axisMaximum)
}
open override var chartYMin: Double
{
return min(leftAxis._axisMinimum, rightAxis._axisMinimum)
}
/// `true` if either the left or the right or both axes are inverted.
@objc open var isAnyAxisInverted: Bool
{
return leftAxis.isInverted || rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
@objc open var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled }
set { _autoScaleMinMaxEnabled = newValue }
}
/// **default**: false
/// `true` if auto scaling on the y axis is enabled.
@objc open var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled }
/// Sets a minimum width to the specified y axis.
@objc open func setYAxisMinWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.minWidth = width
}
else
{
rightAxis.minWidth = width
}
}
/// **default**: 0.0
///
/// - Returns: The (custom) minimum width of the specified Y axis.
@objc open func getYAxisMinWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.minWidth
}
else
{
return rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
@objc open func setYAxisMaxWidth(_ axis: YAxis.AxisDependency, width: CGFloat)
{
if axis == .left
{
leftAxis.maxWidth = width
}
else
{
rightAxis.maxWidth = width
}
}
/// Zero (0.0) means there's no maximum width
///
/// **default**: 0.0 (no maximum specified)
///
/// - Returns: The (custom) maximum width of the specified Y axis.
@objc open func getYAxisMaxWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.maxWidth
}
else
{
return rightAxis.maxWidth
}
}
/// - Returns the width of the specified y axis.
@objc open func getYAxisWidth(_ axis: YAxis.AxisDependency) -> CGFloat
{
if axis == .left
{
return leftAxis.requiredSize().width
}
else
{
return rightAxis.requiredSize().width
}
}
// MARK: - BarLineScatterCandleBubbleChartDataProvider
/// - Returns: The Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
open func getTransformer(forAxis axis: YAxis.AxisDependency) -> Transformer
{
if axis == .left
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
/// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled
open override var maxVisibleCount: Int
{
get
{
return _maxVisibleCount
}
set
{
_maxVisibleCount = newValue
}
}
open func isInverted(axis: YAxis.AxisDependency) -> Bool
{
return getAxis(axis).isInverted
}
/// The lowest x-index (value on the x-axis) that is still visible on he chart.
open var lowestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentLeft,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return max(xAxis._axisMinimum, Double(pt.x))
}
/// The highest x-index (value on the x-axis) that is still visible on the chart.
open var highestVisibleX: Double
{
var pt = CGPoint(
x: viewPortHandler.contentRight,
y: viewPortHandler.contentBottom)
getTransformer(forAxis: .left).pixelToValues(&pt)
return min(xAxis._axisMaximum, Double(pt.x))
}
}
|
apache-2.0
|
e1dc37728e2de0b144156b6ece829f95
| 34.242763 | 238 | 0.581745 | 5.473929 | false | false | false | false |
dusek/firefox-ios
|
Client/Frontend/Bookmarks/BookmarksViewController.swift
|
1
|
4711
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class BookmarksViewController: UITableViewController {
private let BOOKMARK_CELL_IDENTIFIER = "BOOKMARK_CELL"
private let BOOKMARK_HEADER_IDENTIFIER = "BOOKMARK_HEADER"
var source: BookmarksModel!
var _profile: Profile!
var profile: Profile! {
get {
return _profile
}
set (profile) {
self._profile = profile
self.source = profile.bookmarks.nullModel
}
}
func onNewModel(model: BookmarksModel) {
// Switch out the model and redisplay.
self.source = model
dispatch_async(dispatch_get_main_queue()) {
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
}
func onModelFailure(e: Any) {
// Do nothing.
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.sectionFooterHeight = 0
//tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: BOOKMARK_CELL_IDENTIFIER)
let nib = UINib(nibName: "TabsViewControllerHeader", bundle: nil)
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: BOOKMARK_HEADER_IDENTIFIER)
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
}
func reloadData() {
self.source.reloadData(self.onNewModel, self.onModelFailure)
}
func refresh() {
reloadData()
}
override func viewDidAppear(animated: Bool) {
reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.source.current.count
}
private let FAVICON_SIZE = 32
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(BOOKMARK_CELL_IDENTIFIER, forIndexPath: indexPath) as UITableViewCell
let bookmark: BookmarkNode = self.source.current[indexPath.row]
cell.imageView?.image = bookmark.icon
cell.textLabel?.text = bookmark.title
cell.textLabel?.font = UIFont(name: "FiraSans-SemiBold", size: 13)
cell.textLabel?.textColor = UIColor.darkGrayColor()
cell.indentationWidth = 20
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 42
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BOOKMARK_HEADER_IDENTIFIER) as? UIView
if let label = view?.viewWithTag(1) as? UILabel {
label.text = "Recent Bookmarks"
}
return view
}
// func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// let objects = UINib(nibName: "TabsViewControllerHeader", bundle: nil).instantiateWithOwner(nil, options: nil)
// if let view = objects[0] as? UIView {
// if let label = view.viewWithTag(1) as? UILabel {
// // TODO: More button
// }
// }
// return view
// }
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let bookmark = self.source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
// Click it.
UIApplication.sharedApplication().openURL(NSURL(string: item.url)!)
break
case let folder as BookmarkFolder:
// Descend into the folder.
self.source.selectFolder(folder, success: self.onNewModel, failure: self.onModelFailure)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
|
mpl-2.0
|
9052465446c7cdeb5f6594fafaf6890e
| 34.421053 | 149 | 0.641477 | 5.131808 | false | false | false | false |
xuzhuoxi/SearchKit
|
Source/code/file/TextFileReader.swift
|
1
|
3003
|
//
// TextFileReader.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/29.
//
//
import Foundation
public class TextFileReader {
private let path : String!
private let chunkSize: Int = 4096
public var encoding: NSStringEncoding
public var atEOF: Bool = false
let fileHandle: NSFileHandle!
let buffer: NSMutableData!
let delimData: NSData!
public init(path: String, encoding: NSStringEncoding = NSUTF8StringEncoding, delimiter: String = "\n") {
self.path = path
self.encoding = encoding
self.fileHandle = NSFileHandle(forReadingAtPath: path)
self.delimData = delimiter.dataUsingEncoding(encoding)
self.buffer = NSMutableData(capacity: chunkSize)
}
public func nextLine() -> String? {
if atEOF {
return nil
}
// Read data chunks from file until a line delimiter is found.
var range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))
while range.location == NSNotFound {
let tmpData = fileHandle.readDataOfLength(chunkSize)
if tmpData.length == 0 {
// EOF or read error.
atEOF = true
if buffer.length > 0 {
// Buffer contains last line in file (not terminated by delimiter).
let line = NSString(data: buffer, encoding: encoding)
buffer.length = 0
return line as String?
}
// No more lines.
return nil
}
buffer.appendData(tmpData)
range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))
}
// Convert complete line (excluding the delimiter) to a string.
let line = NSString(data: buffer.subdataWithRange(NSMakeRange(0, range.location)),
encoding: encoding)
// Remove line (and the delimiter) from the buffer.
let cleaningRange = NSMakeRange(0, range.location + range.length)
buffer.replaceBytesInRange(cleaningRange, withBytes: nil, length: 0)
return line as? String
}
deinit {
fileHandle?.closeFile()
}
}
//public init?(
// path: Path,
// delimiter: String = "\n",
// encoding: NSStringEncoding = NSUTF8StringEncoding,
// chunkSize: Int = 4096
// ) {
// self.chunkSize = chunkSize
// self.encoding = encoding
//
// guard let fileHandle = path.fileHandleForReading,
// delimData = delimiter.dataUsingEncoding(encoding),
// buffer = NSMutableData(capacity: chunkSize) else {
// self.fileHandle = nil
// self.delimData = nil
// self.buffer = nil
// return nil
// }
// self.fileHandle = fileHandle
// self.delimData = delimData
// self.buffer = buffer
//}
|
mit
|
63193b2b93201afde85a74afd2dd03b1
| 31.586957 | 108 | 0.573574 | 4.779904 | false | false | false | false |
apple/swift-tools-support-core
|
Tests/TSCBasicPerformanceTests/WritableByteStreamPerfTests.swift
|
1
|
7117
|
/*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import TSCBasic
import TSCTestSupport
struct ByteSequence: Sequence {
let bytes16 = [UInt8](repeating: 0, count: 1 << 4)
func makeIterator() -> ByteSequenceIterator {
return ByteSequenceIterator(bytes16: bytes16)
}
}
extension ByteSequence: ByteStreamable {
func write(to stream: WritableByteStream) {
stream.write(sequence: self)
}
}
struct ByteSequenceIterator: IteratorProtocol {
let bytes16: [UInt8]
var index: Int
init(bytes16: [UInt8]) {
self.bytes16 = bytes16
index = 0
}
mutating func next() -> UInt8? {
if index == bytes16.count { return nil }
defer { index += 1 }
return bytes16[index]
}
}
class OutputByteStreamPerfTests: XCTestCasePerf {
func test1MBOfSequence_X10() {
#if canImport(Darwin)
let sequence = ByteSequence()
measure {
for _ in 0..<10 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 16) {
stream <<< sequence
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOfByte_X10() {
#if canImport(Darwin)
let byte = UInt8(0)
measure {
for _ in 0..<10 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 20) {
stream <<< byte
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOfCharacters_X1() {
#if canImport(Darwin)
measure {
for _ in 0..<1 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 20) {
stream <<< Character("X")
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOf16ByteArrays_X100() {
#if canImport(Darwin)
// Test writing 1MB worth of 16 byte strings.
let bytes16 = [UInt8](repeating: 0, count: 1 << 4)
measure {
for _ in 0..<100 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 16) {
stream <<< bytes16
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
// This should give same performance as 16ByteArrays_X100.
func test1MBOf16ByteArraySlice_X100() {
#if canImport(Darwin)
let bytes32 = [UInt8](repeating: 0, count: 1 << 5)
// Test writing 1MB worth of 16 byte strings.
let bytes16 = bytes32.suffix(from: bytes32.count/2)
measure {
for _ in 0..<100 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 16) {
stream <<< bytes16
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOf1KByteArrays_X1000() {
#if canImport(Darwin)
// Test writing 1MB worth of 1K byte strings.
let bytes1k = [UInt8](repeating: 0, count: 1 << 10)
measure {
for _ in 0..<1000 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 10) {
stream <<< bytes1k
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOf16ByteStrings_X10() {
#if canImport(Darwin)
// Test writing 1MB worth of 16 byte strings.
let string16 = String(repeating: "X", count: 1 << 4)
measure {
for _ in 0..<10 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 16) {
stream <<< string16
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOf1KByteStrings_X100() {
#if canImport(Darwin)
// Test writing 1MB worth of 1K byte strings.
let bytes1k = String(repeating: "X", count: 1 << 10)
measure {
for _ in 0..<100 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 10) {
stream <<< bytes1k
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func test1MBOfJSONEncoded16ByteStrings_X10() {
#if canImport(Darwin)
// Test writing 1MB worth of JSON encoded 16 byte strings.
let string16 = String(repeating: "X", count: 1 << 4)
measure {
for _ in 0..<10 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 16) {
stream.writeJSONEscaped(string16)
}
XCTAssertEqual(stream.bytes.count, 1 << 20)
}
}
#endif
}
func testFormattedJSONOutput() {
#if canImport(Darwin)
// Test the writing of JSON formatted output using stream operators.
struct Thing {
var value: String
init(_ value: String) { self.value = value }
}
let listOfStrings: [String] = (0..<10).map { "This is the number: \($0)!\n" }
let listOfThings: [Thing] = listOfStrings.map(Thing.init)
measure {
for _ in 0..<10 {
let stream = BufferedOutputByteStream()
for _ in 0..<(1 << 10) {
for string in listOfStrings {
stream <<< Format.asJSON(string)
}
stream <<< Format.asJSON(listOfStrings)
stream <<< Format.asJSON(listOfThings, transform: { $0.value })
}
XCTAssertGreaterThan(stream.bytes.count, 1000)
}
}
#endif
}
func testJSONToString_X100() {
#if canImport(Darwin)
let foo = JSON.dictionary([
"foo": .string("bar"),
"bar": .int(2),
"baz": .array([1, 2, 3].map(JSON.int)),
])
let bar = JSON.dictionary([
"poo": .array([foo, foo, foo]),
"foo": .int(1),
])
let baz = JSON.dictionary([
"poo": .array([foo, bar, foo]),
"foo": .int(1),
])
let json = JSON.array((0..<100).map { _ in baz })
measure {
for _ in 0..<100 {
let result = json.toString()
XCTAssertGreaterThan(result.utf8.count, 10)
}
}
#endif
}
}
|
apache-2.0
|
ba273031715f1d866d7d69ec2c8f10a0
| 27.813765 | 85 | 0.487284 | 4.448125 | false | true | false | false |
blstream/TOZ_iOS
|
TOZ_iOS/AppDelegate.swift
|
1
|
1280
|
//
// AppDelegate.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import UIKit
import HockeySDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
BITHockeyManager.shared().configure(withIdentifier: "1c4560d21290458c8ae1e5156e194155")
BITHockeyManager.shared().start()
UITableView.appearance().backgroundColor = Color.TableView.background
UITableView.appearance().separatorColor = Color.TableView.separator
UITableViewCell.appearance().backgroundColor = Color.Cell.Background.primary
UITabBar.appearance().barTintColor = Color.TabBar.Background.primary
UITabBar.appearance().tintColor = Color.TabBar.Icons.pressed
UITabBar.appearance().unselectedItemTintColor = Color.TabBar.Icons.primary
UITabBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = Color.TitleBar.Background.primary
UINavigationBar.appearance().tintColor = Color.TitleBar.Button.primary
UINavigationBar.appearance().barStyle = .black
return true
}
}
|
apache-2.0
|
e326c66d44ed796f62c3320b89f7ce60
| 35.542857 | 144 | 0.741986 | 5.136546 | false | false | false | false |
sschiau/swift
|
test/Constraints/function_builder_diags.swift
|
2
|
5458
|
// RUN: %target-typecheck-verify-swift -disable-availability-checking
@_functionBuilder
struct TupleBuilder { // expected-note 2{{struct 'TupleBuilder' declared here}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
}
@_functionBuilder
struct TupleBuilderWithoutIf { // expected-note {{struct 'TupleBuilderWithoutIf' declared here}}
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: T1) -> T1 {
return t1
}
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
func tuplifyWithoutIf<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) {
print(body(cond))
}
func testDiags() {
// For loop
tuplify(true) { _ in
17
for c in name { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilder'}}
// expected-error@-1 {{use of unresolved identifier 'name'}}
}
}
// Declarations
tuplify(true) { _ in
17
let x = 17 // expected-error{{closure containing a declaration cannot be used with function builder 'TupleBuilder'}}
x + 25
}
// Statements unsupported by the particular builder.
tuplifyWithoutIf(true) {
if $0 { // expected-error{{closure containing control flow statement cannot be used with function builder 'TupleBuilderWithoutIf'}}
"hello"
}
}
}
struct A { }
struct B { }
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) -> A { // expected-note {{found this candidate}}
return A()
}
func overloadedTuplify<T>(_ cond: Bool, @TupleBuilderWithoutIf body: (Bool) -> T) -> B { // expected-note {{found this candidate}}
return B()
}
func testOverloading(name: String) {
let a1 = overloadedTuplify(true) { b in
if b {
"Hello, \(name)"
}
}
let _: A = a1
_ = overloadedTuplify(true) { b in // expected-error {{ambiguous use of 'overloadedTuplify(_:body:)'}}
b ? "Hello, \(name)" : "Goodbye"
42
overloadedTuplify(false) {
$0 ? "Hello, \(name)" : "Goodbye"
42
if $0 {
"Hello, \(name)"
}
}
}
}
protocol P {
associatedtype T
}
struct AnyP : P {
typealias T = Any
init<T>(_: T) where T : P {}
}
struct TupleP<U> : P {
typealias T = U
init(_: U) {}
}
@_functionBuilder
struct Builder {
static func buildBlock<S0, S1>(_ stmt1: S0, _ stmt2: S1) // expected-note {{required by static method 'buildBlock' where 'S1' = 'Label<Any>.Type'}}
-> TupleP<(S0, S1)> where S0: P, S1: P {
return TupleP((stmt1, stmt2))
}
}
struct G<C> : P where C : P {
typealias T = C
init(@Builder _: () -> C) {}
}
struct Text : P {
typealias T = String
init(_: T) {}
}
struct Label<L> : P where L : P { // expected-note {{'L' declared as parameter to type 'Label'}}
typealias T = L
init(@Builder _: () -> L) {}
}
func test_51167632() -> some P {
AnyP(G { // expected-error {{type 'Label<Any>.Type' cannot conform to 'P'; only struct/enum/class types can conform to protocols}}
Text("hello")
Label // expected-error {{generic parameter 'L' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{10-10=<<#L: P#>>}}
})
}
struct SR11440 {
typealias ReturnsTuple<T> = () -> (T, T)
subscript<T, U>(@TupleBuilder x: ReturnsTuple<T>) -> (ReturnsTuple<U>) -> Void { //expected-note {{in call to 'subscript(_:)'}}
return { _ in }
}
func foo() {
// This is okay, we apply the function builder for the subscript arg.
self[{
5
5
}]({
(5, 5)
})
// But we shouldn't perform the transform for the argument to the call
// made on the function returned from the subscript.
self[{ // expected-error {{generic parameter 'U' could not be inferred}}
5
5
}]({
5
5
})
}
}
func acceptInt(_: Int, _: () -> Void) { }
// SR-11350 crash due to improper recontextualization.
func erroneousSR11350(x: Int) {
tuplify(true) { b in
17
x + 25
Optional(tuplify(false) { b in
if b {
acceptInt(0) { }
}
}).domap(0) // expected-error{{value of type 'Optional<()>' has no member 'domap'}}
}
}
|
apache-2.0
|
97dae9dcf9860f3a5654b29712536e0d
| 24.268519 | 149 | 0.580249 | 3.00882 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS
|
WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Calypso/Embeds/WordPressPasteboardDelegate.swift
|
2
|
1069
|
import UIKit
import Aztec
class WordPressTextViewPasteboardDelegate: AztecTextViewPasteboardDelegate {
override func tryPastingURL(in textView: TextView) -> Bool {
let selectedRange = textView.selectedRange
/// TODO: support pasting multiple URLs
guard UIPasteboard.general.hasURLs, // There are URLs on the pasteboard
let url = UIPasteboard.general.url, // We can get the first one
selectedRange.length == 0, // No text is selected in the TextView
EmbedURLProcessor(url: url).isValidEmbed // The pasteboard contains an embeddable URL
else {
return super.tryPastingURL(in: textView)
}
let result = super.tryPastingString(in: textView)
if result {
// Bump the input to the next line – we need the embed link to be the only
// text on this line – otherwise it can't be autoconverted.
textView.insertText(String(.lineSeparator))
}
return result
}
}
|
mpl-2.0
|
b60d9eb7492015ae344f1e019fd79714
| 37 | 100 | 0.625 | 5.066667 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Localization/Sources/Localization/LocalizationConstants+Swap.swift
|
1
|
2742
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
// swiftlint:disable all
import Foundation
extension LocalizationConstants {
public enum Swap {
public enum Trending {
public enum Header {
public static let title = NSLocalizedString(
"Swap Your Crypto",
comment: "Swap Your Crypto"
)
public static let description = NSLocalizedString(
"Instantly exchange your crypto into any currency we offer for your wallet.",
comment: "Instantly exchange your crypto into any currency we offer for your wallet."
)
}
public static let trending = NSLocalizedString(
"Trending", comment: "Trending"
)
public static let newSwap = NSLocalizedString(
"New Swap", comment: "New Swap"
)
}
public static let completed = NSLocalizedString(
"Completed",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let delayed = NSLocalizedString(
"Delayed",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let expired = NSLocalizedString(
"Expired",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let failed = NSLocalizedString(
"Failed",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let inProgress = NSLocalizedString(
"In Progress",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let pending = NSLocalizedString(
"Pending",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let refundInProgress = NSLocalizedString(
"Refund in Progress",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let refunded = NSLocalizedString(
"Refunded",
comment: "Text shown on the exchange list cell indicating the trade status"
)
public static let swap = NSLocalizedString(
"Swap",
comment: "Text shown for the crypto exchange service."
)
public static let receive = NSLocalizedString(
"Receive",
comment: "Text displayed when reviewing the amount to be received for an exchange order"
)
}
}
|
lgpl-3.0
|
16f89682290e1073c02dbad0557f1943
| 37.605634 | 105 | 0.589201 | 5.894624 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
BlockchainTests/AppFeature/Mocks/MockURIHandler.swift
|
1
|
620
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureAppUI
@testable import BlockchainApp
class MockURIHandler: URIHandlingAPI {
var passthroughSubject = PassthroughSubject<DeeplinkOutcome, AppDeeplinkError>()
var canHandle = false
var canHandleCalled = false
func canHandle(url: URL) -> Bool {
canHandleCalled = true
return canHandle
}
var handleCalled = false
func handle(url: URL) -> AnyPublisher<DeeplinkOutcome, AppDeeplinkError> {
handleCalled = true
return passthroughSubject.eraseToAnyPublisher()
}
}
|
lgpl-3.0
|
e2685925b2d2589540d8e4672bdeaa8d
| 23.76 | 84 | 0.717286 | 4.835938 | false | false | false | false |
huonw/swift
|
stdlib/public/core/Print.swift
|
3
|
8822
|
//===--- Print.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Writes the textual representations of the given items into the standard
/// output.
///
/// You can pass zero or more items to the `print(_:separator:terminator:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a string,
/// a closed range of integers, and a group of floating-point values to
/// standard output:
///
/// print("One two three four five")
/// // Prints "One two three four five"
///
/// print(1...5)
/// // Prints "1...5"
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `print(_:separator:terminator:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// for n in 1...5 {
/// print(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
public func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the standard output.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:)` function. The textual representation
/// for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints the debugging
/// representation of a string, a closed range of integers, and a group of
/// floating-point values to standard output:
///
/// debugPrint("One two three four five")
/// // Prints "One two three four five"
///
/// debugPrint(1...5)
/// // Prints "ClosedRange(1...5)"
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `debugPrint(_:separator:terminator:)` includes
/// a newline by default. To print the items without a trailing newline, pass
/// an empty string as `terminator`.
///
/// for n in 1...5 {
/// debugPrint(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
public func debugPrint(
_ items: Any...,
separator: String = " ",
terminator: String = "\n") {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items into the given output
/// stream.
///
/// You can pass zero or more items to the `print(_:separator:terminator:to:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a closed
/// range of integers to a string:
///
/// var range = "My range: "
/// print(1...5, to: &range)
/// // range == "My range: 1...5\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `print(_:separator:terminator:to:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// print(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_print(items, separator: separator, terminator: terminator, to: &output)
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the given output stream.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:to:)` function. The textual
/// representation for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints a closed range of
/// integers to a string:
///
/// var range = "My range: "
/// debugPrint(1...5, to: &range)
/// // range == "My range: ClosedRange(1...5)\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `debugPrint(_:separator:terminator:to:)`
/// includes a newline by default. To print the items without a trailing
/// newline, pass an empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// debugPrint(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
@usableFromInline
@inline(never)
internal func _print<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
@usableFromInline
@inline(never)
internal func _debugPrint<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_debugPrint_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
|
apache-2.0
|
b941f71519177f92ded3ea7d8eceb150
| 32.543726 | 80 | 0.612446 | 3.680434 | false | false | false | false |
pi3r0/PHClaudyTouchBar
|
PHClaudyTouchBar/PHClaudyTouchBar/WindowController.swift
|
1
|
3660
|
//
// WindowController.swift
// PHClaudyTouchBar
//
// Created by Pierre Houguet on 25/07/2017.
// Copyright © 2017 Pierre Houguet. All rights reserved.
//
import Cocoa
class WindowController: NSWindowController, NSTouchBarDelegate {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
@available(OSX 10.12.2, *)
override func makeTouchBar() -> NSTouchBar? {
guard let viewController = contentViewController as? ViewController else {
return nil
}
return viewController.makeTouchBar()
}
// func Claudy(sender: NSButton) {
// let title = sender.title
//
// guard let sound = NSSound(named: title) else {
// return
// }
// sound.play()
// }
//
// @available(OSX 10.12.2, *)
// override func makeTouchBar() -> NSTouchBar? {
// let touchBar = NSTouchBar()
// touchBar.delegate = self
// touchBar.customizationIdentifier = .touchBar
//
// touchBar.defaultItemIdentifiers = [.connasse, .couilles, .stress, .flexibleSpace,.beer, .out, .alien, .flexibleSpace,.goodnight]
// touchBar.customizationAllowedItemIdentifiers = [.iam ,.connasse, .couilles, .stress,.shaved,.beer, .out, .missed, .alien, .goodnight]
//
// return touchBar
// }
//
//
// @available(OSX 10.12.2, *)
// func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem? {
// let touchBarItem = NSCustomTouchBarItem(identifier: identifier)
// var title = "";
// var label = "";
// switch identifier {
// case NSTouchBarItemIdentifier.iam:
// title = "👦"
// label = "Je suis claudy"
// break;
// case NSTouchBarItemIdentifier.goodnight:
// title = "🌑"
// label = "Terminer bonsoir"
// break
// case NSTouchBarItemIdentifier.out:
// title = "⛔"
// label = "Ou tu sors, ou j'te sors"
// break
// case NSTouchBarItemIdentifier.beer:
// title = "🍺"
// label = "J'aime bien la mousse"
// break
// case NSTouchBarItemIdentifier.connasse:
//
// title = "👸"
// label = "Connasse"
// break
// case NSTouchBarItemIdentifier.couilles:
//
// title = "🏑"
// label = "Pas commencer à jouer avec mes couilles"
//
// break
// case NSTouchBarItemIdentifier.shaved:
// title = "💇"
// label = "Est ce que t'es epilée"
// break
// case NSTouchBarItemIdentifier.missed:
// title = "🐴"
// label = "Il t'ont pas loupé"
// break
// case NSTouchBarItemIdentifier.stress:
// title = "😤"
// label = "T'es tendue"
// break
// case NSTouchBarItemIdentifier.alien:
// title = "👽"
// label = "Alien"
// break;
// default:
// title = ""
// return nil;
// }
//
// if title != "" {
// let button = NSButton(title: title, target: self, action: #selector(Claudy))
// touchBarItem.view = button
// touchBarItem.customizationLabel = label;
// return touchBarItem
//
// }
// return nil;
// }
//
}
|
mit
|
30cda08ba8c5ba19e52510655b4a5837
| 30.267241 | 144 | 0.530742 | 4.016611 | false | false | false | false |
JaSpa/swift
|
stdlib/public/core/ContiguousArrayBuffer.swift
|
5
|
22254
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Class used whose sole instance is used as storage for empty
/// arrays. The instance is defined in the runtime and statically
/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
@objc_non_lazy_realization
internal final class _EmptyArrayStorage
: _ContiguousArrayStorageBase {
init(_doNotCallMe: ()) {
_sanityCheckFailure("creating instance of _EmptyArrayStorage")
}
#if _runtime(_ObjC)
override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
return try body(UnsafeBufferPointer(start: nil, count: 0))
}
override func _getNonVerbatimBridgedCount() -> Int {
return 0
}
override func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> {
return _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, 0, 0)
}
#endif
override func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
return false
}
/// A type that every element in the array is.
override var staticElementType: Any.Type {
return Void.self
}
}
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
internal var _emptyArrayStorage : _EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
}
// The class that implements the storage for a ContiguousArray<Element>
@_versioned
final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
deinit {
_elementPointer.deinitialize(count: countAndCapacity.count)
_fixLifetime(self)
}
#if _runtime(_ObjC)
/// If the `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
final override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
var result: R?
try self._withVerbatimBridgedUnsafeBufferImpl {
result = try body($0)
}
return result
}
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
internal final func _withVerbatimBridgedUnsafeBufferImpl(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
if _isBridgedVerbatimToObjectiveC(Element.self) {
let count = countAndCapacity.count
let elements = UnsafeRawPointer(_elementPointer)
.assumingMemoryBound(to: AnyObject.self)
defer { _fixLifetime(self) }
try body(UnsafeBufferPointer(start: elements, count: count))
}
}
/// Returns the number of elements in the array.
///
/// - Precondition: `Element` is bridged non-verbatim.
override internal func _getNonVerbatimBridgedCount() -> Int {
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
return countAndCapacity.count
}
/// Bridge array elements and return a new buffer that owns them.
///
/// - Precondition: `Element` is bridged non-verbatim.
override internal func _getNonVerbatimBridgedHeapBuffer() ->
_HeapBuffer<Int, AnyObject> {
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
let count = countAndCapacity.count
let result = _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, count, count)
let resultPtr = result.baseAddress
let p = _elementPointer
for i in 0..<count {
(resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i]))
}
_fixLifetime(self)
return result
}
#endif
/// Returns `true` if the `proposedElementType` is `Element` or a subclass of
/// `Element`. We can't store anything else without violating type
/// safety; for example, the destructor has static knowledge that
/// all of the elements can be destroyed as `Element`.
override func canStoreElements(
ofDynamicType proposedElementType: Any.Type
) -> Bool {
#if _runtime(_ObjC)
return proposedElementType is Element.Type
#else
// FIXME: Dynamic casts don't currently work without objc.
// rdar://problem/18801510
return false
#endif
}
/// A type that every element in the array is.
override var staticElementType: Any.Type {
return Element.self
}
internal final var _elementPointer : UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self))
}
}
@_versioned
@_fixed_layout
internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Make a buffer with uninitialized elements. After using this
/// method, you must either initialize the `count` elements at the
/// result's `.firstElementAddress` or set the result's `.count`
/// to zero.
internal init(
_uninitializedCount uninitializedCount: Int,
minimumCapacity: Int
) {
let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity)
if realMinimumCapacity == 0 {
self = _ContiguousArrayBuffer<Element>()
}
else {
_storage = Builtin.allocWithTailElems_1(
_ContiguousArrayStorage<Element>.self,
realMinimumCapacity._builtinWordValue, Element.self)
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage))
let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr)
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress
_initStorageHeader(
count: uninitializedCount, capacity: realCapacity)
}
}
/// Initialize using the given uninitialized `storage`.
/// The storage is assumed to be uninitialized. The returned buffer has the
/// body part of the storage initialized, but not the elements.
///
/// - Warning: The result has uninitialized elements.
///
/// - Warning: storage may have been stack-allocated, so it's
/// crucial not to call, e.g., `malloc_size` on it.
internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {
_storage = storage
_initStorageHeader(count: count, capacity: count)
}
internal init(_ storage: _ContiguousArrayStorageBase) {
_storage = storage
}
/// Initialize the body part of our storage.
///
/// - Warning: does not initialize elements
internal func _initStorageHeader(count: Int, capacity: Int) {
#if _runtime(_ObjC)
let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)
#else
let verbatim = false
#endif
// We can initialize by assignment because _ArrayBody is a trivial type,
// i.e. contains no references.
_storage.countAndCapacity = _ArrayBody(
count: count,
capacity: capacity,
elementTypeIsBridgedVerbatim: verbatim)
}
/// True, if the array is native and does not need a deferred type check.
internal var arrayPropertyIsNativeTypeChecked: Bool {
return true
}
/// A pointer to the first element.
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(_storage,
Element.self))
}
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return firstElementAddress
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: firstElementAddress,
count: count))
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
//===--- _ArrayBufferProtocol conformance -----------------------------------===//
/// Create an empty buffer.
internal init() {
_storage = _emptyArrayStorage
}
internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
self = buffer
}
internal mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>? {
if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) {
return self
}
return nil
}
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
return self
}
@_versioned
@inline(__always)
internal func getElement(_ i: Int) -> Element {
_sanityCheck(i >= 0 && i < count, "Array index out of range")
return firstElementAddress[i]
}
/// Get or set the value of the ith element.
@_versioned
internal subscript(i: Int) -> Element {
@inline(__always)
get {
return getElement(i)
}
@inline(__always)
nonmutating set {
_sanityCheck(i >= 0 && i < count, "Array index out of range")
// FIXME: Manually swap because it makes the ARC optimizer happy. See
// <rdar://problem/16831852> check retain/release order
// firstElementAddress[i] = newValue
var nv = newValue
let tmp = nv
nv = firstElementAddress[i]
firstElementAddress[i] = tmp
}
}
/// The number of elements the buffer stores.
@_versioned
internal var count: Int {
get {
return _storage.countAndCapacity.count
}
nonmutating set {
_sanityCheck(newValue >= 0)
_sanityCheck(
newValue <= capacity,
"Can't grow an array buffer past its capacity")
_storage.countAndCapacity.count = newValue
}
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inline(__always)
func _checkValidSubscript(_ index : Int) {
_precondition(
(index >= 0) && (index < count),
"Index out of range"
)
}
/// The number of elements the buffer can store without reallocation.
internal var capacity: Int {
return _storage.countAndCapacity.capacity
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_sanityCheck(bounds.lowerBound >= 0)
_sanityCheck(bounds.upperBound >= bounds.lowerBound)
_sanityCheck(bounds.upperBound <= count)
let initializedCount = bounds.upperBound - bounds.lowerBound
target.initialize(
from: firstElementAddress + bounds.lowerBound, count: initializedCount)
_fixLifetime(owner)
return target + initializedCount
}
/// Returns a `_SliceBuffer` containing the given `bounds` of values
/// from this buffer.
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
return _SliceBuffer(
owner: _storage,
subscriptBaseAddress: subscriptBaseAddress,
indices: bounds,
hasNativeBuffer: true)
}
set {
fatalError("not implemented")
}
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
///
/// - Note: This does not mean the buffer is mutable. Other factors
/// may need to be considered, such as whether the buffer could be
/// some immutable Cocoa container.
internal mutating func isUniquelyReferenced() -> Bool {
return _isUnique(&_storage)
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned. NOTE: this does not mean
/// the buffer is mutable; see the comment on isUniquelyReferenced.
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
return _isUniqueOrPinned(&_storage)
}
#if _runtime(_ObjC)
/// Convert to an NSArray.
///
/// - Precondition: `Element` is bridged to Objective-C.
///
/// - Complexity: O(1).
internal func _asCocoaArray() -> _NSArrayCore {
if count == 0 {
return _emptyArrayStorage
}
if _isBridgedVerbatimToObjectiveC(Element.self) {
return _storage
}
return _SwiftDeferredNSArray(_nativeStorage: _storage)
}
#endif
/// An object that keeps the elements stored in this buffer alive.
@_versioned
internal var owner: AnyObject {
return _storage
}
/// An object that keeps the elements stored in this buffer alive.
internal var nativeOwner: AnyObject {
return _storage
}
/// A value that identifies the storage used by the buffer.
///
/// Two buffers address the same elements when they have the same
/// identity and count.
internal var identity: UnsafeRawPointer {
return UnsafeRawPointer(firstElementAddress)
}
/// Returns `true` iff we have storage for elements of the given
/// `proposedElementType`. If not, we'll be treated as immutable.
func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {
return _storage.canStoreElements(ofDynamicType: proposedElementType)
}
/// Returns `true` if the buffer stores only elements of type `U`.
///
/// - Precondition: `U` is a class or `@objc` existential.
///
/// - Complexity: O(*n*)
func storesOnlyElementsOfType<U>(
_: U.Type
) -> Bool {
_sanityCheck(_isClassOrObjCExistential(U.self))
if _fastPath(_storage.staticElementType is U.Type) {
// Done in O(1)
return true
}
// Check the elements
for x in self {
if !(x is U) {
return false
}
}
return true
}
internal var _storage: _ContiguousArrayStorageBase
}
/// Append the elements of `rhs` to `lhs`.
internal func += <Element, C : Collection>(
lhs: inout _ContiguousArrayBuffer<Element>, rhs: C
) where C.Iterator.Element == Element {
let oldCount = lhs.count
let newCount = oldCount + numericCast(rhs.count)
let buf: UnsafeMutableBufferPointer<Element>
if _fastPath(newCount <= lhs.capacity) {
buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count))
lhs.count = newCount
}
else {
var newLHS = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCount,
minimumCapacity: _growArrayCapacity(lhs.capacity))
newLHS.firstElementAddress.moveInitialize(
from: lhs.firstElementAddress, count: oldCount)
lhs.count = 0
swap(&lhs, &newLHS)
buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count))
}
var (remainders,writtenUpTo) = buf.initialize(from: rhs)
// ensure that exactly rhs.count elements were written
_precondition(remainders.next() == nil, "rhs underreported its count")
_precondition(writtenUpTo == buf.endIndex, "rhs overreported its count")
}
extension _ContiguousArrayBuffer : RandomAccessCollection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
internal var endIndex: Int {
return count
}
internal typealias Indices = CountableRange<Int>
}
extension Sequence {
public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> {
return _copySequenceToContiguousArray(self)
}
}
internal func _copySequenceToContiguousArray<
S : Sequence
>(_ source: S) -> ContiguousArray<S.Iterator.Element> {
let initialCapacity = source.underestimatedCount
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<S.Iterator.Element>(
initialCapacity: initialCapacity)
var iterator = source.makeIterator()
// FIXME(performance): use _copyContents(initializing:).
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(iterator.next()!)
}
// Add remaining elements, if any.
while let element = iterator.next() {
builder.add(element)
}
return builder.finish()
}
extension Collection {
public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> {
return _copyCollectionToContiguousArray(self)
}
}
extension _ContiguousArrayBuffer {
internal func _copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(_buffer: self)
}
}
/// This is a fast implementation of _copyToContiguousArray() for collections.
///
/// It avoids the extra retain, release overhead from storing the
/// ContiguousArrayBuffer into
/// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support
/// ARC loops, the extra retain, release overhead cannot be eliminated which
/// makes assigning ranges very slow. Once this has been implemented, this code
/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.
internal func _copyCollectionToContiguousArray<
C : Collection
>(_ source: C) -> ContiguousArray<C.Iterator.Element>
{
let count: Int = numericCast(source.count)
if count == 0 {
return ContiguousArray()
}
let result = _ContiguousArrayBuffer<C.Iterator.Element>(
_uninitializedCount: count,
minimumCapacity: 0)
var p = result.firstElementAddress
var i = source.startIndex
for _ in 0..<count {
// FIXME(performance): use _copyContents(initializing:).
p.initialize(to: source[i])
source.formIndex(after: &i)
p += 1
}
_expectEnd(of: source, is: i)
return ContiguousArray(_buffer: result)
}
/// A "builder" interface for initializing array buffers.
///
/// This presents a "builder" interface for initializing an array buffer
/// element-by-element. The type is unsafe because it cannot be deinitialized
/// until the buffer has been finalized by a call to `finish`.
internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
internal var result: _ContiguousArrayBuffer<Element>
internal var p: UnsafeMutablePointer<Element>
internal var remainingCapacity: Int
/// Initialize the buffer with an initial size of `initialCapacity`
/// elements.
@inline(__always) // For performance reasons.
init(initialCapacity: Int) {
if initialCapacity == 0 {
result = _ContiguousArrayBuffer()
} else {
result = _ContiguousArrayBuffer(
_uninitializedCount: initialCapacity,
minimumCapacity: 0)
}
p = result.firstElementAddress
remainingCapacity = result.capacity
}
/// Add an element to the buffer, reallocating if necessary.
@inline(__always) // For performance reasons.
mutating func add(_ element: Element) {
if remainingCapacity == 0 {
// Reallocate.
let newCapacity = max(_growArrayCapacity(result.capacity), 1)
var newResult = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCapacity, minimumCapacity: 0)
p = newResult.firstElementAddress + result.capacity
remainingCapacity = newResult.capacity - result.capacity
newResult.firstElementAddress.moveInitialize(
from: result.firstElementAddress, count: result.capacity)
result.count = 0
swap(&result, &newResult)
}
addWithExistingCapacity(element)
}
/// Add an element to the buffer, which must have remaining capacity.
@inline(__always) // For performance reasons.
mutating func addWithExistingCapacity(_ element: Element) {
_sanityCheck(remainingCapacity > 0,
"_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity")
remainingCapacity -= 1
p.initialize(to: element)
p += 1
}
/// Finish initializing the buffer, adjusting its count to the final
/// number of elements.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inline(__always) // For performance reasons.
mutating func finish() -> ContiguousArray<Element> {
// Adjust the initialized count of the buffer.
result.count = result.capacity - remainingCapacity
return finishWithOriginalCount()
}
/// Finish initializing the buffer, assuming that the number of elements
/// exactly matches the `initialCount` for which the initialization was
/// started.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inline(__always) // For performance reasons.
mutating func finishWithOriginalCount() -> ContiguousArray<Element> {
_sanityCheck(remainingCapacity == result.capacity - result.count,
"_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count")
var finalResult = _ContiguousArrayBuffer<Element>()
swap(&finalResult, &result)
remainingCapacity = 0
return ContiguousArray(_buffer: finalResult)
}
}
|
apache-2.0
|
f774384aa4dc4a615dd3099f54f29514
| 31.579795 | 110 | 0.695173 | 4.771012 | false | false | false | false |
3DprintFIT/octoprint-ios-client
|
OctoPhone/View Related/Settings/SettingsCollectionViewCell.swift
|
1
|
1322
|
//
// SettingsCollectionViewCell.swift
// OctoPhone
//
// Created by Josef Dolezal on 09/03/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
import SnapKit
import ReactiveSwift
/// Cell for settings page
class SettingsCollectionViewCell: UICollectionViewCell {
/// Reuse identifier of cell
static let identifier = "SettingsCollectionViewCell"
/// Settings name text label
private let settingsTextLabel = UILabel()
/// Cell logic
let viewModel = MutableProperty<SettingsCellViewModelType?>(nil)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
contentView.addSubview(settingsTextLabel)
bindViewModel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
settingsTextLabel.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0))
}
}
/// Binds available view model outputs to view
private func bindViewModel() {
let vm = viewModel.producer.skipNil()
settingsTextLabel.reactive.text <~ vm.flatMap(.latest) { $0.outputs.name }
}
}
|
mit
|
6e82302dc2927db60990797fff066e52
| 24.403846 | 100 | 0.675246 | 4.803636 | false | false | false | false |
makingspace/NetworkingServiceKit
|
NetworkingServiceKit/Classes/Networking/NetworkURLProtocol.swift
|
1
|
4741
|
//
// NetworkURLProtocol.swift
// Makespace Inc.
//
// Created by Phillipe Casorla Sagot on 9/20/17.
//
import UIKit
/// Custom URLProtocol for intercepting requests
class NetworkURLProtocol: URLProtocol {
private var session: URLSession?
private var sessionTask: URLSessionDataTask?
override init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
super.init(request: request, cachedResponse: cachedResponse, client: client)
if session == nil {
session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
}
}
/// Check if we should intercept a request
///
/// - Parameter request: request to be intercepted based on our delegate and baseURL
/// - Returns: if we should intercept
override class func canInit(with request: URLRequest) -> Bool {
let baseURL = APIConfiguration.current.baseURL
if ServiceLocator.shouldInterceptRequests,
let delegate = ServiceLocator.shared.delegate,
let urlString = request.url?.absoluteString,
urlString.contains(baseURL) {
return delegate.shouldInterceptRequest(with: request)
}
return false
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override var cachedResponse: CachedURLResponse? {
return nil
}
/// Load the request, if we find this request is an intercepted one, execute the new request
override func startLoading() {
if let delegate = ServiceLocator.shared.delegate,
let newRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest,
let modifiedRequest = delegate.processIntercept(for: newRequest) {
sessionTask = session?.dataTask(with: modifiedRequest as URLRequest)
sessionTask?.resume()
if ServiceLocator.logLevel != .none {
print("☢️ ServiceLocator: Intercepted request, NEW: \(modifiedRequest.url?.absoluteString ?? "")")
}
}
}
override func stopLoading() {
sessionTask?.cancel()
}
}
// MARK: - URLSessionDataDelegate
extension NetworkURLProtocol: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
let policy = URLCache.StoragePolicy(rawValue: request.cachePolicy.rawValue) ?? .notAllowed
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: policy)
completionHandler(.allow)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
client?.urlProtocol(self, didFailWithError: error)
} else {
client?.urlProtocolDidFinishLoading(self)
}
}
func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
client?.urlProtocol(self, wasRedirectedTo: request, redirectResponse: response)
completionHandler(request)
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
guard let error = error else { return }
client?.urlProtocol(self, didFailWithError: error)
}
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let protectionSpace = challenge.protectionSpace
let sender = challenge.sender
if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let serverTrust = protectionSpace.serverTrust {
let credential = URLCredential(trust: serverTrust)
sender?.use(credential, for: challenge)
completionHandler(.useCredential, credential)
return
}
}
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
client?.urlProtocolDidFinishLoading(self)
}
}
|
mit
|
b18b6a314fbc95aa68665b442769530a
| 37.512195 | 114 | 0.646612 | 5.862624 | false | false | false | false |
SunLiner/Floral
|
Floral/Floral/Classes/Malls/Order/View/View/PayView/PayView.swift
|
1
|
5565
|
//
// PayView.swift
// Floral
//
// Created by ALin on 16/6/3.
// Copyright © 2016年 ALin. All rights reserved.
// 支付界面
import UIKit
class PayView: UIView {
/// 总价
var totalPrice : String?
{
didSet{
if let iPrice = totalPrice {
priceLabel.text = "¥" + iPrice
}
}
}
private var selectedPayItem : PayItemView?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static var g_self : PayView?
private func setup()
{
PayView.g_self = self
backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.4)
payView.backgroundColor = UIColor.whiteColor()
addSubview(payView)
payView.addSubview(needpayText)
payView.addSubview(priceLabel)
payView.addSubview(underLine)
payView.addSubview(weichat)
payView.addSubview(alipay)
payView.addSubview(entryPay)
payView.snp_makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(350)
}
needpayText.snp_makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(15)
}
priceLabel.snp_makeConstraints { (make) in
make.left.equalTo(needpayText.snp_right).offset(15)
make.top.equalTo(needpayText)
}
underLine.snp_makeConstraints { (make) in
make.top.equalTo(needpayText.snp_bottom).offset(5)
make.left.equalTo(needpayText)
make.right.equalTo(0)
make.height.equalTo(1)
}
alipay.snp_makeConstraints { (make) in
make.top.equalTo(underLine.snp_bottom).offset(5)
make.left.equalTo(needpayText)
make.right.equalTo(0)
make.height.equalTo(60)
}
weichat.snp_makeConstraints { (make) in
make.top.equalTo(alipay.snp_bottom).offset(5)
make.left.equalTo(alipay)
make.right.equalTo(0)
make.height.equalTo(60)
}
entryPay.snp_makeConstraints { (make) in
make.size.equalTo(CGSize(width: 278, height: 39))
make.centerX.equalTo(self)
make.bottom.equalTo(-20)
}
payView.transform = CGAffineTransformMakeTranslation(0, 350)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PayView.endAnim)))
}
// MARK: - 动画
/// 开始动画
func startAnim() {
UIView.animateWithDuration(0.5) {
self.payView.transform = CGAffineTransformIdentity
}
}
/// 结束动画
func endAnim() {
UIView.animateWithDuration(0.5, animations: {
self.payView.transform = CGAffineTransformMakeTranslation(0, 350)
}) { (_) in
self.removeFromSuperview()
}
}
// MARK: - 懒加载
/// 总视图
private lazy var payView = UIView()
/// "需支付"
private lazy var needpayText : UILabel = {
let text = UILabel(textColor: UIColor.blackColor(), font: defaultFont14)
text.text = "需支付:"
return text
}()
/// 价格
private lazy var priceLabel = UILabel(textColor: UIColor.orangeColor(), font: defaultFont14)
/// 下划线
private lazy var underLine = UIImageView(image: UIImage(named: "underLine"))
/// 支付宝
private lazy var alipay : PayItemView = {
let bao = PayItemView()
bao.payInfo = Pay(dict: ["icon" : UIImage(named:"f_alipay_26x26")!,
"title" : "支付宝支付",
"des" : "推荐有支付宝账号的用户使用"])
bao.selected = true
bao.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PayView.selectPayItem(_:))))
return bao
}()
/// 微信
private lazy var weichat : PayItemView = {
let wchat = PayItemView()
wchat.payInfo = Pay(dict: ["icon" : UIImage(named:"f_wechat_26x26")!,
"title" : "微信支付",
"des" : "推荐安装微信5.0及以上版本使用"])
wchat.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PayView.selectPayItem(_:))))
return wchat
}()
/// 确认支付
private lazy var entryPay = UIButton(title: nil, imageName: "f_okPay_278x39", target: g_self!, selector: #selector(PayView.entryBuy), font: nil, titleColor: nil)
// MARK: - 点击事件
/// 选择支付项
@objc private func selectPayItem(tap : UITapGestureRecognizer)
{
selectedPayItem = tap.view as? PayItemView
if tap.view! == weichat { // 选中微信
weichat.selected = true
alipay.selected = false
}else{
weichat.selected = false
alipay.selected = true
}
}
/// 点击确认支付
@objc private func entryBuy()
{
endAnim()
if selectedPayItem == weichat {
showErrorMessage("恭喜您使用微信支付了" + totalPrice! + "元")
}else{
showErrorMessage("恭喜您使用支付宝支付了" + totalPrice! + "元")
}
}
}
|
mit
|
e09a7aaf1ff5f5c157a4243b843a5a7f
| 28.40884 | 165 | 0.559083 | 4.142412 | false | false | false | false |
EstebanVallejo/sdk-ios
|
MercadoPagoSDK/MercadoPagoSDK/CardToken.swift
|
2
|
12155
|
//
// CardToken.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 31/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class CardToken : NSObject {
let MIN_LENGTH_NUMBER : Int = 10
let MAX_LENGTH_NUMBER : Int = 19
let now = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth, fromDate: NSDate())
public var cardNumber : String?
public var securityCode : String?
public var expirationMonth : Int = 0
public var expirationYear : Int = 0
public var cardholder : Cardholder?
public var device : Device?
public init (cardNumber: String?, expirationMonth: Int, expirationYear: Int,
securityCode: String?, cardholderName: String, docType: String, docNumber: String) {
super.init()
self.cardholder = Cardholder()
self.cardholder?.name = cardholderName
self.cardholder?.identification = Identification()
self.cardholder?.identification?.number = docNumber
self.cardholder?.identification?.type = docType
self.cardNumber = normalizeCardNumber(cardNumber)
self.expirationMonth = expirationMonth
self.expirationYear = normalizeYear(expirationYear)
self.securityCode = securityCode
}
public func normalizeCardNumber(number: String?) -> String? {
if number == nil {
return nil
}
return number!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).stringByReplacingOccurrencesOfString("\\s+|-", withString: "")
}
public func validate() -> Bool {
return validate(true)
}
public func validate(includeSecurityCode: Bool) -> Bool {
var result : Bool = validateCardNumber() == nil && validateExpiryDate() == nil && validateIdentification() == nil && validateCardholderName() == nil
if (includeSecurityCode) {
result = result && validateSecurityCode() == nil
}
return result
}
public func validateCardNumber() -> NSError? {
var userInfo : [String : String]?
if String.isNullOrEmpty(cardNumber) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["cardNumber" : "Ingresa el número de la tarjeta de crédito".localized])
} else if count(self.cardNumber!) < MIN_LENGTH_NUMBER || count(self.cardNumber!) > MAX_LENGTH_NUMBER {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["cardNumber" : "invalid_field".localized])
} else {
return nil
}
}
public func validateCardNumber(paymentMethod: PaymentMethod) -> NSError? {
var userInfo : [String : String]?
let validCardNumber = self.validateCardNumber()
if validCardNumber != nil {
return validCardNumber
} else {
let setting : Setting? = Setting.getSettingByBin(paymentMethod.settings, bin: getBin())
if setting == nil {
if userInfo == nil {
userInfo = [String : String]()
}
userInfo?.updateValue("El número de tarjeta que ingresaste no se corresponde con el tipo de tarjeta".localized, forKey: "cardNumber")
} else {
// Validate card length
if (count(cardNumber!) != setting?.cardNumber.length) {
if userInfo == nil {
userInfo = [String : String]()
}
userInfo?.updateValue(("invalid_card_length".localized as NSString).stringByReplacingOccurrencesOfString("%1$s", withString: "\(setting?.cardNumber.length)"), forKey: "cardNumber")
}
// Validate luhn
if "standard" == setting?.cardNumber.validation && !checkLuhn(cardNumber!) {
if userInfo == nil {
userInfo = [String : String]()
}
userInfo?.updateValue("El número de tarjeta que ingresaste es incorrecto".localized, forKey: "cardNumber")
}
}
}
if userInfo == nil {
return nil
} else {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: userInfo)
}
}
public func validateSecurityCode() -> NSError? {
return validateSecurityCode(securityCode)
}
public func validateSecurityCode(securityCode: String?) -> NSError? {
if String.isNullOrEmpty(self.securityCode) || count(self.securityCode!) < 3 || count(self.securityCode!) > 4 {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["securityCode" : "invalid_field".localized])
} else {
return nil
}
}
public func validateSecurityCodeWithPaymentMethod(paymentMethod: PaymentMethod) -> NSError? {
let validSecurityCode = self.validateSecurityCode(securityCode)
if validSecurityCode != nil {
return validSecurityCode
} else {
let range = Range(start: cardNumber!.startIndex,
end: advance(cardNumber!.startIndex, 6))
return validateSecurityCodeWithPaymentMethod(securityCode!, paymentMethod: paymentMethod, bin: cardNumber!.substringWithRange(range))
}
}
public func validateSecurityCodeWithPaymentMethod(securityCode: String, paymentMethod: PaymentMethod, bin: String) -> NSError? {
let setting : Setting? = Setting.getSettingByBin(paymentMethod.settings, bin: getBin())
// Validate security code length
let cvvLength = setting?.securityCode.length
if ((cvvLength != 0) && (count(securityCode) != cvvLength)) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["securityCode" : ("invalid_cvv_length".localized as NSString).stringByReplacingOccurrencesOfString("%1$s", withString: "\(cvvLength)")])
} else {
return nil
}
}
public func validateExpiryDate() -> NSError? {
return validateExpiryDate(expirationMonth, year: expirationYear)
}
public func validateExpiryDate(month: Int, year: Int) -> NSError? {
if !validateExpMonth(month) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["expiryDate" : "invalid_field".localized])
}
if !validateExpYear(year) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["expiryDate" : "invalid_field".localized])
}
if hasMonthPassed(self.expirationYear, month: self.expirationMonth) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["expiryDate" : "invalid_field".localized])
}
return nil
}
public func validateExpMonth(month: Int) -> Bool {
return (month >= 1 && month <= 12)
}
public func validateExpYear(year: Int) -> Bool {
return !hasYearPassed(year)
}
public func validateIdentification() -> NSError? {
let validType = validateIdentificationType()
if validType != nil {
return validType
} else {
let validNumber = validateIdentificationNumber()
if validNumber != nil {
return validNumber
}
}
return nil
}
public func validateIdentificationType() -> NSError? {
if String.isNullOrEmpty(cardholder!.identification!.type) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["identification" : "invalid_field".localized])
} else {
return nil
}
}
public func validateIdentificationNumber() -> NSError? {
if String.isNullOrEmpty(cardholder!.identification!.number) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["identification" : "invalid_field".localized])
} else {
return nil
}
}
public func validateIdentificationNumber(identificationType: IdentificationType?) -> NSError? {
if identificationType != nil {
if cardholder?.identification != nil && cardholder?.identification?.number != nil {
let len = count(cardholder!.identification!.number!)
let min = identificationType!.minLength
let max = identificationType!.maxLength
if min != 0 && max != 0 {
if len > max && len < min {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["identification" : "invalid_field".localized])
} else {
return nil
}
} else {
return validateIdentificationNumber()
}
} else {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["identification" : "invalid_field".localized])
}
} else {
return validateIdentificationNumber()
}
}
public func validateCardholderName() -> NSError? {
if String.isNullOrEmpty(self.cardholder?.name) {
return NSError(domain: "mercadopago.sdk.card.error", code: 1, userInfo: ["cardholder" : "invalid_field".localized])
} else {
return nil
}
}
public func hasYearPassed(year: Int) -> Bool {
let normalized : Int = normalizeYear(year)
return normalized < now.year
}
public func hasMonthPassed(year: Int, month: Int) -> Bool {
return hasYearPassed(year) || normalizeYear(year) == now.year && month < (now.month + 1)
}
public func normalizeYear(year: Int) -> Int {
if year < 100 && year >= 0 {
let currentYear : String = String(now.year)
let range = Range(start: currentYear.startIndex,
end: advance(currentYear.endIndex, -2))
let prefix : String = currentYear.substringWithRange(range)
return String(prefix + String(year)).toInt()!
}
return year
}
public func checkLuhn(cardNumber : String) -> Bool {
var sum : Int = 0
var alternate = false
if count(cardNumber) == 0 {
return false
}
for var index = (count(cardNumber)-1); index >= 0; index-- {
let range = NSRange(location: index, length: 1)
var s = cardNumber as NSString
s = s.substringWithRange(NSRange(location: index, length: 1))
var n : Int = s.integerValue
if (alternate)
{
n *= 2
if (n > 9)
{
n = (n % 10) + 1
}
}
sum += n
alternate = !alternate
}
return (sum % 10 == 0)
}
public func getBin() -> String? {
let range = Range(start: cardNumber!.startIndex, end: advance(cardNumber!.startIndex, 6))
var bin :String? = count(cardNumber!) >= 6 ? cardNumber!.substringWithRange(range) : nil
return bin
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"card_number": String.isNullOrEmpty(self.cardNumber) ? JSON.null : self.cardNumber!,
"security_code" : String.isNullOrEmpty(self.securityCode) ? JSON.null : self.securityCode!,
"expiration_month" : self.expirationMonth,
"expiration_year" : self.expirationYear,
"cardholder" : self.cardholder == nil ? JSON.null : JSON.parse(self.cardholder!.toJSONString()).mutableCopyOfTheObject(),
"device" : self.device == nil ? JSON.null : self.device!.toJSONString()
]
return JSON(obj).toString()
}
}
|
mit
|
6748261a69637f605de69f1d7f2dbe65
| 39.506667 | 221 | 0.583409 | 4.937424 | false | false | false | false |
Antondomashnev/Sourcery
|
SourceryTests/Stub/Performance-Code/Kiosk/App/Models/SaleArtworkViewModel.swift
|
2
|
5918
|
import Foundation
import RxSwift
private let kNoBidsString = ""
class SaleArtworkViewModel: NSObject {
fileprivate let saleArtwork: SaleArtwork
init (saleArtwork: SaleArtwork) {
self.saleArtwork = saleArtwork
}
}
// Extension for computed properties
extension SaleArtworkViewModel {
// MARK: Computed values we don't expect to ever change.
var estimateString: String {
// Default to estimateCents
switch (saleArtwork.estimateCents, saleArtwork.lowEstimateCents, saleArtwork.highEstimateCents) {
// Default to estimateCents.
case (.some(let estimateCents), _, _):
let dollars = NumberFormatter.currencyString(forDollarCents: estimateCents as NSNumber!)!
return "Estimate: \(dollars)"
// Try to extract non-nil low/high estimates.
case (_, .some(let lowCents), .some(let highCents)):
let lowDollars = NumberFormatter.currencyString(forDollarCents: lowCents as NSNumber!)!
let highDollars = NumberFormatter.currencyString(forDollarCents: highCents as NSNumber!)!
return "Estimate: \(lowDollars)–\(highDollars)"
default: return ""
}
}
var thumbnailURL: URL? {
return saleArtwork.artwork.defaultImage?.thumbnailURL() as URL?
}
var thumbnailAspectRatio: CGFloat? {
return saleArtwork.artwork.defaultImage?.aspectRatio
}
var artistName: String? {
return saleArtwork.artwork.artists?.first?.name
}
var titleAndDateAttributedString: NSAttributedString {
return saleArtwork.artwork.titleAndDate
}
var saleArtworkID: String {
return saleArtwork.id
}
// Observables representing values that change over time.
func numberOfBids() -> Observable<String> {
return saleArtwork.rx.observe(NSNumber.self, "bidCount").map { optionalBidCount -> String in
guard let bidCount = optionalBidCount, bidCount.intValue > 0 else {
return kNoBidsString
}
let suffix = bidCount == 1 ? "" : "s"
return "\(bidCount) bid\(suffix) placed"
}
}
// The language used here is very specific – see https://github.com/artsy/eidolon/pull/325#issuecomment-64121996 for details
var numberOfBidsWithReserve: Observable<String> {
// Ignoring highestBidCents; only there to trigger on bid update.
let highestBidString = saleArtwork.rx.observe(NSNumber.self, "highestBidCents").map { "\($0)" }
let reserveStatus = saleArtwork.rx.observe(String.self, "reserveStatus").map { input -> String in
switch input {
case .some(let reserveStatus):
return reserveStatus
default:
return ""
}
}
return Observable.combineLatest([numberOfBids(), reserveStatus, highestBidString]) { strings -> String in
let numberOfBidsString = strings[0]
let reserveStatus = ReserveStatus.initOrDefault(strings[1])
// if there is no reserve, just return the number of bids string.
if reserveStatus == .NoReserve {
return numberOfBidsString
} else {
if numberOfBidsString == kNoBidsString {
// If there are no bids, then return only this string.
return "This lot has a reserve"
} else if reserveStatus == .ReserveNotMet {
return "(\(numberOfBidsString), Reserve not met)"
} else { // implicitly, reserveStatus is .ReserveMet
return "(\(numberOfBidsString), Reserve met)"
}
}
}
}
func lotNumber() -> Observable<String?> {
return saleArtwork.rx.observe(NSNumber.self, "lotNumber").map { lotNumber in
if let lotNumber = lotNumber as? Int {
return "Lot \(lotNumber)"
} else {
return ""
}
}
}
func forSale() -> Observable<Bool> {
return saleArtwork.artwork.rx.observe(String.self, "soldStatus").filterNil().map { status in
return Artwork.SoldStatus.fromString(status) == .notSold
}
}
func currentBid(prefix: String = "", missingPrefix: String = "") -> Observable<String> {
return saleArtwork.rx.observe(NSNumber.self, "highestBidCents").map { [weak self] highestBidCents in
if let currentBidCents = highestBidCents as? Int {
let formatted = NumberFormatter.currencyString(forDollarCents: currentBidCents as NSNumber) ?? ""
return "\(prefix)\(formatted)"
} else {
let formatted = NumberFormatter.currencyString(forDollarCents: self?.saleArtwork.openingBidCents ?? 0) ?? ""
return "\(missingPrefix)\(formatted)"
}
}
}
func currentBidOrOpeningBid() -> Observable<String> {
let observables = [
saleArtwork.rx.observe(NSNumber.self, "bidCount"),
saleArtwork.rx.observe(NSNumber.self, "openingBidCents"),
saleArtwork.rx.observe(NSNumber.self, "highestBidCents")
]
return Observable.combineLatest(observables) { numbers -> Int in
let bidCount = (numbers[0] ?? 0) as Int
let openingBid = numbers[1] as Int?
let highestBid = numbers[2] as Int?
return (bidCount > 0 ? highestBid : openingBid) ?? 0
}.map(centsToPresentableDollarsString)
}
func currentBidOrOpeningBidLabel() -> Observable<String> {
return saleArtwork.rx.observe(NSNumber.self, "bidCount").map { input in
guard let count = input as? Int else { return "" }
if count > 0 {
return "Current Bid:"
} else {
return "Opening Bid:"
}
}
}
}
|
mit
|
403d74a1a25fd1ad07695eb7be22669d
| 35.506173 | 128 | 0.606696 | 5.033191 | false | false | false | false |
vanshg/MacAssistant
|
Pods/KeyHolder/Lib/KeyHolder/RecordView.swift
|
1
|
15126
|
//
// RecordView.swift
//
// KeyHolder
// GitHub: https://github.com/clipy
// HP: https://clipy-app.com
//
// Created by Econa77 on 2016/06/17.
//
// Copyright © 2016-2018 Clipy Project.
//
import Cocoa
import Carbon
import Magnet
public protocol RecordViewDelegate: class {
func recordViewShouldBeginRecording(_ recordView: RecordView) -> Bool
func recordView(_ recordView: RecordView, canRecordKeyCombo keyCombo: KeyCombo) -> Bool
func recordViewDidClearShortcut(_ recordView: RecordView)
func recordView(_ recordView: RecordView, didChangeKeyCombo keyCombo: KeyCombo)
func recordViewDidEndRecording(_ recordView: RecordView)
}
@IBDesignable open class RecordView: NSView {
// MARK: - Properties
@IBInspectable open var backgroundColor: NSColor = .white {
didSet { needsDisplay = true }
}
@IBInspectable open var tintColor: NSColor = .controlAccentPolyfill {
didSet { needsDisplay = true }
}
@IBInspectable open var borderColor: NSColor = .white {
didSet { layer?.borderColor = borderColor.cgColor }
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet { layer?.borderWidth = borderWidth }
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer?.cornerRadius = cornerRadius
needsDisplay = true
noteFocusRingMaskChanged()
}
}
@IBInspectable open var showsClearButton: Bool = true {
didSet { needsDisplay = true }
}
open weak var delegate: RecordViewDelegate?
open var didChange: ((KeyCombo?) -> Void)?
open var isRecording = false
open var keyCombo: KeyCombo? {
didSet { needsDisplay = true }
}
open var isEnabled = true {
didSet {
needsDisplay = true
if !isEnabled { endRecording() }
noteFocusRingMaskChanged()
}
}
fileprivate let clearButton = NSButton()
fileprivate let clearNormalImage = Util.bundleImage(name: "clear-off")
fileprivate let clearAlternateImage = Util.bundleImage(name: "clear-on")
fileprivate let validModifiers: [NSEvent.ModifierFlags] = [.shift, .control, .option, .command]
fileprivate let validModifiersText: [NSString] = ["⇧", "⌃", "⌥", "⌘"]
fileprivate var inputModifiers = NSEvent.ModifierFlags(rawValue: 0)
fileprivate var doubleTapModifier = NSEvent.ModifierFlags(rawValue: 0)
fileprivate var multiModifiers = false
fileprivate var fontSize: CGFloat {
return bounds.height / 1.7
}
fileprivate var clearSize: CGFloat {
return fontSize / 1.3
}
fileprivate var marginY: CGFloat {
return (bounds.height - fontSize) / 2.6
}
fileprivate var marginX: CGFloat {
return marginY * 1.5
}
// MARK: - Override Properties
open override var isOpaque: Bool {
return false
}
open override var isFlipped: Bool {
return true
}
open override var focusRingMaskBounds: NSRect {
return (isEnabled && window?.firstResponder == self) ? bounds : NSRect.zero
}
// MARK: - Initialize
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
initView()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initView()
}
fileprivate func initView() {
clearButton.bezelStyle = .shadowlessSquare
clearButton.setButtonType(.momentaryChange)
clearButton.isBordered = false
clearButton.title = ""
clearButton.target = self
clearButton.action = #selector(RecordView.clearAndEndRecording)
addSubview(clearButton)
}
// MARK: - Draw
open override func drawFocusRingMask() {
if isEnabled && window?.firstResponder == self {
NSBezierPath(roundedRect: bounds, xRadius: cornerRadius, yRadius: cornerRadius).fill()
}
}
override open func draw(_ dirtyRect: NSRect) {
drawBackground(dirtyRect)
drawModifiers(dirtyRect)
drawKeyCode(dirtyRect)
drawClearButton(dirtyRect)
}
fileprivate func drawBackground(_ dirtyRect: NSRect) {
backgroundColor.setFill()
NSBezierPath(roundedRect: bounds, xRadius: cornerRadius, yRadius: cornerRadius).fill()
let rect = NSRect(x: borderWidth / 2, y: borderWidth / 2, width: bounds.width - borderWidth, height: bounds.height - borderWidth)
let path = NSBezierPath(roundedRect: rect, xRadius: cornerRadius, yRadius: cornerRadius)
path.lineWidth = borderWidth
borderColor.set()
path.stroke()
}
fileprivate func drawModifiers(_ dirtyRect: NSRect) {
let fontSize = self.fontSize
let modifiers: NSEvent.ModifierFlags
if let keyCombo = self.keyCombo {
modifiers = KeyTransformer.cocoaFlags(from: keyCombo.modifiers)
} else {
modifiers = inputModifiers
}
for (i, text) in validModifiersText.enumerated() {
let rect = NSRect(x: marginX + (fontSize * CGFloat(i)), y: marginY, width: fontSize, height: bounds.height)
text.draw(in: rect, withAttributes: modifierTextAttributes(modifiers, checkModifier: validModifiers[i]))
}
}
fileprivate func drawKeyCode(_ dirtyRext: NSRect) {
guard let keyCombo = self.keyCombo else { return }
let fontSize = self.fontSize
let minX = (fontSize * 4) + (marginX * 2)
let width = bounds.width - minX - (marginX * 2) - clearSize
if width <= 0 { return }
let text = (keyCombo.doubledModifiers) ? "double tap" : keyCombo.characters
text.draw(in: NSRect(x: minX, y: marginY, width: width, height: bounds.height), withAttributes: keyCodeTextAttributes())
}
fileprivate func drawClearButton(_ dirtyRext: NSRect) {
let clearSize = self.clearSize
clearNormalImage?.size = CGSize(width: clearSize, height: clearSize)
clearAlternateImage?.size = CGSize(width: clearSize, height: clearSize)
clearButton.image = clearNormalImage
clearButton.alternateImage = clearAlternateImage
let x = bounds.width - clearSize - marginX
let y = (bounds.height - clearSize) / 2
clearButton.frame = NSRect(x: x, y: y, width: clearSize, height: clearSize)
clearButton.isHidden = !showsClearButton
}
// MARK: - NSResponder
override open var acceptsFirstResponder: Bool {
return isEnabled
}
override open var canBecomeKeyView: Bool {
return super.canBecomeKeyView && NSApp.isFullKeyboardAccessEnabled
}
override open var needsPanelToBecomeKey: Bool {
return true
}
override open func resignFirstResponder() -> Bool {
endRecording()
return super.resignFirstResponder()
}
override open func acceptsFirstMouse(for theEvent: NSEvent?) -> Bool {
return true
}
override open func mouseDown(with theEvent: NSEvent) {
if !isEnabled {
super.mouseDown(with: theEvent)
return
}
let locationInView = convert(theEvent.locationInWindow, from: nil)
if isMousePoint(locationInView, in: bounds) && !isRecording {
_ = beginRecording()
} else {
super.mouseDown(with: theEvent)
}
}
open override func cancelOperation(_ sender: Any?) {
endRecording()
}
override open func keyDown(with theEvent: NSEvent) {
if !performKeyEquivalent(with: theEvent) { super.keyDown(with: theEvent) }
}
override open func performKeyEquivalent(with theEvent: NSEvent) -> Bool {
if !isEnabled { return false }
if window?.firstResponder != self { return false }
let keyCodeInt = Int(theEvent.keyCode)
if isRecording && validateModifiers(inputModifiers) {
let modifiers = KeyTransformer.carbonFlags(from: theEvent.modifierFlags)
if let keyCombo = KeyCombo(keyCode: keyCodeInt, carbonModifiers: modifiers) {
if delegate?.recordView(self, canRecordKeyCombo: keyCombo) ?? true {
self.keyCombo = keyCombo
didChange?(keyCombo)
delegate?.recordView(self, didChangeKeyCombo: keyCombo)
endRecording()
return true
}
}
return false
} else if isRecording && KeyTransformer.containsFunctionKey(keyCodeInt) {
if let keyCombo = KeyCombo(keyCode: keyCodeInt, carbonModifiers: 0) {
if delegate?.recordView(self, canRecordKeyCombo: keyCombo) ?? true {
self.keyCombo = keyCombo
didChange?(keyCombo)
delegate?.recordView(self, didChangeKeyCombo: keyCombo)
endRecording()
return true
}
}
return false
} else if Int(theEvent.keyCode) == kVK_Space {
return beginRecording()
}
return false
}
override open func flagsChanged(with theEvent: NSEvent) {
if isRecording {
inputModifiers = theEvent.modifierFlags
needsDisplay = true
// For dobule tap
let commandTapped = inputModifiers.contains(.command)
let shiftTapped = inputModifiers.contains(.shift)
let controlTapped = inputModifiers.contains(.control)
let optionTapped = inputModifiers.contains(.option)
let totalHash = commandTapped.intValue + optionTapped.intValue + shiftTapped.intValue + controlTapped.intValue
if totalHash > 1 {
multiModifiers = true
return
}
if multiModifiers || totalHash == 0 {
multiModifiers = false
return
}
if (doubleTapModifier.contains(.command) && commandTapped) ||
(doubleTapModifier.contains(.shift) && shiftTapped) ||
(doubleTapModifier.contains(.control) && controlTapped) ||
(doubleTapModifier.contains(.option) && optionTapped) {
if let keyCombo = KeyCombo(doubledCocoaModifiers: doubleTapModifier) {
if delegate?.recordView(self, canRecordKeyCombo: keyCombo) ?? true {
self.keyCombo = keyCombo
didChange?(keyCombo)
delegate?.recordView(self, didChangeKeyCombo: keyCombo)
endRecording()
}
}
doubleTapModifier = NSEvent.ModifierFlags(rawValue: 0)
} else {
if commandTapped {
doubleTapModifier = .command
} else if shiftTapped {
doubleTapModifier = .shift
} else if controlTapped {
doubleTapModifier = .control
} else if optionTapped {
doubleTapModifier = .option
} else {
doubleTapModifier = NSEvent.ModifierFlags(rawValue: 0)
}
}
// Clean Flag
let delay = 0.3 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: { [weak self] in
self?.doubleTapModifier = NSEvent.ModifierFlags(rawValue: 0)
})
} else {
inputModifiers = NSEvent.ModifierFlags(rawValue: 0)
}
super.flagsChanged(with: theEvent)
}
}
// MARK: - Text Attributes
private extension RecordView {
func modifierTextAttributes(_ modifiers: NSEvent.ModifierFlags, checkModifier: NSEvent.ModifierFlags) -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.baseWritingDirection = .leftToRight
let textColor: NSColor
if !isEnabled {
textColor = .disabledControlTextColor
} else if modifiers.contains(checkModifier) {
textColor = tintColor
} else {
textColor = .lightGray
}
return [.font: NSFont.systemFont(ofSize: floor(fontSize)),
.foregroundColor: textColor,
.paragraphStyle: paragraphStyle]
}
func keyCodeTextAttributes() -> [NSAttributedString.Key: Any] {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.baseWritingDirection = .leftToRight
return [.font: NSFont.systemFont(ofSize: floor(fontSize)),
.foregroundColor: tintColor,
.paragraphStyle: paragraphStyle]
}
}
// MARK: - Recording
public extension RecordView {
public func beginRecording() -> Bool {
if !isEnabled { return false }
if isRecording { return true }
needsDisplay = true
if let delegate = delegate , !delegate.recordViewShouldBeginRecording(self) {
NSSound.beep()
return false
}
willChangeValue(forKey: "recording")
isRecording = true
didChangeValue(forKey: "recording")
updateTrackingAreas()
return true
}
public func endRecording() {
if !isRecording { return }
inputModifiers = NSEvent.ModifierFlags(rawValue: 0)
doubleTapModifier = NSEvent.ModifierFlags(rawValue: 0)
multiModifiers = false
willChangeValue(forKey: "recording")
isRecording = false
didChangeValue(forKey: "recording")
updateTrackingAreas()
needsDisplay = true
if window?.firstResponder == self && !canBecomeKeyView { window?.makeFirstResponder(nil) }
delegate?.recordViewDidEndRecording(self)
}
}
// MARK: - Clear Keys
public extension RecordView {
public func clear() {
keyCombo = nil
inputModifiers = NSEvent.ModifierFlags(rawValue: 0)
needsDisplay = true
didChange?(nil)
delegate?.recordViewDidClearShortcut(self)
}
@objc public func clearAndEndRecording() {
clear()
endRecording()
}
}
// MARK: - Modifiers
private extension RecordView {
func validateModifiers(_ modifiers: NSEvent.ModifierFlags?) -> Bool {
guard let modifiers = modifiers else { return false }
return KeyTransformer.carbonFlags(from: modifiers) != 0
}
}
// MARK: - Bool Extension
private extension Bool {
var intValue: Int {
return NSNumber(value: self).intValue
}
}
// MARK: - NSColor Extensio
// nmacOS 10.14 polyfill
private extension NSColor {
static let controlAccentPolyfill: NSColor = {
if #available(macOS 10.14, *) {
return NSColor.controlAccentColor
} else {
return NSColor(red: 0.10, green: 0.47, blue: 0.98, alpha: 1)
}
}()
}
|
mit
|
edf0157697b0f726d857b18ba1f31cc0
| 33.993056 | 140 | 0.61798 | 5.017259 | false | false | false | false |
cojoj/DVR
|
DVR/SessionDownloadTask.swift
|
1
|
1213
|
class SessionDownloadTask: NSURLSessionDownloadTask {
// MARK: - Types
typealias Completion = (NSURL?, NSURLResponse?, NSError?) -> Void
// MARK: - Properties
weak var session: Session!
let request: NSURLRequest
let completion: Completion?
// MARK: - Initializers
init(session: Session, request: NSURLRequest, completion: Completion? = nil) {
self.session = session
self.request = request
self.completion = completion
}
// MARK: - NSURLSessionTask
override func cancel() {
// Don't do anything
}
override func resume() {
let task = SessionDataTask(session: session, request: request) { data, response, error in
let location: NSURL?
if let data = data {
// Write data to temporary file
let tempURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent(NSUUID().UUIDString))
data.writeToURL(tempURL, atomically: true)
location = tempURL
} else {
location = nil
}
self.completion?(location, response, error)
}
task.resume()
}
}
|
mit
|
cfc5b70a51b4b7c2c87ed153a8b289b3
| 26.568182 | 128 | 0.592745 | 5.343612 | false | false | false | false |
fhisa/SwiftLearnTalk
|
20150606/swift_spec.swift
|
1
|
2088
|
/**
Swift用のBDDライブラリ Quick による振舞いの記述例
このコードの前半部分でプログラムした2種類のSwiftクラスの振舞いを
後半部分(describe('Swift') の行以降)でRSpecを使って定義しています。
後半部分は振舞いを記述するためのDSL(Domain Specific Language)
として見ることができます。
*/
/****** 以下、2種類のSwiftクラスのプログラム(RSpecで振舞い定義の対象) ******/
/// 生物学上のSwiftクラス
class Biology {
class Swift {
let description: String
init() {
description = "a kind of swallow"
}
}
}
/// ソフトウェア技術上のSwiftクラス
class SoftwareTechnology {
class Swift {
let description: String
init() {
description = "a programming language"
}
}
}
/****** 以下、RSpecでの振舞い定義 ******/
import Quick
import Nimble
class SwiftSpec: QuickSpec {
override func spec() {
describe("Swift") {
var biological_description: String!
var software_technological_description: String!
beforeEach {
biological_description = "a kind of swallow"
software_technological_description = "a programming language"
}
context("Biology") {
var swift: Biology.Swift!
beforeEach { swift = Biology.Swift() }
it("is \(biological_description)") {
expect(swift.description).to(equal(biological_description))
}
it("is not \(software_technological_description)") {
expect(@swift.description).toNot(equal(software_technological_description))
}
}
context("SoftwareTechnology") {
var swift: SoftwareTechnology.Swift!
beforeEach { swift = SoftwareTechnology.Swift() }
it("is not \(biological_description)") {
expect(swift.description).toNot(equal(biological_description))
}
it("is \(software_technological_description)") {
expect(@swift.description).to(equal(software_technological_description))
}
}
}
}
}
|
mit
|
55d3615496a51e4115c010335d94af55
| 22.76 | 85 | 0.64422 | 3.36862 | false | false | false | false |
wjk/MacBond
|
MacBond/Bond.swift
|
1
|
7239
|
//
// Bond.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// MARK: Helpers
public class BondBox<T> {
weak var bond: Bond<T>?
public init(_ b: Bond<T>) { bond = b }
}
// MARK: - Scalar Dynamic
// MARK: Bond
public class Bond<T> {
public typealias Listener = T -> Void
public var listener: Listener?
public var bondedDynamics: [Dynamic<T>] = []
public init() {
}
public init(_ listener: Listener) {
self.listener = listener
}
public func bind(dynamic: Dynamic<T>, fire: Bool = true) {
dynamic.bonds.append(BondBox(self))
self.bondedDynamics.append(dynamic)
if fire {
self.listener?(dynamic.value)
}
}
public func unbindAll() {
for dynamic in bondedDynamics {
var bondsToKeep: [BondBox<T>] = []
for bondBox in dynamic.bonds {
if let bond = bondBox.bond {
if bond !== self {
bondsToKeep.append(bondBox)
} else {
}
}
}
dynamic.bonds = bondsToKeep
}
self.bondedDynamics.removeAll(keepCapacity: true)
}
}
// MARK: Dynamic
public class Dynamic<T> {
public var value: T {
didSet {
// clear weak bonds
bonds = bonds.filter {
bondBox in bondBox.bond != nil
}
// notify
for bondBox in bonds {
bondBox.bond?.listener?(value)
}
}
}
public var bonds: [BondBox<T>] = []
public init(_ v: T) {
value = v
}
}
// MARK: Dynamic additions
public extension Dynamic
{
public func map<U>(f: T -> U) -> Dynamic<U> {
return _map(self, f)
}
public func filter(f: T -> Bool) -> Dynamic<T> {
return _filter(self, f)
}
}
// MARK: Protocols
public protocol Dynamical {
typealias DynamicType
func designatedDynamic() -> Dynamic<DynamicType>
}
public protocol Bondable {
typealias BondType
var designatedBond: Bond<BondType> { get }
}
// MARK: - Functional paradigm
public class DynamicExtended<T>: Dynamic<T> {
public override init(_ v: T) {
super.init(v)
}
internal var retainedObjects: [AnyObject] = []
internal func retain(object: AnyObject) {
retainedObjects.append(object)
}
}
// MARK: Map
public func map<T, U>(dynamic: Dynamic<T>, f: T -> U) -> Dynamic<U> {
return _map(dynamic, f)
}
public func map<S: Dynamical, T, U where S.DynamicType == T>(dynamical: S, f: T -> U) -> Dynamic<U> {
return _map(dynamical.designatedDynamic(), f)
}
private func _map<T, U>(dynamic: Dynamic<T>, f: T -> U) -> Dynamic<U> {
let dyn = DynamicExtended<U>(f(dynamic.value))
let bond = Bond<T> { [unowned dyn] t in dyn.value = f(t) }
bond.bind(dynamic)
dyn.retain(bond)
return dyn
}
// MARK: Filter
public func filter<T>(dynamic: Dynamic<T>, f: T -> Bool) -> Dynamic<T> {
return _filter(dynamic, f)
}
public func map<S: Dynamical, T where S.DynamicType == T>(dynamical: S, f: T -> Bool) -> Dynamic<T> {
return _filter(dynamical.designatedDynamic(), f)
}
private func _filter<T>(dynamic: Dynamic<T>, f: T -> Bool) -> Dynamic<T> {
let dyn = DynamicExtended<T>(dynamic.value) // TODO FIX INITAL
let bond = Bond<T> { [unowned dyn] t in if f(t) { dyn.value = t } }
bond.bind(dynamic)
dyn.retain(bond)
return dyn
}
// MARK: Reduce
public func reduce<A, B, T>(dA: Dynamic<A>, dB: Dynamic<B>, v0: T, f: (A, B) -> T) -> Dynamic<T> {
return _reduce(dA, dB, v0, f)
}
public func reduce<A, B, C, T>(dA: Dynamic<A>, dB: Dynamic<B>, dC: Dynamic<C>, v0: T, f: (A, B, C) -> T) -> Dynamic<T> {
return _reduce(dA, dB, dC, v0, f)
}
public func _reduce<A, B, T>(dA: Dynamic<A>, dB: Dynamic<B>, v0: T, f: (A, B) -> T) -> Dynamic<T> {
let dyn = DynamicExtended<T>(v0)
let bA = Bond<A> { [unowned dyn, weak dB] in
if let dB = dB { dyn.value = f($0, dB.value) }
}
let bB = Bond<B> { [unowned dyn, weak dA] in
if let dA = dA { dyn.value = f(dA.value, $0) }
}
bA.bind(dA)
bB.bind(dB)
dyn.retain(bA)
dyn.retain(bB)
return dyn
}
public func _reduce<A, B, C, T>(dA: Dynamic<A>, dB: Dynamic<B>, dC: Dynamic<C>, v0: T, f: (A, B, C) -> T) -> Dynamic<T> {
let dyn = DynamicExtended<T>(v0)
let bA = Bond<A> { [unowned dyn, weak dB, weak dC] in
if let dB = dB { if let dC = dC { dyn.value = f($0, dB.value, dC.value) } }
}
let bB = Bond<B> { [unowned dyn, weak dA, weak dC] in
if let dA = dA { if let dC = dC { dyn.value = f(dA.value, $0, dC.value) } }
}
let bC = Bond<C> { [unowned dyn, weak dA, weak dB] in
if let dA = dA { if let dB = dB { dyn.value = f(dA.value, dB.value, $0) } }
}
bA.bind(dA)
bB.bind(dB)
bC.bind(dC)
dyn.retain(bA)
dyn.retain(bB)
dyn.retain(bC)
return dyn
}
// MARK: Operators
// Bind and fire
infix operator ->> { associativity left precedence 105 }
public func ->> <T>(left: Dynamic<T>, right: Bond<T>) {
right.bind(left)
}
public func ->> <T>(left: Dynamic<T>, right: T -> Void) -> Bond<T> {
let bond = Bond<T>(right)
bond.bind(left)
return bond
}
public func ->> <T: Dynamical, U where T.DynamicType == U>(left: T, right: Bond<U>) {
left.designatedDynamic() ->> right
}
public func ->> <T: Dynamical, U: Bondable where T.DynamicType == U.BondType>(left: T, right: U) {
left.designatedDynamic() ->> right.designatedBond
}
public func ->> <T, U: Bondable where U.BondType == T>(left: Dynamic<T>, right: U) {
left ->> right.designatedBond
}
// Bind only
infix operator ->| { associativity left precedence 105 }
public func ->| <T>(left: Dynamic<T>, right: Bond<T>) {
right.bind(left, fire: false)
}
public func ->| <T>(left: Dynamic<T>, right: T -> Void) -> Bond<T> {
let bond = Bond<T>(right)
bond.bind(left, fire: false)
return bond
}
public func ->| <T: Dynamical, U where T.DynamicType == U>(left: T, right: Bond<U>) {
left.designatedDynamic() ->| right
}
public func ->| <T: Dynamical, U: Bondable where T.DynamicType == U.BondType>(left: T, right: U) {
left.designatedDynamic() ->| right.designatedBond
}
public func ->| <T, U: Bondable where U.BondType == T>(left: Dynamic<T>, right: U) {
left ->| right.designatedBond
}
|
mit
|
5b642e6afd7a715994cdf72c9f476498
| 24.048443 | 121 | 0.6226 | 3.114888 | false | false | false | false |
oliverkulpakko/ATMs
|
ATMs/View/Controllers/SettingsViewController.swift
|
1
|
2633
|
//
// SettingsViewController.swift
// ATMs
//
// Created by Oliver Kulpakko on 15/09/2018.
// Copyright © 2018 East Studios. All rights reserved.
//
import UIKit
import AcknowList
class SettingsViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "settings.title".localized
supportLabel.text = "settings.contactSupport".localized
acknowledgementsLabel.text = "acknowledgements.title".localized
thresholdSlider.setValue(UserDefaults.standard.float(forKey: "NearbyThreshold") / 100_000, animated: false)
}
@IBAction func done(_ sender: Any) {
UserDefaults.standard.set(Float(thresholdSlider.value * 100_000), forKey: "NearbyThreshold")
dismiss(animated: true, completion: nil)
}
// MARK: IBOutlets
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var thresholdMinimumValueLabel: UILabel!
@IBOutlet var thresholdSlider: UISlider!
@IBOutlet var thresholdMaximumValueLabel: UILabel!
@IBOutlet var supportLabel: UILabel!
@IBOutlet var acknowledgementsLabel: UILabel!
// MARK: Enums
enum Section: CaseIterable {
case threshold
case support
}
enum SupportItem: CaseIterable {
case contactSupport
case toAcknowledgements
}
}
extension SettingsViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section.allCases[section] {
case .threshold:
return "settings.nearbyThresholdTitle".localized
default:
return nil
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section.allCases[section] {
case .threshold:
return "settings.nearbyThresholdFooterTitle".localized
case .support:
let year = Calendar.current.component(.year, from: Date())
return String(format: "© Oliver Kulpakko 2015 - %i, %@ (%@)",
year,
UIApplication.shared.version,
UIApplication.shared.build)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch Section.allCases[indexPath.section] {
case .support:
switch SupportItem.allCases[indexPath.row] {
case .contactSupport:
if let url = URL(string: "mailto:[email protected]") {
UIApplication.shared.openURL(url)
}
case .toAcknowledgements:
let viewController = AcknowListViewController()
viewController.title = "acknowledgements.title".localized
navigationController?.pushViewController(viewController, animated: true)
}
default:
break
}
}
}
|
mit
|
83592b18b5e89646847cc1bdcefb5536
| 25.846939 | 109 | 0.736222 | 4.047692 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceComponents/Tests/EventDetailComponentTests/View Model Tests/WhenPreparingViewModel_ForEventWithKage_EventDetailViewModelFactoryShould.swift
|
1
|
782
|
import EurofurenceModel
import EventDetailComponent
import XCTest
import XCTEurofurenceModel
class WhenPreparingViewModel_ForEventWithKage_EventDetailViewModelFactoryShould: XCTestCase {
func testProduceKageHeadingAfterDescriptionComponent() {
let event = FakeEvent.randomStandardEvent
event.isKageEvent = true
let context = EventDetailViewModelFactoryTestBuilder().build(for: event)
let visitor = context.prepareVisitorForTesting()
let expected = EventKageMessageViewModel(message: "May contain traces of cockroach and wine")
XCTAssertEqual(expected, visitor.visited(ofKind: EventKageMessageViewModel.self))
XCTAssertTrue(visitor.does(EventKageMessageViewModel.self, precede: EventDescriptionViewModel.self))
}
}
|
mit
|
5ba4ad25d822bd7d69fa1eed0749a2c8
| 40.157895 | 108 | 0.789003 | 5.356164 | false | true | false | false |
ashfurrow/FunctionalReactiveAwesome
|
Pods/RxCocoa/RxCocoa/RxCocoa/Common/ControlTarget.swift
|
1
|
2074
|
//
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
#if os(iOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(OSX)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: NSObject, Disposable {
typealias Callback = (Control) -> Void
let selector: Selector = "eventHandler:"
let control: Control
#if os(iOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS)
init(control: Control, controlEvents: UIControlEvents, callback: Callback) {
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, forControlEvents: controlEvents)
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(OSX)
init(control: Control, callback: Callback) {
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.methodForSelector(selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(sender: Control!) {
if let callback = self.callback {
callback(self.control)
}
}
func dispose() {
MainScheduler.ensureExecutingOnScheduler()
#if os(iOS)
self.control.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents)
#elseif os(OSX)
self.control.target = nil
self.control.action = nil
#endif
self.callback = nil
}
deinit {
dispose()
}
}
|
mit
|
4411ebb1e9090dd49e3e1f94ccfebf4a
| 22.579545 | 100 | 0.61379 | 4.671171 | false | false | false | false |
nhatminh12369/LineChart
|
LineChart/LineChart.swift
|
1
|
12344
|
//
// LineChart.swift
// LineChart
//
// Created by Nguyen Vu Nhat Minh on 25/8/17.
// Copyright © 2017 Nguyen Vu Nhat Minh. All rights reserved.
//
import UIKit
struct PointEntry {
let value: Int
let label: String
}
extension PointEntry: Comparable {
static func <(lhs: PointEntry, rhs: PointEntry) -> Bool {
return lhs.value < rhs.value
}
static func ==(lhs: PointEntry, rhs: PointEntry) -> Bool {
return lhs.value == rhs.value
}
}
class LineChart: UIView {
/// gap between each point
let lineGap: CGFloat = 60.0
/// preseved space at top of the chart
let topSpace: CGFloat = 40.0
/// preserved space at bottom of the chart to show labels along the Y axis
let bottomSpace: CGFloat = 40.0
/// The top most horizontal line in the chart will be 10% higher than the highest value in the chart
let topHorizontalLine: CGFloat = 110.0 / 100.0
var isCurved: Bool = false
/// Active or desactive animation on dots
var animateDots: Bool = false
/// Active or desactive dots
var showDots: Bool = false
/// Dot inner Radius
var innerRadius: CGFloat = 8
/// Dot outer Radius
var outerRadius: CGFloat = 12
var dataEntries: [PointEntry]? {
didSet {
self.setNeedsLayout()
}
}
/// Contains the main line which represents the data
private let dataLayer: CALayer = CALayer()
/// To show the gradient below the main line
private let gradientLayer: CAGradientLayer = CAGradientLayer()
/// Contains dataLayer and gradientLayer
private let mainLayer: CALayer = CALayer()
/// Contains mainLayer and label for each data entry
private let scrollView: UIScrollView = UIScrollView()
/// Contains horizontal lines
private let gridLayer: CALayer = CALayer()
/// An array of CGPoint on dataLayer coordinate system that the main line will go through. These points will be calculated from dataEntries array
private var dataPoints: [CGPoint]?
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
convenience init() {
self.init(frame: CGRect.zero)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
mainLayer.addSublayer(dataLayer)
scrollView.layer.addSublayer(mainLayer)
gradientLayer.colors = [#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7).cgColor, UIColor.clear.cgColor]
scrollView.layer.addSublayer(gradientLayer)
self.layer.addSublayer(gridLayer)
self.addSubview(scrollView)
self.backgroundColor = #colorLiteral(red: 0, green: 0.3529411765, blue: 0.6156862745, alpha: 1)
}
override func layoutSubviews() {
scrollView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
if let dataEntries = dataEntries {
scrollView.contentSize = CGSize(width: CGFloat(dataEntries.count) * lineGap, height: self.frame.size.height)
mainLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(dataEntries.count) * lineGap, height: self.frame.size.height)
dataLayer.frame = CGRect(x: 0, y: topSpace, width: mainLayer.frame.width, height: mainLayer.frame.height - topSpace - bottomSpace)
gradientLayer.frame = dataLayer.frame
dataPoints = convertDataEntriesToPoints(entries: dataEntries)
gridLayer.frame = CGRect(x: 0, y: topSpace, width: self.frame.width, height: mainLayer.frame.height - topSpace - bottomSpace)
if showDots { drawDots() }
clean()
drawHorizontalLines()
if isCurved {
drawCurvedChart()
} else {
drawChart()
}
maskGradientLayer()
drawLables()
}
}
/**
Convert an array of PointEntry to an array of CGPoint on dataLayer coordinate system
*/
private func convertDataEntriesToPoints(entries: [PointEntry]) -> [CGPoint] {
if let max = entries.max()?.value,
let min = entries.min()?.value {
var result: [CGPoint] = []
let minMaxRange: CGFloat = CGFloat(max - min) * topHorizontalLine
for i in 0..<entries.count {
let height = dataLayer.frame.height * (1 - ((CGFloat(entries[i].value) - CGFloat(min)) / minMaxRange))
let point = CGPoint(x: CGFloat(i)*lineGap + 40, y: height)
result.append(point)
}
return result
}
return []
}
/**
Draw a zigzag line connecting all points in dataPoints
*/
private func drawChart() {
if let dataPoints = dataPoints,
dataPoints.count > 0,
let path = createPath() {
let lineLayer = CAShapeLayer()
lineLayer.path = path.cgPath
lineLayer.strokeColor = UIColor.white.cgColor
lineLayer.fillColor = UIColor.clear.cgColor
dataLayer.addSublayer(lineLayer)
}
}
/**
Create a zigzag bezier path that connects all points in dataPoints
*/
private func createPath() -> UIBezierPath? {
guard let dataPoints = dataPoints, dataPoints.count > 0 else {
return nil
}
let path = UIBezierPath()
path.move(to: dataPoints[0])
for i in 1..<dataPoints.count {
path.addLine(to: dataPoints[i])
}
return path
}
/**
Draw a curved line connecting all points in dataPoints
*/
private func drawCurvedChart() {
guard let dataPoints = dataPoints, dataPoints.count > 0 else {
return
}
if let path = CurveAlgorithm.shared.createCurvedPath(dataPoints) {
let lineLayer = CAShapeLayer()
lineLayer.path = path.cgPath
lineLayer.strokeColor = UIColor.white.cgColor
lineLayer.fillColor = UIColor.clear.cgColor
dataLayer.addSublayer(lineLayer)
}
}
/**
Create a gradient layer below the line that connecting all dataPoints
*/
private func maskGradientLayer() {
if let dataPoints = dataPoints,
dataPoints.count > 0 {
let path = UIBezierPath()
path.move(to: CGPoint(x: dataPoints[0].x, y: dataLayer.frame.height))
path.addLine(to: dataPoints[0])
if isCurved,
let curvedPath = CurveAlgorithm.shared.createCurvedPath(dataPoints) {
path.append(curvedPath)
} else if let straightPath = createPath() {
path.append(straightPath)
}
path.addLine(to: CGPoint(x: dataPoints[dataPoints.count-1].x, y: dataLayer.frame.height))
path.addLine(to: CGPoint(x: dataPoints[0].x, y: dataLayer.frame.height))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
maskLayer.fillColor = UIColor.white.cgColor
maskLayer.strokeColor = UIColor.clear.cgColor
maskLayer.lineWidth = 0.0
gradientLayer.mask = maskLayer
}
}
/**
Create titles at the bottom for all entries showed in the chart
*/
private func drawLables() {
if let dataEntries = dataEntries,
dataEntries.count > 0 {
for i in 0..<dataEntries.count {
let textLayer = CATextLayer()
textLayer.frame = CGRect(x: lineGap*CGFloat(i) - lineGap/2 + 40, y: mainLayer.frame.size.height - bottomSpace/2 - 8, width: lineGap, height: 16)
textLayer.foregroundColor = #colorLiteral(red: 0.5019607843, green: 0.6784313725, blue: 0.8078431373, alpha: 1).cgColor
textLayer.backgroundColor = UIColor.clear.cgColor
textLayer.alignmentMode = CATextLayerAlignmentMode.center
textLayer.contentsScale = UIScreen.main.scale
textLayer.font = CTFontCreateWithName(UIFont.systemFont(ofSize: 0).fontName as CFString, 0, nil)
textLayer.fontSize = 11
textLayer.string = dataEntries[i].label
mainLayer.addSublayer(textLayer)
}
}
}
/**
Create horizontal lines (grid lines) and show the value of each line
*/
private func drawHorizontalLines() {
guard let dataEntries = dataEntries else {
return
}
var gridValues: [CGFloat]? = nil
if dataEntries.count < 4 && dataEntries.count > 0 {
gridValues = [0, 1]
} else if dataEntries.count >= 4 {
gridValues = [0, 0.25, 0.5, 0.75, 1]
}
if let gridValues = gridValues {
for value in gridValues {
let height = value * gridLayer.frame.size.height
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: height))
path.addLine(to: CGPoint(x: gridLayer.frame.size.width, y: height))
let lineLayer = CAShapeLayer()
lineLayer.path = path.cgPath
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.strokeColor = #colorLiteral(red: 0.2784313725, green: 0.5411764706, blue: 0.7333333333, alpha: 1).cgColor
lineLayer.lineWidth = 0.5
if (value > 0.0 && value < 1.0) {
lineLayer.lineDashPattern = [4, 4]
}
gridLayer.addSublayer(lineLayer)
var minMaxGap:CGFloat = 0
var lineValue:Int = 0
if let max = dataEntries.max()?.value,
let min = dataEntries.min()?.value {
minMaxGap = CGFloat(max - min) * topHorizontalLine
lineValue = Int((1-value) * minMaxGap) + Int(min)
}
let textLayer = CATextLayer()
textLayer.frame = CGRect(x: 4, y: height, width: 50, height: 16)
textLayer.foregroundColor = #colorLiteral(red: 0.5019607843, green: 0.6784313725, blue: 0.8078431373, alpha: 1).cgColor
textLayer.backgroundColor = UIColor.clear.cgColor
textLayer.contentsScale = UIScreen.main.scale
textLayer.font = CTFontCreateWithName(UIFont.systemFont(ofSize: 0).fontName as CFString, 0, nil)
textLayer.fontSize = 12
textLayer.string = "\(lineValue)"
gridLayer.addSublayer(textLayer)
}
}
}
private func clean() {
mainLayer.sublayers?.forEach({
if $0 is CATextLayer {
$0.removeFromSuperlayer()
}
})
dataLayer.sublayers?.forEach({$0.removeFromSuperlayer()})
gridLayer.sublayers?.forEach({$0.removeFromSuperlayer()})
}
/**
Create Dots on line points
*/
private func drawDots() {
var dotLayers: [DotCALayer] = []
if let dataPoints = dataPoints {
for dataPoint in dataPoints {
let xValue = dataPoint.x - outerRadius/2
let yValue = (dataPoint.y + lineGap) - (outerRadius * 2)
let dotLayer = DotCALayer()
dotLayer.dotInnerColor = UIColor.white
dotLayer.innerRadius = innerRadius
dotLayer.backgroundColor = UIColor.white.cgColor
dotLayer.cornerRadius = outerRadius / 2
dotLayer.frame = CGRect(x: xValue, y: yValue, width: outerRadius, height: outerRadius)
dotLayers.append(dotLayer)
mainLayer.addSublayer(dotLayer)
if animateDots {
let anim = CABasicAnimation(keyPath: "opacity")
anim.duration = 1.0
anim.fromValue = 0
anim.toValue = 1
dotLayer.add(anim, forKey: "opacity")
}
}
}
}
}
|
mit
|
fa1049107621c9228aa52d757df146c4
| 35.735119 | 160 | 0.573361 | 4.802724 | false | false | false | false |
SwifterSwift/SwifterSwift
|
Sources/SwifterSwift/AppKit/NSImageExtensions.swift
|
1
|
2237
|
// NSImageExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
// MARK: - Methods
public extension NSImage {
/// SwifterSwift: NSImage scaled to maximum size with respect to aspect ratio.
///
/// - Parameter maxSize: maximum size
/// - Returns: scaled NSImage
func scaled(toMaxSize maxSize: NSSize) -> NSImage {
let imageWidth = size.width
let imageHeight = size.height
guard imageHeight > 0 else { return self }
// Get ratio (landscape or portrait)
let ratio: CGFloat
if imageWidth > imageHeight {
// Landscape
ratio = maxSize.width / imageWidth
} else {
// Portrait
ratio = maxSize.height / imageHeight
}
// Calculate new size based on the ratio
let newWidth = imageWidth * ratio
let newHeight = imageHeight * ratio
// Create a new NSSize object with the newly calculated size
let newSize = NSSize(width: newWidth.rounded(.down), height: newHeight.rounded(.down))
// Cast the NSImage to a CGImage
var imageRect = CGRect(origin: .zero, size: size)
guard let imageRef = cgImage(forProposedRect: &imageRect, context: nil, hints: nil) else { return self }
return NSImage(cgImage: imageRef, size: newSize)
}
/// SwifterSwift: Write NSImage to url.
///
/// - Parameters:
/// - url: Desired file URL.
/// - type: Type of image (default is .jpeg).
/// - compressionFactor: used only for JPEG files. The value is a float between 0.0 and 1.0, with 1.0 resulting in no compression and 0.0 resulting in the maximum compression possible.
func write(to url: URL, fileType type: NSBitmapImageRep.FileType = .jpeg, compressionFactor: NSNumber = 1.0) {
// https://stackoverflow.com/a/45042611/3882644
guard let data = tiffRepresentation else { return }
guard let imageRep = NSBitmapImageRep(data: data) else { return }
guard let imageData = imageRep.representation(using: type, properties: [.compressionFactor: compressionFactor]) else { return }
try? imageData.write(to: url)
}
}
#endif
|
mit
|
00825d4e59ddeffe70d639a75d8aa6c7
| 36.283333 | 190 | 0.646848 | 4.650728 | false | false | false | false |
MattYY/PersistentLog
|
SampleApp/Source/Log/Views/MultiLineTextCell.swift
|
1
|
7520
|
//
// MuliLineTextCell.swift
// TestHarness
//
// Created by Josh Rooke-Ley on 4/10/15.
// Copyright (c) 2015 Fossil Group, Inc. All rights reserved.
//
import UIKit
internal class MultiLineTextCell: UITableViewCell {
struct Constants {
static let ReuseIdentifier = "MultiLineTextCellReuseIdentifier"
private static let SmallMargin = CGFloat(10.0)
private static let MessageButtonHeight = CGFloat(30.0)
}
private var messageOneTextViewHeightConstraint: NSLayoutConstraint!
var levelColor: UIColor = .whiteColor() {
didSet {
self.setNeedsLayout()
}
}
var customTextColor: UIColor = .blackColor() {
didSet {
self.setNeedsLayout()
}
}
var dateText: String = "" {
didSet {
self.dateLabel.text = dateText
}
}
var functionText: String = "" {
didSet {
self.functionLabel.text = functionText
}
}
var messageOneText: String? {
didSet {
messageOneTextView.text = messageOneText
}
}
private let dateLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = UIFont.boldSystemFontOfSize(14)
view.textColor = .blackColor()
view.textAlignment = .Left
view.numberOfLines = 1
return view
}()
private let functionLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = UIFont.systemFontOfSize(12)
view.textColor = .blackColor()
view.textAlignment = .Left
view.numberOfLines = 1
return view
}()
private let messageOneTextView: UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .whiteColor()
view.textColor = .blackColor()
view.font = .systemFontOfSize(12)
view.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10)
view.textContainer.lineBreakMode = .ByCharWrapping
view.editable = false
return view
}()
private let divider: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .blackColor()
return view
}()
required internal init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layout()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layout()
}
override func layoutSubviews() {
super.layoutSubviews()
dateLabel.textColor = customTextColor
functionLabel.textColor = customTextColor
contentView.backgroundColor = levelColor
}
}
extension MultiLineTextCell {
private func layout() {
contentView.backgroundColor = .whiteColor()
contentView.addSubview(dateLabel)
contentView.addSubview(functionLabel)
contentView.addSubview(messageOneTextView)
contentView.addSubview(divider)
//dateLabel
contentView.addConstraint(NSLayoutConstraint(
item: dateLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: contentView,
attribute: .Top,
multiplier: 1.0,
constant: Constants.SmallMargin)
)
contentView.addConstraint(NSLayoutConstraint(
item: dateLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1.0,
constant: Constants.SmallMargin)
)
contentView.addConstraint(NSLayoutConstraint(
item: dateLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1.0,
constant: -Constants.SmallMargin)
)
dateLabel.setContentHuggingPriority(750, forAxis: .Vertical)
//functionLabel
contentView.addConstraint(NSLayoutConstraint(
item: functionLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: dateLabel,
attribute: .Bottom,
multiplier: 1.0,
constant: 0)
)
contentView.addConstraint(NSLayoutConstraint(
item: functionLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1.0,
constant: Constants.SmallMargin)
)
contentView.addConstraint(NSLayoutConstraint(
item: functionLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1.0,
constant: -Constants.SmallMargin)
)
functionLabel.setContentHuggingPriority(750, forAxis: .Vertical)
//messageOneTextView
contentView.addConstraint(NSLayoutConstraint(
item: messageOneTextView,
attribute: .Top,
relatedBy: .Equal,
toItem: functionLabel,
attribute: .Bottom,
multiplier: 1.0,
constant: Constants.SmallMargin)
)
contentView.addConstraint(NSLayoutConstraint(
item: messageOneTextView,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1.0,
constant: 0)
)
contentView.addConstraint(NSLayoutConstraint(
item: messageOneTextView,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1.0,
constant: 0)
)
contentView.addConstraint(NSLayoutConstraint(
item: messageOneTextView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0)
)
contentView.addConstraint(NSLayoutConstraint(
item: divider,
attribute: .Left,
relatedBy: .Equal,
toItem: contentView,
attribute: .Left,
multiplier: 1.0,
constant: 0.0)
)
contentView.addConstraint(NSLayoutConstraint(
item: divider,
attribute: .Right,
relatedBy: .Equal,
toItem: contentView,
attribute: .Right,
multiplier: 1.0,
constant: 0.0)
)
contentView.addConstraint(NSLayoutConstraint(
item: divider,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .Height,
multiplier: 1.0,
constant: 1.0)
)
contentView.addConstraint(NSLayoutConstraint(
item: divider,
attribute: .Bottom,
relatedBy: .Equal,
toItem: contentView,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0)
)
}
}
|
mit
|
9c60a5882f90fef854f9829d8ddea13c
| 27.812261 | 75 | 0.559176 | 5.425685 | false | false | false | false |
hashemi/slox
|
slox/Parser.swift
|
1
|
13321
|
//
// Parser.swift
// slox
//
// Created by Ahmad Alhashemi on 2017-03-21.
// Copyright © 2017 Ahmad Alhashemi. All rights reserved.
//
class Parser {
private struct ParseError: Error {}
let tokens: [Token]
var current = 0
private var isAtEnd: Bool {
return peek.type == .eof
}
private var peek: Token {
return tokens[current]
}
private var previous: Token {
return tokens[current - 1]
}
init(_ tokens: [Token]) {
self.tokens = tokens
}
func parse() throws -> [Stmt] {
var statements: [Stmt] = []
while !isAtEnd {
if let statement = try declaration() {
statements.append(statement)
}
}
return statements
}
private func match(_ type: TokenType) -> Bool {
if check(type) {
advance()
return true
}
return false
}
private func match(_ type1: TokenType, _ type2: TokenType) -> Bool {
return match(type1) || match(type2)
}
private func match(_ t1: TokenType, _ t2: TokenType, _ t3: TokenType, _ t4: TokenType) -> Bool {
return match(t1) || match(t2) || match(t3) || match(t4)
}
@discardableResult private func consume(_ type: TokenType, _ message: String) throws -> Token {
if check(type) { return advance() }
throw error(peek, message)
}
private func check(_ tokenType: TokenType) -> Bool {
if isAtEnd { return false }
return peek.type == tokenType
}
@discardableResult private func advance() -> Token {
if !isAtEnd { current += 1 }
return previous
}
private func error(_ token: Token, _ message: String) -> Error {
Lox.error(token, message)
return ParseError()
}
private func synchronize() {
advance()
while !isAtEnd {
if previous.type == .semicolon { return }
switch peek.type {
case .class, .fun, .var, .for, .if, .while, .print, .return: return
default: advance()
}
}
}
}
// Expressions
extension Parser {
private func expression() throws -> Expr {
return try assignment()
}
private func assignment() throws -> Expr {
let expr = try or()
if match(.equal) {
let equals = previous
let value = try assignment()
if case let .variable(name) = expr {
return .assign(name: name, value: value)
}
if case let .get(object, name) = expr {
return .set(object: object, name: name, value: value)
}
throw error(equals, "Invalid assignment target.")
}
return expr
}
private func or() throws -> Expr {
var expr = try and()
while match(.or) {
let op = previous
let right = try and()
expr = .logical(left: expr, op: op, right: right)
}
return expr
}
private func and() throws -> Expr {
var expr = try equality()
while match(.and) {
let op = previous
let right = try equality()
expr = .logical(left: expr, op: op, right: right)
}
return expr
}
private func equality() throws -> Expr {
var expr = try comparison()
while match(.bangEqual, .equalEqual) {
let op = previous
let right = try comparison()
expr = .binary(left: expr, op: op, right: right)
}
return expr
}
private func comparison() throws -> Expr {
var expr = try term()
while match(.greater, .greaterEqual, .less, .lessEqual) {
let op = previous
let right = try term()
expr = .binary(left: expr, op: op, right: right)
}
return expr
}
private func term() throws -> Expr {
var expr = try factor()
while match(.minus, .plus) {
let op = previous
let right = try factor()
expr = .binary(left: expr, op: op, right: right)
}
return expr
}
private func factor() throws -> Expr {
var expr = try unary()
while match(.slash, .star) {
let op = previous
let right = try unary()
expr = .binary(left: expr, op: op, right: right)
}
return expr
}
private func unary() throws -> Expr {
if match(.bang, .minus) {
let op = previous
let right = try unary()
return .unary(op: op, right: right)
}
return try call()
}
private func call() throws -> Expr {
var expr = try primary()
while true {
if match(.leftParen) {
expr = try finishCall(expr)
} else if match(.dot) {
let name = try consume(.identifier, "Expect property name after '.'.")
expr = .get(object: expr, name: name)
} else {
break
}
}
return expr
}
private func finishCall(_ callee: Expr) throws -> Expr {
var arguments: [Expr] = []
if !check(.rightParen) {
repeat {
if arguments.count == 8 {
_ = error(peek, "Cannot have more than 8 arguments.")
}
arguments.append(try expression())
} while match(.comma)
}
let paren = try consume(.rightParen, "Expect ')' after arguments.")
return .call(callee: callee, paren: paren, arguments: arguments)
}
private func primary() throws -> Expr {
if match(.false) { return .literal(value: .bool(false)) }
if match(.true) { return .literal(value: .bool(true)) }
if match(.nil) { return .literal(value: .null) }
if match(.number) { return .literal(value: .number(Double(previous.lexeme)!)) }
if match(.string) {
// remove quotes
let lexeme = previous.lexeme
let range = lexeme.index(after: lexeme.startIndex)..<lexeme.index(before: lexeme.endIndex)
return .literal(value: .string(String(lexeme[range])))
}
if match(.super) {
let keyword = previous
try consume(.dot, "Expect '.' after 'super'.")
let method = try consume(.identifier, "Expect superclass method name.")
return .super(keyword: keyword, method: method)
}
if match(.this) { return .this(keyword: previous) }
if match(.identifier) { return .variable(name: previous) }
if match(.leftParen) {
let expr = try expression()
try consume(.rightParen, "Expect ')' after expression.")
return .grouping(expr: expr)
}
throw error(peek, "Expect expression.")
}
}
// Statements
extension Parser {
private func declaration() throws -> Stmt? {
do {
if match(.class) {
return try classDeclaration()
}
if match(.fun) {
return try function("function")
}
if match(.var) {
return try varDeclaration()
}
return try statement()
} catch is ParseError {
synchronize()
return nil
}
}
private func classDeclaration() throws -> Stmt {
let name = try consume(.identifier, "Expect class name.")
let superclass: Expr?
if match(.less) {
try consume(.identifier, "Expect superclass name.")
superclass = Expr.variable(name: previous)
} else {
superclass = nil
}
try consume(.leftBrace, "Expect '{' before class body.")
var methods: [Stmt] = []
while !check(.rightBrace) && !isAtEnd {
try methods.append(function("method"))
}
try consume(.rightBrace, "Expect '}' after class body.")
return .class(name: name, superclass: superclass, methods: methods)
}
private func statement() throws -> Stmt {
if match(.for) {
return try forStatement()
}
if match(.if) {
return try ifStatement()
}
if match(.print) {
return try printStatement()
}
if match(.return) {
return try returnStatement()
}
if match(.while) {
return try whileStatement()
}
if match(.leftBrace) {
return .block(statements: try block())
}
return try expressionStatement()
}
private func forStatement() throws -> Stmt {
try consume(.leftParen, "Expect '(' after 'for'.")
var initializer: Stmt?
if match(.semicolon) {
initializer = nil
} else if match(.var) {
initializer = try varDeclaration()
} else {
initializer = try expressionStatement()
}
let condition = check(.semicolon) ? Expr.literal(value: .bool(true)) : try expression()
try consume(.semicolon, "Expect ';' after loop condition.")
let increment = check(.rightParen) ? nil : try expression()
try consume(.rightParen, "Expect ')' after for clauses.")
var body = try statement()
if let increment = increment {
body = .block(statements: [body, .expr(expr: increment)])
}
body = .while(condition: condition, body: body)
if let initializer = initializer {
body = .block(statements: [initializer, body])
}
return body
}
private func ifStatement() throws -> Stmt {
try consume(.leftParen, "Expect '(' after 'if'.")
let condition = try expression()
try consume(.rightParen, "Expect ')' after if condition.")
let thenBranch = try statement()
let elseBranch = match(.else) ? try statement() : nil
return .if(expr: condition, then: thenBranch, else: elseBranch)
}
private func printStatement() throws -> Stmt {
let expr = try expression()
try consume(.semicolon, "Expect ';' after value.")
return .print(expr: expr)
}
private func returnStatement() throws -> Stmt {
let keyword = previous
let value: Expr = check(.semicolon) ? .literal(value: .null) : try expression()
try consume(.semicolon, "Expect ';' after return value.")
return .return(keyword: keyword, value: value)
}
private func varDeclaration() throws -> Stmt {
let name = try consume(.identifier, "Expect variable name.")
let initializer = match(.equal) ? try expression() : .literal(value: .null)
try consume(.semicolon, "Expect ';' after variable declaration.")
return .variable(name: name, initializer: initializer)
}
private func whileStatement() throws -> Stmt {
try consume(.leftParen, "Expect '(' after 'while'.")
let condition = try expression()
try consume(.rightParen, "Expect ')' after condition.")
let body = try statement()
return .while(condition: condition, body: body)
}
private func expressionStatement() throws -> Stmt {
let expr = try expression()
try consume(.semicolon, "Expect ';' after expression.")
return .expr(expr: expr)
}
private func function(_ kind: String) throws -> Stmt {
let name = try consume(.identifier, "Expect \(kind) name.")
try consume(.leftParen, "Expect '(' after \(kind) name.")
var parameters: [Token] = []
if !check(.rightParen) {
repeat {
if parameters.count >= 8 {
_ = error(peek, "Cannot have more than 8 parameters.")
}
parameters.append(try consume(.identifier, "Expect parameter name."))
} while match(.comma)
}
try consume(.rightParen, "Expect ')' after parameters.")
try consume(.leftBrace, "Expect '{' before \(kind) body.")
let body = try block()
return .function(name: name, parameters: parameters, body: body)
}
private func block() throws -> [Stmt] {
var statements: [Stmt] = []
while !check(.rightBrace) && !isAtEnd {
if let statement = try declaration() {
statements.append(statement)
}
}
try consume(.rightBrace, "Expect '}' after block.")
return statements
}
}
|
mit
|
5494acc6a0b5aa29e29468f5df22bfdc
| 28.019608 | 102 | 0.506607 | 4.863089 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Augmented reality/Collect data in AR/CollectDataAR.swift
|
1
|
23995
|
// Copyright 2019 Esri.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import UIKit
import ARKit
import ArcGISToolkit
import ArcGIS
/// The health of a tree.
private enum TreeHealth: Int16, CaseIterable {
/// The tree is dead.
case dead = 0
/// The tree is distressed.
case distressed = 5
/// The tree is healthy.
case healthy = 10
/// The human readable name of the tree's health.
var title: String {
switch self {
case .dead:
return "Dead"
case .distressed:
return "Distressed"
case .healthy:
return "Healthy"
}
}
}
class CollectDataAR: UIViewController {
// UI controls and state
@IBOutlet var addBBI: UIBarButtonItem!
@IBOutlet var arView: ArcGISARView!
@IBOutlet var arKitStatusLabel: UILabel!
@IBOutlet var calibrationBBI: UIBarButtonItem!
@IBOutlet var helpLabel: UILabel!
@IBOutlet var realScaleModePicker: UISegmentedControl!
@IBOutlet var toolbar: UIToolbar!
private var calibrationViewController: CollectDataARCalibrationViewController?
private var isCalibrating = false {
didSet {
if isCalibrating {
arView.sceneView.scene?.baseSurface?.opacity = 0.5
if realScaleModePicker.selectedSegmentIndex == 1 {
helpLabel.text = "Pan the map to finish calibrating"
}
} else {
arView.sceneView.scene?.baseSurface?.opacity = 0
// Dismiss popover
if let controller = calibrationViewController {
controller.dismiss(animated: true)
}
}
}
}
// Feature service
private let featureTable = AGSServiceFeatureTable(url: URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/AR_Tree_Survey/FeatureServer/0")!)
private var featureLayer: AGSFeatureLayer?
private var lastEditedFeature: AGSArcGISFeature?
// Graphics and symbology
private var featureGraphic: AGSGraphic?
private let graphicsOverlay = AGSGraphicsOverlay()
private let tappedPointSymbol = AGSSimpleMarkerSceneSymbol(style: .diamond,
color: .orange,
height: 0.5,
width: 0.5,
depth: 0.5,
anchorPosition: .center)
override func viewDidLoad() {
super.viewDidLoad()
// Create and prep the calibration view controller
calibrationViewController = CollectDataARCalibrationViewController(arcgisARView: arView)
calibrationViewController?.preferredContentSize = CGSize(width: 250, height: 100)
calibrationViewController?.useContinuousPositioning = true
// Set delegates and configure arView
arView.sceneView.touchDelegate = self
arView.arSCNView.debugOptions = .showFeaturePoints
arView.arSCNViewDelegate = self
arView.locationDataSource = AGSCLLocationDataSource()
configureSceneForAR()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["CollectDataAR"]
}
private func configureSceneForAR() {
// Create scene with imagery basemap
let scene = AGSScene(basemapStyle: .arcGISImagery)
// Create an elevation source and add it to the scene
let elevationSource = AGSArcGISTiledElevationSource(url:
URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!)
scene.baseSurface?.elevationSources.append(elevationSource)
// Allow camera to go beneath the surface
scene.baseSurface?.navigationConstraint = .none
// Create a feature layer and add it to the scene
featureLayer = AGSFeatureLayer(featureTable: featureTable)
scene.operationalLayers.add(featureLayer!)
featureLayer?.sceneProperties?.surfacePlacement = .absolute
// Display the scene
arView.sceneView.scene = scene
// Create and add the graphics overlay for showing WIP new features
arView.sceneView.graphicsOverlays.add(graphicsOverlay)
graphicsOverlay.sceneProperties?.surfacePlacement = .absolute
graphicsOverlay.renderer = AGSSimpleRenderer(symbol: tappedPointSymbol)
}
// MARK: - View lifecycle management
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Start AR tracking; if we're local, only use the data source to get the initial position
arView.startTracking(realScaleModePicker.selectedSegmentIndex == 1 ? .initial : .continuous)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
arView.stopTracking()
}
@IBAction func showCalibrationPopup(_ sender: UIBarButtonItem) {
if let controller = calibrationViewController {
if realScaleModePicker.selectedSegmentIndex == 0 { // Roaming
isCalibrating = true
} else { // Local
isCalibrating.toggle()
}
if isCalibrating {
showPopup(controller, sourceButton: sender)
} else {
helpLabel.text = "Tap to record a feature"
}
}
}
@IBAction func addFeature(_ sender: UIBarButtonItem) {
if let coreVideoBuffer = arView.arSCNView.session.currentFrame?.capturedImage {
// Get image as useful object
// NOTE: everything here assumes photo is taken in portrait layout (not landscape)
var coreImage = CIImage(cvImageBuffer: coreVideoBuffer)
let transform = coreImage.orientationTransform(for: .right)
coreImage = coreImage.transformed(by: transform)
let ciContext = CIContext()
let imageHeight = CVPixelBufferGetHeight(coreVideoBuffer)
let imageWidth = CVPixelBufferGetWidth(coreVideoBuffer)
let imageRef = ciContext.createCGImage(coreImage,
from: CGRect(x: 0, y: 0, width: imageHeight, height: imageWidth))
let rotatedImage = UIImage(cgImage: imageRef!)
askUserForTreeHealth { [weak self] (healthValue: Int16) in
self?.createFeature(wtih: rotatedImage, healthState: healthValue)
}
} else {
presentAlert(message: "Didn't get image for tap")
}
}
@IBAction func setRealScaleMode(_ sender: UISegmentedControl) {
arView.stopTracking()
if sender.selectedSegmentIndex == 0 {
// Roaming - continuous update
arView.startTracking(.continuous)
helpLabel.text = "Using CoreLocation + ARKit"
calibrationViewController?.useContinuousPositioning = true
} else {
// Local - only update once, then manually calibrate
arView.startTracking(.initial)
helpLabel.text = "Using ARKit only"
calibrationViewController?.useContinuousPositioning = false
}
// Turn off calibration when switching modes
isCalibrating = false
}
}
// MARK: - Add and identify features on tap
extension CollectDataAR: AGSGeoViewTouchDelegate {
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// Remove any existing graphics
graphicsOverlay.graphics.removeAllObjects()
// Try to get the real-world position of that tapped AR plane
if let planeLocation = arView.arScreenToLocation(screenPoint: screenPoint) {
// If a plane was found, use that
let graphic = AGSGraphic(geometry: planeLocation, symbol: nil)
graphicsOverlay.graphics.add(graphic)
addBBI.isEnabled = true
helpLabel.text = "Placed relative to ARKit plane"
} else {
presentAlert(message: "Didn't find anything. Try again.")
// No point found - disable adding the feature
addBBI.isEnabled = false
}
}
}
// MARK: - Feature management
extension CollectDataAR {
private func askUserForTreeHealth(with completion: @escaping (_ healthValue: Int16) -> Void) {
// Display an alert allowing users to select tree health
let healthStatusMenu = UIAlertController(title: "Take picture and add tree",
message: "How healthy is this tree?",
preferredStyle: .actionSheet)
TreeHealth.allCases.forEach { (treeHealth) in
let alertAction = UIAlertAction(title: treeHealth.title, style: .default) { (_) in
completion(treeHealth.rawValue)
}
healthStatusMenu.addAction(alertAction)
}
// Add "cancel" item.
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
healthStatusMenu.addAction(cancelAction)
healthStatusMenu.popoverPresentationController?.barButtonItem = addBBI
self.present(healthStatusMenu, animated: true, completion: nil)
}
func applyEdits() {
featureTable.applyEdits { [weak self] (featureEditResults: [AGSFeatureEditResult]?, error: Error?) in
if let error = error {
self?.presentAlert(message: "Error while applying edits :: \(error.localizedDescription)")
} else {
if let featureEditResults = featureEditResults,
featureEditResults.first?.completedWithErrors == false {
self?.presentAlert(message: "Edits applied successfully")
}
}
}
}
private func createFeature(wtih capturedImage: UIImage, healthState healthValue: Int16) {
guard let featureGraphic = graphicsOverlay.graphics.firstObject as? AGSGraphic,
let featurePoint = featureGraphic.geometry as? AGSPoint else { return }
// Update the help label
helpLabel.text = "Adding feature"
// Create attributes for the new feature
let featureAttributes = ["Health": healthValue, "Height": 3.2, "Diameter": 1.2] as [String: Any]
if let newFeature = featureTable.createFeature(attributes: featureAttributes, geometry: featurePoint) as? AGSArcGISFeature {
lastEditedFeature = newFeature
// add the feature to the feature table
featureTable.add(newFeature) { [weak self] (error: Error?) in
guard let self = self else { return }
if let error = error {
self.presentAlert(message: "Error while adding feature: \(error.localizedDescription)")
} else {
self.featureTable.applyEdits { [weak self] (_, err) in
guard let self = self else { return }
if let error = err {
self.presentAlert(error: error)
return
}
newFeature.refresh()
if let data = capturedImage.jpegData(compressionQuality: 1) {
newFeature.addAttachment(withName: "ARCapture.jpg", contentType: "jpg", data: data) { (_, err) in
if let error = err {
self.presentAlert(error: error)
}
self.featureTable.applyEdits()
}
}
}
}
}
// enable interaction with map view
helpLabel.text = "Tap to create a feature"
graphicsOverlay.graphics.removeAllObjects()
addBBI.isEnabled = false
} else {
presentAlert(message: "Error creating feature")
}
}
}
// MARK: - Calibration view management
extension CollectDataAR {
private func showPopup(_ controller: UIViewController, sourceButton: UIBarButtonItem) {
controller.modalPresentationStyle = .popover
if let presentationController = controller.popoverPresentationController {
presentationController.delegate = self
presentationController.barButtonItem = sourceButton
presentationController.permittedArrowDirections = [.down, .up]
}
present(controller, animated: true)
}
}
extension CollectDataAR: UIPopoverPresentationControllerDelegate {
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
// Detect when the popover closes and stop calibrating, but only if in roaming mode
// In local mode, the user should have an opportunity to adjust the basemap
if realScaleModePicker.selectedSegmentIndex == 0 {
isCalibrating = false
helpLabel.text = "Tap to record a feature"
}
}
}
extension CollectDataAR: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// show presented controller as popovers even on small displays
return .none
}
}
// MARK: - Calibration view controller
class CollectDataARCalibrationViewController: UIViewController {
/// The camera controller used to adjust user interactions.
private let arcgisARView: ArcGISARView
/// The `UISlider` used to adjust elevation.
private let elevationSlider: UISlider = {
let slider = UISlider(frame: .zero)
slider.minimumValue = -50.0
slider.maximumValue = 50.0
slider.isEnabled = false
return slider
}()
/// The UISlider used to adjust heading.
private let headingSlider: UISlider = {
let slider = UISlider(frame: .zero)
slider.minimumValue = -10.0
slider.maximumValue = 10.0
return slider
}()
/// Determines whether continuous positioning is in use
/// Showing the elevation slider is only appropriate when using local positioning
var useContinuousPositioning = true {
didSet {
if useContinuousPositioning {
elevationSlider.isEnabled = false
elevationSlider.removeTarget(self, action: #selector(elevationChanged(_:)), for: .valueChanged)
elevationSlider.removeTarget(self, action: #selector(touchUpElevation(_:)), for: [.touchUpInside, .touchUpOutside])
} else {
elevationSlider.isEnabled = true
// Set up events for the heading slider
elevationSlider.addTarget(self, action: #selector(elevationChanged(_:)), for: .valueChanged)
elevationSlider.addTarget(self, action: #selector(touchUpElevation(_:)), for: [.touchUpInside, .touchUpOutside])
}
}
}
/// The elevation delta amount based on the elevation slider value.
private var joystickElevation: Double {
let deltaElevation = Double(elevationSlider.value)
return pow(deltaElevation, 2) / 50.0 * (deltaElevation < 0 ? -1.0 : 1.0)
}
/// The heading delta amount based on the heading slider value.
private var joystickHeading: Double {
let deltaHeading = Double(headingSlider.value)
return pow(deltaHeading, 2) / 25.0 * (deltaHeading < 0 ? -1.0 : 1.0)
}
/// Initialized a new calibration view with the given scene view and camera controller.
///
/// - Parameters:
/// - arcgisARView: The ArcGISARView we are calibrating..
init(arcgisARView: ArcGISARView) {
self.arcgisARView = arcgisARView
super.init(nibName: nil, bundle: nil)
// Add the heading label and slider.
let headingLabel = UILabel(frame: .zero)
headingLabel.text = "Heading:"
headingLabel.textColor = .yellow
view.addSubview(headingLabel)
headingLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
headingLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
headingLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16)
])
view.addSubview(headingSlider)
headingSlider.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
headingSlider.leadingAnchor.constraint(equalTo: headingLabel.trailingAnchor, constant: 16),
headingSlider.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
headingSlider.centerYAnchor.constraint(equalTo: headingLabel.centerYAnchor)
])
// Add the elevation label and slider.
let elevationLabel = UILabel(frame: .zero)
elevationLabel.text = "Elevation:"
elevationLabel.textColor = .yellow
view.addSubview(elevationLabel)
elevationLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
elevationLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
elevationLabel.bottomAnchor.constraint(equalTo: headingLabel.topAnchor, constant: -24)
])
view.addSubview(elevationSlider)
elevationSlider.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
elevationSlider.leadingAnchor.constraint(equalTo: elevationLabel.trailingAnchor, constant: 16),
elevationSlider.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
elevationSlider.centerYAnchor.constraint(equalTo: elevationLabel.centerYAnchor)
])
// Setup actions for the two sliders. The sliders operate as "joysticks",
// where moving the slider thumb will start a timer
// which roates or elevates the current camera when the timer fires. The elevation and heading delta
// values increase the further you move away from center. Moving and holding the thumb a little bit from center
// will roate/elevate just a little bit, but get progressively more the further from center the thumb is moved.
headingSlider.addTarget(self, action: #selector(headingChanged(_:)), for: .touchDown)
headingSlider.addTarget(self, action: #selector(touchUpHeading(_:)), for: [.touchUpInside, .touchUpOutside, .touchCancel])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// The timers for the "joystick" behavior.
private var elevationTimer: Timer?
private var headingTimer: Timer?
/// Handle an elevation slider value-changed event.
///
/// - Parameter sender: The slider tapped on.
@objc
func elevationChanged(_ sender: UISlider) {
if elevationTimer == nil {
// Create a timer which elevates the camera when fired.
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] (_) in
let delta = self?.joystickElevation ?? 0.0
self?.elevate(delta)
}
// Add the timer to the main run loop.
RunLoop.main.add(timer, forMode: .default)
elevationTimer = timer
}
}
/// Handle an heading slider value-changed event.
///
/// - Parameter sender: The slider tapped on.
@objc
func headingChanged(_ sender: UISlider) {
if headingTimer == nil {
// Create a timer which rotates the camera when fired.
let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] (_) in
let delta = self?.joystickHeading ?? 0.0
self?.rotate(delta)
}
// Add the timer to the main run loop.
RunLoop.main.add(timer, forMode: .default)
headingTimer = timer
}
}
/// Handle an elevation slider touchUp event. This will stop the timer.
///
/// - Parameter sender: The slider tapped on.
@objc
func touchUpElevation(_ sender: UISlider) {
elevationTimer?.invalidate()
elevationTimer = nil
sender.value = 0.0
}
/// Handle a heading slider touchUp event. This will stop the timer.
///
/// - Parameter sender: The slider tapped on.
@objc
func touchUpHeading(_ sender: UISlider) {
headingTimer?.invalidate()
headingTimer = nil
sender.value = 0.0
}
/// Rotates the camera by `deltaHeading`.
///
/// - Parameter deltaHeading: The amount to rotate the camera.
private func rotate(_ deltaHeading: Double) {
let camera = arcgisARView.originCamera
let newHeading = camera.heading + deltaHeading
arcgisARView.originCamera = camera.rotate(toHeading: newHeading, pitch: camera.pitch, roll: camera.roll)
}
/// Change the cameras altitude by `deltaAltitude`.
///
/// - Parameter deltaAltitude: The amount to elevate the camera.
private func elevate(_ deltaAltitude: Double) {
let camera = arcgisARView.originCamera
arcgisARView.originCamera = camera.elevate(withDeltaAltitude: deltaAltitude)
}
}
// MARK: - tracking status display
extension CollectDataAR: ARSCNViewDelegate {
public func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
// Don't show anything in roaming mode; constant location tracking reset means
// ARKit will always be initializing
if realScaleModePicker.selectedSegmentIndex == 0 {
arKitStatusLabel.isHidden = true
return
}
switch camera.trackingState {
case .normal:
arKitStatusLabel.isHidden = true
case .notAvailable:
arKitStatusLabel.text = "ARKit location not available"
arKitStatusLabel.isHidden = false
case .limited(let reason):
arKitStatusLabel.isHidden = false
switch reason {
case .excessiveMotion:
arKitStatusLabel.text = "Try moving your phone more slowly"
arKitStatusLabel.isHidden = false
case .initializing:
arKitStatusLabel.text = "Keep moving your phone"
arKitStatusLabel.isHidden = false
case .insufficientFeatures:
arKitStatusLabel.text = "Try turning on more lights and moving around"
arKitStatusLabel.isHidden = false
case .relocalizing:
// this won't happen as this sample doesn't use relocalization
break
@unknown default:
break
}
}
}
}
|
apache-2.0
|
912a7c00b91ce174da885a1942392608
| 41.469027 | 173 | 0.627381 | 5.192599 | false | false | false | false |
steelwheels/Coconut
|
CoconutData/Source/Text/CNText.swift
|
1
|
9474
|
/**
* @file CNText.h
* @brief Define CNText class
* @par Copyright
* Copyright (C) 2017 Steel Wheels Project
*/
import Foundation
public protocol CNText
{
func append(string src: String)
func prepend(string src: String)
func isEmpty() -> Bool
func toStrings(indent idt: Int) -> Array<String>
}
public extension CNText
{
func toStrings() -> Array<String> {
return self.toStrings(indent: 0)
}
func indentString(indent idt: Int) -> String {
var str: String = ""
for _ in 0..<idt {
str = str + " "
}
return str
}
}
private func adjustString(string str: String, length len: Int) -> String {
var newstr = str
let rest = len - str.utf8.count
for _ in 0..<rest {
newstr += " "
}
return newstr
}
private func split(string src: String) -> Array<String> {
let lines = src.split(separator: "\n")
var result: Array<String> = []
for line in lines {
result.append(String(line))
}
return result
}
public class CNTextLine: CNText
{
private var mLines: Array<String>
public init(){
mLines = []
}
public init(string src: String){
mLines = split(string: src)
}
public var lineCount: Int { get { return mLines.count }}
public func line(at index: Int) -> String? {
if 0<=index && index<mLines.count {
return mLines[index]
} else {
return nil
}
}
public func set(string src: String){
mLines = split(string: src)
}
public func append(string src: String){
let lines = split(string: src)
mLines = merge(lines0: mLines, lines1: lines)
}
public func prepend(string src: String){
let lines = split(string: src)
mLines = merge(lines0: lines, lines1: mLines)
}
public func isEmpty() -> Bool {
return mLines.isEmpty
}
private func merge(lines0 ln0: Array<String>, lines1 ln1: Array<String>) -> Array<String> {
if ln0.count == 0 {
return ln1
} else if ln1.count == 0 {
return ln0
} else { // ln0.count > 0 && ln1.count > 0
var result = ln0
result[result.count - 1] += ln1[0]
for i in 1..<ln1.count {
result.append(ln1[i])
}
return result
}
}
public var width: Int { get {
var result: Int = 0
mLines.forEach({
(_ line: String) -> Void in
result = max(result, line.utf8.count)
})
return result
}}
public func toStrings(indent idt: Int) -> Array<String> {
let spaces = indentString(indent: idt)
var result: Array<String> = []
for line in mLines {
result.append(spaces + line)
}
return result
}
}
public class CNLabeledText: CNText
{
public var mLabel: String
public var mText: CNText
public init(label lab: String, text txt: CNText){
mLabel = lab
mText = txt
}
public func append(string src: String) {
mText.append(string: src)
}
public func prepend(string src: String) {
mText.prepend(string: src)
}
public func isEmpty() -> Bool {
return mLabel.isEmpty && mText.isEmpty()
}
public func toStrings(indent idt: Int) -> Array<String> {
let bodies = mText.toStrings(indent: 0)
var result: Array<String> = []
if bodies.count > 0 {
/* 1st line */
result.append(indentString(indent: idt) + mLabel + bodies[0])
/* Other lines*/
let idtstr = indentString(indent: idt + 1)
for i in 1..<bodies.count {
result.append(idtstr + bodies[i])
}
}
return result
}
}
public class CNTextList: CNText
{
private var mItems: Array<CNText>
public var separator: String
public init(){
mItems = []
separator = ""
}
public func add(text src: CNText){
mItems.append(src)
}
public func append(string src: String) {
if let item = mItems.last {
item.append(string: src)
} else {
let line = CNTextLine(string: src)
mItems.append(line)
}
}
public func insert(text src: CNText, at pos: Int) {
mItems.insert(src, at: pos)
}
public func prepend(string src: String) {
if mItems.count > 0 {
mItems[0].prepend(string: src)
} else {
let line = CNTextLine(string: src)
mItems.append(line)
}
}
public func isEmpty() -> Bool {
return mItems.isEmpty
}
public func toStrings(indent idt: Int) -> Array<String> {
var result: Array<String> = []
let count = mItems.count
guard count > 0 else {
return []
}
let idtstr = indentString(indent: idt)
let lastidx = count - 1
for i in 0..<count {
let substrs = mItems[i].toStrings()
if substrs.count > 0 {
for substr in substrs {
result.append(idtstr + substr)
}
if i != lastidx {
result[result.count - 1] += separator
}
}
}
return result
}
}
public class CNTextSection: CNText
{
public var header: String
public var footer: String
public var separator: String?
private var mContents: Array<CNText>
public init() {
self.header = ""
self.footer = ""
self.separator = nil
self.mContents = []
}
public var contentCount: Int { get { return mContents.count }}
public func add(text src: CNText){
mContents.append(src)
}
public func insert(text src: CNText){
mContents.insert(src, at: 0)
}
public func append(string src: String){
if let last = mContents.last as? CNTextLine {
last.append(string: src)
} else {
let newtxt = CNTextLine(string: src)
self.add(text: newtxt)
}
}
public func prepend(string src: String){
if let first = mContents.first as? CNTextLine {
first.prepend(string: src)
} else {
let newtxt = CNTextLine(string: src)
self.insert(text: newtxt)
}
}
public func isEmpty() -> Bool {
return self.header.isEmpty && self.footer.isEmpty && mContents.isEmpty
}
public func toStrings(indent idt: Int) -> Array<String> {
var result: Array<String> = []
var nextidt = idt
let spaces = indentString(indent: idt)
if !self.header.isEmpty {
result.append(spaces + self.header)
nextidt += 1
}
let cnum = mContents.count
for c in 0..<cnum {
let content = mContents[c]
let lines = content.toStrings(indent: nextidt)
let lnum = lines.count
for i in 0..<lnum {
var line: String = lines[i]
/* Insert separator to the end of last line */
if c < cnum - 1 && i == lnum - 1 {
if let sep = separator {
line += sep
}
}
result.append(line)
}
}
if !self.footer.isEmpty {
result.append(spaces + self.footer)
}
return result
}
}
public class CNTextRecord
{
private var mColumns: Array<CNTextLine>
public init(){
mColumns = []
}
public var columnCount: Int { get { return mColumns.count }}
public var columns: Array<CNTextLine> {
get { return mColumns }
}
public func append(string src: String) {
append(line: CNTextLine(string: src))
}
public func append(line src: CNTextLine) {
mColumns.append(src)
}
public func prepend(string src: String) {
mColumns.insert(CNTextLine(string: src), at: 0)
}
public func prepend(line src: CNTextLine) {
mColumns.insert(src, at: 0)
}
public var widths: Array<Int> { get {
var result: Array<Int> = []
mColumns.forEach({
(_ column: CNTextLine) -> Void in
result.append(column.width)
})
return result
}}
public var maxLineCount: Int { get {
var result: Int = 0
mColumns.forEach({
(_ column: CNTextLine) -> Void in
result = max(result, column.lineCount)
})
return result
}}
public func toStrings(widths widthvals: Array<Int>) -> Array<String> {
var result: Array<String> = []
for lindex in 0..<self.maxLineCount {
var line: String = ""
for cindex in 0..<mColumns.count {
let column = mColumns[cindex]
let colstr: String
if let str = column.line(at: lindex) {
colstr = str
} else {
colstr = ""
}
line += adjustString(string: colstr, length: widthvals[cindex] + 1)
}
result.append(line)
}
return result
}
}
public class CNTextTable: CNText
{
public var mRecords: Array<CNTextRecord>
public init(){
mRecords = []
}
public var count: Int { get { return mRecords.count }}
public var records: Array<CNTextRecord> {
get { return mRecords }
set(recs) { mRecords = recs }
}
public func add(record src: CNTextRecord) {
mRecords.append(src)
}
public func insert(record src: CNTextRecord){
mRecords.insert(src, at: 0)
}
public func append(string src: String) {
if mRecords.count > 0 {
mRecords[mRecords.count - 1].append(string: src)
} else {
let newrec = CNTextRecord()
newrec.append(string: src)
mRecords.append(newrec)
}
}
public func prepend(string src: String) {
if mRecords.count > 0 {
mRecords[mRecords.count - 1].prepend(string: src)
} else {
let newrec = CNTextRecord()
newrec.prepend(string: src)
mRecords.append(newrec)
}
}
public func isEmpty() -> Bool {
return mRecords.isEmpty
}
public var maxColumnCount: Int { get {
var result: Int = 0
mRecords.forEach({
(_ rec: CNTextRecord) -> Void in
result = max(result, rec.columnCount)
})
return result
}}
public func toStrings(indent idt: Int) -> Array<String> {
/* Get max column num */
let maxcolnum = self.maxColumnCount
/* Initialize column width */
var widths: Array<Int> = Array(repeating: 0, count: maxcolnum)
/* Get max width for each column */
mRecords.forEach({
(_ rec: CNTextRecord) -> Void in
for i in 0..<rec.columnCount {
let col = rec.columns[i]
widths[i] = max(widths[i], col.width)
}
})
/* make lines */
let spaces = indentString(indent: idt)
var results: Array<String> = []
mRecords.forEach({
(_ rec: CNTextRecord) -> Void in
let lines = rec.toStrings(widths: widths)
for line in lines {
results.append(spaces + line)
}
})
return results
}
}
|
lgpl-2.1
|
3460ebf75e94e896dadc7f10dadbfc44
| 19.418103 | 92 | 0.647245 | 2.900796 | false | false | false | false |
Djecksan/MobiTask
|
Pods/ObjectMapper/ObjectMapper/Core/Operators.swift
|
20
|
12998
|
//
// Operators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
// Copyright (c) 2014 hearst. All rights reserved.
//
/**
* This file defines a new operator which is used to create a mapping between an object and a JSON key value.
* There is an overloaded operator definition for each type of object that is supported in ObjectMapper.
* This provides a way to add custom logic to handle specific types of objects
*/
infix operator <- {}
// MARK:- Objects with Basic types
/// Object of Basic type
public func <- <T>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.basicType(&left, object: right.value())
} else {
ToJSON.basicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional object of basic type
public func <- <T>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped optional object of basic type
public func <- <T>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalBasicType(&left, object: right.value())
} else {
ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Raw Representable types
/// Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T, right: Map) {
left <- (right, EnumTransform())
}
/// Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T?, right: Map) {
left <- (right, EnumTransform())
}
/// Implicitly Unwrapped Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(inout left: T!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Arrays of Raw Representable type
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T], right: Map) {
left <- (right, EnumTransform())
}
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) {
left <- (right, EnumTransform())
}
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Dictionaries of Raw Representable type
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) {
left <- (right, EnumTransform())
}
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) {
left <- (right, EnumTransform())
}
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) {
left <- (right, EnumTransform())
}
// MARK:- Transforms
/// Object of Basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.basicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Optional object of basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Implicitly unwrapped optional object of basic type with Transform
public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) {
if right.0.mappingType == MappingType.FromJSON {
var value: T? = right.1.transformFromJSON(right.0.currentValue)
FromJSON.optionalBasicType(&left, object: value)
} else {
var value: Transform.JSON? = right.1.transformToJSON(left)
ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary)
}
}
/// Array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional array of Basic type with Transform
public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONArrayWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONArrayWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.basicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
/// Implicitly unwrapped optional dictionary of Basic type with Transform
public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) {
let (map, transform) = right
if map.mappingType == MappingType.FromJSON {
let values = fromJSONDictionaryWithTransform(map.currentValue, transform)
FromJSON.optionalBasicType(&left, object: values)
} else {
let values = toJSONDictionaryWithTransform(left, transform)
ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary)
}
}
private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] {
if let values = input as? [AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return []
}
}
private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] {
if let values = input as? [String: AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return [:]
}
}
private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
// MARK:- Mappable Objects - <T: Mappable>
/// Object conforming to Mappable
public func <- <T: Mappable>(inout left: T, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.object(&left, object: right.currentValue)
} else {
ToJSON.object(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Mappable objects
public func <- <T: Mappable>(inout left: T?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped optional Mappable objects
public func <- <T: Mappable>(inout left: T!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObject(&left, object: right.currentValue)
} else {
ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable>
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectDictionary(&left, object: right.currentValue)
} else {
ToJSON.objectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionary(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Dictionary of Mappable objects <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.objectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable>
public func <- <T: Mappable>(inout left: Dictionary<String, [T]>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
// MARK:- Array of Mappable objects - Array<T: Mappable>
/// Array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.objectArray(&left, object: right.currentValue)
} else {
ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Optional array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>?, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
/// Implicitly unwrapped Optional array of Mappable objects
public func <- <T: Mappable>(inout left: Array<T>!, right: Map) {
if right.mappingType == MappingType.FromJSON {
FromJSON.optionalObjectArray(&left, object: right.currentValue)
} else {
ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary)
}
}
|
mit
|
f4300a42a84979cd8a2a687a9f743632
| 36.353448 | 125 | 0.719188 | 4.011728 | false | false | false | false |
envoy/Ambassador
|
Ambassador/Readers/URLParametersReader.swift
|
1
|
2029
|
//
// URLParametersReader.swift
// Ambassador
//
// Created by Fang-Pen Lin on 6/10/16.
// Copyright © 2016 Fang-Pen Lin. All rights reserved.
//
import Foundation
import Embassy
public struct URLParametersReader {
public enum LocalError: Error {
case utf8EncodingError
}
/// Read all data into bytes array and parse it as URL parameter
/// - Parameter input: the SWSGI input to read from
/// - Parameter errorHandler: the handler to be called when failed to read URL parameters
/// - Parameter handler: the handler to be called when finish reading all data and parsed as URL
/// parameter
public static func read(
_ input: SWSGIInput,
errorHandler: ((Error) -> Void)? = nil,
handler: @escaping (([(String, String)]) -> Void)
) {
DataReader.read(input) { data in
do {
guard let string = String(bytes: data, encoding: .utf8) else {
throw LocalError.utf8EncodingError
}
let parameters = URLParametersReader.parseURLParameters(string)
handler(parameters)
} catch {
if let errorHandler = errorHandler {
errorHandler(error)
}
}
}
}
/// Parse given string as URL parameters
/// - Parameter string: URL encoded parameter string to parse
/// - Returns: array of (key, value) pairs of URL encoded parameters
public static func parseURLParameters(_ string: String) -> [(String, String)] {
let parameters = string.components(separatedBy: "&")
return parameters.map { parameter in
let parts = parameter.components(separatedBy: "=")
let key = parts[0]
let value = Array(parts[1..<parts.count]).joined(separator: "=")
return (
key.removingPercentEncoding ?? key,
value.removingPercentEncoding ?? value
)
}
}
}
|
mit
|
40aa62e4f82a5604c25bb9f102171412
| 33.965517 | 101 | 0.581854 | 4.794326 | false | false | false | false |
blitzagency/events
|
Events/Models/Handler.swift
|
1
|
1958
|
//
// Handler.swift
// Events
//
// Created by Adam Venturella on 12/2/15.
// Copyright © 2015 BLITZ. All rights reserved.
//
import Foundation
public protocol EventHandler {
var publisher: EventManagerBase { get }
var subscriber: EventManagerBase { get }
var listener: Listener { get }
}
public protocol PublisherCallback {
associatedtype Event
var callback: (Event) -> () { get }
}
public protocol PublisherDataCallback {
associatedtype Event
var callback: (Event) -> () { get }
}
// Swift does not allow struct inheritance
// because of that, these are classes as we need to be
// able to cast up and down the type heirarchy in
// EventManager.trigger
public class HandlerBase: EventHandler {
public unowned let publisher: EventManagerBase
public unowned let subscriber: EventManagerBase
public unowned let listener: Listener
public init(publisher: EventManagerBase, subscriber: EventManagerBase, listener: Listener){
self.publisher = publisher
self.subscriber = subscriber
self.listener = listener
}
}
public class HandlerPublisher<Publisher>: HandlerBase, PublisherCallback {
public let callback: (EventPublisher<Publisher>) -> ()
public init(publisher: EventManagerBase, subscriber: EventManagerBase, listener: Listener, callback: @escaping (EventPublisher<Publisher>) -> ()){
self.callback = callback
super.init(publisher: publisher, subscriber: subscriber, listener: listener)
}
}
public class HandlerPublisherData<Publisher, Data>: HandlerBase, PublisherDataCallback {
public let callback: (EventPublisherData<Publisher, Data>) -> ()
public init(publisher: EventManagerBase, subscriber: EventManagerBase, listener: Listener, callback: @escaping (EventPublisherData<Publisher, Data>) -> ()){
self.callback = callback
super.init(publisher: publisher, subscriber: subscriber, listener: listener)
}
}
|
mit
|
54fff89143180a3313f2c4ea92ca427d
| 28.651515 | 160 | 0.719469 | 4.615566 | false | false | false | false |
belatrix/BelatrixEventsIOS
|
Hackatrix/Controller/MainVC.swift
|
1
|
7088
|
//
// MainVC.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 9/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
class MainVC: UIViewController {
//MARK: - Properties
@IBOutlet weak var bannerImage: UIImageView!
@IBOutlet weak var upcomingCollectionView: UICollectionView!
@IBOutlet weak var pastCollectionView: UICollectionView!
@IBOutlet weak var featureTitle: UILabel!
@IBOutlet weak var activityUpcoming: UIActivityIndicatorView!
@IBOutlet weak var activityPass: UIActivityIndicatorView!
@IBOutlet weak var scrollView: UIScrollView!
var featuredBanner:Event! = nil
var upcomingEvents:[Event] = [] {
didSet {
self.activityUpcoming.stopAnimating()
self.upcomingCollectionView.reloadData()
}
}
var pastEvents:[Event] = [] {
didSet {
self.activityPass.stopAnimating()
self.pastCollectionView.reloadData()
}
}
var eventTypeSelected:EventType!
var currentEventSelected:IndexPath!
//MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.getBanner {
self.addTitleinMainBanner()
self.addActionToEventsTo(images: self.bannerImage)
}
self.addRefreshController()
self.getEventOf(type: .upcoming)
self.getEventOf(type: .past)
}
//MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == K.segue.detail {
let tabBarVC = segue.destination as! UITabBarController
let detailVC = tabBarVC.viewControllers?[0] as! DetailVC
let interactionVC = tabBarVC.viewControllers?[1] as! InteractionVC
if self.eventTypeSelected == .upcoming {
interactionVC.detailEvent = self.upcomingEvents[currentEventSelected.row]
detailVC.detailEvent = self.upcomingEvents[currentEventSelected.row]
} else if self.eventTypeSelected == .past {
interactionVC.detailEvent = self.pastEvents[currentEventSelected.row]
detailVC.detailEvent = self.pastEvents[currentEventSelected.row]
} else {
interactionVC.detailEvent = self.featuredBanner
detailVC.detailEvent = self.featuredBanner
}
}
}
//MARK: - Functions
func getBanner(complete:@escaping ()->Void) {
Alamofire.request(api.url.event.featured).responseJSON { response in
if let responseServer = response.result.value {
let json = JSON(responseServer)
self.featuredBanner = Event(data: json)
self.bannerImage.af_setImage(
withURL: URL(string: self.featuredBanner.image!)!,
imageTransition: .crossDissolve(0.2)
)
complete()
}
}
}
func addTitleinMainBanner(){
self.featureTitle.text = featuredBanner.title
}
func addActionToEventsTo(images eventImage:UIImageView) {
let actionTap = UITapGestureRecognizer(target: self, action: #selector(self.showDetail))
actionTap.numberOfTapsRequired = 1
eventImage.isUserInteractionEnabled = true
eventImage.addGestureRecognizer(actionTap)
}
func showDetail() {
self.eventTypeSelected = .current
self.performSegue(withIdentifier: K.segue.detail, sender: nil)
}
func getEventOf(type:EventType) {
var eventURL = api.url.event.upcoming
if type == .past {
eventURL = api.url.event.past
}
Alamofire.request(eventURL).responseJSON { response in
if let responseServer = response.result.value {
let json = JSON(responseServer)
for (_,subJson):(String, JSON) in json {
if type == .upcoming {
self.upcomingEvents.append(Event(data: subJson))
} else {
self.pastEvents.append(Event(data: subJson))
}
}
}
}
}
func addRefreshController() {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(self.refreshContent), for: .valueChanged)
if #available(iOS 10.0, *) {
self.scrollView.refreshControl = refresh
} else {
self.scrollView.addSubview(refresh)
}
}
func refreshContent(sender:UIRefreshControl) {
self.getBanner {
self.addTitleinMainBanner()
self.addActionToEventsTo(images: self.bannerImage)
}
self.upcomingEvents = []
self.upcomingCollectionView.reloadData()
self.getEventOf(type: .upcoming)
self.pastEvents = []
self.pastCollectionView.reloadData()
self.getEventOf(type: .past)
sender.endRefreshing()
}
}
//MARK: - UICollectionViewDataSource
extension MainVC : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 0 {
return self.upcomingEvents.count
}else if collectionView.tag == 1 {
return self.pastEvents.count
}else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.cell.event, for: indexPath) as! EventCell
if collectionView.tag == 0 {
let urlUpcoming = URL(string: self.upcomingEvents[indexPath.row].image!)
cell.eventImage.af_setImage(withURL: urlUpcoming!, imageTransition: .crossDissolve(0.2))
cell.eventTitle.text = self.upcomingEvents[indexPath.row].title!
} else if collectionView.tag == 1 {
let urlPast = URL(string: self.pastEvents[indexPath.row].image!)
cell.eventImage.af_setImage(withURL: urlPast!, imageTransition: .crossDissolve(0.2))
cell.eventTitle.text = self.pastEvents[indexPath.row].title!
}
return cell
}
}
//MARK: - UICollectionViewDelegate
extension MainVC: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView.tag == 0 {
self.currentEventSelected = indexPath
self.eventTypeSelected = .upcoming
} else if collectionView.tag == 1 {
self.currentEventSelected = indexPath
self.eventTypeSelected = .past
}
self.performSegue(withIdentifier: K.segue.detail, sender: nil)
}
}
|
apache-2.0
|
94534649b9267fd7c194913b9e6eff2b
| 33.072115 | 121 | 0.611542 | 5.040541 | false | false | false | false |
elfketchup/SporkVN
|
SporkVN/VN Classes/VNTestScene.swift
|
1
|
18221
|
//
// VNTestScene.h
//
// Created by James Briones on 8/30/12.
// Copyright 2012. All rights reserved.
//
import SpriteKit
import AVFoundation
/*
Some important notes:
The labels have X and Y values, but these aren't X and Y in pixel coordinates. Rather, they're in percentages
(where 0.01 is 1% while 1.00 is 100%), and they're used to position things in relation to the width and height
of the screen. For example, if you were to position the "Start New Game" label at
X: 0.5
Y: 0.3
...then horizontally, it would be at the middle of the screen (50%) while it would be positioned at only 30% of
the screen's height.
Also, (0.0, 0.0) would be the bottom-left corner of the screen, while (1.0, 1.0) should be the upper-right corner.
*/
// Dictionary keys for the UI elements
let VNTestSceneStartNewGameLabelX = "startnewgame label x"
let VNTestSceneStartNewGameLabelY = "startnewgame label y"
let VNTestSceneStartNewGameText = "startnewgame text"
let VNTestSceneStartNewGameFont = "startnewgame font"
let VNTestSceneStartNewGameSize = "startnewgame size"
let VNTestSceneStartNewGameColorDict = "startnewgame color"
let VNTestSceneContinueLabelX = "continue label x"
let VNTestSceneContinueLabelY = "continue label y"
let VNTestSceneContinueText = "continue text"
let VNTestSceneContinueFont = "continue font"
let VNTestSceneContinueSize = "continue size"
let VNTestSceneContinueColor = "continue color"
let VNTestSceneTitleX = "title x"
let VNTestSceneTitleY = "title y"
let VNTestSceneTitleImage = "title image"
let VNTestSceneBackgroundImage = "background image"
let VNTestSceneScriptToLoad = "script to load"
let VNTestSceneMenuMusic = "menu music"
let VNTestSceneZForBackgroundImage = CGFloat(10.0)
let VNTestSceneZForLabels = CGFloat(20.0)
let VNTestSceneZForTitle = CGFloat(30.0)
class VNTestScene : SKScene
{
//CCLabelTTF* playLabel;
//CCLabelTTF* loadLabel;
var playLabel:SMTextNode?
var loadLabel:SMTextNode?
var title:SKSpriteNode?
var backgroundImage:SKSpriteNode?
var nameOfScript:String?
//var testScene:VNScene?
// music stuff
var isPlayingMusic = false;
var backgroundMusic:AVAudioPlayer? = nil
var sceneNode:VNSceneNode? = nil
// This loads the user interface for the title menu. Default view settings are first loaded into a dictionary,
// and then custom settings are loaded from a file (assuming file the exists, of course!). After that, the actual
// CCSprite / CCLabelTTF objects are created from that information.
//- (void)loadUI
func loadUI() {
let defaultSettings = self.loadDefaultUI()
let standardSettings = NSMutableDictionary(dictionary: defaultSettings)
var customSettings:NSDictionary? = nil
// Load the custom settings stored in a file
let dictionaryFilePath:String? = Bundle.main.path(forResource: "main_menu", ofType: "plist")
if dictionaryFilePath != nil {
customSettings = NSDictionary(contentsOfFile: dictionaryFilePath!)
if customSettings != nil && customSettings!.count > 0 {
standardSettings.addEntries(from: customSettings! as! [AnyHashable: Any])
print("[VNTestScene] UI settings have been loaded from file.")
}
}
// Check if no custom settings could be loaded. if this is the case, just log it for diagnostics purposes
if( customSettings == nil ) {
print("[VNTestScene] UI settings could not be loaded from a file.");
}
//println("Standard settings are: \n\n\(standardSettings)")
// For the "Start New Game" button, get the values from the dictionary
let startLabelX = SMNumberInDictionaryToCGFloat(standardSettings, objectNamed: VNTestSceneStartNewGameLabelX)
let startLabelY = SMNumberInDictionaryToCGFloat(standardSettings, objectNamed: VNTestSceneStartNewGameLabelY)
let startFontSize:CGFloat = CGFloat( (standardSettings.object(forKey: VNTestSceneStartNewGameSize) as! NSNumber).doubleValue )
let startText = standardSettings.object(forKey: VNTestSceneStartNewGameText) as! NSString
let startFont = standardSettings.object(forKey: VNTestSceneStartNewGameFont) as! NSString
let startColors = standardSettings.object(forKey: VNTestSceneStartNewGameColorDict) as! NSDictionary
// Decode start colors
let startColorR = (startColors.object(forKey: "r") as! NSNumber).intValue
let startColorG = (startColors.object(forKey: "g") as! NSNumber).intValue
let startColorB = (startColors.object(forKey: "b") as! NSNumber).intValue
// Now create the actual label
playLabel = SMTextNode(fontNamed: startFont as String)
playLabel!.text = startText as String
playLabel!.fontSize = startFontSize
playLabel!.color = SMColorFromRGB(startColorR, g: startColorG, b: startColorB)
playLabel!.position = SMPositionWithNormalizedCoordinates(startLabelX, normalizedY: startLabelY)
playLabel!.zPosition = VNTestSceneZForLabels
self.addChild(playLabel!)
// Now grab the values for the Continue button
let continueLabelX:CGFloat = CGFloat( (standardSettings.object(forKey: VNTestSceneContinueLabelX) as! NSNumber).doubleValue )
let continueLabelY:CGFloat = CGFloat( (standardSettings.object(forKey: VNTestSceneContinueLabelY) as! NSNumber).doubleValue )
let continueFontSize:CGFloat = CGFloat( (standardSettings.object(forKey: VNTestSceneContinueSize) as! NSNumber).doubleValue )
let continueText = standardSettings.object(forKey: VNTestSceneContinueText) as! NSString
let continueFont = standardSettings.object(forKey: VNTestSceneContinueFont) as! NSString
let continueColors = standardSettings.object(forKey: VNTestSceneContinueColor) as! NSDictionary
// Decode continue colors
let continueColorR = (continueColors.object(forKey: "r") as! NSNumber).intValue
let continueColorG = (continueColors.object(forKey: "g") as! NSNumber).intValue
let continueColorB = (continueColors.object(forKey: "b") as! NSNumber).intValue
// Load the "Continue" label
//loadLabel = [CCLabelTTF labelWithString:continueText fontName:continueFont fontSize:continueFontSize];
//loadLabel = [[SKLabelNode alloc] initWithFontNamed:continueFont];
loadLabel = SMTextNode(fontNamed: continueFont as String)
loadLabel!.fontSize = continueFontSize
loadLabel!.text = continueText as String
loadLabel!.position = SMPositionWithNormalizedCoordinates( continueLabelX, normalizedY: continueLabelY );
loadLabel!.color = SMColorFromRGB(continueColorR, g: continueColorG, b: continueColorB);
loadLabel!.zPosition = VNTestSceneZForLabels
self.addChild(loadLabel!)
// Load the title info
let titleX = SMNumberInDictionaryToCGFloat(standardSettings, objectNamed: VNTestSceneTitleX)
let titleY = SMNumberInDictionaryToCGFloat(standardSettings, objectNamed: VNTestSceneTitleY)
let titleImageName = standardSettings.object(forKey: VNTestSceneTitleImage) as! String
title = SKSpriteNode(imageNamed: titleImageName)
title!.position = SMPositionWithNormalizedCoordinates(titleX, normalizedY: titleY)
title!.zPosition = VNTestSceneZForTitle
self.addChild(title!)
// Load background image
let backgroundImageFilename = standardSettings.object(forKey: VNTestSceneBackgroundImage) as! String
backgroundImage = SKSpriteNode(imageNamed: backgroundImageFilename)
backgroundImage!.position = SMPositionWithNormalizedCoordinates(0.5, normalizedY: 0.5)
backgroundImage!.zPosition = VNTestSceneZForBackgroundImage
self.addChild(backgroundImage!)
// Grab script name information
//nameOfScript = standardSettings[VNTestSceneScriptToLoad];
nameOfScript = standardSettings.object(forKey: VNTestSceneScriptToLoad) as? String
// The music data is loaded last since it looks weird if music is playing but nothing has shown up on the screen yet.
let musicFilename:NSString? = standardSettings.object(forKey: VNTestSceneMenuMusic) as? NSString
// Make sure the music isn't set to 'nil'
if musicFilename != nil && musicFilename!.caseInsensitiveCompare("nil") != ComparisonResult.orderedSame {
self.playBackgroundMusic(musicFilename! as String)
}
}
// This creates a dictionary that's got the default UI values loaded onto them. If you want to change how it looks,
// you should open up "main_menu.plist" and set your own custom values for things there.
//- (NSDictionary*)loadDefaultUI
func loadDefaultUI() -> NSDictionary
{
let resourcesDict = NSMutableDictionary(capacity: 13)
// Create default white colors
//var whiteColorDict = NSDictionary(dictionaryLiteral: 255, "r", 255, "g", 255, "b")
let whiteColorDict = NSDictionary(dictionary: ["r":255, "g":255, "b":255])
// Create settings for the "start new game" button
resourcesDict.setObject(0.5, forKey: VNTestSceneStartNewGameLabelX as NSCopying)
resourcesDict.setObject(0.3, forKey: VNTestSceneStartNewGameLabelY as NSCopying)
resourcesDict.setObject("Helvetica", forKey: VNTestSceneStartNewGameFont as NSCopying)
resourcesDict.setObject(18, forKey: VNTestSceneStartNewGameSize as NSCopying)
resourcesDict.setObject(whiteColorDict.copy(), forKey: VNTestSceneStartNewGameColorDict as NSCopying)
// Create settings for "continue" button
resourcesDict.setObject(0.5, forKey: VNTestSceneContinueLabelX as NSCopying)
resourcesDict.setObject(0.2, forKey: VNTestSceneContinueLabelX as NSCopying)
resourcesDict.setObject("Helvetica", forKey: VNTestSceneContinueFont as NSCopying)
resourcesDict.setObject(18, forKey: VNTestSceneContinueSize as NSCopying)
resourcesDict.setObject(whiteColorDict.copy(), forKey: VNTestSceneContinueColor as NSCopying)
// Set up title data
resourcesDict.setObject(0.5, forKey: VNTestSceneTitleX as NSCopying)
resourcesDict.setObject(0.75, forKey: VNTestSceneTitleY as NSCopying)
resourcesDict.setObject("title.png", forKey: VNTestSceneTitleImage as NSCopying)
// Set up background image
resourcesDict.setObject("skyspace.png", forKey: VNTestSceneBackgroundImage as NSCopying)
// Set up script data
resourcesDict.setObject("demo script", forKey: VNTestSceneScriptToLoad as NSCopying)
// Set default music data
resourcesDict.setObject("nil", forKey: VNTestSceneMenuMusic as NSCopying)
return NSDictionary(dictionary: resourcesDict)
}
/* Game starting and loading */
func startNewGame()
{
// Create a blank dictionary with no real data, except for the name of which script file to load.
// You can pass this in to VNLayer with nothing but that information, and it will load a new game
// (or at least, a new VNLayer scene!)
let settingsForScene = NSDictionary(object: nameOfScript!, forKey: VNSceneToPlayKey as NSCopying)
/*
// Create an all-new scene and add VNLayer to it
let scene = VNScene(size: self.size, settings: settingsForScene)
scene.scaleMode = self.scaleMode
scene.previousScene = self
self.view!.presentScene(scene)*/
//let w = self.frame.width
//let h = self.frame.height
sceneNode = VNSceneNode(settings: settingsForScene)
sceneNode!.loadDataOnView(view: self.view!)
sceneNode!.zPosition = 9999
self.addChild(sceneNode!)
// hide menu
self.isUserInteractionEnabled = false
playLabel!.alpha = 0
loadLabel!.alpha = 0
title!.alpha = 0.0
backgroundImage!.alpha = 0
}
func loadSavedGame()
{
//if SMRecord.sharedRecord.hasAnySavedData() == false {
if SMRecord.sharedRecord.hasSavedLocalData() == false { //&& SMRecord.sharedRecord.hasSavedCloudData() == false {
print("[VNTestScene] ERROR: No saved data, cannot continue game!");
return;
}
// The following's not very pretty, but it is pretty useful...
print("[VNTestScene] For diagnostics purporses, here's a flag dump from EKRecord:\n \(SMRecord.sharedRecord.flags())")
// Load saved-game records from EKRecord. The activity dictionary holds data about what the last thing the user was doing
// (presumably, watching a scene), how far the player got, relevent data that needs to be reloaded, etc.
//let activityRecords = SMRecord.sharedRecord.activityDict()
let activityRecords = SMRecord.sharedRecord.dictionaryOfActivityInformation()
let lastActivity:NSString? = activityRecords.object(forKey: SMRecordActivityTypeKey) as? NSString
if lastActivity == nil {
print("[VNTestScene] ERROR: No previous activity found. No saved game can be loaded.");
return;
}
let savedData = activityRecords.object(forKey: SMRecordActivityDataKey) as! NSDictionary
print("[VNTestScene] Saved data is \(savedData)")
// Unlike when the player is starting a new game, the name of the script to load doesn't have to be passed.
// It should already be stored within the Activity Records from EKRecord.
//[[CCDirector sharedDirector] pushScene:[VNScene sceneWithSettings:savedData]];
/*
let loadedGameScene = VNScene(size: self.size, settings: savedData)
loadedGameScene.scaleMode = self.scaleMode
loadedGameScene.previousScene = self;
self.view!.presentScene(loadedGameScene)*/
sceneNode = VNSceneNode(settings: savedData)
sceneNode!.loadDataOnView(view: self.view!)
self.addChild(sceneNode!)
sceneNode!.zPosition = 9999
// hide menu
self.isUserInteractionEnabled = false
playLabel!.alpha = 0
loadLabel!.alpha = 0
title!.alpha = 0.0
backgroundImage!.alpha = 0
}
/* Audio */
func stopMenuMusic()
{
if isPlayingMusic == true {
//OALSimpleAudio.sharedInstance().stopBg()
if backgroundMusic != nil {
backgroundMusic!.stop()
}
}
isPlayingMusic = false
}
func playBackgroundMusic(_ filename:String)
{
if SMStringLength(filename) < 1 {
return;
}
self.stopMenuMusic()
//backgroundMusic = smaudio
//OALSimpleAudio.sharedInstance().playBg(filename, loop: true)
backgroundMusic = SMAudioSoundFromFile(filename)
if backgroundMusic == nil {
print("[VNTestScene] ERROR: Could not load background music from file named: \(filename)")
} else {
backgroundMusic!.numberOfLoops = -1;
backgroundMusic!.play()
}
isPlayingMusic = true
}
/* Touch controls */
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
let touch = t
let touchPos = touch.location(in: self)
if SMBoundingBoxOfSprite(playLabel!).contains(touchPos) == true {
self.stopMenuMusic()
self.startNewGame()
}
if( SMBoundingBoxOfSprite(loadLabel!).contains(touchPos) ) {
if loadLabel!.alpha > 0.98 {
self.stopMenuMusic()
self.loadSavedGame()
}
}
}
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
SMSetScreenSizeInPoints(size.width, height: size.height)
let previousSaveData = SMRecord.sharedRecord.hasSavedLocalData()
isPlayingMusic = false
self.loadUI()
// If there's no previous data, then the "Continue" / "Load Game" label will be partially transparent.
if previousSaveData == false {
loadLabel!.alpha = 0.5
} else {
loadLabel!.alpha = 1.0
}
self.isUserInteractionEnabled = true
}
override func update(_ currentTime: TimeInterval) {
if sceneNode != nil {
sceneNode!.update(currentTime)
// check if VNSceneNode is done running; if it is, then remove it and restore control to the menu scene
if sceneNode!.isFinished == true {
sceneNode!.removeFromParent()
sceneNode = nil
// restore menu
self.isUserInteractionEnabled = true
loadLabel!.alpha = 1.0
playLabel!.alpha = 1.0
backgroundImage!.alpha = 1.0
title!.alpha = 1.0
}
}
}
}
|
mit
|
0e2b541418c697150fa767710c3de956
| 42.659314 | 134 | 0.640305 | 4.71436 | false | true | false | false |
mrdepth/EVEUniverse
|
Legacy/Neocom/Neocom/IndustryJobsPresenter.swift
|
2
|
1716
|
//
// IndustryJobsPresenter.swift
// Neocom
//
// Created by Artem Shimanski on 11/9/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import TreeController
import EVEAPI
class IndustryJobsPresenter: TreePresenter {
typealias View = IndustryJobsViewController
typealias Interactor = IndustryJobsInteractor
typealias Presentation = [Tree.Item.IndustryJobRow]
weak var view: View?
lazy var interactor: Interactor! = Interactor(presenter: self)
var content: Interactor.Content?
var presentation: Presentation?
var loading: Future<Presentation>?
required init(view: View) {
self.view = view
}
func configure() {
view?.tableView.register([Prototype.IndustryJobCell.default])
interactor.configure()
applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in
self?.applicationWillEnterForeground()
}
}
private var applicationWillEnterForegroundObserver: NotificationObserver?
func presentation(for content: Interactor.Content) -> Future<Presentation> {
let activeStatus = Set<ESI.Industry.JobStatus>([.active, .paused])
var jobs = content.value.jobs
let i = jobs.partition {activeStatus.contains($0.currentStatus)}
let active = jobs[i...].sorted{$0.endDate < $1.endDate}
.map { Tree.Item.IndustryJobRow($0, location: content.value.locations?[$0.stationID]) }
let finished = jobs[..<i].sorted{$0.endDate > $1.endDate}
.map { Tree.Item.IndustryJobRow($0, location: content.value.locations?[$0.stationID]) }
return .init(active + finished)
}
}
|
lgpl-2.1
|
e38ed919eecc695c105741810764d797
| 30.181818 | 200 | 0.75277 | 3.933486 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.