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
gitkong/FLTableViewComponent
FLComponentDemo/FLComponentDemo/Demo-collectionView/DemoCollectionComponentOne.swift
1
2908
// // DemoCollectionComponentOne.swift // FLComponentDemo // // Created by gitKong on 2017/5/17. // Copyright © 2017年 gitKong. All rights reserved. // import UIKit class DemoCollectionComponentOne: FLCollectionBaseComponent { override func register() { super.register() self.collectionView?.registerNib(DemoCollectionViewCell.self, withReuseIdentifier: cellIdentifier) } override func numberOfItems() -> NSInteger { return 12 } override func cellForItem(at item: Int) -> UICollectionViewCell { let cell : DemoCollectionViewCell = super.cellForItem(at: item) as! DemoCollectionViewCell cell.backgroundColor = UIColor.red cell.textLabel.text = stringFromSize(at: item) return cell } private func stringFromSize(at item: Int) -> String{ return "\(customSize(at: item))" } private func customSize(at item: Int) -> CGSize { var width : CGFloat = 100, height : CGFloat = 100 switch item { case 0: width = 120 height = 60 case 1: width = 60 height = 80 case 2: width = 100 height = 60 case 3: width = 90 height = 50 case 4: width = 130 height = 40 case 5: width = 60 height = 60 case 6: width = 60 height = 120 default: width = 30 height = 50 } return CGSize.init(width: width, height: height) } override func headerView() -> FLCollectionHeaderFooterView { let headerView : FLCollectionHeaderFooterView = super.headerView() headerView.backgroundColor = UIColor.gray return headerView } override func additionalOperationForReuseHeaderView(_ headerView: FLCollectionHeaderFooterView?){ let btn : UIButton = UIButton.init(type: UIButtonType.contactAdd) btn.frame = CGRect.init(x: 30, y: 0, width: 30, height: 30) headerView?.addSubview(btn) } override func heightForHeader() -> CGFloat { return 30 } override func footerView() -> FLCollectionHeaderFooterView { let footerView : FLCollectionHeaderFooterView = super.footerView() footerView.backgroundColor = UIColor.purple return footerView } override func heightForFooter() -> CGFloat { return 60 } override func sizeForItem(at item: Int) -> CGSize { return customSize(at: item) } override func sectionInset() -> UIEdgeInsets { return UIEdgeInsets.zero } override func minimumLineSpacing() -> CGFloat { return 50 } override func minimumInteritemSpacing() -> CGFloat { return 50 } }
mit
16e266cbf89502b6bc73cbd68a6af4f6
25.898148
106
0.586231
5.114437
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Playlist/Views/PlaylistCell.swift
1
3135
// // PlaylistCell.swift // MusicApp // // Created by Hưng Đỗ on 6/15/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift import RxDataSources import Action import NSObject_Rx class PlaylistCell: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() collectionView.delegate = self } private var playlistSubscription: Disposable? private var didSelectActionSubscription: Disposable? var playlists: PlaylistCollection! { didSet { playlistSubscription = Observable.just(playlists) .map { collection in collection.playlists } .map { playlists in [PlaylistItemSection(model: "Playlist Collection", items: playlists)] } .bind(to: collectionView.rx.items(dataSource: dataSource)) } } var didSelectAction: Action<Playlist, Void>! { didSet { didSelectActionSubscription = collectionView.rx.modelSelected(Playlist.self) .bind(to: didSelectAction.inputs) } } var registerPreviewAction: Action<UIView, Void>! var playAction: Action<Playlist, Void>! override func prepareForReuse() { playlistSubscription?.dispose() didSelectActionSubscription?.dispose() } deinit { playlistSubscription?.dispose() didSelectActionSubscription?.dispose() } fileprivate lazy var dataSource: RxCollectionViewSectionedReloadDataSource<PlaylistItemSection> = { let dataSource = RxCollectionViewSectionedReloadDataSource<PlaylistItemSection>() dataSource.configureCell = { dataSource, collectionView, indexPath, playlist in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PlaylistItemCell.self), for: indexPath) if let cell = cell as? PlaylistItemCell { let buttonAction = CocoaAction { return self.playAction.execute(playlist).map { _ in } } cell.configure(name: playlist.name, singer: playlist.singer, image: playlist.avatar, action: buttonAction) self.registerPreviewAction.execute(cell) } return cell } return dataSource }() } extension PlaylistCell: UICollectionViewDelegateFlowLayout, PlaylistCellOptions { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return size(of: collectionView) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return itemPadding } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return itemPadding } }
mit
609bffb6f7bf7bd868697effbdcf2d09
33.395604
175
0.675719
5.80705
false
false
false
false
satorun/designPattern
AbstractFactory/AbstractFactory/ListPage.swift
1
592
// // ListPage.swift // AbstractFactory // // Created by satorun on 2016/02/05. // Copyright © 2016年 satorun. All rights reserved. // class ListPage: Page { override func makeHTML() -> String { var buffer = "<html><head><title>\(title)</title></head>\n" buffer += "<body>\n" buffer += "<h1>\(title)</h1>" buffer += "<ul>\n" for item in content { buffer += item.makeHTML() } buffer += "</ul>\n" buffer += "<hr><address>\(author)</address>" buffer += "</body></html>\n" return buffer } }
mit
424627f57de6cce885b7df1584195221
25.818182
67
0.517827
3.704403
false
false
false
false
caodong1991/SwiftStudyNote
Swift.playground/Pages/15 - Deinitialization.xcplaygroundpage/Contents.swift
1
2059
import Foundation // 析构过程 /* 析构器只适用于类类型,当一个类的实例被释放之前,析构器会被立即调用。 析构器用关键字deinit标示。 */ // 析构过程原理 /* Swift会自动释放不在需要的实例以释放资源。 Swift通过自动引用计数处理实例的内存管理。 通常当你的实例被释放时不需要手动去清理。 但是,当使用自己的资源时,可能需要进行一些额外的清理。 */ /* 在类的定义中,每个类最多只能有一个析构器,而且析构器不带任何参数。 deinit { // 执行析构过程 } */ /* 析构器是在实例释放发生前被自动调用的,析构器不允许被主动调用的。 子类继承了父类的析构器,并且在子类析构器实现的最后,父类的析构器会被自动调用。 即使子类没有提供自己的析构器,父类的析构器也同样会被调用。 */ // 析构器实践 struct Bank { static var coinsInBank = 10_000 static func distribute(coins numberOfConinsRequested: Int) -> Int { let numberOfConinsToVend = min(numberOfConinsRequested, coinsInBank) coinsInBank -= numberOfConinsToVend return numberOfConinsToVend } static func receive(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.distribute(coins: coins) } func win(coins: Int) { coinsInPurse += Bank.distribute(coins: coins) } deinit { Bank.receive(coins: coinsInPurse) } } var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") print("There are now \(Bank.coinsInBank) coins left in the bank") playerOne!.win(coins: 2_000) print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse)") print("The bank now only has \(Bank.coinsInBank) coins left") playerOne = nil print("PlayerOne has left the game") print("The bank now has \(Bank.coinsInBank) coins")
mit
aed3040347fc00116770a082f7780d36
21.343284
79
0.700067
2.935294
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Mocks/MockStoreKit1Wrapper.swift
1
1290
// // Created by RevenueCat on 3/2/20. // Copyright (c) 2020 Purchases. All rights reserved. // @testable import RevenueCat import StoreKit class MockStoreKit1Wrapper: StoreKit1Wrapper { var payment: SKPayment? var addPaymentCallCount = 0 var mockAddPaymentTransactionState: SKPaymentTransactionState = .purchasing var mockCallUpdatedTransactionInstantly = false override func add(_ newPayment: SKPayment) { payment = newPayment addPaymentCallCount += 1 if mockCallUpdatedTransactionInstantly { let transaction = MockTransaction() transaction.mockPayment = newPayment transaction.mockState = mockAddPaymentTransactionState delegate?.storeKit1Wrapper(self, updatedTransaction: transaction) } } var finishCalled = false var finishProductIdentifier: String? override func finishTransaction(_ transaction: SKPaymentTransaction) { self.finishCalled = true self.finishProductIdentifier = transaction.productIdentifier } weak var mockDelegate: StoreKit1WrapperDelegate? override var delegate: StoreKit1WrapperDelegate? { get { return mockDelegate } set { mockDelegate = newValue } } }
mit
fe2d1e6bd546d3b06c55db76613a6f87
27.666667
79
0.689922
5.308642
false
false
false
false
jmgc/swift
stdlib/public/core/ArrayBuffer.swift
1
21943
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // 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 // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims @usableFromInline internal typealias _ArrayBridgeStorage = _BridgeStorage<__ContiguousArrayStorageBase> @usableFromInline @frozen internal struct _ArrayBuffer<Element>: _ArrayBufferProtocol { /// Create an empty buffer. @inlinable internal init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } @inlinable internal init(nsArray: AnyObject) { _internalInvariant(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Precondition: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @inlinable __consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deferring checking each element's `U`-ness until it is accessed. /// /// - Precondition: `U` is a class or `@objc` existential derived from /// `Element`. @inlinable __consuming internal func downcast<U>( toBufferWithDeferredTypeCheckOf _: U.Type ) -> _ArrayBuffer<U> { _internalInvariant(_isClassOrObjCExistential(Element.self)) _internalInvariant(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/20028320> generic metatype casting doesn't work // _internalInvariant(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage(native: _native._storage, isFlagged: true)) } @inlinable internal var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// @inlinable internal init(storage: _ArrayBridgeStorage) { _storage = storage } @usableFromInline internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. @inlinable internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// This function should only be used for internal sanity checks. /// To guard a buffer mutation, use `beginCOWMutation`. @inlinable internal mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedUnflaggedNative() } return _storage.isUniquelyReferencedNative() && _isNative } /// Returns `true` and puts the buffer in a mutable state iff the buffer's /// storage is uniquely-referenced. /// /// - Precondition: The buffer must be immutable. /// /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer /// is mutated. @_alwaysEmitIntoClient internal mutating func beginCOWMutation() -> Bool { let isUnique: Bool if !_isClassOrObjCExistential(Element.self) { isUnique = _storage.beginCOWMutationUnflaggedNative() } else if !_storage.beginCOWMutationNative() { return false } else { isUnique = _isNative } #if INTERNAL_CHECKS_ENABLED if isUnique { _native.isImmutable = false } #endif return isUnique } /// Puts the buffer in an immutable state. /// /// - Precondition: The buffer must be mutable or the empty array singleton. /// /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated /// until the next call of `beginCOWMutation`. @_alwaysEmitIntoClient @inline(__always) internal mutating func endCOWMutation() { #if INTERNAL_CHECKS_ENABLED _native.isImmutable = true #endif _storage.endCOWMutation() } /// Convert to an NSArray. /// /// O(1) if the element type is bridged verbatim, O(*n*) otherwise. @inlinable internal func _asCocoaArray() -> AnyObject { return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative.buffer } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew() -> _ArrayBuffer { return _consumeAndCreateNew(bufferIsUnique: false, minimumCapacity: count, growForAppend: false) } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced and the elements are moved - instead of copied - to the new /// buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`, but at least kept at `minimumCapacity`. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) -> _ArrayBuffer { let newCapacity = _growArrayCapacity(oldCapacity: capacity, minimumCapacity: minimumCapacity, growForAppend: growForAppend) let c = count _internalInvariant(newCapacity >= c) let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: c, minimumCapacity: newCapacity) if bufferIsUnique { // As an optimization, if the original buffer is unique, we can just move // the elements instead of copying. let dest = newBuffer.firstElementAddress dest.moveInitialize(from: mutableFirstElementAddress, count: c) _native.mutableCount = 0 } else { _copyContents( subRange: 0..<c, initializing: newBuffer.mutableFirstElementAddress) } return _ArrayBuffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @inlinable internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.mutableCapacity >= minimumCapacity) { return b } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) @usableFromInline internal func _typeCheckSlowPath(_ index: Int) { if _fastPath(_isNative) { let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { let element = _nonNative[index] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } } @inlinable internal func _typeCheck(_ subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange.lowerBound ..< subRange.upperBound { _typeCheckSlowPath(i) } } } /// 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. @inlinable @discardableResult __consuming internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(bounds) if _fastPath(_isNative) { return _native._copyContents(subRange: bounds, initializing: target) } let buffer = UnsafeMutableRawPointer(target) .assumingMemoryBound(to: AnyObject.self) let result = _nonNative._copyContents( subRange: bounds, initializing: buffer) return UnsafeMutableRawPointer(result).assumingMemoryBound(to: Element.self) } public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { // This customization point is not implemented for internal types. // Accidentally calling it would be a catastrophic performance bug. fatalError("unsupported") } /// Returns a `_SliceBuffer` containing the given sub-range of elements in /// `bounds` from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(bounds) if _fastPath(_isNative) { return _native[bounds] } return _nonNative[bounds].unsafeCastElements(to: Element.self) } set { fatalError("not implemented") } } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { _internalInvariant(_isNative, "must be a native buffer") return _native.firstElementAddress } /// A mutable pointer to the first element. /// /// - Precondition: the buffer must be mutable. @_alwaysEmitIntoClient internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> { _internalInvariant(_isNative, "must be a native buffer") return _native.mutableFirstElementAddress } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return _fastPath(_isNative) ? firstElementAddress : nil } /// The number of elements the buffer stores. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCount` or `mutableCount` instead. @inlinable internal var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.endIndex } set { _internalInvariant(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient internal var immutableCount: Int { return _fastPath(_isNative) ? _native.immutableCount : _nonNative.endIndex } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableCount: Int { @inline(__always) get { _internalInvariant( _isNative, "attempting to get mutating-count of non-native buffer") return _native.mutableCount } @inline(__always) set { _internalInvariant(_isNative, "attempting to update count of Cocoa array") _native.mutableCount = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeTypeCheckedBounds( _ index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal func _checkValidSubscriptMutating(_ index: Int) { _native._checkValidSubscriptMutating(index) } /// The number of elements the buffer can store without reallocation. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCapacity` or `mutableCapacity` instead. @inlinable internal var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.endIndex } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient internal var immutableCapacity: Int { return _fastPath(_isNative) ? _native.immutableCapacity : _nonNative.count } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableCapacity: Int { _internalInvariant(_isNative, "attempting to get mutating-capacity of non-native buffer") return _native.mutableCapacity } @inlinable @inline(__always) internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), to: Element.self) } @inline(never) @inlinable // @specializable internal func _getElementSlowPath(_ i: Int) -> AnyObject { _internalInvariant( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = cast(toBufferOf: AnyObject.self)._native[i] precondition( element is Element, """ Down-casted Array element failed to match the target type Expected \(Element.self) but found \(type(of: element)) """ ) } else { // ObjC arrays do their own subscript checking. element = _nonNative[i] precondition( element is Element, """ NSArray element failed to match the Swift Array Element type Expected \(Element.self) but found \(type(of: element)) """ ) } return element } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replaceSubrange( i..<(i + 1), with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body( UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _internalInvariant( _isNative || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body(UnsafeMutableBufferPointer( start: firstElementAddressIfContiguous, count: count)) } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative.buffer } /// An object that keeps the elements stored in this buffer alive. /// /// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`. @inlinable internal var nativeOwner: AnyObject { _internalInvariant(_isNative, "Expect a native array") return _native._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. @inlinable internal var identity: UnsafeRawPointer { if _isNative { return _native.identity } else { return UnsafeRawPointer( Unmanaged.passUnretained(_nonNative.buffer).toOpaque()) } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable 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:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> //===--- private --------------------------------------------------------===// internal typealias Storage = _ContiguousArrayStorage<Element> @usableFromInline internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @inlinable internal var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isUnflaggedNative } } /// Our native representation. /// /// - Precondition: `_isNative`. @inlinable internal var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.unflaggedNativeInstance) } /// Fast access to the native representation. /// /// - Precondition: `_isNativeTypeChecked`. @inlinable internal var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.unflaggedNativeInstance) } @inlinable internal var _nonNative: _CocoaArrayWrapper { get { _internalInvariant(_isClassOrObjCExistential(Element.self)) return _CocoaArrayWrapper(_storage.objCInstance) } } } #endif
apache-2.0
c13b72e5b648dea2c769eb825c373579
31.505185
93
0.669751
4.821138
false
false
false
false
SlayterDev/iOS-Window-Manager
WindowManager/Dock.swift
1
3020
// // Dock.swift // WindowManager // // Created by bslayter on 6/19/17. // // import UIKit class Dock: UIView { lazy var dockItems = [DockItem]() let standardOffset: CGFloat = 30 let standardItemSize: CGFloat = 100 func getItemFrame(forIndex index: Int) -> CGRect { return CGRect(x: CGFloat(index) * standardItemSize + standardOffset, y: frame.origin.y, width: standardItemSize, height: standardItemSize) } func moveWindowToDock(window: BSWindow) { let itemFrame = getItemFrame(forIndex: dockItems.count) let dockItem = DockItem(withWindow: window) UIView.animate(withDuration: 0.25, animations: { window.frame = itemFrame }, completion: { _ in window.removeFromSuperview() self.addDockItem(dockItem) }) } func addDockItem(_ dockItem: DockItem) { dockItem.imageView = UIImageView(image: dockItem.windowThumbnail).then { self.addSubview($0) $0.contentMode = .scaleAspectFit $0.tag = self.dockItems.count let tapGesture = UITapGestureRecognizer() tapGesture.addTarget(self, action: #selector(restoreDockItem(_:))) $0.isUserInteractionEnabled = true $0.addGestureRecognizer(tapGesture) } dockItems.append(dockItem) makeDockItemConstraints() } func makeDockItemConstraints() { for (i, obj) in dockItems.enumerated() { obj.imageView?.snp.makeConstraints { (make) in if i > 0 { make.left.equalTo(dockItems[i - 1].imageView!.snp.right).offset(standardOffset) } else { make.left.equalTo(self).offset(standardOffset) } make.bottom.equalTo(self) make.height.width.equalTo(standardItemSize) } } } func removeDockItem(_ dockItem: DockItem) { if let index = dockItems.index(of: dockItem) { dockItems.remove(at: index) dockItem.imageView?.removeFromSuperview() makeDockItemConstraints() } } func restoreDockItem(_ tapGesture: UITapGestureRecognizer) { guard let imageView = tapGesture.view else { return } guard let index = dockItems.index(where: { $0.imageView == imageView }) else { return } let dockItem = dockItems[index] guard let window = dockItem.window else { return } guard let targetFrame = window.toolbar.previousFrame else { return } WindowManager.shared.addWindowToDesktop(window: window) window.frame = getItemFrame(forIndex: index) UIView.animate(withDuration: 0.25, animations: { self.removeDockItem(dockItem) window.frame = targetFrame }, completion: { _ in WindowManager.shared.focus(window: window) }) } }
mit
119117b339deef3b729fc19a416ec7b7
32.186813
99
0.589073
4.534535
false
false
false
false
dduan/swift
test/1_stdlib/Interval.swift
1
5859
//===--- Interval.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // // XFAIL: interpret import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif // Check that the generic parameter is called 'Bound'. protocol TestProtocol1 {} extension HalfOpenInterval where Bound : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension ClosedInterval where Bound : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } var IntervalTestSuite = TestSuite("Interval") IntervalTestSuite.test("Ambiguity") { // Ensure type deduction still works as expected; these will fail to // compile if it's broken var pieToPie = -3.1415927..<3.1415927 expectType(HalfOpenInterval<Double>.self, &pieToPie) var pieThruPie = -3.1415927...3.1415927 expectType(ClosedInterval<Double>.self, &pieThruPie) var zeroToOne = 0..<1 expectType(Range<Int>.self, &zeroToOne) var zeroThruOne = 0...1 // If/when we get a separate ClosedRange representation, this test // will have to change. expectType(Range<Int>.self, &zeroThruOne) } IntervalTestSuite.test("PatternMatching") { let pie = 3.1415927 let expectations : [(Double, halfOpen: Bool, closed: Bool)] = [ (-2 * pie, false, false), (-pie, true, true), (0, true, true), (pie, false, true), (2 * pie, false, false) ] for (x, halfOpenExpected, closedExpected) in expectations { var halfOpen: Bool switch x { case -3.1415927..<3.1415927: halfOpen = true default: halfOpen = false } var closed: Bool switch x { case -3.1415927...3.1415927: closed = true default: closed = false } expectEqual(halfOpenExpected, halfOpen) expectEqual(closedExpected, closed) } } IntervalTestSuite.test("Overlaps") { func expectOverlaps< I0: Interval, I1: Interval where I0.Bound == I1.Bound >(expectation: Bool, _ lhs: I0, _ rhs: I1) { if expectation { expectTrue(lhs.overlaps(rhs)) expectTrue(rhs.overlaps(lhs)) } else { expectFalse(lhs.overlaps(rhs)) expectFalse(rhs.overlaps(lhs)) } } // 0-4, 5-10 expectOverlaps(false, 0..<4, 5..<10) expectOverlaps(false, 0..<4, 5...10) expectOverlaps(false, 0...4, 5..<10) expectOverlaps(false, 0...4, 5...10) // 0-5, 5-10 expectOverlaps(false, 0..<5, 5..<10) expectOverlaps(false, 0..<5, 5...10) expectOverlaps(true, 0...5, 5..<10) expectOverlaps(true, 0...5, 5...10) // 0-6, 5-10 expectOverlaps(true, 0..<6, 5..<10) expectOverlaps(true, 0..<6, 5...10) expectOverlaps(true, 0...6, 5..<10) expectOverlaps(true, 0...6, 5...10) // 0-20, 5-10 expectOverlaps(true, 0..<20, 5..<10) expectOverlaps(true, 0..<20, 5...10) expectOverlaps(true, 0...20, 5..<10) expectOverlaps(true, 0...20, 5...10) // 0-0, 0-5 expectOverlaps(false, 0..<0, 0..<5) expectOverlaps(false, 0..<0, 0...5) } IntervalTestSuite.test("Emptiness") { expectTrue((0.0..<0.0).isEmpty) expectFalse((0.0...0.0).isEmpty) expectFalse((0.0..<0.1).isEmpty) expectFalse((0.0..<0.1).isEmpty) } IntervalTestSuite.test("start/end") { expectEqual(0.0, (0.0..<0.1).start) expectEqual(0.0, (0.0...0.1).start) expectEqual(0.1, (0.0..<0.1).end) expectEqual(0.1, (0.0...0.1).end) } // Something to test with that distinguishes debugDescription from description struct X<T : Comparable> : Comparable, CustomStringConvertible, CustomDebugStringConvertible { init(_ a: T) { self.a = a } var description: String { return String(a) } var debugDescription: String { return "X(\(String(reflecting: a)))" } var a: T } func < <T : Comparable>(lhs: X<T>, rhs: X<T>) -> Bool { return lhs.a < rhs.a } func == <T : Comparable>(lhs: X<T>, rhs: X<T>) -> Bool { return lhs.a == rhs.a } IntervalTestSuite.test("CustomStringConvertible/CustomDebugStringConvertible") { expectEqual("0.0..<0.1", String(X(0.0)..<X(0.1))) expectEqual("0.0...0.1", String(X(0.0)...X(0.1))) expectEqual( "HalfOpenInterval(X(0.0)..<X(0.5))", String(reflecting: HalfOpenInterval(X(0.0)..<X(0.5)))) expectEqual( "ClosedInterval(X(0.0)...X(0.5))", String(reflecting: ClosedInterval(X(0.0)...X(0.5)))) } IntervalTestSuite.test("rdar12016900") { do { let wc = 0 expectFalse((0x00D800 ..< 0x00E000).contains(wc)) } do { let wc = 0x00D800 expectTrue((0x00D800 ..< 0x00E000).contains(wc)) } } IntervalTestSuite.test("clamp") { expectEqual( (5..<10).clamp(0..<3), 5..<5) expectEqual( (5..<10).clamp(0..<9), 5..<9) expectEqual( (5..<10).clamp(0..<13), 5..<10) expectEqual( (5..<10).clamp(7..<9), 7..<9) expectEqual( (5..<10).clamp(7..<13), 7..<10) expectEqual( (5..<10).clamp(13..<15), 10..<10) expectEqual( (5...10).clamp(0...3), 5...5) expectEqual( (5...10).clamp(0...9), 5...9) expectEqual( (5...10).clamp(0...13), 5...10) expectEqual( (5...10).clamp(7...9), 7...9) expectEqual( (5...10).clamp(7...13), 7...10) expectEqual( (5...10).clamp(13...15), 10...10) } runAllTests()
apache-2.0
758d534ba47ca7272c26f1ebed7613b6
24.25431
94
0.620242
3.217463
false
true
false
false
hgani/ganilib-ios
glib/Classes/View/Helper/EventHelper.swift
1
585
import UIKit public class EventHelper<T: UIView> { private unowned let view: T private var onClick: ((T) -> Void)? public init(_ view: T) { self.view = view } open func onClick(_ command: @escaping (T) -> Void) { onClick = command let singleTap = UITapGestureRecognizer(target: self, action: #selector(performClick)) view.isUserInteractionEnabled = true view.addGestureRecognizer(singleTap) } @objc open func performClick() { if let callback = self.onClick { callback(view) } } }
mit
128c0bf50a243cdbb2939ff47152fb95
23.375
93
0.606838
4.431818
false
false
false
false
roecrew/AudioKit
Examples/iOS/AnalogSynthX/AnalogSynthX/CustomControls/VerticalSlider.swift
1
5079
// // VerticalSlider.swift // Swift Synth // // Created by Matthew Fecher on 1/11/16. // Copyright (c) 2016 AudioKit. All rights reserved. // Slider code adapted from: // http://www.totem.training/swift-ios-tips-tricks-tutorials-blog/paint-code-and-live-views import UIKit protocol VerticalSliderDelegate { func sliderValueDidChange(value: Double, tag: Int) } @IBDesignable class VerticalSlider: UIControl { var minValue: CGFloat = 0.0 var maxValue: CGFloat = 1.0 var currentValue: CGFloat = 0.45 { didSet { if currentValue < 0 { currentValue = 0 } if currentValue > maxValue { currentValue = maxValue } self.sliderValue = CGFloat((currentValue - minValue) / (maxValue - minValue)) setupView() } } let knobSize = CGSize(width: 43, height: 31) let barMargin: CGFloat = 20.0 var knobRect: CGRect! var barLength: CGFloat = 164.0 var isSliding = false var sliderValue: CGFloat = 0.5 var delegate: VerticalSliderDelegate? //// Image Declarations var slider_top = UIImage(named: "slider_top.png") var slider_track = UIImage(named: "slider_track.png") override init(frame: CGRect) { super.init(frame: frame) contentMode = .Redraw } required init?(coder: NSCoder) { super.init(coder: coder) self.userInteractionEnabled = true contentMode = .Redraw } class override func requiresConstraintBasedLayout() -> Bool { return true } } // MARK: - Lifecycle extension VerticalSlider { override func awakeFromNib() { super.awakeFromNib() setupView() } func setupView() { knobRect = CGRect(x: 0, y: convertValueToY(currentValue) - (knobSize.height / 2), width: knobSize.width, height: knobSize.height) barLength = bounds.height - (barMargin * 2) let bundle = NSBundle(forClass: self.dynamicType) slider_top = UIImage(named: "slider_top", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)! slider_track = UIImage(named: "slider_track", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)! } override func drawRect(rect: CGRect) { drawVerticalSlider(controlFrame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height), knobRect: knobRect) } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setupView() } } // MARK: - Helpers extension VerticalSlider { func convertYToValue(y: CGFloat) -> CGFloat { let offsetY = bounds.height - barMargin - y let value = (offsetY * maxValue) / barLength return value } func convertValueToY(value: CGFloat) -> CGFloat { let rawY = (value * barLength) / maxValue let offsetY = bounds.height - barMargin - rawY return offsetY } } // MARK: - Control Touch Handling extension VerticalSlider { override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { if CGRectContainsPoint(knobRect, touch.locationInView(self)) { isSliding = true } return true } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { let rawY = touch.locationInView(self).y if isSliding { let value = convertYToValue(rawY) if value != minValue || value != maxValue { currentValue = value delegate?.sliderValueDidChange(Double(currentValue), tag: self.tag) setNeedsDisplay() } } return true } override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { isSliding = false } func drawVerticalSlider(controlFrame controlFrame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 216), knobRect: CGRect = CGRect(x: 0, y: 89, width: 36, height: 32)) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Background Drawing let backgroundRect = CGRectMake(controlFrame.minX + 2, controlFrame.minY + 10, 38, 144) let backgroundPath = UIBezierPath(rect: backgroundRect) CGContextSaveGState(context) backgroundPath.addClip() slider_track!.drawInRect(CGRectMake(floor(backgroundRect.minX + 0.5), floor(backgroundRect.minY + 0.5), slider_track!.size.width, slider_track!.size.height)) CGContextRestoreGState(context) //// Slider Top Drawing let sliderTopRect = CGRectMake(knobRect.origin.x, knobRect.origin.y, knobRect.size.width, knobRect.size.height) let sliderTopPath = UIBezierPath(rect: sliderTopRect) CGContextSaveGState(context) sliderTopPath.addClip() slider_top!.drawInRect(CGRectMake(floor(sliderTopRect.minX + 0.5), floor(sliderTopRect.minY + 0.5), slider_top!.size.width, slider_top!.size.height)) CGContextRestoreGState(context) } }
mit
18fa54908fa66b14a19c2ba83ef50aec
31.980519
172
0.646781
4.428073
false
false
false
false
patbonecrusher/Cards
Cards/Deck.swift
1
861
// // Deck.swift // PaymeProto // // Created by pat on 6/15/14. // Copyright (c) 2014 CovenOfChaos. All rights reserved. // import Foundation public class Deck: CardPile { public convenience init(includeJoker:Bool = true) { self.init(cards: { let ranksPerSuit = 13 var deck = [Card]() for index in 0..<52 { let suit = Suit(rawValue: index / ranksPerSuit) let rank = Rank(rawValue: index % ranksPerSuit + 1) let card = Card(rank: rank!, suit: suit!) deck.append(card) } if (includeJoker) { deck.append(Card(rank: Rank.JokerLow, suit: Suit.Special)); deck.append(Card(rank: Rank.JokerHigh, suit: Suit.Special)); } return deck }()) } public override init(cards: [Card]) { super.init(cards: cards) } }
mit
20d9453f987b722dac119345673fac05
20.525
68
0.569106
3.528689
false
false
false
false
alexhillc/AXPhotoViewer
Source/Classes/Views/AXOverlayView.swift
1
15955
// // AXOverlayView.swift // AXPhotoViewer // // Created by Alex Hill on 5/28/17. // Copyright © 2017 Alex Hill. All rights reserved. // import UIKit @objc open class AXOverlayView: UIView, AXStackableViewContainerDelegate { #if os(iOS) /// The toolbar used to set the `titleView`, `leftBarButtonItems`, `rightBarButtonItems` @objc public let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: 320, height: 44))) /// The title view displayed in the toolbar. This view is sized and centered between the `leftBarButtonItems` and `rightBarButtonItems`. /// This is prioritized over `title`. @objc public var titleView: AXOverlayTitleViewProtocol? { didSet { assert(self.titleView == nil ? true : self.titleView is UIView, "`titleView` must be a UIView.") if self.window == nil { return } self.updateToolbarBarButtonItems() } } /// The bar button item used internally to display the `titleView` attribute in the toolbar. var titleViewBarButtonItem: UIBarButtonItem? /// The title displayed in the toolbar. This string is centered between the `leftBarButtonItems` and `rightBarButtonItems`. /// Overwrites `internalTitle`. @objc public var title: String? { didSet { self.updateTitleBarButtonItem() } } /// The title displayed in the toolbar. This string is centered between the `leftBarButtonItems` and `rightBarButtonItems`. /// This is used internally by the library to set a default title. Overwritten by `title`. var internalTitle: String? { didSet { self.updateTitleBarButtonItem() } } /// The title text attributes inherited by the `title`. @objc public var titleTextAttributes: [NSAttributedString.Key: Any]? { didSet { self.updateTitleBarButtonItem() } } /// The bar button item used internally to display the `title` attribute in the toolbar. let titleBarButtonItem = UIBarButtonItem(customView: UILabel()) /// The bar button item that appears in the top left corner of the overlay. @objc public var leftBarButtonItem: UIBarButtonItem? { set(value) { if let value = value { self.leftBarButtonItems = [value] } else { self.leftBarButtonItems = nil } } get { return self.leftBarButtonItems?.first } } /// The bar button items that appear in the top left corner of the overlay. @objc public var leftBarButtonItems: [UIBarButtonItem]? { didSet { if self.window == nil { return } self.updateToolbarBarButtonItems() } } /// The bar button item that appears in the top right corner of the overlay. @objc public var rightBarButtonItem: UIBarButtonItem? { set(value) { if let value = value { self.rightBarButtonItems = [value] } else { self.rightBarButtonItems = nil } } get { return self.rightBarButtonItems?.first } } /// The bar button items that appear in the top right corner of the overlay. @objc public var rightBarButtonItems: [UIBarButtonItem]? { didSet { if self.window == nil { return } self.updateToolbarBarButtonItems() } } #endif /// The caption view to be used in the overlay. @objc open var captionView: AXCaptionViewProtocol = AXCaptionView() { didSet { guard let oldCaptionView = oldValue as? UIView else { assertionFailure("`oldCaptionView` must be a UIView.") return } guard let captionView = self.captionView as? UIView else { assertionFailure("`captionView` must be a UIView.") return } let index = self.bottomStackContainer.subviews.firstIndex(of: oldCaptionView) oldCaptionView.removeFromSuperview() self.bottomStackContainer.insertSubview(captionView, at: index ?? 0) self.setNeedsLayout() } } /// Whether or not to animate `captionView` changes. Defaults to true. @objc public var animateCaptionViewChanges: Bool = true { didSet { self.captionView.animateCaptionInfoChanges = self.animateCaptionViewChanges } } /// The inset of the contents of the `OverlayView`. Use this property to adjust layout for things such as status bar height. /// For internal use only. var contentInset: UIEdgeInsets = .zero { didSet { self.setNeedsLayout() } } /// Container to embed all content anchored at the top of the `overlayView`. /// Add custom subviews to the top container in the order that you wish to stack them. These must be self-sizing views. @objc public var topStackContainer: AXStackableViewContainer! /// Container to embed all content anchored at the bottom of the `overlayView`. /// Add custom subviews to the bottom container in the order that you wish to stack them. These must be self-sizing views. @objc public var bottomStackContainer: AXStackableViewContainer! /// A flag that is set at the beginning and end of `OverlayView.setShowInterface(_:alongside:completion:)` fileprivate var isShowInterfaceAnimating = false /// Closures to be processed at the end of `OverlayView.setShowInterface(_:alongside:completion:)` fileprivate var showInterfaceCompletions = [() -> Void]() fileprivate var isFirstLayout: Bool = true @objc public init() { super.init(frame: .zero) self.topStackContainer = AXStackableViewContainer(views: [], anchoredAt: .top) self.topStackContainer.backgroundColor = AXConstants.overlayForegroundColor self.topStackContainer.delegate = self self.addSubview(self.topStackContainer) #if os(iOS) self.toolbar.backgroundColor = .clear self.toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) self.topStackContainer.addSubview(self.toolbar) #endif self.bottomStackContainer = AXStackableViewContainer(views: [], anchoredAt: .bottom) self.bottomStackContainer.backgroundColor = AXConstants.overlayForegroundColor self.bottomStackContainer.delegate = self self.addSubview(self.bottomStackContainer) self.captionView.animateCaptionInfoChanges = true if let captionView = self.captionView as? UIView { self.bottomStackContainer.addSubview(captionView) } NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: .main) { [weak self] (note) in self?.setNeedsLayout() } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } open override func didMoveToWindow() { super.didMoveToWindow() #if os(iOS) if self.window != nil { self.updateToolbarBarButtonItems() } #endif } open override func layoutSubviews() { super.layoutSubviews() self.topStackContainer.contentInset = UIEdgeInsets(top: self.contentInset.top, left: self.contentInset.left, bottom: 0, right: self.contentInset.right) self.topStackContainer.frame = CGRect(origin: .zero, size: self.topStackContainer.sizeThatFits(self.frame.size)) self.bottomStackContainer.contentInset = UIEdgeInsets(top: 0, left: self.contentInset.left, bottom: self.contentInset.bottom, right: self.contentInset.right) let bottomStackSize = self.bottomStackContainer.sizeThatFits(self.frame.size) self.bottomStackContainer.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.size.height - bottomStackSize.height), size: bottomStackSize) self.isFirstLayout = false } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let view = super.hitTest(point, with: event) as? UIControl { return view } return nil } // MARK: - Completions func performAfterShowInterfaceCompletion(_ closure: @escaping () -> Void) { self.showInterfaceCompletions.append(closure) if !self.isShowInterfaceAnimating { self.processShowInterfaceCompletions() } } func processShowInterfaceCompletions() { for completion in self.showInterfaceCompletions { completion() } self.showInterfaceCompletions.removeAll() } // MARK: - Show / hide interface func setShowInterface(_ show: Bool, animated: Bool, alongside closure: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) { let alpha: CGFloat = show ? 1 : 0 if abs(alpha - self.alpha) <= .ulpOfOne { return } self.isShowInterfaceAnimating = true if abs(alpha - 1) <= .ulpOfOne { self.isHidden = false } let animations = { [weak self] in self?.alpha = alpha closure?() } let internalCompletion: (_ finished: Bool) -> Void = { [weak self] (finished) in if abs(alpha) <= .ulpOfOne { self?.isHidden = true } self?.isShowInterfaceAnimating = false completion?(finished) self?.processShowInterfaceCompletions() } if animated { UIView.animate(withDuration: AXConstants.frameAnimDuration, animations: animations, completion: internalCompletion) } else { animations() internalCompletion(true) } } // MARK: - AXCaptionViewProtocol func updateCaptionView(photo: AXPhotoProtocol) { self.captionView.applyCaptionInfo(attributedTitle: photo.attributedTitle ?? nil, attributedDescription: photo.attributedDescription ?? nil, attributedCredit: photo.attributedCredit ?? nil) if self.isFirstLayout { self.setNeedsLayout() return } let size = self.bottomStackContainer.sizeThatFits(self.frame.size) let animations = { [weak self] in guard let `self` = self else { return } self.bottomStackContainer.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.size.height - size.height), size: size) self.bottomStackContainer.setNeedsLayout() self.bottomStackContainer.layoutIfNeeded() } if self.animateCaptionViewChanges { UIView.animate(withDuration: AXConstants.frameAnimDuration, animations: animations) } else { animations() } } // MARK: - AXStackableViewContainerDelegate func stackableViewContainer(_ stackableViewContainer: AXStackableViewContainer, didAddSubview: UIView) { self.setNeedsLayout() } func stackableViewContainer(_ stackableViewContainer: AXStackableViewContainer, willRemoveSubview: UIView) { DispatchQueue.main.async { [weak self] in self?.setNeedsLayout() } } #if os(iOS) // MARK: - UIToolbar convenience func updateToolbarBarButtonItems() { let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixedSpace.width = AXConstants.overlayBarButtonItemSpacing var barButtonItems = [UIBarButtonItem]() if let leftBarButtonItems = self.leftBarButtonItems { let last = leftBarButtonItems.last for barButtonItem in leftBarButtonItems { barButtonItems.append(barButtonItem) if barButtonItem != last { barButtonItems.append(fixedSpace) } } } barButtonItems.append(flexibleSpace) var centerBarButtonItem: UIBarButtonItem? if let titleView = self.titleView as? UIView { if let titleViewBarButtonItem = self.titleViewBarButtonItem, titleViewBarButtonItem.customView === titleView { centerBarButtonItem = titleViewBarButtonItem } else { self.titleViewBarButtonItem = UIBarButtonItem(customView: titleView) centerBarButtonItem = self.titleViewBarButtonItem } } else { centerBarButtonItem = self.titleBarButtonItem } if let centerBarButtonItem = centerBarButtonItem { barButtonItems.append(centerBarButtonItem) barButtonItems.append(flexibleSpace) } if let rightBarButtonItems = self.rightBarButtonItems?.reversed() { let last = rightBarButtonItems.last for barButtonItem in rightBarButtonItems { barButtonItems.append(barButtonItem) if barButtonItem != last { barButtonItems.append(fixedSpace) } } } self.toolbar.items = barButtonItems } func updateTitleBarButtonItem() { func defaultAttributes() -> [NSAttributedString.Key: Any] { let pointSize: CGFloat = 17.0 var font: UIFont if #available(iOS 8.2, *) { font = UIFont.systemFont(ofSize: pointSize, weight: UIFont.Weight.semibold) } else { font = UIFont(name: "HelveticaNeue-Medium", size: pointSize)! } return [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white ] } var attributedText: NSAttributedString? if let title = self.title { attributedText = NSAttributedString(string: title, attributes: self.titleTextAttributes ?? defaultAttributes()) } else if let internalTitle = self.internalTitle { attributedText = NSAttributedString(string: internalTitle, attributes: self.titleTextAttributes ?? defaultAttributes()) } if let attributedText = attributedText { guard let titleBarButtonItemLabel = self.titleBarButtonItem.customView as? UILabel else { return } if titleBarButtonItemLabel.attributedText != attributedText { titleBarButtonItemLabel.attributedText = attributedText titleBarButtonItemLabel.sizeToFit() } } } #endif }
mit
d8a630272dae8eaf579d5c8cecd3074f
37.167464
151
0.590259
5.66951
false
false
false
false
JetBrains/kotlin-native
performance/KotlinVsSwift/ring/src/LoopBenchmark.swift
4
980
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Foundation class LoopBenchmark { var array: [Value] init() { var list: [Value] = [] for n in classValues(Constants.BENCHMARK_SIZE) { list.append(n) } array = list } func arrayLoop() { for x in array { Blackhole.consume(x) } } func arrayIndexLoop() { for i in array.indices { Blackhole.consume(array[i]) } } func rangeLoop() { for i in 0...Constants.BENCHMARK_SIZE { Blackhole.consume(i) } } func arrayWhileLoop() { var i = 0 let s = array.count while (i < s) { Blackhole.consume(array[i]) i += 1 } } func arrayForeachLoop() { array.forEach { Blackhole.consume($0) } } }
apache-2.0
67796f810df2fe70a12eabd039cd7505
19
101
0.515306
3.828125
false
false
false
false
marty-suzuki/QiitaWithFluxSample
QiitaWithFluxSample/Source/Common/Extension/Apple/Date.ISO8601.swift
1
718
// // Date.ISO8601.swift // QiitaWithFluxSample // // Created by marty-suzuki on 2017/04/16. // Copyright © 2017年 marty-suzuki. All rights reserved. // import Foundation extension Date { private static let ISO8601Formatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") //dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" return dateFormatter }() init?(ISO8601String string: String) { guard let date = Date.ISO8601Formatter.date(from: string) else { return nil } self = date } }
mit
41b1079cb5bd704a2818b7d81b011c77
25.481481
72
0.643357
4.085714
false
false
false
false
Jnosh/swift
stdlib/public/core/LazySequence.swift
2
7795
//===--- LazySequence.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 // //===----------------------------------------------------------------------===// /// A sequence on which normally-eager operations such as `map` and /// `filter` are implemented lazily. /// /// Lazy sequences can be used to avoid needless storage allocation /// and computation, because they use an underlying sequence for /// storage and compute their elements on demand. For example, /// /// [1, 2, 3].lazy.map { $0 * 2 } /// /// is a sequence containing { `2`, `4`, `6` }. Each time an element /// of the lazy sequence is accessed, an element of the underlying /// array is accessed and transformed by the closure. /// /// Sequence operations taking closure arguments, such as `map` and /// `filter`, are normally eager: they use the closure immediately and /// return a new array. Using the `lazy` property gives the standard /// library explicit permission to store the closure and the sequence /// in the result, and defer computation until it is needed. /// /// To add new lazy sequence operations, extend this protocol with /// methods that return lazy wrappers that are themselves /// `LazySequenceProtocol`s. For example, given an eager `scan` /// method defined as follows /// /// extension Sequence { /// /// Returns an array containing the results of /// /// /// /// p.reduce(initial, nextPartialResult) /// /// /// /// for each prefix `p` of `self`, in order from shortest to /// /// longest. For example: /// /// /// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15] /// /// /// /// - Complexity: O(n) /// func scan<ResultElement>( /// _ initial: ResultElement, /// _ nextPartialResult: (ResultElement, Element) -> ResultElement /// ) -> [ResultElement] { /// var result = [initial] /// for x in self { /// result.append(nextPartialResult(result.last!, x)) /// } /// return result /// } /// } /// /// we can build a sequence that lazily computes the elements in the /// result of `scan`: /// /// struct LazyScanIterator<Base : IteratorProtocol, ResultElement> /// : IteratorProtocol { /// mutating func next() -> ResultElement? { /// return nextElement.map { result in /// nextElement = base.next().map { nextPartialResult(result, $0) } /// return result /// } /// } /// private var nextElement: ResultElement? // The next result of next(). /// private var base: Base // The underlying iterator. /// private let nextPartialResult: (ResultElement, Base.Element) -> ResultElement /// } /// /// struct LazyScanSequence<Base: Sequence, ResultElement> /// : LazySequenceProtocol // Chained operations on self are lazy, too /// { /// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> { /// return LazyScanIterator( /// nextElement: initial, base: base.makeIterator(), nextPartialResult) /// } /// private let initial: ResultElement /// private let base: Base /// private let nextPartialResult: /// (ResultElement, Base.Element) -> ResultElement /// } /// /// and finally, we can give all lazy sequences a lazy `scan` method: /// /// extension LazySequenceProtocol { /// /// Returns a sequence containing the results of /// /// /// /// p.reduce(initial, nextPartialResult) /// /// /// /// for each prefix `p` of `self`, in order from shortest to /// /// longest. For example: /// /// /// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15] /// /// /// /// - Complexity: O(1) /// func scan<ResultElement>( /// _ initial: ResultElement, /// _ nextPartialResult: (ResultElement, Element) -> ResultElement /// ) -> LazyScanSequence<Self, ResultElement> { /// return LazyScanSequence( /// initial: initial, base: self, nextPartialResult) /// } /// } /// /// - See also: `LazySequence`, `LazyCollectionProtocol`, `LazyCollection` /// /// - Note: The explicit permission to implement further operations /// lazily applies only in contexts where the sequence is statically /// known to conform to `LazySequenceProtocol`. Thus, side-effects such /// as the accumulation of `result` below are never unexpectedly /// dropped or deferred: /// /// extension Sequence where Element == Int { /// func sum() -> Int { /// var result = 0 /// _ = self.map { result += $0 } /// return result /// } /// } /// /// [We don't recommend that you use `map` this way, because it /// creates and discards an array. `sum` would be better implemented /// using `reduce`]. public protocol LazySequenceProtocol : Sequence { /// A `Sequence` that can contain the same elements as this one, /// possibly with a simpler type. /// /// - See also: `elements` associatedtype Elements : Sequence = Self where Elements.Iterator.Element == Iterator.Element /// A sequence containing the same elements as this one, possibly with /// a simpler type. /// /// When implementing lazy operations, wrapping `elements` instead /// of `self` can prevent result types from growing an extra /// `LazySequence` layer. For example, /// /// _prext_ example needed /// /// Note: this property need not be implemented by conforming types, /// it has a default implementation in a protocol extension that /// just returns `self`. var elements: Elements { get } } /// When there's no special associated `Elements` type, the `elements` /// property is provided. extension LazySequenceProtocol where Elements == Self { /// Identical to `self`. public var elements: Self { return self } } /// A sequence containing the same elements as a `Base` sequence, but /// on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceProtocol` public struct LazySequence<Base : Sequence> : LazySequenceProtocol, _SequenceWrapper { /// Creates a sequence that has the same elements as `base`, but on /// which some operations such as `map` and `filter` are implemented /// lazily. internal init(_base: Base) { self._base = _base } public var _base: Base /// The `Base` (presumably non-lazy) sequence from which `self` was created. public var elements: Base { return _base } } extension Sequence { /// A sequence containing the same elements as this sequence, /// but on which some operations, such as `map` and `filter`, are /// implemented lazily. /// /// - SeeAlso: `LazySequenceProtocol`, `LazySequence` public var lazy: LazySequence<Self> { return LazySequence(_base: self) } } /// Avoid creating multiple layers of `LazySequence` wrapper. /// Anything conforming to `LazySequenceProtocol` is already lazy. extension LazySequenceProtocol { /// Identical to `self`. public var lazy: Self { return self } } @available(*, unavailable, renamed: "LazySequenceProtocol") public typealias LazySequenceType = LazySequenceProtocol extension LazySequenceProtocol { @available(*, unavailable, message: "Please use Array initializer instead.") public var array: [Element] { Builtin.unreachable() } }
apache-2.0
a1ae55509733d1a48f8c3adab00b1a35
36.296651
87
0.624631
4.362059
false
false
false
false
kennixdev/APICall
APICall/Sources/APIDebugLog.swift
1
7026
// // APIDebugLog.swift // // Created by Kennix on 6/15/17. // Copyright © 2017 Kennix. All rights reserved. // import Foundation struct APIDebugLog { static func printRequestLog<T: APIRepository>(repo: T,req: URLRequest?, isPrintLog: Bool, isNotiLog: Bool) { guard isPrintLog || isNotiLog else { return } guard let aReq = req else { return } var link: String = aReq.url?.absoluteString ?? "" let timeStr = Date.getNowAsString() var text = "" text += "\n===================== Start Sending Request =====================\n" text += "* Time: \(timeStr)\n" text += "\n* Request URL:\n \(link)" if let beautifulURLString = link.removingPercentEncoding { link = beautifulURLString text += "\n\n* Beautificated URL: \n\(beautifulURLString)" } if let httpMethod = aReq.httpMethod { text += "\n\n* Method: \n \(httpMethod)" } if let headers = aReq.allHTTPHeaderFields, headers.count > 0 { text += "\n\n* Headers:" for (key, value) in headers { text += "\n \(key): \(value)" } } if let body = aReq.httpBody { guard let rawParams = String.init(data: body, encoding: String.Encoding.utf8) else { return } text += "\n\n* Body:" let params = rawParams.components(separatedBy: "&") for param in params { let paramPair = param.components(separatedBy: "=") if paramPair.count < 2 { continue } text += "\n\(paramPair[0]): \(paramPair[1])" } } text += "\n\n* Parameters:\n" text += String.toPrettyJsonString(fromDict: repo.configParameters()) ?? "" text += "\n===================== End Of Request Sent =====================\n" if isPrintLog { print(text) } if isNotiLog { notiLog(type: .request, link: link, content: text, time: timeStr) } } static func printResponseLog(networkResponseInfo: NetworkResponseInfo, isPrintLog: Bool, isNotiLog: Bool) { guard isPrintLog || isNotiLog else { return } let req = networkResponseInfo.request let res = networkResponseInfo.urlResponse let value = networkResponseInfo.responseString let error = networkResponseInfo.error var link: String = req?.url?.absoluteString ?? "" let timeStr = Date.getNowAsString() var text = "" text += "\n===================== Receive Response =====================\n" text += "* Time: \(timeStr)\n" text += "\n* Request URL:\n \(link)" if let beautifulURLString = link.removingPercentEncoding { link = beautifulURLString text += "\n\n* Beautificated URL: \n\(beautifulURLString)" } if let statusCode = res?.statusCode { text += "\n\n* Response Code:\n \(statusCode)" } else { text += "\n\n* Response Code:\n - " } if let rawHeaders = res?.allHeaderFields { text += "\n\n* Header from response:" for (key, value) in rawHeaders { text += "\n \(key): \(value)" } } if let aValue = value { if let jsonString = aValue.toPrettyJsonString() { text += "\n\n* Response:\n\(jsonString)" } else { text += "\n\n* Response:\n\(aValue)" } } if let error = error { text += "\n\n* Error:\n\(error)" } text += "\n\n===================== End Of Response =====================\n" if isPrintLog { print(text) } if isNotiLog { notiLog(type: .response, link: link, content: text, time: timeStr) } } static func printCancelRequest(req: URLRequest?, isPrintLog: Bool, isNotiLog: Bool) { guard isPrintLog || isNotiLog else { return } guard let aReq = req else { return } var link: String = aReq.url?.absoluteString ?? "" let timeStr = Date.getNowAsString() var text = "" text += "\n===================== Request Canceled =====================\n" text += "* Time: \(timeStr)\n" text += "\n* Request URL:\n \(link)" if let beautifulURLString = link.removingPercentEncoding { link = beautifulURLString text += "\n\n* Beautificated URL: \n\(beautifulURLString)" } text += "\n\n===================== End Of Cancel Request =====================\n" if isPrintLog { print(text) } if isNotiLog { notiLog(type: .cancel, link: link, content: text, time: timeStr) } } private static func notiLog( type: APICallHelper.DebugLogNotification.DebugType, link: String, content: String, time: String) { let noti = Notification(name: APICallHelper.DebugLogNotification.notiName, object: nil, userInfo: [APICallHelper.DebugLogNotification.typeTag: type.rawValue, APICallHelper.DebugLogNotification.linkTag: link, APICallHelper.DebugLogNotification.contentTag: content, APICallHelper.DebugLogNotification.timeTag: time]) NotificationCenter.default.post(noti) } } func printlog (_ items: Any..., file: StaticString = #file, fun: StaticString = #function, line: UInt = #line) { guard APICallHelper.isDebugLog else { return } if items.count == 1 { print(items[0]) } else { print(items) } let filepath = "\(file)" let filename = filepath.components(separatedBy: "/").last ?? "" let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" print(" - [\(formatter.string(from: NSDate() as Date))] - \(filename) - \(fun) m\(line)") } extension String { func toPrettyJsonString() -> String? { if let data = self.data(using: String.Encoding.utf8), let jsonObj = try? JSONSerialization.jsonObject(with: data), let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObj, options: .prettyPrinted), let jsonString = String.init(data: prettyJsonData, encoding: String.Encoding.utf8) { return jsonString } return nil } static func toPrettyJsonString(fromDict:[String: Any]) -> String? { if fromDict.count > 0, // let jsonObj = try? JSONSerialization.data(withJSONObject: fromDict), let prettyJsonData = try? JSONSerialization.data(withJSONObject: fromDict, options: .prettyPrinted), let jsonString = String.init(data: prettyJsonData, encoding: String.Encoding.utf8) { return jsonString } else { return nil } } } extension Date { static func getNowAsString() -> String { let date = Date() let format = "yyyy.MM.dd HH:mm:ss.SSS" let formatter = DateFormatter() formatter.dateFormat = format formatter.timeZone = TimeZone.current return formatter.string(from: date) } }
mit
3f345d344308149cd7514b1a31118877
41.065868
322
0.565409
4.257576
false
false
false
false
duliodenis/v
V/V/Model/ContextSyncManager.swift
1
3056
// // ContextSyncManager.swift // V // // Created by Dulio Denis on 7/24/16. // Copyright © 2016 Dulio Denis. All rights reserved. // // Job of this Class is to maintain the main context syned with the background context import UIKit import CoreData class ContextSyncManager: NSObject { private var mainContext: NSManagedObjectContext private var backgroundContext: NSManagedObjectContext var remoteStore: RemoteStore? init(mainContext: NSManagedObjectContext, backgroundContext: NSManagedObjectContext) { self.mainContext = mainContext self.backgroundContext = backgroundContext super.init() // Add two observers to watch for Save Notifications to the main and background contexts NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("mainContextSaved:"), name: NSManagedObjectContextDidSaveNotification, object: mainContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("backgroundContextSaved:"), name: NSManagedObjectContextDidSaveNotification, object: backgroundContext) } func mainContextSaved(notification: NSNotification) { backgroundContext.performBlock({ let inserted = self.objectsForKey(NSInsertedObjectsKey, dictionary: notification.userInfo!, context: self.backgroundContext) let updated = self.objectsForKey(NSUpdatedObjectsKey, dictionary: notification.userInfo!, context: self.backgroundContext) let deleted = self.objectsForKey(NSDeletedObjectsKey, dictionary: notification.userInfo!, context: self.backgroundContext) self.backgroundContext.mergeChangesFromContextDidSaveNotification(notification) self.remoteStore?.store(inserted: inserted, updated: updated, deleted: deleted) }) } func backgroundContextSaved(notification: NSNotification) { mainContext.performBlock({ // use objects for key to properly fault objects self.objectsForKey(NSUpdatedObjectsKey, dictionary: notification.userInfo!, context: self.mainContext).forEach{$0.willAccessValueForKey(nil) } self.mainContext.mergeChangesFromContextDidSaveNotification(notification) }) } private func objectsForKey(key: String, dictionary: NSDictionary, context: NSManagedObjectContext) -> [NSManagedObject] { // unwrap the dictionary by getting the value using the key parameter // returning an empty array if there is no value guard let set = (dictionary[key] as? NSSet) else {return []} // if there are valid objects convert them to an arrayof NSManagedObjects guard let objects = set.allObjects as? [NSManagedObject] else {return []} // get the object from the context using the objectID attribute return objects.map{context.objectWithID($0.objectID)} } }
mit
c0637ae2990ff3b203bfcea738eb20f3
40.849315
185
0.694599
5.85249
false
false
false
false
swordray/ruby-china-ios
RubyChina/Classes/Controllers/SignInController.swift
1
6009
// // SignInController.swift // RubyChina // // Created by Jianqiu Xiao on 2018/3/23. // Copyright © 2018 Jianqiu Xiao. All rights reserved. // import Alamofire class SignInController: ViewController { private var passwordField: UITextField! private var tableView: UITableView! private var usernameField: UITextField! override init() { super.init() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismiss)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(action)) title = "登录" } override func loadView() { tableView = UITableView(frame: .zero, style: .grouped) tableView.cellLayoutMarginsFollowReadableWidth = true tableView.dataSource = self tableView.delegate = self view = tableView usernameField = UITextField() usernameField.autocapitalizationType = .none usernameField.autocorrectionType = .no usernameField.clearButtonMode = .whileEditing usernameField.delegate = self usernameField.font = .preferredFont(forTextStyle: .body) usernameField.placeholder = "帐号" usernameField.returnKeyType = .next usernameField.textContentType = .username passwordField = UITextField() passwordField.clearButtonMode = .whileEditing passwordField.delegate = self passwordField.font = .preferredFont(forTextStyle: .body) passwordField.isSecureTextEntry = true passwordField.placeholder = "密码" passwordField.returnKeyType = .join passwordField.textContentType = .password } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) usernameField.becomeFirstResponder() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.preferredContentSize = tableView.contentSize } private func signIn() { view.endEditing(true) showHUD() let username = usernameField.text ?? "" let password = passwordField.text ?? "" AF.request( baseURL.appendingPathComponent("sessions").appendingPathExtension("json"), method: .post, parameters: [ "username": username, "password": password, ] ) .responseJSON { response in switch response.response?.statusCode ?? 0 { case 200..<300: User.current = try? User(json: response.value ?? [:]) SecAddSharedWebCredential((self.baseURL.host ?? "") as CFString, username as CFString, password as CFString) { _ in } self.dismiss(animated: true) let topicsController = (self.presentingViewController as? UINavigationController)?.viewControllers.first as? TopicsController topicsController?.updateRightBarButtonItem() topicsController?.refetchData() case 401: let alertController = UIAlertController(title: "帐号或密码错误", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "好", style: .default)) self.present(alertController, animated: true) default: self.networkError() } self.hideHUD() } } @objc private func action() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) [("注册", "account/sign_up"), ("忘记密码", "account/password/new")].forEach { title, pathComponent in alertController.addAction(UIAlertAction(title: title, style: .default) { _ in let webViewController = WebViewController() webViewController.title = title webViewController.url = self.baseURL.appendingPathComponent(pathComponent) self.navigationController?.pushViewController(webViewController, animated: true) }) } alertController.addAction(UIAlertAction(title: "取消", style: .cancel)) present(alertController, animated: true) } } extension SignInController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [2, 1][section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = UITableViewCell() cell.selectionStyle = .none cell.textLabel?.text = " " let textField = [usernameField, passwordField][indexPath.row] ?? .init() cell.contentView.addSubview(textField) textField.snp.makeConstraints { $0.edges.equalTo(cell.textLabel ?? .init()) } return cell case 1: let cell = UITableViewCell() cell.textLabel?.text = "登录" cell.textLabel?.textColor = tableView.tintColor return cell default: return .init() } } } extension SignInController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 { tableView.deselectRow(at: indexPath, animated: true) signIn() } } } extension SignInController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case usernameField: passwordField.becomeFirstResponder() case passwordField: signIn() default: break } return false } }
mit
44e52fbf1e75e8d51c2818adfb8762ad
33.252874
141
0.630201
5.539033
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/Common/GLRenderBuffer.swift
1
1037
// // GLRenderBuffer.swift // SwiftGL // // Created by jerry on 2015/8/26. // Copyright © 2015年 Jerry Chan. All rights reserved. // import UIKit import OpenGLES.ES3 import GLKit import SwiftGL class GLRenderBuffer { var viewRenderbuffer:GLuint = 0 var glcontext:EAGLContext! var eaglLayer:CAEAGLLayer! init(view:UIView) { self.glcontext = EAGLContext(api: EAGLRenderingAPI.openGLES3) if self.glcontext == nil { print("Failed to create ES context", terminator: "") } EAGLContext.setCurrent(self.glcontext) eaglLayer = view.layer as! CAEAGLLayer eaglLayer.isOpaque = false eaglLayer.drawableProperties = [kEAGLDrawablePropertyColorFormat:kEAGLColorFormatRGBA8,kEAGLDrawablePropertyRetainedBacking:true] glGenRenderbuffers(1, &viewRenderbuffer) glBindRenderbuffer(GL_RENDERBUFFER_ENUM, viewRenderbuffer); glcontext.renderbufferStorage(Int(GL_RENDERBUFFER), from: eaglLayer) } }
mit
4e46c3965d9a455921f1aea0ab62436e
26.945946
137
0.682785
3.858209
false
false
false
false
robjwells/adventofcode-solutions
2015/swift/AdventOfCode2015/AdventOfCode2015/AoC2015_01.swift
1
868
// // AoC2015-01.swift // AdventOfCode2015 // // Created by Rob Wells on 2019-08-18. // Copyright © 2019 Rob Wells. All rights reserved. // import Foundation struct AoC2015_01: AdventOfCodeSolution { static var year: Int = 2015 static var day: Int = 1 static func solvePartOne(input: String) -> String { let result = input.reduce(0) { floor, direction in direction == "(" ? floor + 1 : floor - 1 } return "\(result)" } static func solvePartTwo(input: String) -> String { var floor = 0 for (index, character) in input.enumerated() { floor += (character == "(" ? 1 : -1) if floor == -1 { return "\(index + 1)" // Problem starts from position 1 } } return "Did not enter basement, reached floor \(floor)" } }
mit
0c0d52eee4f8ac4201a390b08a55d6da
26.09375
72
0.550173
3.870536
false
false
false
false
arslanbilal/cryptology-project
Cryptology Project/Cryptology Project/Classes/Controllers/LoginController/LoginViewController.swift
1
6861
// // LoginController.swift // Cryptology Project // // Created by Bilal Arslan on 13/03/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import UIKit import RealmSwift class LoginViewController: UIViewController { let loginView = LoginView(frame: CGRectZero) let realm = try! Realm() var generateadCaptcha: String = "" // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() loginView.signInButton.addTarget(self, action: #selector(didTapSignInButton(_:)), forControlEvents: .TouchUpInside) loginView.signUpButton.addTarget(self, action: #selector(didTapSignUpButton(_:)), forControlEvents: .TouchUpInside) loginView.logButton.addTarget(self, action: #selector(didTapLogButton(_:)), forControlEvents: .TouchUpInside) loginView.steganographerButton.addTarget(self, action: #selector(didTapSteganographerButton(_:)), forControlEvents: .TouchUpInside) self.view.addSubview(loginView) loginView.autoPinEdgesToSuperviewEdges() self.generateRandomNumber() } // MARK: - Random Number Generator func generateRandomNumber() { generateadCaptcha = CaptchaGenerator.generate() loginView.generatedCodeLabel.text = generateadCaptcha } // MARK: - Button Actions func didTapSignInButton(sender: UIButton) { let username = loginView.usernameTextField.text! let password = loginView.passwordTextField.text! let inputCode = loginView.generatedCodeTextField.text! if username != "" && password != "" && inputCode != "" { if generateadCaptcha == inputCode { let user = realm.objects(RealmUser).filter("username = '\(username)'").first if user != nil { if !(user!.isLocked) { if user!.attemptableDate.timeIntervalSince1970 < NSDate().timeIntervalSince1970 { if user!.checkPassword(password) { ActiveUser.sharedInstance.setActiveUser(user!) loginView.usernameTextField.text = "" loginView.passwordTextField.text = "" try! realm.write { user!.wrongAttemptCount = 0 user!.attemptableDate = NSDate() } self.presentViewController(TabBarController(), animated: true, completion: nil) } else { let wrongAttemptCount = user!.wrongAttemptCount + 1 if wrongAttemptCount == 3 { let date = NSDate.init(timeIntervalSinceNow: 60 * 30) // 30 min delay try! realm.write { user!.attemptableDate = date// 20 sec user!.wrongAttemptCount = wrongAttemptCount } showAlertView("Wrong Password!", message: "Account's login is delayed. You must try at date: \(Helper.getStringDateFromDate(date))", style: .Alert) } else if wrongAttemptCount >= 5 { try! realm.write { user!.isLocked = true user!.wrongAttemptCount = 5 } showAlertView("Important Error!", message: "User is Locked! You can not login anymore! Please contact the customer service.", style: .Alert) } else { try! realm.write { user!.wrongAttemptCount = wrongAttemptCount } showAlertView("Login Error", message: "Could not entring the App.\n'username' or 'password' is wrong.", style: .Alert) } } } else { showAlertView("Login Error!", message: "Login is delayed to date: \(Helper.getStringDateFromDate(user!.attemptableDate)). Try after this date.", style: .Alert) } } else { showAlertView("Login Error\nUser is Locked", message: "You can not sign in because user is locked with multiple wrong attempt. Please contact the customer service.", style: .Alert) } } else { showAlertView("Login Error", message: "Could not entring the App.\n'username' or 'password' is wrong.", style: .Alert) } } else { showAlertView("Login Error", message: "Enterred Code is not equal the Generated Code", style: .Alert) } } else { showAlertView("Login Error", message: "Please fill the all missing fileds.", style: .Alert) } loginView.passwordTextField.text = "" loginView.generatedCodeTextField.text = "" generateRandomNumber() } func didTapSignUpButton(sender: UIBarButtonItem) { //! Sign up process is not possible in this version. //generateRandomNumber() } func didTapLogButton(sender :UIBarButtonItem) { let manInTheMiddleTableViewController = ManInTheMiddleTableViewController() manInTheMiddleTableViewController.exitButton = true self.presentViewController(NavigationController(rootViewController: manInTheMiddleTableViewController), animated: true, completion: nil) } func didTapSteganographerButton(sender :UIBarButtonItem) { let steganographerViewController = SteganographerViewController() steganographerViewController.exitButton = true self.presentViewController(NavigationController(rootViewController: steganographerViewController), animated: true, completion: nil) } // MARK: - AlertViewInitialise func showAlertView(title: String, message: String, style: UIAlertControllerStyle) { let alertController = UIAlertController.init(title: title, message: message, preferredStyle: style) alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
7249984d92215ef94431cc1c4f272921
50.19403
204
0.546793
6.065429
false
false
false
false
stripe/stripe-ios
Stripe/STPPaymentActivityIndicatorView.swift
1
4320
// // STPPaymentActivityIndicatorView.swift // StripeiOS // // Created by Jack Flintermann on 5/12/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import UIKit /// This class can be used wherever you'd use a `UIActivityIndicatorView` and is intended to have a similar API. It renders as a spinning circle with a gap in it, similar to what you see in the App Store app or in the Apple Pay dialog when making a purchase. To change its color, set the `tintColor` property. public class STPPaymentActivityIndicatorView: UIView { /// Tell the view to start or stop spinning. If `hidesWhenStopped` is true, it will fade in/out if animated is true. @objc public func setAnimating( _ animating: Bool, animated: Bool ) { if animating == _animating { return } _animating = animating if animating { if hidesWhenStopped { UIView.animate( withDuration: animated ? 0.2 : 0, animations: { self.alpha = 1.0 } ) } var currentRotation = Double(0) if let currentLayer = layer.presentation() { currentRotation = Double( truncating: (currentLayer.value(forKeyPath: "transform.rotation.z") as! NSNumber) ) } let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = NSNumber(value: Float(currentRotation)) let toValue = NSNumber(value: currentRotation + 2 * Double.pi) animation.toValue = toValue animation.duration = 1.0 animation.repeatCount = Float.infinity layer.add(animation, forKey: "rotation") } else { if hidesWhenStopped { UIView.animate( withDuration: animated ? 0.2 : 0, animations: { self.alpha = 0.0 } ) } } } private var _animating = false /// Whether or not the view is animating. @objc public var animating: Bool { get { _animating } set(animating) { setAnimating(animating, animated: false) } } private var _hidesWhenStopped = true /// If true, the view will hide when it is not spinning. Default is true. @objc public var hidesWhenStopped: Bool { get { _hidesWhenStopped } set(hidesWhenStopped) { _hidesWhenStopped = hidesWhenStopped if !animating && hidesWhenStopped { alpha = 0 } else { alpha = 1 } } } private weak var indicatorLayer: CAShapeLayer? /// :nodoc: @objc override init( frame: CGRect ) { var initialFrame = frame if initialFrame.isEmpty { initialFrame = CGRect(x: frame.origin.x, y: frame.origin.y, width: 40, height: 40) } super.init(frame: initialFrame) backgroundColor = UIColor.clear let layer = CAShapeLayer() layer.backgroundColor = UIColor.clear.cgColor layer.fillColor = UIColor.clear.cgColor layer.strokeColor = tintColor.cgColor layer.strokeStart = 0 layer.lineCap = .round layer.strokeEnd = 0.75 layer.lineWidth = 2.0 indicatorLayer = layer self.layer.addSublayer(layer) alpha = 0 } /// :nodoc: @objc public override var tintColor: UIColor! { get { return super.tintColor } set(tintColor) { super.tintColor = tintColor indicatorLayer?.strokeColor = tintColor.cgColor } } /// :nodoc: @objc public override func layoutSubviews() { super.layoutSubviews() var bounds = self.bounds bounds.size.width = CGFloat(min(bounds.size.width, bounds.size.height)) bounds.size.height = bounds.size.width let path = UIBezierPath(ovalIn: bounds) indicatorLayer?.path = path.cgPath } required init?( coder aDecoder: NSCoder ) { super.init(coder: aDecoder) } }
mit
063a640661e6f319b52dbc27de61ba92
30.992593
309
0.559157
4.947308
false
false
false
false
sonnygauran/trailer
Shared/PRLabel.swift
1
1893
import CoreData #if os(iOS) import UIKit #endif final class PRLabel: DataItem { @NSManaged var color: NSNumber? @NSManaged var name: String? @NSManaged var url: String? @NSManaged var pullRequest: PullRequest? @NSManaged var issue: Issue? class func labelWithName(name: String, withParent: DataItem) -> PRLabel? { let f = NSFetchRequest(entityName: "PRLabel") f.fetchLimit = 1 f.returnsObjectsAsFaults = false if withParent is PullRequest { f.predicate = NSPredicate(format: "name == %@ and pullRequest == %@", name, withParent) } else { f.predicate = NSPredicate(format: "name == %@ and issue == %@", name, withParent) } let res = try! withParent.managedObjectContext?.executeFetchRequest(f) as! [PRLabel] return res.first } class func labelWithInfo(info: [NSObject : AnyObject], withParent: DataItem) -> PRLabel { let name = N(info, "name") as? String ?? "(unnamed label)" var l = PRLabel.labelWithName(name, withParent: withParent) if l==nil { DLog("Creating PRLabel: %@", name) l = NSEntityDescription.insertNewObjectForEntityForName("PRLabel", inManagedObjectContext: withParent.managedObjectContext!) as? PRLabel l!.name = name l!.serverId = 0 l!.updatedAt = never() l!.createdAt = never() l!.apiServer = withParent.apiServer if let p = withParent as? PullRequest { l!.pullRequest = p } else if let i = withParent as? Issue { l!.issue = i } } else { DLog("Updating PRLabel: %@", name) } l!.url = N(info, "url") as? String if let c = N(info, "color") as? String { l!.color = NSNumber(unsignedInt: parseFromHex(c)) } else { l!.color = 0 } l!.postSyncAction = PostSyncAction.DoNothing.rawValue return l! } func colorForDisplay() -> COLOR_CLASS { if let c = color?.unsignedIntValue { return colorFromUInt32(c) } else { return COLOR_CLASS.blackColor() } } }
mit
832a36f3d7794a41c1a53f74f334f211
28.123077
139
0.674062
3.448087
false
false
false
false
sonnygauran/trailer
PocketTrailer/DetailViewController.swift
1
4930
import WebKit import CoreData final class DetailViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var statusLabel: UILabel! private var _webView: WKWebView? var isVisible: Bool = false var catchupWithDataItemWhenLoaded : NSManagedObjectID? var detailItem: NSURL? { didSet { if detailItem != oldValue && _webView != nil { configureView() } } } override func viewDidLoad() { super.viewDidLoad() title = "Loading..." let webConfiguration = WKWebViewConfiguration() _webView = WKWebView(frame: view.bounds, configuration: webConfiguration) _webView!.navigationDelegate = self _webView!.scrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) _webView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight) _webView!.translatesAutoresizingMaskIntoConstraints = true _webView!.hidden = true view.addSubview(_webView!) if detailItem == nil { showEmpty() } else { configureView() } } func configureView() { if let d = detailItem { DLog("Will load: %@", d.absoluteString) _webView!.loadRequest(NSURLRequest(URL: d)) } else { showEmpty() } } private func showEmpty() { statusLabel.textColor = UIColor.lightGrayColor() statusLabel.text = "Please select an item from the list on the left, or select 'Settings' to add servers, or show/hide repositories.\n\n(You may have to login to GitHub the first time you visit a private item)" statusLabel.hidden = false navigationItem.rightBarButtonItem?.enabled = false title = nil _webView?.hidden = true } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) navigationItem.leftBarButtonItem = (traitCollection.horizontalSizeClass==UIUserInterfaceSizeClass.Compact) ? nil : splitViewController?.displayModeButtonItem() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if _webView != nil && _webView!.loading { spinner.startAnimating() } else { spinner.stopAnimating() catchupWithComments() } isVisible = true } override func viewDidDisappear(animated: Bool) { isVisible = false super.viewDidDisappear(animated) } func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { spinner.startAnimating() statusLabel.hidden = true statusLabel.text = "" _webView?.hidden = true title = "Loading..." navigationItem.rightBarButtonItem = nil api.networkIndicationStart() } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { let res = navigationResponse.response as! NSHTTPURLResponse if res.statusCode == 404 { showMessage("Not Found", "\nPlease ensure you are logged in with the correct account on GitHub\n\nIf you are using two-factor auth: There is a bug between Github and iOS which may cause your login to fail. If it happens, temporarily disable two-factor auth and log in from here, then re-enable it afterwards. You will only need to do this once.") } decisionHandler(WKNavigationResponsePolicy.Allow) } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { spinner.stopAnimating() statusLabel.hidden = true _webView?.hidden = false navigationItem.rightBarButtonItem?.enabled = true title = _webView?.title navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: Selector("shareSelected")) api.networkIndicationEnd() catchupWithComments() } private func catchupWithComments() { if let oid = catchupWithDataItemWhenLoaded, dataItem = existingObjectWithID(oid) as? ListableItem { catchupWithDataItemWhenLoaded = nil if let count = dataItem.unreadComments?.integerValue where count > 0 { dataItem.catchUpWithComments() DataManager.saveDB() } } } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { loadFailed(error) } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { loadFailed(error) } private func loadFailed(error: NSError) { spinner.stopAnimating() statusLabel.textColor = UIColor.redColor() statusLabel.text = "Loading Error: " + error.localizedDescription statusLabel.hidden = false _webView?.hidden = true title = "Error" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: Selector("configureView")) api.networkIndicationEnd() } func shareSelected() { if let u = _webView?.URL { popupManager.shareFromView(self, buttonItem: navigationItem.rightBarButtonItem!, url: u) } } }
mit
2078e09f7fc292b0c6a6ec2b8c6bf8fb
32.310811
351
0.759635
4.313211
false
true
false
false
epodkorytov/OCTextInput
OCTextInput/Classes/OCTextInput.swift
1
26940
import Foundation import UIKit public protocol OCTextInputDelegate: class { func OCTextInputDidBeginEditing(_ OCTextInput: OCTextInput) func OCTextInputDidEndEditing(_ OCTextInput: OCTextInput) func OCTextInputDidChange(_ OCTextInput: OCTextInput) func OCTextInputShouldChangeCharacters(_ OCTextInput: OCTextInput, inRange range: NSRange, replacementString string: String) -> Bool func OCTextInputShouldBeginEditing(_ OCTextInput: OCTextInput) -> Bool func OCTextInputShouldEndEditing(_ OCTextInput: OCTextInput) -> Bool func OCTextInputShouldReturn(_ OCTextInput: OCTextInput) -> Bool func OCTextInputShouldClear(_ OCTextInput: OCTextInput) -> Bool func OCTextInputWillChangeValidState(_ OCTextInput: OCTextInput) } public extension OCTextInputDelegate { func OCTextInputDidBeginEditing(_ OCTextInput: OCTextInput) {} func OCTextInputDidEndEditing(_ OCTextInput: OCTextInput) {} func OCTextInputDidChange(_ OCTextInput: OCTextInput) {} func OCTextInputShouldChangeCharacters(_ OCTextInput: OCTextInput, inRange range: NSRange, replacementString string: String) -> Bool { return true } func OCTextInputShouldBeginEditing(_ OCTextInput: OCTextInput) -> Bool { return true } func OCTextInputShouldEndEditing(_ OCTextInput: OCTextInput) -> Bool { return true } func OCTextInputShouldReturn(_ OCTextInput: OCTextInput) -> Bool { return true } func OCTextInputShouldClear(_ OCTextInput: OCTextInput) -> Bool { return true } func OCTextInputWillChangeValidState(_ OCTextInput: OCTextInput) {} } public class OCTextInput: UIControl { public typealias OCTextInputType = OCTextInputFieldConfigurator.OCTextInputType open var tapAction: (() -> Void)? open weak var delegate: OCTextInputDelegate? open fileprivate(set) var isActive = false open var type: OCTextInputType = .standard { didSet { configureType() } } open var returnKeyType: UIReturnKeyType! = .default { didSet { textInput.changeReturnKeyType(with: returnKeyType) } } open var placeHolderText = OCTextInputDefaults.Placeholder().text { didSet { placeholderLayer.string = placeHolderText } } open var regEx : RegExCheck? { didSet { } } open var characterCounter : CharacterCounter? { didSet { showCharacterCounter() } } open var animatePlaceHolder = OCTextInputDefaults.Placeholder().animate open var style: OCTextInputStyle = OCTextInputStyleDefault() { didSet { configureStyle() } } open var text: String? { get { return textInput.currentText } set { if !textInput.view.isFirstResponder { (newValue != nil) ? configurePlaceholderAsInactiveHint() : configurePlaceholderAsDefault() } textInput.currentText = newValue } } open var selectedTextRange: UITextRange? { get { return textInput.currentSelectedTextRange } set { textInput.currentSelectedTextRange = newValue } } open var beginningOfDocument: UITextPosition? { get { return textInput.currentBeginningOfDocument } } open var isValid: Bool! = true { willSet { if newValue != self.isValid { delegate?.OCTextInputWillChangeValidState(self) } } } // fileprivate let lineView = AnimatedLine() fileprivate let placeholderLayer = CATextLayer() fileprivate let additionView: UIView = { let view = UIView() view.backgroundColor = UIColor.clear view.translatesAutoresizingMaskIntoConstraints = false return view }() fileprivate let errorLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false return label }() fileprivate let counterLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.textAlignment = .right label.translatesAutoresizingMaskIntoConstraints = false return label }() fileprivate let lineWidth: CGFloat = 1.0 / UIScreen.main.scale fileprivate let counterLabelRightMargin: CGFloat = 15.0 fileprivate let counterLabelTopMargin: CGFloat = 0.0 fileprivate var isResigningResponder = false fileprivate var isPlaceholderAsHint = false fileprivate var hasCounterLabel = false fileprivate var textInput: TextInput! fileprivate var textInputTrailingConstraint: NSLayoutConstraint! fileprivate var disclosureViewWidthConstraint: NSLayoutConstraint! fileprivate var disclosureView: UIView? fileprivate var placeholderErrorText: String? fileprivate var placeholderPosition: CGPoint { if isPlaceholderAsHint { return CGPoint(x: style.marginInsets.left, y: style.yHintPositionOffset) } else { return CGPoint(x: style.marginInsets.left, y: style.marginInsets.top + style.yPlaceholderPositionOffset) } } // public convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { super.init(frame: frame) setupCommonElements() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCommonElements() } // override open var intrinsicContentSize: CGSize { let normalHeight : CGFloat = textInput.view.intrinsicContentSize.height return CGSize(width: UIView.noIntrinsicMetric, height: normalHeight + style.marginInsets.top + style.marginInsets.bottom) } open override func updateConstraints() { addLineViewConstraints() addTextInputConstraints() super.updateConstraints() } open override func layoutSubviews() { super.layoutSubviews() layoutPlaceholderLayer() } fileprivate func layoutPlaceholderLayer() { let frameHeightCorrectionFactor: CGFloat = 1.2 placeholderLayer.frame = CGRect(origin: placeholderPosition, size: CGSize(width: bounds.width, height: style.textInputFont.pointSize * frameHeightCorrectionFactor)) } // mark: Configuration fileprivate func addAdditionViewConstraints() { pinLeading(toLeadingOf: additionView, constant: style.marginInsets.left) let _ = pinTrailing(toTrailingOf: additionView, constant: style.marginInsets.right) pinBottom(toBottomOf: additionView, constant: 0.0) } fileprivate func addLineViewConstraints() { addAdditionViewConstraints() pinLeading(toLeadingOf: lineView, constant: style.marginInsets.left) let _ = pinTrailing(toTrailingOf: lineView, constant: style.marginInsets.right) lineView.setHeight(to: lineWidth) let constant : CGFloat = 1.0 //characterCounter != nil ? -counterLabel.intrinsicContentSize.height - counterLabelTopMargin : 0 lineView.pinBottom(toTopOf: additionView, constant: constant) } fileprivate func addTextInputConstraints() { pinLeading(toLeadingOf: textInput.view, constant: style.marginInsets.left) if disclosureView == nil { textInputTrailingConstraint = pinTrailing(toTrailingOf: textInput.view, constant: style.marginInsets.right) } pinTop(toTopOf: textInput.view, constant: style.marginInsets.top) textInput.view.pinBottom(toTopOf: lineView, constant: style.marginInsets.bottom) } fileprivate func setupCommonElements() { addAdditionView() addLine() addPlaceHolder() addTapGestureRecognizer() addTextInput() } fileprivate func addAdditionView() { addSubview(additionView) } fileprivate func addLine() { lineView.defaultColor = style.lineInactiveColor lineView.translatesAutoresizingMaskIntoConstraints = false addSubview(lineView) } fileprivate func addPlaceHolder() { placeholderLayer.masksToBounds = false placeholderLayer.string = placeHolderText placeholderLayer.foregroundColor = style.inactiveColor.cgColor placeholderLayer.fontSize = style.textInputFont.pointSize placeholderLayer.font = style.textInputFont placeholderLayer.contentsScale = UIScreen.main.scale placeholderLayer.backgroundColor = UIColor.clear.cgColor layoutPlaceholderLayer() layer.addSublayer(placeholderLayer) } fileprivate func addTapGestureRecognizer() { let tap = UITapGestureRecognizer(target: self, action: #selector(viewWasTapped)) addGestureRecognizer(tap) } fileprivate func addTextInput() { textInput = OCTextInputFieldConfigurator.configure(with: type) textInput.textInputDelegate = self textInput.view.tintColor = style.activeColor textInput.textColor = style.textInputFontColor textInput.font = style.textInputFont textInput.view.translatesAutoresizingMaskIntoConstraints = false addSubview(textInput.view) invalidateIntrinsicContentSize() } fileprivate func updateCounter() { guard let counterText = counterLabel.text else { return } let components = counterText.components(separatedBy: "/") let characters = (text != nil) ? text!.count : 0 counterLabel.text = "\(characters)/\(components[1])" } // mark: States and animations fileprivate func configurePlaceholderAsActiveHint() { if !animatePlaceHolder { configurePlaceholderAsHiden() return } isPlaceholderAsHint = true if let counter = characterCounter { if counter.visibleState == .active { counterLabel.isHidden = false } } configurePlaceholderWith(fontSize: style.placeholderMinFontSize, foregroundColor: style.activeColor.cgColor, text: placeHolderText) lineView.fillLine(with: style.activeColor) } fileprivate func configurePlaceholderAsInactiveHint() { isPlaceholderAsHint = true if let counter = characterCounter { if counter.visibleState == .active { counterLabel.isHidden = true } } configurePlaceholderWith(fontSize: style.placeholderMinFontSize, foregroundColor: style.inactiveColor.cgColor, text: placeHolderText) lineView.animateToInitialState() } fileprivate func configurePlaceholderAsDefault() { isPlaceholderAsHint = false if let counter = characterCounter { if counter.visibleState == .active { counterLabel.isHidden = true } } configurePlaceholderWith(fontSize: style.textInputFont.pointSize, foregroundColor: style.inactiveColor.cgColor, text: placeHolderText) lineView.animateToInitialState() } fileprivate func configurePlaceholderAsErrorHint() { isPlaceholderAsHint = true if let counter = characterCounter { if counter.visibleState == .active { counterLabel.isHidden = false //true } } configurePlaceholderWith(fontSize: style.placeholderMinFontSize, foregroundColor: style.errorColor.cgColor, text: placeHolderText) lineView.fillLine(with: style.errorColor) } fileprivate func configurePlaceholderAsHiden() { isPlaceholderAsHint = false if let counter = characterCounter { if counter.visibleState == .active { counterLabel.isHidden = true } } configurePlaceholderWith(fontSize: style.textInputFont.pointSize, foregroundColor: style.invisibleColor.cgColor, text: placeHolderText) lineView.fillLine(with: style.activeColor) } fileprivate func configurePlaceholderWith(fontSize: CGFloat, foregroundColor: CGColor, text: String?) { placeholderLayer.fontSize = fontSize placeholderLayer.foregroundColor = foregroundColor placeholderLayer.string = text layoutPlaceholderLayer() } fileprivate func animatePlaceholder(to applyConfiguration: () -> Void) { let function = CAMediaTimingFunction(controlPoints: 0.3, 0.0, 0.5, 0.95) transactionAnimation(with: OCTextInputDefaults.Placeholder().duration, timingFuncion: function, animations: applyConfiguration) } // mark: Behaviours @objc fileprivate func viewWasTapped(sender: UIGestureRecognizer) { if let tapAction = tapAction { tapAction() } else { becomeFirstResponder() } } fileprivate func styleDidChange() { lineView.defaultColor = style.lineInactiveColor placeholderLayer.foregroundColor = style.inactiveColor.cgColor let fontSize = style.textInputFont.pointSize placeholderLayer.fontSize = fontSize placeholderLayer.font = style.textInputFont textInput.view.tintColor = style.activeColor textInput.textColor = style.textInputFontColor textInput.font = style.textInputFont invalidateIntrinsicContentSize() layoutIfNeeded() } @discardableResult override open func becomeFirstResponder() -> Bool { isActive = true let firstResponder = textInput.view.becomeFirstResponder() counterLabel.textColor = style.activeColor placeholderErrorText = nil animatePlaceholder(to: configurePlaceholderAsActiveHint) return firstResponder } override open var isFirstResponder: Bool { return textInput.view.isFirstResponder } override open func resignFirstResponder() -> Bool { guard !isResigningResponder else { return true } isActive = false isResigningResponder = true let resignFirstResponder = textInput.view.resignFirstResponder() isResigningResponder = false counterLabel.textColor = style.inactiveColor /* if let textInputError = textInput as? TextInputError { textInputError.removeErrorHintMessage() } */ // If the placeholder is showing an error we want to keep this state. Otherwise revert to inactive state. if placeholderErrorText == nil { animateToInactiveState() clearError() } return resignFirstResponder } fileprivate func animateToInactiveState() { guard let text = textInput.currentText, !text.isEmpty else { animatePlaceholder(to: configurePlaceholderAsDefault) return } animatePlaceholder(to: configurePlaceholderAsInactiveHint) } override open var canResignFirstResponder: Bool { return textInput.view.canResignFirstResponder } override open var canBecomeFirstResponder: Bool { guard !isResigningResponder else { return false } if let disclosureView = disclosureView, disclosureView.isFirstResponder { return false } return textInput.view.canBecomeFirstResponder } //Error label open func show(error errorMessage: String, placeholderText: String? = nil) { placeholderErrorText = errorMessage showError(text: placeholderErrorText!) animatePlaceholder(to: configurePlaceholderAsErrorHint) } open func clearError() { isValid = true placeholderErrorText = nil errorLabel.removeConstraints(errorLabel.constraints) errorLabel.removeFromSuperview() if isActive { animatePlaceholder(to: configurePlaceholderAsActiveHint) } else { animateToInactiveState() } } fileprivate func showError(text : String) { isValid = false errorLabel.text = text errorLabel.textColor = style.errorColor errorLabel.font = style.counterLabelFont additionView.addSubview(errorLabel) additionView.pinTop(toTopOf: errorLabel, constant: 0) additionView.pinLeading(toLeadingOf: errorLabel, constant: 0) additionView.pinBottom(toBottomOf: errorLabel, constant: 0) if counterLabel.superview == nil { let _ = errorLabel.pinTrailing(toTrailingOf: additionView, constant: counterLabelRightMargin) } else { let _ = errorLabel.pinTrailing(toLeadingOf: counterLabel, constant: 5) } additionView.invalidateIntrinsicContentSize() } // fileprivate func configureType() { textInput.view.removeFromSuperview() addTextInput() } fileprivate func configureStyle() { styleDidChange() if isActive { configurePlaceholderAsActiveHint() } else { isPlaceholderAsHint ? configurePlaceholderAsInactiveHint() : configurePlaceholderAsDefault() } } open func showCharacterCounterLabel(with maximum: Int) { let characters = (text != nil) ? text!.count : 0 counterLabel.text = "\(characters)/\(maximum)" counterLabel.textColor = isActive ? style.activeColor : style.inactiveColor counterLabel.font = style.counterLabelFont counterLabel.translatesAutoresizingMaskIntoConstraints = false addCharacterCounterConstraints() invalidateIntrinsicContentSize() } fileprivate func showCharacterCounter() { guard let counter = characterCounter else { return } if counter.visibleState == .never { return } var limit = "" if counter.min == 0 && counter.max > 0 { limit = "\(counter.max)" } else if counter.min > 0 && counter.max > 0 { limit = "\(counter.min)-\(counter.max)" } let characters = (text != nil) ? text!.count : 0 if limit.count > 0 { counterLabel.text = "\(characters)/\(limit)" } else { counterLabel.text = "\(characters)" } counterLabel.textColor = isActive ? style.activeColor : style.inactiveColor counterLabel.font = style.counterLabelFont counterLabel.isHidden = counter.visibleState != .always additionView.addSubview(counterLabel) addCharacterCounterConstraints() invalidateIntrinsicContentSize() } fileprivate func addCharacterCounterConstraints() { additionView.pinTop(toTopOf: counterLabel, constant: counterLabelTopMargin) additionView.pinBottom(toBottomOf: counterLabel, constant: 0.0) let _ = additionView.pinTrailing(toTrailingOf: counterLabel, constant: counterLabelRightMargin) additionView.invalidateIntrinsicContentSize() } open func removeCharacterCounterLabel() { counterLabel.removeConstraints(counterLabel.constraints) counterLabel.removeFromSuperview() additionView.invalidateIntrinsicContentSize() } // open func addDisclosureView(disclosureView: UIView) { if let constraint = textInputTrailingConstraint { removeConstraint(constraint) } self.disclosureView?.removeFromSuperview() self.disclosureView = disclosureView addSubview(disclosureView) textInputTrailingConstraint = textInput.view.pinTrailing(toLeadingOf: disclosureView, constant: 0) disclosureView.alignHorizontalAxis(toSameAxisOfView: textInput.view) disclosureView.pinBottom(toBottomOf: self, constant: 12) let _ = disclosureView.pinTrailing(toTrailingOf: self, constant: 16) } open func removeDisclosureView() { guard disclosureView != nil else { return } disclosureView?.removeFromSuperview() disclosureView = nil textInput.view.removeConstraint(textInputTrailingConstraint) textInputTrailingConstraint = pinTrailing(toTrailingOf: textInput.view, constant: style.marginInsets.right) } open func position(from: UITextPosition, offset: Int) -> UITextPosition? { return textInput.currentPosition(from: from, offset: offset) } fileprivate func checkByRegExp() throws { let text = self.textInput.currentText! if text.count == 0 { throw RegExCheckError.empty } guard let regEx = regEx else { return } let regex = try! NSRegularExpression(pattern: regEx.expression) let results = regex.matches(in: text, range: NSRange(location: 0, length: text.count)) if results.count == 0 { throw RegExCheckError.validationError(regEx.errorMessage!) } } } extension OCTextInput: TextInputDelegate { open func textInputDidBeginEditing(textInput: TextInput) { becomeFirstResponder() delegate?.OCTextInputDidBeginEditing(self) } open func textInputDidEndEditing(textInput: TextInput) { do { try checkByRegExp() //clearError() } catch let error as RegExCheckError { switch error { case .empty: configurePlaceholderAsActiveHint() break case .validationError(let msg): show(error: msg, placeholderText: placeHolderText) break } } catch let error as NSError { print(error.localizedDescription) } let _ = resignFirstResponder() delegate?.OCTextInputDidEndEditing(self) } open func textInputDidChange(textInput: TextInput) { updateCounter() delegate?.OCTextInputDidChange(self) } open func textInput(textInput: TextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let text = textInput.currentText, case let start = text.utf16.index(text.utf16.startIndex, offsetBy: range.lowerBound), case let end = text.utf16.index(text.utf16.startIndex, offsetBy: range.upperBound), let startIndex = start.samePosition(in: text), let endIndex = end.samePosition(in: text) { let newString = text.replacingCharacters(in: startIndex..<endIndex, with: string) if let counter = characterCounter { if counter.visibleState != .never && counter.observerType?.type != .pass { if newString.count < counter.min || newString.count > counter.max { if let msg = counter.observerType?.info { show(error: msg, placeholderText: placeHolderText) } else { configurePlaceholderAsErrorHint() } if newString.count > counter.max && counter.observerType?.type == .keep { return delegate?.OCTextInputShouldChangeCharacters(self, inRange: NSMakeRange(0, 0), replacementString: "") ?? false } } else { clearError() } } } } return delegate?.OCTextInputShouldChangeCharacters(self, inRange: range, replacementString: string) ?? true } open func textInputShouldBeginEditing(textInput: TextInput) -> Bool { return delegate?.OCTextInputShouldBeginEditing(self) ?? true } open func textInputShouldEndEditing(textInput: TextInput) -> Bool { return delegate?.OCTextInputShouldEndEditing(self) ?? true } open func textInputShouldReturn(textInput: TextInput) -> Bool { return delegate?.OCTextInputShouldReturn(self) ?? true } open func textInputShouldClear(textInput: TextInput) -> Bool { clearError() return delegate?.OCTextInputShouldClear(self) ?? true } } public protocol TextInput { var view: UIView { get } var currentText: String? { get set } var font: UIFont? { get set } var textColor: UIColor? { get set } var textInputDelegate: TextInputDelegate? { get set } var currentSelectedTextRange: UITextRange? { get set } var currentBeginningOfDocument: UITextPosition? { get } func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? } public extension TextInput where Self: UIView { var view: UIView { return self } } public protocol TextInputDelegate: class { func textInputDidBeginEditing(textInput: TextInput) func textInputDidEndEditing(textInput: TextInput) func textInputDidChange(textInput: TextInput) func textInput(textInput: TextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool func textInputShouldBeginEditing(textInput: TextInput) -> Bool func textInputShouldEndEditing(textInput: TextInput) -> Bool func textInputShouldReturn(textInput: TextInput) -> Bool func textInputShouldClear(textInput: TextInput) -> Bool } public extension TextInputDelegate { func textInputDidBeginEditing(textInput: TextInput) {} func textInputDidEndEditing(textInput: TextInput) {} func textInputDidChange(textInput: TextInput) {} func textInput(textInput: TextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { return true } func textInputShouldBeginEditing(textInput: TextInput) -> Bool { return true } func textInputShouldEndEditing(textInput: TextInput) -> Bool { return true } func textInputShouldReturn(textInput: TextInput) -> Bool { return true } func textInputShouldClear(textInput: TextInput) -> Bool { return true } } public protocol TextInputError { func configureErrorState(with message: String?) func removeErrorHintMessage() }
mit
47f21e2ea6528bf4777f46cbcc0c1dad
35.504065
172
0.646177
5.47561
false
false
false
false
FotiosTragopoulos/Core-Geometry
Core Geometry/Cir1ViewFilling.swift
1
1539
// // Cir1ViewFilling.swift // Core Geometry // // Created by Fotios Tragopoulos on 15/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Cir1ViewFilling: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() let xView = viewWithTag(14)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(14)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(14)?.frame.size.width let height = self.viewWithTag(14)?.frame.size.height let size = CGSize(width: width! * 0.8, height: height! * 0.8) let rectPlacementX = CGFloat(size.width/2) let rectPlacementY = CGFloat(size.height/2) let shapePosition = CGPoint(x: (xView! - rectPlacementX), y: (yView! - rectPlacementY)) let rectangle = CGRect(origin: shapePosition, size: size) context?.setFillColor(UIColor.white.cgColor) context?.fillEllipse(in: rectangle) context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
apache-2.0
1a1c30093c971cc9501d88e22290d046
35.619048
219
0.652796
4.058047
false
false
false
false
lazyjean/CellLayout
CellLayout/CellLayoutViewModel.swift
1
1725
// // CellLayoutViewModel.swift // CellLayout // // Created by liuzhen on 2017/10/23. // import Foundation import ReactiveSwift open class CellLayoutViewModel: NSObject { let (reload, reloadObserver) = Signal<(), Never>.pipe() public let insert = MutableProperty<([IndexPath], UITableView.RowAnimation)?>(nil) public let scroll = MutableProperty<(IndexPath, UITableView.ScrollPosition, Bool)?>(nil) public func reloadData() { self.build() self.reloadObserver.send(value: ()) } public var storage = CellLayoutStorage() func build() { self.storage.invalidRows() self.buildLayout() } open func buildLayout() { } required public override init() { } open func insertRows(at: [CellLayoutRow], with: UITableView.RowAnimation) { var indexed:[IndexPath] = [] for i in 0..<at.count { switch with { case .top: indexed.insert((IndexPath(row: i, section: 0)), at: i) storage.rows.insert(at[i], at: i) default: indexed.append(IndexPath(row: storage.rows.count, section: 0)) storage.rows.append(at[i]) } } self.insert.value = (indexed, with) } public func scrollsToBottom(animated: Bool = true) { if self.storage.rows.count > 0 { self.scroll.value = (IndexPath(row: self.storage.rows.count - 1, section: 0), .bottom, animated) } } public func scrollsToTop(animated: Bool = true) { if self.storage.rows.count > 0 { self.scroll.value = (IndexPath(row: 0, section: 0), .top, animated) } } }
mit
3776f10013ec6e540e369443ae328383
26.380952
108
0.57913
4.186893
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/Cells/RevealControllerCell.swift
1
1065
/// /// RevealControllerCell.swift // protocol RevealControllerResponder: class { func revealControllerTapped(info: Any) } class RevealControllerCell: CollectionViewCell { static let reuseIdentifier = "RevealControllerCell" struct Size { static let height: CGFloat = 40 static let margins: CGFloat = 15 } var text: String? { get { return label.text } set { label.text = newValue } } private let label = StyledLabel(style: .gray) private let arrow = UIImageView() override func style() { arrow.interfaceImage = .forwardChevron } override func arrange() { contentView.addSubview(label) contentView.addSubview(arrow) label.snp.makeConstraints { make in make.leading.equalTo(contentView).offset(Size.margins) make.centerY.equalTo(contentView) } arrow.snp.makeConstraints { make in make.trailing.equalTo(contentView).inset(Size.margins) make.centerY.equalTo(contentView) } } }
mit
00c39387e845ea9913800d20e2232874
24.357143
66
0.641315
4.650655
false
false
false
false
bigyelow/rexxar-ios
RexxarDemo/PartialRXRViewController.swift
1
1813
// // PartialRexxarViewController.swift // RexxarDemo // // Created by GUO Lin on 5/19/16. // Copyright © 2016 Douban.Inc. All rights reserved. // import UIKit class PartialRexxarViewController: UIViewController { var rexxarURI: URL var childRexxarViewController: RXRViewController required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(URI: URL) { rexxarURI = URI childRexxarViewController = FullRXRViewController(uri: rexxarURI) super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGray childRexxarViewController.view.backgroundColor = UIColor.white addChildViewController(childRexxarViewController) childRexxarViewController.view.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 500) view.addSubview(childRexxarViewController.view) childRexxarViewController.didMove(toParentViewController: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) childRexxarViewController.beginAppearanceTransition(true, animated: animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) childRexxarViewController.endAppearanceTransition() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) childRexxarViewController.beginAppearanceTransition(false, animated: animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) childRexxarViewController.endAppearanceTransition() } }
mit
77f6306e4e5068aa34e3c7b08a1834b7
28.704918
82
0.69702
4.755906
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/Presenters/StreamHeaderCellPresenter.swift
1
1835
//// /// StreamHeaderCellPresenter.swift // import TimeAgoInWords struct StreamHeaderCellPresenter { static func configure( _ cell: UICollectionViewCell, streamCellItem: StreamCellItem, streamKind: StreamKind, indexPath: IndexPath, currentUser: User? ) { guard let cell = cell as? StreamHeaderCell, let post = streamCellItem.jsonable as? Post else { return } let isGridView = streamCellItem.isGridView(streamKind: streamKind) switch streamKind { case .postDetail: cell.showUsername = false default: cell.showUsername = true } var author = post.author var repostedBy: User? cell.isGridView = isGridView cell.chevronHidden = true if let repostAuthor = post.repostAuthor { repostedBy = author author = repostAuthor } let isAuthor = currentUser?.isAuthorOf(post: post) ?? false let followButtonVisible = !isAuthor && streamKind.isDetail(post: post) var category: Category? if streamKind.showsCategory { category = post.category } let isSubmission: Bool if streamKind.showsSubmission, post.artistInviteId != nil { isSubmission = true } else { isSubmission = false } cell.setDetails( user: author, repostedBy: repostedBy, category: category, isSubmission: isSubmission ) cell.followButtonVisible = followButtonVisible if isGridView { cell.timeStamp = "" } else { cell.timeStamp = post.createdAt.timeAgoInWords() } cell.layoutIfNeeded() } }
mit
8e6f399da81cb33e8b6736fb524244f7
24.136986
78
0.571662
5.055096
false
false
false
false
danielmartin/swift
benchmark/single-source/Hash.swift
2
18530
//===--- Hash.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 // //===----------------------------------------------------------------------===// // Derived from the C samples in: // Source: http://en.wikipedia.org/wiki/MD5 and // http://en.wikipedia.org/wiki/SHA-1 import TestsUtils public let HashTest = BenchmarkInfo( name: "HashTest", runFunction: run_HashTest, tags: [.validation, .algorithm]) class Hash { /// C'tor. init(_ bs: Int) { blocksize = bs messageLength = 0 dataLength = 0 assert(blocksize <= 64, "Invalid block size") } /// Add the bytes in \p Msg to the hash. func update(_ Msg: String) { for c in Msg.unicodeScalars { data[dataLength] = UInt8(ascii: c) dataLength += 1 messageLength += 1 if dataLength == blocksize { hash() } } } /// Add the bytes in \p Msg to the hash. func update(_ Msg: [UInt8]) { for c in Msg { data[dataLength] = c dataLength += 1 messageLength += 1 if dataLength == blocksize { hash() } } } /// \returns the hash of the data that was updated. func digest() -> String { fillBlock() hash() let x = hashState() return x } // private: // Hash state: final var messageLength: Int = 0 final var dataLength: Int = 0 final var data = [UInt8](repeating: 0, count: 64) final var blocksize: Int /// Hash the internal data. func hash() { fatalError("Pure virtual") } /// \returns a string representation of the state. func hashState() -> String { fatalError("Pure virtual") } func hashStateFast(_ Res: inout [UInt8]) { fatalError("Pure virtual") } /// Blow the data to fill the block. func fillBlock() { fatalError("Pure virtual") } var HexTbl = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] final var HexTblFast : [UInt8] = [48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102] /// Convert a 4-byte integer to a hex string. final func toHex(_ In: UInt32) -> String { var In = In var Res = "" for _ in 0..<8 { Res = HexTbl[Int(In & 0xF)] + Res In = In >> 4 } return Res } final func toHexFast(_ In: UInt32, _ Res: inout Array<UInt8>, _ Index : Int) { var In = In for i in 0..<4 { // Convert one byte each iteration. Res[Index + 2*i] = HexTblFast[Int(In >> 4) & 0xF] Res[Index + 2*i + 1] = HexTblFast[Int(In & 0xF)] In = In >> 8 } } /// Left-rotate \p x by \p c. final func rol(_ x: UInt32, _ c: UInt32) -> UInt32 { return x &<< c | x &>> (32 &- c) } /// Right-rotate \p x by \p c. final func ror(_ x: UInt32, _ c: UInt32) -> UInt32 { return x &>> c | x &<< (32 &- c) } } final class MD5 : Hash { // Integer part of the sines of integers (in radians) * 2^32. var k : [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee , 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 , 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be , 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 , 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa , 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 , 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed , 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a , 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c , 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 , 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 , 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 , 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 , 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 , 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 , 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ] // Per-round shift amounts var r : [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] // State var h0: UInt32 = 0 var h1: UInt32 = 0 var h2: UInt32 = 0 var h3: UInt32 = 0 init() { super.init(64) reset() } func reset() { // Set the initial values. h0 = 0x67452301 h1 = 0xefcdab89 h2 = 0x98badcfe h3 = 0x10325476 messageLength = 0 dataLength = 0 } func appendBytes(_ Val: Int, _ Message: inout Array<UInt8>, _ Offset : Int) { Message[Offset] = UInt8(truncatingIfNeeded: Val) Message[Offset + 1] = UInt8(truncatingIfNeeded: Val >> 8) Message[Offset + 2] = UInt8(truncatingIfNeeded: Val >> 16) Message[Offset + 3] = UInt8(truncatingIfNeeded: Val >> 24) } override func fillBlock() { // Pre-processing: // Append "1" bit to message // Append "0" bits until message length in bits -> 448 (mod 512) // Append length mod (2^64) to message var new_len = messageLength + 1 while (new_len % (512/8) != 448/8) { new_len += 1 } // Append the "1" bit - most significant bit is "first" data[dataLength] = UInt8(0x80) dataLength += 1 // Append "0" bits for _ in 0..<(new_len - (messageLength + 1)) { if dataLength == blocksize { hash() } data[dataLength] = UInt8(0) dataLength += 1 } // Append the len in bits at the end of the buffer. // initial_len>>29 == initial_len*8>>32, but avoids overflow. appendBytes(messageLength * 8, &data, dataLength) appendBytes(messageLength>>29 * 8, &data, dataLength+4) dataLength += 8 } func toUInt32(_ Message: Array<UInt8>, _ Offset: Int) -> UInt32 { let first = UInt32(Message[Offset + 0]) let second = UInt32(Message[Offset + 1]) << 8 let third = UInt32(Message[Offset + 2]) << 16 let fourth = UInt32(Message[Offset + 3]) << 24 return first | second | third | fourth } var w = [UInt32](repeating: 0, count: 16) override func hash() { assert(dataLength == blocksize, "Invalid block size") // Break chunk into sixteen 32-bit words w[j], 0 ≤ j ≤ 15 for i in 0..<16 { w[i] = toUInt32(data, i*4) } // We don't need the original data anymore. dataLength = 0 var a = h0 var b = h1 var c = h2 var d = h3 var f, g: UInt32 // Main loop: for i in 0..<64 { if i < 16 { f = (b & c) | ((~b) & d) g = UInt32(i) } else if i < 32 { f = (d & b) | ((~d) & c) g = UInt32(5*i + 1) % 16 } else if i < 48 { f = b ^ c ^ d g = UInt32(3*i + 5) % 16 } else { f = c ^ (b | (~d)) g = UInt32(7*i) % 16 } let temp = d d = c c = b b = b &+ rol(a &+ f &+ k[i] &+ w[Int(g)], r[i]) a = temp } // Add this chunk's hash to result so far: h0 = a &+ h0 h1 = b &+ h1 h2 = c &+ h2 h3 = d &+ h3 } func reverseBytes(_ In: UInt32) -> UInt32 { let B0 = (In >> 0 ) & 0xFF let B1 = (In >> 8 ) & 0xFF let B2 = (In >> 16) & 0xFF let B3 = (In >> 24) & 0xFF return (B0 << 24) | (B1 << 16) | (B2 << 8) | B3 } override func hashState() -> String { var S = "" for h in [h0, h1, h2, h3] { S += toHex(reverseBytes(h)) } return S } override func hashStateFast(_ Res: inout [UInt8]) { #if !NO_RANGE var Idx: Int = 0 for h in [h0, h1, h2, h3] { toHexFast(h, &Res, Idx) Idx += 8 } #else toHexFast(h0, &Res, 0) toHexFast(h1, &Res, 8) toHexFast(h2, &Res, 16) toHexFast(h3, &Res, 24) #endif } } class SHA1 : Hash { // State var h0: UInt32 = 0 var h1: UInt32 = 0 var h2: UInt32 = 0 var h3: UInt32 = 0 var h4: UInt32 = 0 init() { super.init(64) reset() } func reset() { // Set the initial values. h0 = 0x67452301 h1 = 0xEFCDAB89 h2 = 0x98BADCFE h3 = 0x10325476 h4 = 0xC3D2E1F0 messageLength = 0 dataLength = 0 } override func fillBlock() { // Append a 1 to the message. data[dataLength] = UInt8(0x80) dataLength += 1 var new_len = messageLength + 1 while ((new_len % 64) != 56) { new_len += 1 } for _ in 0..<new_len - (messageLength + 1) { if dataLength == blocksize { hash() } data[dataLength] = UInt8(0x0) dataLength += 1 } // Append the original message length as 64bit big endian: let len_in_bits = Int64(messageLength)*8 for i in 0..<(8 as Int64) { let val = (len_in_bits >> ((7-i)*8)) & 0xFF data[dataLength] = UInt8(val) dataLength += 1 } } override func hash() { assert(dataLength == blocksize, "Invalid block size") // Init the "W" buffer. var w = [UInt32](repeating: 0, count: 80) // Convert the Byte array to UInt32 array. var word: UInt32 = 0 for i in 0..<64 { word = word << 8 word = word &+ UInt32(data[i]) if i%4 == 3 { w[i/4] = word; word = 0 } } // Init the rest of the "W" buffer. for t in 16..<80 { // splitting into 2 subexpressions to help typechecker let lhs = w[t-3] ^ w[t-8] let rhs = w[t-14] ^ w[t-16] w[t] = rol(lhs ^ rhs, 1) } dataLength = 0 var A = h0 var B = h1 var C = h2 var D = h3 var E = h4 var K: UInt32, F: UInt32 for t in 0..<80 { if t < 20 { K = 0x5a827999 F = (B & C) | ((B ^ 0xFFFFFFFF) & D) } else if t < 40 { K = 0x6ed9eba1 F = B ^ C ^ D } else if t < 60 { K = 0x8f1bbcdc F = (B & C) | (B & D) | (C & D) } else { K = 0xca62c1d6 F = B ^ C ^ D } let Temp: UInt32 = rol(A,5) &+ F &+ E &+ w[t] &+ K E = D D = C C = rol(B,30) B = A A = Temp } h0 = h0 &+ A h1 = h1 &+ B h2 = h2 &+ C h3 = h3 &+ D h4 = h4 &+ E } override func hashState() -> String { var Res: String = "" for state in [h0, h1, h2, h3, h4] { Res += toHex(state) } return Res } } class SHA256 : Hash { // State var h0: UInt32 = 0 var h1: UInt32 = 0 var h2: UInt32 = 0 var h3: UInt32 = 0 var h4: UInt32 = 0 var h5: UInt32 = 0 var h6: UInt32 = 0 var h7: UInt32 = 0 var k : [UInt32] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] init() { super.init(64) reset() } func reset() { // Set the initial values. h0 = 0x6a09e667 h1 = 0xbb67ae85 h2 = 0x3c6ef372 h3 = 0xa54ff53a h4 = 0x510e527f h5 = 0x9b05688c h6 = 0x1f83d9ab h7 = 0x5be0cd19 messageLength = 0 dataLength = 0 } override func fillBlock() { // Append a 1 to the message. data[dataLength] = UInt8(0x80) dataLength += 1 var new_len = messageLength + 1 while ((new_len % 64) != 56) { new_len += 1 } for _ in 0..<new_len - (messageLength+1) { if dataLength == blocksize { hash() } data[dataLength] = UInt8(0) dataLength += 1 } // Append the original message length as 64bit big endian: let len_in_bits = Int64(messageLength)*8 for i in 0..<(8 as Int64) { let val = (len_in_bits >> ((7-i)*8)) & 0xFF data[dataLength] = UInt8(val) dataLength += 1 } } override func hash() { assert(dataLength == blocksize, "Invalid block size") // Init the "W" buffer. var w = [UInt32](repeating: 0, count: 64) // Convert the Byte array to UInt32 array. var word: UInt32 = 0 for i in 0..<64 { word = word << 8 word = word &+ UInt32(data[i]) if i%4 == 3 { w[i/4] = word; word = 0 } } // Init the rest of the "W" buffer. for i in 16..<64 { let s0 = ror(w[i-15], 7) ^ ror(w[i-15], 18) ^ (w[i-15] >> 3) let s1 = ror(w[i-2], 17) ^ ror(w[i-2], 19) ^ (w[i-2] >> 10) w[i] = w[i-16] &+ s0 &+ w[i-7] &+ s1 } dataLength = 0 var a = h0 var b = h1 var c = h2 var d = h3 var e = h4 var f = h5 var g = h6 var h = h7 for i in 0..<64 { let S1 = ror(e, 6) ^ ror(e, 11) ^ ror(e, 25) let ch = (e & f) ^ ((~e) & g) let temp1 = h &+ S1 &+ ch &+ k[i] &+ w[i] let S0 = ror(a, 2) ^ ror(a, 13) ^ ror(a, 22) let maj = (a & b) ^ (a & c) ^ (b & c) let temp2 = S0 &+ maj h = g g = f f = e e = d &+ temp1 d = c c = b b = a a = temp1 &+ temp2 } h0 = h0 &+ a h1 = h1 &+ b h2 = h2 &+ c h3 = h3 &+ d h4 = h4 &+ e h5 = h5 &+ f h6 = h6 &+ g h7 = h7 &+ h } override func hashState() -> String { var Res: String = "" for state in [h0, h1, h2, h3, h4, h5, h6, h7] { Res += toHex(state) } return Res } } func == (lhs: [UInt8], rhs: [UInt8]) -> Bool { if lhs.count != rhs.count { return false } for idx in 0..<lhs.count { if lhs[idx] != rhs[idx] { return false } } return true } @inline(never) public func run_HashTest(_ N: Int) { let TestMD5 = ["" : "d41d8cd98f00b204e9800998ecf8427e", "The quick brown fox jumps over the lazy dog." : "e4d909c290d0fb1ca068ffaddf22cbd0", "The quick brown fox jumps over the lazy cog." : "68aa5deab43e4df2b5e1f80190477fb0"] let TestSHA1 = ["" : "da39a3ee5e6b4b0d3255bfef95601890afd80709", "The quick brown fox jumps over the lazy dog" : "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", "The quick brown fox jumps over the lazy cog" : "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"] let TestSHA256 = ["" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "The quick brown fox jumps over the lazy dog" : "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", "The quick brown fox jumps over the lazy dog." : "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"] let size = 50 for _ in 1...10*N { // Check for precomputed values. let MD = MD5() for (K, V) in TestMD5 { MD.update(K) CheckResults(MD.digest() == V) MD.reset() } // Check that we don't crash on large strings. var S: String = "" for _ in 1...size { S += "a" MD.reset() MD.update(S) } // Check that the order in which we push values does not change the result. MD.reset() var L: String = "" for _ in 1...size { L += "a" MD.update("a") } let MD2 = MD5() MD2.update(L) CheckResults(MD.digest() == MD2.digest()) // Test the famous MD5 collision from 2009: http://www.mscs.dal.ca/~selinger/md5collision/ let Src1 : [UInt8] = [0xd1, 0x31, 0xdd, 0x02, 0xc5, 0xe6, 0xee, 0xc4, 0x69, 0x3d, 0x9a, 0x06, 0x98, 0xaf, 0xf9, 0x5c, 0x2f, 0xca, 0xb5, 0x87, 0x12, 0x46, 0x7e, 0xab, 0x40, 0x04, 0x58, 0x3e, 0xb8, 0xfb, 0x7f, 0x89, 0x55, 0xad, 0x34, 0x06, 0x09, 0xf4, 0xb3, 0x02, 0x83, 0xe4, 0x88, 0x83, 0x25, 0x71, 0x41, 0x5a, 0x08, 0x51, 0x25, 0xe8, 0xf7, 0xcd, 0xc9, 0x9f, 0xd9, 0x1d, 0xbd, 0xf2, 0x80, 0x37, 0x3c, 0x5b, 0xd8, 0x82, 0x3e, 0x31, 0x56, 0x34, 0x8f, 0x5b, 0xae, 0x6d, 0xac, 0xd4, 0x36, 0xc9, 0x19, 0xc6, 0xdd, 0x53, 0xe2, 0xb4, 0x87, 0xda, 0x03, 0xfd, 0x02, 0x39, 0x63, 0x06, 0xd2, 0x48, 0xcd, 0xa0, 0xe9, 0x9f, 0x33, 0x42, 0x0f, 0x57, 0x7e, 0xe8, 0xce, 0x54, 0xb6, 0x70, 0x80, 0xa8, 0x0d, 0x1e, 0xc6, 0x98, 0x21, 0xbc, 0xb6, 0xa8, 0x83, 0x93, 0x96, 0xf9, 0x65, 0x2b, 0x6f, 0xf7, 0x2a, 0x70] let Src2 : [UInt8] = [0xd1, 0x31, 0xdd, 0x02, 0xc5, 0xe6, 0xee, 0xc4, 0x69, 0x3d, 0x9a, 0x06, 0x98, 0xaf, 0xf9, 0x5c, 0x2f, 0xca, 0xb5, 0x07, 0x12, 0x46, 0x7e, 0xab, 0x40, 0x04, 0x58, 0x3e, 0xb8, 0xfb, 0x7f, 0x89, 0x55, 0xad, 0x34, 0x06, 0x09, 0xf4, 0xb3, 0x02, 0x83, 0xe4, 0x88, 0x83, 0x25, 0xf1, 0x41, 0x5a, 0x08, 0x51, 0x25, 0xe8, 0xf7, 0xcd, 0xc9, 0x9f, 0xd9, 0x1d, 0xbd, 0x72, 0x80, 0x37, 0x3c, 0x5b, 0xd8, 0x82, 0x3e, 0x31, 0x56, 0x34, 0x8f, 0x5b, 0xae, 0x6d, 0xac, 0xd4, 0x36, 0xc9, 0x19, 0xc6, 0xdd, 0x53, 0xe2, 0x34, 0x87, 0xda, 0x03, 0xfd, 0x02, 0x39, 0x63, 0x06, 0xd2, 0x48, 0xcd, 0xa0, 0xe9, 0x9f, 0x33, 0x42, 0x0f, 0x57, 0x7e, 0xe8, 0xce, 0x54, 0xb6, 0x70, 0x80, 0x28, 0x0d, 0x1e, 0xc6, 0x98, 0x21, 0xbc, 0xb6, 0xa8, 0x83, 0x93, 0x96, 0xf9, 0x65, 0xab, 0x6f, 0xf7, 0x2a, 0x70] let H1 = MD5() let H2 = MD5() H1.update(Src1) H2.update(Src2) let A1 = H1.digest() let A2 = H2.digest() CheckResults(A1 == A2) CheckResults(A1 == "79054025255fb1a26e4bc422aef54eb4") H1.reset() H2.reset() let SH = SHA1() let SH256 = SHA256() for (K, V) in TestSHA1 { SH.update(K) CheckResults(SH.digest() == V) SH.reset() } for (K, V) in TestSHA256 { SH256.update(K) CheckResults(SH256.digest() == V) SH256.reset() } // Check that we don't crash on large strings. S = "" for _ in 1...size { S += "a" SH.reset() SH.update(S) } // Check that the order in which we push values does not change the result. SH.reset() L = "" for _ in 1...size { L += "a" SH.update("a") } let SH2 = SHA1() SH2.update(L) CheckResults(SH.digest() == SH2.digest()) } }
apache-2.0
9a821db39a03af433a96fe0e2f4b4b2a
26.650746
196
0.551063
2.604527
false
false
false
false
SheffieldKevin/SwiftSVG
SwiftSVG/Utilities/Renderer.swift
1
13773
// // Renderer.swift // SwiftSVG // // Created by Jonathan Wight on 8/26/15. // Copyright © 2015 No. All rights reserved. // import SwiftGraphics public protocol Renderer: AnyObject { func concatTransform(transform:CGAffineTransform) func concatCTM(transform:CGAffineTransform) func pushGraphicsState() func restoreGraphicsState() func startDocument(viewBox: CGRect) func startGroup(id: String?) func endElement() func startElement(id: String?) func addPath(path:PathGenerator) func addCGPath(path: CGPath) func drawPath(mode: CGPathDrawingMode) func drawText(textRenderer: TextRenderer) func fillPath() func render() -> String var strokeColor:CGColor? { get set } var fillColor:CGColor? { get set } var lineWidth:CGFloat? { get set } var style:Style { get set } } // MARK: - public protocol CustomSourceConvertible { func toSource() -> String } extension CGAffineTransform: CustomSourceConvertible { public func toSource() -> String { return "CGAffineTransform(\(a), \(b), \(c), \(d), \(tx), \(ty))" } } // MARK: - CGContext renderer extension CGContext: Renderer { public func concatTransform(transform:CGAffineTransform) { CGContextConcatCTM(self, transform) } public func concatCTM(transform:CGAffineTransform) { CGContextConcatCTM(self, transform) } public func pushGraphicsState() { CGContextSaveGState(self) } public func restoreGraphicsState() { CGContextRestoreGState(self) } public func startDocument(viewBox: CGRect) { } public func startGroup(id: String?) { } public func endElement() { } public func startElement(id: String?) { } public func addCGPath(path: CGPath) { CGContextAddPath(self, path) } public func addPath(path:PathGenerator) { addCGPath(path.cgpath) } public func drawPath(mode: CGPathDrawingMode) { CGContextDrawPath(self, mode) } public func drawText(textRenderer: TextRenderer) { self.pushGraphicsState() CGContextTranslateCTM(self, 0.0, textRenderer.textOrigin.y) CGContextScaleCTM(self, 1.0, -1.0) let line = CTLineCreateWithAttributedString(textRenderer.cttext) CGContextSetTextPosition(self, textRenderer.textOrigin.x, 0.0) CTLineDraw(line, self) self.restoreGraphicsState() } public func fillPath() { CGContextFillPath(self) } public func render() -> String { return "" } } //MARK: - MovingImagesRenderer public class MovingImagesRenderer: Renderer { class MIRenderElement: Node { internal typealias ParentType = MIRenderContainer internal weak var parent: MIRenderContainer? = nil internal var movingImages = [NSString : AnyObject]() internal func generateJSONDict() -> [NSString : AnyObject] { return movingImages } } class MIRenderContainer: MIRenderElement, GroupNode { internal var children = [MIRenderElement]() override init() { super.init() } override internal func generateJSONDict() -> [NSString : AnyObject] { self.movingImages[MIJSONKeyElementType] = MIJSONKeyArrayOfElements let arrayOfElements = children.map { $0.generateJSONDict() } self.movingImages[MIJSONKeyArrayOfElements] = arrayOfElements return self.movingImages } } public init() { current = rootElement } internal var rootElement = MIRenderContainer() private var current: MIRenderElement // internal var movingImagesJSON: [NSString : AnyObject] public func concatTransform(transform:CGAffineTransform) { concatCTM(transform) } public func concatCTM(transform:CGAffineTransform) { current.movingImages[MIJSONKeyAffineTransform] = makeCGAffineTransformDictionary(transform) } public func pushGraphicsState() { } public func restoreGraphicsState() { } public func addCGPath(path: CGPath) { } // Should this be throws? public func startGroup(id: String?) { if let current = self.current as? MIRenderContainer { let newItem = MIRenderContainer() if let id = id { newItem.movingImages[MIJSONKeyElementDebugName] = id } current.children.append(newItem) newItem.parent = current self.current = newItem } else { preconditionFailure("Cannot start a new render group. Current element is a leaf") } } public func startElement(id: String?) { if let current = self.current as? MIRenderContainer { let newItem = MIRenderElement() if let id = id { newItem.movingImages[MIJSONKeyElementDebugName] = id } current.children.append(newItem) newItem.parent = current self.current = newItem } else { preconditionFailure("Cannot start a new render element. Current element is a leaf") } } public func startDocument(viewBox: CGRect) { current.movingImages["viewBox"] = makeRectDictionary(viewBox) } public func addPath(path:PathGenerator) { for (key, value) in path.mipath { current.movingImages[key] = value } } public func drawText(textRenderer: TextRenderer) { for (key, value) in textRenderer.mitext { current.movingImages[key] = value } } public func endElement() { if let parent = self.current.parent { self.current = parent } else { preconditionFailure("Cannot end an element when there is no parent.") } } public func drawPath(mode: CGPathDrawingMode) { let miDrawingElement: NSString let evenOdd: NSString? switch(mode) { case CGPathDrawingMode.Fill: miDrawingElement = MIJSONValuePathFillElement evenOdd = Optional.None // evenOdd = "nonwindingrule" case CGPathDrawingMode.Stroke: miDrawingElement = MIJSONValuePathStrokeElement evenOdd = Optional.None case CGPathDrawingMode.EOFill: miDrawingElement = MIJSONValuePathFillElement evenOdd = MIJSONValueEvenOddClippingRule case CGPathDrawingMode.EOFillStroke: miDrawingElement = MIJSONValuePathFillAndStrokeElement evenOdd = MIJSONValueEvenOddClippingRule case CGPathDrawingMode.FillStroke: miDrawingElement = MIJSONValuePathFillAndStrokeElement evenOdd = Optional.None // evenOdd = "nonwindingrule" } if let rule = evenOdd { current.movingImages[MIJSONKeyClippingRule] = rule } if current.movingImages[MIJSONKeyElementType] == nil { current.movingImages[MIJSONKeyElementType] = miDrawingElement } } // Not part of the Render protocol. public func generateJSONDict() -> [NSString : AnyObject] { return rootElement.generateJSONDict() } public func render() -> String { if let jsonString = jsonObjectToString(self.generateJSONDict()) { return jsonString } return "" } public func fillPath() { } public var strokeColor:CGColor? { get { return style.strokeColor } set { style.strokeColor = newValue if let color = newValue { // current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeMIColorDictFromColor(color) current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeHexColor(color: color) } else { current.movingImages[MIJSONKeyStrokeColor] = nil } } } public var fillColor:CGColor? { get { return style.fillColor } set { style.fillColor = newValue if let color = newValue { // current.movingImages[MIJSONKeyFillColor] = SVGColors.makeMIColorDictFromColor(color) current.movingImages[MIJSONKeyFillColor] = SVGColors.makeHexColor(color: color) } else { current.movingImages[MIJSONKeyFillColor] = nil } } } public var lineWidth:CGFloat? { get { return style.lineWidth } set { style.lineWidth = newValue if let lineWidth = newValue { current.movingImages[MIJSONKeyLineWidth] = lineWidth } else { current.movingImages[MIJSONKeyFillColor] = nil } } } public var style:Style = Style() { didSet { if let fillColor = style.fillColor { // current.movingImages[MIJSONKeyFillColor] = SVGColors.makeMIColorDictFromColor(fillColor) current.movingImages[MIJSONKeyFillColor] = SVGColors.makeHexColor(color: fillColor) } if let strokeColor = style.strokeColor { // current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeMIColorDictFromColor(strokeColor) current.movingImages[MIJSONKeyStrokeColor] = SVGColors.makeHexColor(color: strokeColor) } if let lineWidth = style.lineWidth { current.movingImages[MIJSONKeyLineWidth] = lineWidth } if let lineCap = style.lineCap { current.movingImages[MIJSONKeyLineCap] = lineCap.stringValue } if let lineJoin = style.lineJoin { current.movingImages[MIJSONKeyLineJoin] = lineJoin.stringValue } if let miterLimit = style.miterLimit { current.movingImages[MIJSONKeyMiter] = miterLimit } if let alpha = style.alpha { current.movingImages[MIJSONKeyAlpha] = alpha } /* Not yet implemented in SwiftSVG. if let blendMode = newStyle.blendMode { setBlendMode(blendMode) } */ // TODO: Not implemented in MovingImages. /* if let lineDash = newStyle.lineDash { if let lineDashPhase = newStyle.lineDashPhase { setLineDash(lineDash, phase: lineDashPhase) } else { setLineDash(lineDash, phase: 0.0) } } if let flatness = newStyle.flatness { setFlatness(flatness) } */ } } } private extension CGLineCap { var stringValue: NSString { switch(self) { case CGLineCap.Butt: return "kCGLineCapButt" case CGLineCap.Round: return "kCGLineCapRound" case CGLineCap.Square: return "kCGLineCapSquare" } } } private extension CGLineJoin { var stringValue: NSString { switch(self) { case CGLineJoin.Bevel: return "kCGLineJoinBevel" case CGLineJoin.Miter: return "kCGLineJoinMiter" case CGLineJoin.Round: return "kCGLineJoinRound" } } } // MARK: - public class SourceCodeRenderer: Renderer { public internal(set) var source = "" public init() { // Shouldn't this be fill color. Default stroke is no stroke. // whereas default fill is black. ktam? self.style.strokeColor = CGColor.blackColor() } public func concatTransform(transform:CGAffineTransform) { concatCTM(transform) } public func concatCTM(transform:CGAffineTransform) { source += "CGContextConcatCTM(context, \(transform.toSource()))\n" } public func pushGraphicsState() { source += "CGContextSaveGState(context)\n" } public func restoreGraphicsState() { source += "CGContextRestoreGState(self)\n" } public func startGroup(id: String?) { } public func endElement() { } public func startElement(id: String?) { } public func startDocument(viewBox: CGRect) { } public func addCGPath(path: CGPath) { source += "CGContextAddPath(context, \(path))\n" } public func addPath(path:PathGenerator) { addCGPath(path.cgpath) } public func drawPath(mode: CGPathDrawingMode) { source += "CGContextDrawPath(context, TODO)\n" } public func drawText(textRenderer: TextRenderer) { } public func fillPath() { source += "CGContextFillPath(context)\n" } public func render() -> String { return source } public var strokeColor:CGColor? { get { return style.strokeColor } set { style.strokeColor = newValue source += "CGContextSetStrokeColor(context, TODO)\n" } } public var fillColor:CGColor? { get { return style.fillColor } set { style.fillColor = newValue source += "CGContextSetFillColor(context, TODO)\n" } } public var lineWidth:CGFloat? { get { return style.lineWidth } set { style.lineWidth = newValue source += "CGContextSetLineWidth(context, TODO)\n" } } public var style:Style = Style() { didSet { source += "CGContextSetStrokeColor(context, TODO)\n" source += "CGContextSetFillColor(context, TODO)\n" } } }
bsd-2-clause
87207776cf500491c9f532ce6d138460
28.054852
111
0.601147
4.920329
false
false
false
false
EstefaniaGilVaquero/ciceIOS
AppNavigationDataAndres/App_NavigationData/ICTerceraVentanaViewController.swift
1
4517
// // ICTerceraVentanaViewController.swift // App_NavigationData // // Created by formador on 3/6/16. // Copyright © 2016 Cice. All rights reserved. // import UIKit class ICTerceraVentanaViewController: UIViewController { //MARK: - VARIABLES LOCALES GLOBALES var variables = VariablesGlobales() var codigoPostalArray = ["28001", "28006", "28050", "28226"] var ciudadArray = ["Madrid", "Barcelona", "Sevilla", "Valencia"] var posicionGeograficaArray = ["40.4512 / -3.2514", "132.4512 / -35.2514", "140.4512 / -34.2514","10.4512 / -1.2514"] //MARK: - IBOUTLET @IBOutlet weak var myNombreLBL: UILabel! @IBOutlet weak var myApellidoLBL: UILabel! @IBOutlet weak var myTelefonoLBL: UILabel! @IBOutlet weak var myDireccionLBL: UILabel! @IBOutlet weak var myEdadPerroLBL: UILabel! @IBOutlet weak var myCodigoPostalTF: UITextField! @IBOutlet weak var myCiudadTF: UITextField! @IBOutlet weak var myPosicionGeoTF: UITextField! override func viewDidLoad() { super.viewDidLoad() myNombreLBL.text = variables.nombreData myApellidoLBL.text = variables.apellidoData myTelefonoLBL.text = variables.telefonoMovilData myDireccionLBL.text = variables.direccionData myEdadPerroLBL.text = variables.edadPerroData crearPicker(myCodigoPostalTF, myArray: codigoPostalArray, myTag: 0, myDelegateVC: self, myDataSourceVC:self) crearPicker(myCiudadTF, myArray: ciudadArray, myTag: 1, myDelegateVC: self, myDataSourceVC: self) crearPicker(myPosicionGeoTF, myArray: posicionGeograficaArray, myTag: 2, myDelegateVC: self, myDataSourceVC: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueV4"{ let ventanaV4 = segue.destinationViewController as! ICCuartaVenetanaViewController ventanaV4.variables.nombreData = self.myNombreLBL.text ventanaV4.variables.apellidoData = self.myApellidoLBL.text ventanaV4.variables.telefonoMovilData = self.myTelefonoLBL.text ventanaV4.variables.direccionData = self.myDireccionLBL.text ventanaV4.variables.edadPerroData = self.myEdadPerroLBL.text ventanaV4.variables.codigoPostalData = self.myCodigoPostalTF.text ventanaV4.variables.ciudadData = self.myCiudadTF.text ventanaV4.variables.posicionGeograficaData = self.myPosicionGeoTF.text }else{ presentViewController(displayAlertVC("Hey", messageData: "No se ha logrado enviar la info"), animated: true, completion: nil) } } } //MARK: - DELEGATE / DATASOURCE DE PICKERVIEW extension ICTerceraVentanaViewController : UIPickerViewDataSource, UIPickerViewDelegate{ func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView.tag == 0{ return codigoPostalArray.count }else if pickerView.tag == 1{ return ciudadArray.count }else{ return posicionGeograficaArray.count } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView.tag == 0{ return codigoPostalArray[row] }else if pickerView.tag == 1{ return ciudadArray[row] }else{ return posicionGeograficaArray[row] } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView.tag == 0{ myCodigoPostalTF.text = codigoPostalArray[row] //myImagenCiudadIV.image = UIImage(named: imagenesArray[row]) }else if pickerView.tag == 1{ myCiudadTF.text = ciudadArray[row] }else{ myPosicionGeoTF.text = posicionGeograficaArray[row] } } }
apache-2.0
19f6af4fafa67ede1114ffa2c11062c2
34.84127
137
0.670062
3.879725
false
false
false
false
NoodleOfDeath/PastaParser
runtime/swift/Example/GrammarKit_Example/Extensions.SnapKit.swift
1
6324
// // The MIT License (MIT) // // Copyright © 2019 NoodleOfDeath. All rights reserved. // NoodleOfDeath // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SnapKit // MARK: - UIView SnapKit Extensions extension UIView { /// Returns a new `UIEdgeInsets` instance from a specified set of values /// and an unsigned flag. /// /// - Parameters: /// - values: to inset each edge of this view within its /// superview with, in order of top, left, bottom, and right. fileprivate func edgeInsets(for values: [CGFloat]) -> UIEdgeInsets { var edgeInsets = UIEdgeInsets() edgeInsets.top = values.count > 0 ? values[0] : 0.0 edgeInsets.left = values.count > 1 ? values[1] : 0.0 edgeInsets.bottom = values.count > 2 ? values[2] : 0.0 edgeInsets.right = values.count > 3 ? values[3] : 0.0 return edgeInsets } /// Constrains the edges of this view to the edges of its superview using /// specified edge insets. /// /// - Parameters: /// - values: to inset each edge of this view within its /// superview with, in order of top, left, bottom, and right. func constrainToSuperview(_ values: CGFloat...) { constrainToSuperview(edgeInsets: edgeInsets(for: values)) } /// Constrains the edges of this view to the edges of its superview using /// specified edge insets. /// /// - Parameters: /// - edgeInsets: to inset the edges of this view within its /// superview with. func constrainToSuperview(edgeInsets: UIEdgeInsets) { guard let superview = superview else { return } snp.makeConstraints { (dims) in dims.top.equalTo(superview).offset(edgeInsets.top) dims.left.equalTo(superview).offset(edgeInsets.left) dims.bottom.equalTo(superview).offset(edgeInsets.bottom) dims.right.equalTo(superview).offset(edgeInsets.right) } } /// Constrains the edges of this view to the edges of its superview using a /// specified padding constant. /// /// - Parameters: /// - padding: constant to inset the edges of this view within /// its superview with. func constrainToSuperview(padding: CGFloat) { constrainToSuperview(edgeInsets: UIEdgeInsets(top: padding, left: padding, bottom: -padding, right: -padding)) } /// Constrains the edges of this view to the edges of its superview using /// specified edge insets. /// /// - Parameters: /// - edgeInsetSize: to inset the edges of this view within its /// superview with where width is the unsigned horizontal edge inset /// and height is the unsigned vertical edge inset. func constrainToSuperview(edgeInsetSize: CGSize) { constrainToSuperview(edgeInsets: UIEdgeInsets(top: edgeInsetSize.height, left: edgeInsetSize.width, bottom: -edgeInsetSize.height, right: -edgeInsetSize.width)) } /// Adds a subview and constrains its edges to the edges of this view using /// specified edge insets. /// /// - Parameters: /// - subview: to add to this view. /// - values: to inset the edges of this view within its /// superview with, in order of top, left, bottom, and right. func addConstrainedSubview(_ subview: UIView, _ values: CGFloat...) { addSubview(subview) subview.constrainToSuperview(edgeInsets: edgeInsets(for: values)) } /// Adds a subview and constrains its edges to the edges of this view using /// specified edge insets. /// /// - Parameters: /// - subview: to add to this view. /// - edgeInsets: to inset the edges of this view within its /// superview with. func addConstrainedSubview(_ subview: UIView, edgeInsets: UIEdgeInsets) { addSubview(subview) subview.constrainToSuperview(edgeInsets: edgeInsets) } /// Adds a subview and constrains its edges to the edges of this view using /// a specified padding constant. /// /// - Parameters: /// - subview: to add to this view. /// - padding: constant to inset the edges of this view within /// its superview with. func addConstrainedSubview(_ subview: UIView, padding: CGFloat) { addSubview(subview) subview.constrainToSuperview(padding: padding) } /// Adds a subview and constrains its edges to the edges of this view using /// a specified padding constant. /// /// - Parameters: /// - subview: to add to this view. /// - edgeInsetSize: to inset the edges of this view within /// its superview with, where width is the unsigned horizontal edge inset /// and height is the unsigned vertical edge inset. func addConstrainedSubview(_ subview: UIView, edgeInsetSize: CGSize) { addSubview(subview) subview.constrainToSuperview(edgeInsetSize: edgeInsetSize) } }
mit
681bd861b650fbaa9b188feddc0de0f1
41.436242
84
0.634193
4.856375
false
false
false
false
StormXX/STTableBoard
STTableBoard/Views/NewBoardButton.swift
1
3162
// // NewBoardButton.swift // STTableBoard // // Created by DangGu on 16/1/4. // Copyright © 2016年 StormXX. All rights reserved. // protocol NewBoardButtonDelegate: class { func newBoardButtonDidBeClicked(newBoardButton button: NewBoardButton) } import UIKit class NewBoardButton: UIView { var title: String? { didSet { titleLabel.text = title } } var image: UIImage? { didSet { imageView.image = image } } weak var delegate: NewBoardButtonDelegate? fileprivate lazy var imageView: UIImageView = { let view = UIImageView(frame: CGRect.zero) view.contentMode = .scaleAspectFill return view }() fileprivate lazy var tapGesture: UITapGestureRecognizer = { let gesture = UITapGestureRecognizer(target: self, action: #selector(NewBoardButton.viewDidBeClicked)) return gesture }() fileprivate lazy var titleLabel: UILabel = { let label = UILabel(frame: CGRect.zero) label.numberOfLines = 1 label.textColor = UIColor.grayTextColor label.font = UIFont.systemFont(ofSize: 17.0) return label }() override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let roundedPath = UIBezierPath(roundedRect: rect, cornerRadius: 4.0) context?.setFillColor(UIColor.white.cgColor) newBoardButtonBackgroundColor.setFill() roundedPath.fill() let roundedRect = rect.insetBy(dx: 1.0, dy: 1.0) let dashedPath = UIBezierPath(roundedRect: roundedRect, cornerRadius: 4.0) let pattern: [CGFloat] = [6,6] dashedPath.setLineDash(pattern, count: 2, phase: 0.0) dashedLineColor.setStroke() dashedPath.stroke() } override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) addSubview(titleLabel) backgroundColor = UIColor.clear addGestureRecognizer(tapGesture) imageView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false let views: [String:UIView] = ["imageView":imageView, "titleLabel":titleLabel] let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(15)-[imageView(==18)]-(10)-[titleLabel]-(10)-|", options: .alignAllCenterY, metrics: nil, views: views) let imageViewHeight = NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 18.0) let imageViewCenterY = NSLayoutConstraint(item: imageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0) NSLayoutConstraint.activate(horizontalConstraints + [imageViewHeight, imageViewCenterY]) } func viewDidBeClicked() { delegate?.newBoardButtonDidBeClicked(newBoardButton: self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
cc0-1.0
ffd0674ac0de0a05d16392bab515ec68
34.494382
194
0.662551
4.786364
false
false
false
false
digoreis/swift-proposal-analyzer
Sources/Author.swift
2
923
// // Created by Jesse Squires // http://www.jessesquires.com // // // GitHub // https://github.com/jessesquires/swift-proposal-analyzer // // // License // Copyright © 2016 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation /// Represents a proposal author. public struct Author { public let name: String public init(name: String) { self.name = name } } extension Author: CustomStringConvertible { public var description: String { return name } } extension Author: Equatable { public static func ==(lhs: Author, rhs: Author) -> Bool { return lhs.name == rhs.name } } extension Author: Comparable { public static func < (lhs: Author, rhs: Author) -> Bool { return lhs.name < rhs.name } } extension Author: Hashable { public var hashValue: Int { return name.hashValue } }
mit
cc52bcc90963e70aa6840391a08d339b
18.208333
69
0.643167
3.857741
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/View/ErrorBanner.swift
1
1373
// // ErrorBanner.swift // JenkinsiOS // // Created by Robert on 29.10.18. // Copyright © 2018 MobiLab Solutions. All rights reserved. // import UIKit class ErrorBanner: UIView { var errorDetails: String = "" { didSet { errorDetailsLabel?.text = errorDetails } } private var errorDetailsLabel: UILabel? override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { backgroundColor = Constants.UI.grapefruit addErrorLabel() } private func addErrorLabel() { let label = UILabel(frame: bounds) label.textColor = .white label.textAlignment = .center label.font = label.font.withSize(13) label.numberOfLines = 0 addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: topAnchor, constant: 6), label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6), label.leftAnchor.constraint(equalTo: leftAnchor, constant: 8), label.rightAnchor.constraint(equalTo: rightAnchor, constant: -8), ]) errorDetailsLabel = label } }
mit
4ab0930ebf74218f61bc51b5f89ed13a
23.945455
79
0.623178
4.650847
false
false
false
false
Lasithih/LIHAlert
Example/LIHAlert/CustomViewControllers/TableViewController.swift
1
1513
// // TableViewController.swift // LIHAlert // // Created by Lasith Hettiarachchi on 2/23/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit protocol TableDelegate { func optionSelected(text: String) } class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var delegate: TableDelegate? fileprivate var options = ["Option 1", "Option 2", "Option 3", "Option 4"] override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = self.options[indexPath.row] cell.textLabel?.textAlignment = NSTextAlignment.center cell.backgroundColor = UIColor.clear return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.delegate?.optionSelected(text: self.options[indexPath.row]) } }
mit
c5b065ac179d0cf8f23e476bba0c91c2
27.528302
100
0.679233
5.073826
false
false
false
false
lieonCX/Live
Live/View/Home/HomeViewController.swift
1
4842
// // HomeViewController.swift // Live // // Created by lieon on 2017/6/20. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit import RxCocoa import RxSwift class HomeViewController: BaseViewController { fileprivate lazy var searchBtn: UIButton = { let searchBtn = UIButton() searchBtn.frame = CGRect(x: 0, y: 20, width: 44, height: 44) searchBtn.setImage(UIImage(named: "home_nav_search_white"), for: .normal) searchBtn.addTarget(self, action: #selector(self.searchTapAction), for: .touchUpInside) return searchBtn }() fileprivate lazy var moreBtn: UIButton = { let moreBtn = UIButton() moreBtn.frame = CGRect(x:UIScreen.width - 44, y: 20, width: 44, height: 44) moreBtn.setImage(UIImage(named: "home_nav_more"), for: .normal) moreBtn.addTarget(self, action: #selector(self.moreTapAction(btn:)), for: .touchUpInside) return moreBtn }() fileprivate lazy var pageTitleView: PageTitleView = { let pvc = PageTitleView(frame: CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width - 80 * 2, height: 44), titles: ["最新", "热门", " 附近"]) return pvc }() fileprivate lazy var pageContenView: PageContentView = { [unowned self] in var childVCs = [UIViewController]() let latestVC = LatestViewController() let popularVC = PopularViewController() let nearVC = NearViewController() childVCs.append(latestVC) childVCs.append(popularVC) childVCs.append(nearVC) let pageContenView = PageContentView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), childVCs: childVCs, parentVC: self) return pageContenView }() override func viewDidLoad() { super.viewDidLoad() setupUI() tapAction() checkAvailableBrocadcast() } private func setupUI() { automaticallyAdjustsScrollViewInsets = false view.addSubview(pageContenView) let title = UIView() title.frame = CGRect(x: 0, y: 0, width: 44, height: 44) title.backgroundColor = .yellow self.navigationItem.titleView = pageTitleView let leftBtnItem = UIBarButtonItem(customView: searchBtn) self.navigationItem.leftBarButtonItem = leftBtnItem let rightBtnItem = UIBarButtonItem(customView: moreBtn) self.navigationItem.rightBarButtonItem = rightBtnItem } @objc fileprivate func searchTapAction() { self.navigationController?.pushViewController(SearchViewController(), animated: true) } @objc fileprivate func moreTapAction(btn: UIButton) { let point = CGPoint(x: btn.frame.origin.x + btn.bounds.width * 0.5, y: btn.frame.maxY + 12) YBPopupMenu.show(at: point, titles: [" 全部", " 只看男", " 只看女"], icons: nil, menuWidth: 92) { menu in menu?.arrowDirection = .top menu?.rectCorner = UIRectCorner.bottomRight menu?.delegate = self } } private func tapAction() { pageTitleView.titleTapAction = {[weak self] seletedIndex in self?.pageContenView.selected(index: seletedIndex) } pageContenView.tapAction = {[weak self] (progress, souceIndex, targetIndex) in self?.pageTitleView.setTitle(progress: progress, sourceIndex: souceIndex, targetIndex: targetIndex) } } private func checkAvailableBrocadcast() { let broadVM = BroacastViewModel() broadVM.checkAvailableBroadcast() .then(on: DispatchQueue.main, execute: { (info) -> Void in HUD.showAlert(from: self, title: "继续上次直播吗?", mesaage: "您的粉丝还在等你哟", doneActionTitle: "继续", handle: { let vcc = BroadcastViewController() vcc.broacastVM.liveInfo = info self.present(vcc, animated: true, completion: nil) }) }) .catch { _ in } } } extension HomeViewController: YBPopupMenuDelegate { func ybPopupMenuDidSelected(at index: Int, ybPopupMenu: YBPopupMenu!) { guard let vcc: HomeBaseCollectionVC = currentChildVC(pageTitleView.currentIndex) else { return } switch index { case 1: /// 只看男 vcc.param.sex = .male case 2: /// 只看女 vcc.param.sex = .female default: /// 全部 vcc.param.sex = nil break } vcc.collectionView.mj_header.beginRefreshing() } private func currentChildVC<T: HomeBaseCollectionVC>(_ index: Int) -> T? { guard let vcc = childViewControllers[index] as? T else { return nil } return vcc } }
mit
37244882195441f20a04d9d38c1fd88a
37.379032
179
0.627443
4.358059
false
false
false
false
dopcn/DroppingBall
DroppingBall/ViewController.swift
1
4665
// // ViewController.swift // DroppingBall // // Created by weizhou on 7/18/15. // Copyright (c) 2015 weizhou. All rights reserved. // import UIKit import CoreBluetooth class ViewController: UIViewController { static let characteristicUUID = "36BC9D9B-5FF0-4860-9DD9-FEB5CC019186" static let serviceUUID = "0E76CFF0-8F72-4302-83ED-16777697544A" let statusLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 400, height: 30)) let ball: UIView = { let tmp = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) tmp.layer.cornerRadius = 50 tmp.backgroundColor = UIColor.orange return tmp }() let bottom = UIView(frame: CGRect.zero) var animator: UIDynamicAnimator! var peripheralManager: CBPeripheralManager! var characteristic = CBMutableCharacteristic(type: CBUUID(string: ViewController.characteristicUUID), properties: .notify, value: nil, permissions: .readable) override func loadView() { super.loadView() view.backgroundColor = UIColor.white bottom.frame = CGRect(x: 0, y: view.frame.size.height-10, width: view.frame.size.width/2, height: 10) bottom.backgroundColor = UIColor.lightGray view.addSubview(bottom) view.addSubview(ball) ball.center = CGPoint(x: view.frame.size.width/2-100, y: view.frame.size.height - 50 - 10) view.addSubview(statusLabel) statusLabel.center = view.center statusLabel.textAlignment = .center } override func viewDidLoad() { super.viewDidLoad() let gr = UIPanGestureRecognizer(target: self, action: #selector(ViewController.panned(_:))) ball.addGestureRecognizer(gr) animator = UIDynamicAnimator(referenceView: view) let gravority = UIGravityBehavior(items: [ball]) let collison = UICollisionBehavior(items: [ball]) collison.addBoundary(withIdentifier: "boundary" as NSCopying, for: UIBezierPath(rect: bottom.frame)) let itemBehavior = UIDynamicItemBehavior(items: [ball]) itemBehavior.elasticity = 0.6 animator.addBehavior(gravority) animator.addBehavior(collison) peripheralManager = CBPeripheralManager(delegate: self, queue: nil) let gr2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped(_:))) view.addGestureRecognizer(gr2) statusLabel.isHidden = true } override func viewWillDisappear(_ animated: Bool) { peripheralManager.stopAdvertising() super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ViewController: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { guard peripheral.state == .poweredOn else { print("bluetooth is power off\n") return } let service = CBMutableService(type: CBUUID(string: ViewController.serviceUUID), primary: true) service.characteristics = [characteristic] peripheralManager.add(service) peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[CBUUID(string: ViewController.serviceUUID)]]) statusLabel.text = "begin advertising" } func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { statusLabel.text = "did subscribed" } func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { statusLabel.text = "did unsubscribe" } } extension ViewController { func panned(_ sender: UIPanGestureRecognizer) { ball.center = sender.location(in: view) if sender.state == UIGestureRecognizerState.ended { if ball.center.x > self.view.frame.size.width/2 { let json = ["x": ball.center.x - self.view.frame.size.width/2, "y": ball.center.y + 100] let data = try! JSONSerialization.data(withJSONObject: json, options: []) peripheralManager.updateValue(data, for: characteristic, onSubscribedCentrals: nil) statusLabel.text = "data sended" } animator.updateItem(usingCurrentState: ball) } } func tapped(_ sender: UITapGestureRecognizer) { ball.center = CGPoint(x: 200, y: 200) animator.updateItem(usingCurrentState: ball) } }
mit
7d920794f75bf1615fe06d08ad5c3bbf
36.02381
162
0.661308
4.769939
false
false
false
false
swipe-org/swipe
core/SwipeTimer.swift
2
1524
// // SwipeTimer.swift // // Created by Pete Stoppani on 5/23/16. // import Foundation class SwipeTimer : SwipeNode { static var timers = [SwipeTimer]() var timer: Timer? var repeats = false static func create(_ parent: SwipeNode, timerInfo: [String:Any]) { let timer = SwipeTimer(parent: parent, timerInfo: timerInfo) timers.append(timer) } init(parent: SwipeNode, timerInfo: [String:Any]) { super.init(parent: parent) var duration = 0.2 if let value = timerInfo["duration"] as? Double { duration = value } if let value = timerInfo["repeats"] as? Bool { repeats = value } if let eventsInfo = timerInfo["events"] as? [String:Any] { eventHandler.parse(eventsInfo) self.timer = Timer.scheduledTimer(timeInterval: duration, target:self, selector: #selector(SwipeTimer.didTimerTick(_:)), userInfo: nil, repeats: repeats) } } func cancel() { self.timer?.invalidate() self.timer = nil } static func cancelAll() { for timer in timers { timer.cancel() } timers.removeAll() } @objc func didTimerTick(_ timer: Timer) { if !timer.isValid { return } if let actions = eventHandler.actionsFor("tick") { execute(self, actions:actions) } if !repeats { cancel() } } }
mit
79e44c7e00f6b4ebf85ef290f818111b
23.983607
165
0.545932
4.404624
false
false
false
false
timd/ProiOSTableCollectionViews
Ch06/Chapter6/Chapter6/StoryboardTableViewController.swift
1
4374
// // StoryboardTableViewController.swift // Chapter6 // // Created by Tim on 27/09/15. // Copyright (c) 2015 Tim Duckett. All rights reserved. // import UIKit class StoryboardTableViewController: UITableViewController { var tableData = [String]() override func viewDidLoad() { super.viewDidLoad() setupTable() self.tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0) } 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 tableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = tableData[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) switch cellIdentifier { case "BasicCellIdentifier" : cell.textLabel!.text = "Basic cell" case "RightDetailCellIdentifier": cell.textLabel!.text = "Right detail cell" cell.detailTextLabel!.text = "Detail text label" case "LeftDetailCellIdentifier" : cell.textLabel!.text = "Left detail cell" cell.detailTextLabel!.text = "Detail text label" case "SubtitleCellIdentifier" : cell.textLabel!.text = "Subtitle cell" cell.detailTextLabel!.text = "Detail text label" default : // Handles CustomCellIdentifier by process of elimination print("The default custom cell type is empty and has no controls") } 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. } */ } extension StoryboardTableViewController { func setupTable() { tableData.append("BasicCellIdentifier") tableData.append("RightDetailCellIdentifier") tableData.append("LeftDetailCellIdentifier") tableData.append("SubtitleCellIdentifier") tableData.append("CustomCellIdentifier") } }
mit
c3ba585a8a8d3bed4a1e0de3be8ddb92
31.641791
157
0.648148
5.586207
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Extensions/Array+SwiftLint.swift
1
2007
import Dispatch import Foundation extension Array where Element: NSTextCheckingResult { func ranges() -> [NSRange] { return map { $0.range } } } extension Array where Element: Equatable { var unique: [Element] { var uniqueValues = [Element]() for item in self where !uniqueValues.contains(item) { uniqueValues.append(item) } return uniqueValues } } extension Array { static func array(of obj: Any?) -> [Element]? { if let array = obj as? [Element] { return array } else if let obj = obj as? Element { return [obj] } return nil } func group<U: Hashable>(by transform: (Element) -> U) -> [U: [Element]] { return reduce([:]) { dictionary, element in var dictionary = dictionary let key = transform(element) dictionary[key] = (dictionary[key] ?? []) + [element] return dictionary } } func partitioned(by belongsInSecondPartition: (Element) throws -> Bool) rethrows -> (first: ArraySlice<Element>, second: ArraySlice<Element>) { var copy = self let pivot = try copy.partition(by: belongsInSecondPartition) return (copy[0..<pivot], copy[pivot..<count]) } func parallelFlatMap<T>(transform: @escaping ((Element) -> [T])) -> [T] { return parallelMap(transform: transform).flatMap { $0 } } func parallelFlatMap<T>(transform: @escaping ((Element) -> T?)) -> [T] { return parallelMap(transform: transform).compactMap { $0 } } func parallelMap<T>(transform: (Element) -> T) -> [T] { var result = ContiguousArray<T?>(repeating: nil, count: count) return result.withUnsafeMutableBufferPointer { buffer in DispatchQueue.concurrentPerform(iterations: buffer.count) { idx in buffer[idx] = transform(self[idx]) } return buffer.map { $0! } } } }
mit
ce98f5b92df244c63133ce1c4e708bee
30.857143
87
0.579472
4.372549
false
false
false
false
benlangmuir/swift
stdlib/public/Concurrency/Actor.swift
8
3019
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020-2022 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 Swift @_implementationOnly import _SwiftConcurrencyShims /// Common marker protocol providing a shared "base" for both (local) `Actor` /// and (potentially remote) `DistributedActor` types. /// /// The `AnyActor` marker protocol generalizes over all actor types, including /// distributed ones. In practice, this protocol can be used to restrict /// protocols, or generic parameters to only be usable with actors, which /// provides the guarantee that calls may be safely made on instances of given /// type without worrying about the thread-safety of it -- as they are /// guaranteed to follow the actor-style isolation semantics. /// /// While both local and distributed actors are conceptually "actors", there are /// some important isolation model differences between the two, which make it /// impossible for one to refine the other. @_marker @available(SwiftStdlib 5.1, *) public protocol AnyActor: AnyObject, Sendable {} /// Common protocol to which all actors conform. /// /// The `Actor` protocol generalizes over all `actor` types. Actor types /// implicitly conform to this protocol. @available(SwiftStdlib 5.1, *) public protocol Actor: AnyActor { /// Retrieve the executor for this actor as an optimized, unowned /// reference. /// /// This property must always evaluate to the same executor for a /// given actor instance, and holding on to the actor must keep the /// executor alive. /// /// This property will be implicitly accessed when work needs to be /// scheduled onto this actor. These accesses may be merged, /// eliminated, and rearranged with other work, and they may even /// be introduced when not strictly required. Visible side effects /// are therefore strongly discouraged within this property. nonisolated var unownedExecutor: UnownedSerialExecutor { get } } /// Called to initialize the default actor instance in an actor. /// The implementation will call this within the actor's initializer. @available(SwiftStdlib 5.1, *) @_silgen_name("swift_defaultActor_initialize") public func _defaultActorInitialize(_ actor: AnyObject) /// Called to destroy the default actor instance in an actor. /// The implementation will call this within the actor's deinit. @available(SwiftStdlib 5.1, *) @_silgen_name("swift_defaultActor_destroy") public func _defaultActorDestroy(_ actor: AnyObject) @available(SwiftStdlib 5.1, *) @_silgen_name("swift_task_enqueueMainExecutor") @usableFromInline internal func _enqueueOnMain(_ job: UnownedJob)
apache-2.0
c9aead09d227275f39aebf0d40fc00f8
42.128571
80
0.712819
4.695179
false
false
false
false
jngd/advanced-ios10-training
T11E02/T11E02/ViewController.swift
1
1747
// // ViewController.swift // T11E02 // // Created by jngd on 20/10/16. // Copyright © 2016 jngd. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { /***** Vars *****/ var player : AVPlayer = AVPlayer() var playerLayer : AVPlayerLayer = AVPlayerLayer() /***** Outlets *****/ @IBOutlet weak var secondsLabel: UILabel! /***** Actions *****/ @IBAction func sliderValueChanged(_ sender: AnyObject) { player.volume = sender.value } @IBAction func playButton(_ sender: AnyObject) { if (player.status != AVPlayerStatus.readyToPlay) { print("Player is not ready") return; } player.play() } @IBAction func pauseButton(_ sender: AnyObject) { player.pause() } @IBAction func stopButton(_ sender: AnyObject) { player.pause() player.seek(to: CMTime(seconds: 0.0, preferredTimescale: 1)) } /***** Methods *****/ override func viewDidLoad() { super.viewDidLoad() let moviePath = URL(string: "http://www.imaginaformacion.com/recursos/videos/trailerjobs.mp4") secondsLabel.text = "sec" player = AVPlayer(url: moviePath!) playerLayer = AVPlayerLayer(player: player) playerLayer.frame = CGRect(x: 10, y: 10, width: 300, height: 225) player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1.0, preferredTimescale: 1), queue: nil) { (time) -> Void in let valor = time.value as Int64 let timestamp = time.timescale as Int32 let res = Int(valor) / Int(timestamp) self.secondsLabel.text = res.description } self.view.layer.addSublayer(playerLayer) player.play() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
9ce1f1dced865ab6d41e6ee2e9cca325
22.28
96
0.67984
3.645094
false
false
false
false
tenric/VersionUpdate
VersionUpdate/VersionUpdate.swift
1
6231
// // VersionUpdate.swift // Tenric // // Created by Tenric on 16/7/5. // Copyright © 2016年 Tenric. All rights reserved. // import UIKit struct AppChannel { var name: String = "" var infoUrl: String = "" var downloadUrl: String = "" var alertTitle: String = "有新版本了!" var alertMessage: String = "若您选择忽略此版本,仍可以随时升级至最新。" } public class VersionUpdate: NSObject, NSURLSessionDelegate{ var session: NSURLSession! var channels = Dictionary<String,AppChannel>() public func addAppStoreChannelWithAppId(appId:String) { var appStoreChannel = AppChannel() appStoreChannel.name = "AppStore" appStoreChannel.infoUrl = "https://itunes.apple.com/cn/lookup?id=\(appId)" appStoreChannel.downloadUrl = "https://itunes.apple.com/cn/app/id/\(appId)" if let appName = VersionUpdate.appName() { appStoreChannel.alertTitle = "\(appName)有新版本了!" } appStoreChannel.alertMessage = "若您选择忽略此版本,仍可以随时到appstore升级至最新。" channels[appStoreChannel.name] = appStoreChannel } public func addFirChannelWithAppId(appId:String, token:String, downloadUrl:String) { var firChannel = AppChannel() firChannel.name = "Fir" firChannel.infoUrl = "http://api.fir.im/apps/latest/\(appId)?api_token=\(token)" firChannel.downloadUrl = downloadUrl if let appName = VersionUpdate.appName() { firChannel.alertTitle = "\(appName)有新版本了!" } firChannel.alertMessage = "若您选择忽略此版本,仍可以随时到\(downloadUrl)升级至最新。" channels[firChannel.name] = firChannel } public func checkUpdate() { let channelName = VersionUpdate.channelName() if (channelName == nil || channels[channelName!] == nil) { return } let channel = channels[channelName!]! as AppChannel let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.timeoutIntervalForRequest = 20 self.session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil) let url = NSURL(string: channel.infoUrl) let task = self.session.dataTaskWithURL(url!) { (data, response, error) in self.session.finishTasksAndInvalidate() if data == nil { return } if channel.name == "AppStore" { let jsonDic = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let results = jsonDic["results"] as? NSArray if results!.count > 0 { let infoDic = results![0] if let version = infoDic["version"] as? String { self.handleRemoteVersion(version, channel: channel) } } } else if(channel.name == "Fir") { let jsonDic = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary if let version = jsonDic["versionShort"] as? String { self.handleRemoteVersion(version, channel: channel) } } } task.resume() } func handleRemoteVersion(version:String, channel:AppChannel) { if let currentVersion = VersionUpdate.localVersion() { let ret = version.compare(currentVersion) if ret == NSComparisonResult.OrderedAscending { print("服务器版本小于本地版本") } else if ret == NSComparisonResult.OrderedDescending { print("服务器版本大于本地版本") let alert = UIAlertController(title:channel.alertTitle, message:channel.alertMessage, preferredStyle:UIAlertControllerStyle.Alert) let actionUpdate = UIAlertAction(title:"立即更新", style:UIAlertActionStyle.Destructive, handler: { (alertAction: UIAlertAction) -> () in UIApplication.sharedApplication().openURL(NSURL(string: channel.downloadUrl)!) }) let actionCancel = UIAlertAction(title:"忽略此版本", style:UIAlertActionStyle.Cancel, handler:nil) alert.addAction(actionUpdate) alert.addAction(actionCancel) dispatch_async(dispatch_get_main_queue(), { let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController if let viewController = viewController { viewController.presentViewController(alert, animated:true, completion:nil) } }) } else { print("服务器版本等于本地版本") } } } static func localVersion() -> String? { var version: String? let infoDic = NSBundle.mainBundle().infoDictionary if let infoDic = infoDic { version = infoDic["CFBundleShortVersionString"] as? String } return version } static func channelName() -> String? { var channelName: String? let infoDic = NSBundle.mainBundle().infoDictionary if let infoDic = infoDic { channelName = infoDic["Channel"] as? String } return channelName } static func appName() -> String? { var appName: String? let infoDic = NSBundle.mainBundle().infoDictionary if let infoDic = infoDic { appName = infoDic["CFBundleName"] as? String } return appName } }
mit
a0b606c3ad46b36d5a5d152c222db226
32.58427
146
0.562897
5.216405
false
false
false
false
CosmicMind/Motion
Sources/Animator/MotionViewPropertyViewContext.swift
3
3546
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit @available(iOS 10, tvOS 10, *) internal class MotionViewPropertyViewContext: MotionAnimatorViewContext { /// A reference to the UIViewPropertyAnimator. fileprivate var viewPropertyAnimator: UIViewPropertyAnimator! /// Ending effect. fileprivate var endEffect: UIVisualEffect? /// Starting effect. fileprivate var startEffect: UIVisualEffect? override class func canAnimate(view: UIView, state: MotionTargetState, isAppearing: Bool) -> Bool { return view is UIVisualEffectView && nil != state.opacity } override func resume(at progress: TimeInterval, isReversed: Bool) -> TimeInterval { guard let visualEffectView = snapshot as? UIVisualEffectView else { return 0 } if isReversed { viewPropertyAnimator?.stopAnimation(false) viewPropertyAnimator?.finishAnimation(at: .current) viewPropertyAnimator = UIViewPropertyAnimator(duration: duration, curve: .linear) { [weak self] in guard let `self` = self else { return } visualEffectView.effect = isReversed ? self.startEffect : self.endEffect } } viewPropertyAnimator.startAnimation() return duration } override func seek(to progress: TimeInterval) { viewPropertyAnimator?.pauseAnimation() viewPropertyAnimator?.fractionComplete = CGFloat(progress / duration) } override func clean() { super.clean() viewPropertyAnimator?.stopAnimation(false) viewPropertyAnimator?.finishAnimation(at: .current) viewPropertyAnimator = nil } override func startAnimations() -> TimeInterval { guard let visualEffectView = snapshot as? UIVisualEffectView else { return 0 } let appearedEffect = visualEffectView.effect let disappearedEffect = 0 == targetState.opacity ? nil : visualEffectView.effect startEffect = isAppearing ? disappearedEffect : appearedEffect endEffect = isAppearing ? appearedEffect : disappearedEffect visualEffectView.effect = startEffect viewPropertyAnimator = UIViewPropertyAnimator(duration: duration, curve: .linear) { [weak self] in guard let `self` = self else { return } visualEffectView.effect = self.endEffect } viewPropertyAnimator.startAnimation() return duration } }
mit
0f5158c59408abaaf7011cb995cb6877
33.764706
104
0.718556
5.015559
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/StringBuilder.swift
1
3903
/** Supports creation of a String from pieces https://gist.github.com/kristopherjohnson/1fc55e811d944a430289 */ open class StringBuilder { fileprivate var stringValue: String /** Construct with initial String contents :param: string Initial value; defaults to empty string */ public init(string: String = "") { self.stringValue = string } public init(_ size: Int) { self.stringValue = "" } /** Return the String object :return: String */ open func toString() -> String { return stringValue } /** Return the current length of the String object */ open var length: Int { return self.stringValue.characters.count //return countElements(stringValue) } /** Append a String to the object :param: string String :return: reference to this StringBuilder instance */ open func append(_ string: String) { stringValue += string } open func appendCodePoint(_ chr: Character) { stringValue = stringValue + String(chr) } open func appendCodePoints(_ chr: [Character]) { for c in chr { stringValue = stringValue + String(c) } } open func appendCodePoint(_ ch: Int) { stringValue = stringValue + String(Character(UnicodeScalar(ch)!)) } open func appendCodePoint(_ ch: UnicodeScalar) { stringValue = stringValue + String(ch) } open func appendCodePoints(_ chr: [UnicodeScalar]) { for c in chr { stringValue = stringValue + String(c) } } /** Append a Printable to the object :param: value a value supporting the Printable protocol :return: reference to this StringBuilder instance */ @discardableResult open func append<T: CustomStringConvertible>(_ value: T) -> StringBuilder { stringValue += value.description return self } @discardableResult open func insert<T: CustomStringConvertible>(_ offset: Int, _ value: T) -> StringBuilder { stringValue = stringValue.insert(string: value.description, ind: offset) return self } /** Append a String and a newline to the object :param: string String :return: reference to this StringBuilder instance */ @discardableResult open func appendLine(_ string: String) -> StringBuilder { stringValue += string + "\n" return self } /** Append a Printable and a newline to the object :param: value a value supporting the Printable protocol :return: reference to this StringBuilder instance */ @discardableResult open func appendLine<T: CustomStringConvertible>(_ value: T) -> StringBuilder { stringValue += value.description + "\n" return self } /** Reset the object to an empty string :return: reference to this StringBuilder instance */ @discardableResult open func clear() -> StringBuilder { stringValue = "" return self } } /** Append a String to a StringBuilder using operator syntax :param: lhs StringBuilder :param: rhs String */ public func += (lhs: StringBuilder, rhs: String) { lhs.append(rhs) } /** Append a Printable to a StringBuilder using operator syntax :param: lhs Printable :param: rhs String */ public func += <T: CustomStringConvertible>(lhs: StringBuilder, rhs: T) { lhs.append(rhs.description) } /** Create a StringBuilder by concatenating the values of two StringBuilders :param: lhs first StringBuilder :param: rhs second StringBuilder :result StringBuilder */ public func +(lhs: StringBuilder, rhs: StringBuilder) -> StringBuilder { return StringBuilder(string: lhs.toString() + rhs.toString()) }
mit
fa5eac502efbc1fe15797652273f43b1
23.39375
94
0.626185
4.842432
false
false
false
false
yyued/MagicDrag
MagicDrag/Responder/MGDPageLayer.swift
1
6266
// // MGDPageLayer.swift // MagicDrag // // Created by 崔 明辉 on 16/1/27. // Copyright © 2016年 swift. All rights reserved. // import UIKit class MGDPageLayer: UIView { var sceneLayerMap: [Int: MGDSceneLayer] = [:] override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { for sceneLayer in self.subviews { for animateView in sceneLayer.subviews { if let touchableView = animateView as? MGDTouchable where touchableView.canTouch { let innerPoint = animateView.convertPoint(point, fromView: sceneLayer) if animateView.alpha > 0.0 && animateView.pointInside(innerPoint, withEvent: event) { return animateView } } } } return nil } init() { super.init(frame: CGRect.zero) self.translatesAutoresizingMaskIntoConstraints = true self.autoresizingMask = [] self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } static func newLayer(style: String) -> MGDPageLayer? { if style == "stream" { return MGDStreamPageLayer() } else if style == "push" { return MGDPushPageLayer() } else if style == "fix" { return MGDFixPageLayer() } return nil } func addSceneLayer(sceneLayer: MGDSceneLayer, atPage: Int) { sceneLayer.layerAtPage = atPage sceneLayerMap[atPage] = sceneLayer } func scrolling(contentOffsetX: CGFloat) { let currentPage = Int(contentOffsetX / UIScreen.mainScreen().bounds.size.width) let lastPage = currentPage - 1 let nextPage = currentPage + 1 if let sceneLayer = sceneLayerMap[lastPage] { sceneLayer.layerAnimation(1.0) } if let sceneLayer = sceneLayerMap[currentPage] { sceneLayer.layerAnimation((contentOffsetX % UIScreen.mainScreen().bounds.size.width) / UIScreen.mainScreen().bounds.size.width) } if let sceneLayer = sceneLayerMap[nextPage] { sceneLayer.layerAnimation((contentOffsetX % UIScreen.mainScreen().bounds.size.width) / UIScreen.mainScreen().bounds.size.width - 1.0) } } } class MGDStreamPageLayer: MGDPageLayer { override init() { super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func addSceneLayer(sceneLayer: MGDSceneLayer, atPage: Int) { sceneLayer.frame = CGRect( x: UIScreen.mainScreen().bounds.size.width * CGFloat(atPage), y: 0, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height ) sceneLayer.translatesAutoresizingMaskIntoConstraints = true sceneLayer.autoresizingMask = [] addSubview(sceneLayer) super.addSceneLayer(sceneLayer, atPage: atPage) } override func scrolling(contentOffsetX: CGFloat) { self.frame = { var frame = self.frame frame.origin.x = -contentOffsetX return frame }() super.scrolling(contentOffsetX) } } class MGDPushPageLayer: MGDPageLayer { override init() { super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func addSceneLayer(sceneLayer: MGDSceneLayer, atPage: Int) { sceneLayer.frame = CGRect( x: UIScreen.mainScreen().bounds.size.width * CGFloat(atPage > 0 ? 1 : 0), y: 0, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height ) sceneLayer.translatesAutoresizingMaskIntoConstraints = true sceneLayer.autoresizingMask = [] addSubview(sceneLayer) super.addSceneLayer(sceneLayer, atPage: atPage) } override func scrolling(contentOffsetX: CGFloat) { let controlPage = (Int((contentOffsetX + UIScreen.mainScreen().bounds.size.width) / UIScreen.mainScreen().bounds.size.width)) if controlPage <= 0 { return } if let sceneLayer = sceneLayerMap[controlPage] { let sceneOriginX = UIScreen.mainScreen().bounds.size.width - contentOffsetX % UIScreen.mainScreen().bounds.size.width sceneLayer.frame = { var frame = sceneLayer.frame frame.origin.x = sceneOriginX < 1.0 ? 0.0 : sceneOriginX return frame }() } let lastPage = controlPage - 1 if let sceneLayer = sceneLayerMap[lastPage] { sceneLayer.frame = { var frame = sceneLayer.frame frame.origin.x = 0.0 return frame }() } let nextPage = controlPage + 1 if let sceneLayer = sceneLayerMap[nextPage] { sceneLayer.frame = { var frame = sceneLayer.frame frame.origin.x = UIScreen.mainScreen().bounds.size.width return frame }() } super.scrolling(contentOffsetX) } } class MGDFixPageLayer: MGDPageLayer { override init() { super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func addSceneLayer(sceneLayer: MGDSceneLayer, atPage: Int) { sceneLayer.frame = CGRect( x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height ) sceneLayer.translatesAutoresizingMaskIntoConstraints = true sceneLayer.autoresizingMask = [] addSubview(sceneLayer) super.addSceneLayer(sceneLayer, atPage: atPage) } override func scrolling(contentOffsetX: CGFloat) { super.scrolling(contentOffsetX) } }
mit
ae2bedf585bd637427c7bf7c410a324f
31.419689
145
0.592776
4.776336
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/SlidingWindow/CheckInclusion.swift
1
1190
// // CheckInclusion.swift // LeetCode // // Created by 黄伯驹 on 2022/5/30. // Copyright © 2022 伯驹 黄. All rights reserved. // import Foundation /// https://leetcode-cn.com/problems/permutation-in-string/submissions/ func checkInclusion(_ s1: String, _ s2: String) -> Bool { let strs = Array(s2) var left = 0, right = 0 var need: [Character: Int] = [:] for char in s1 { need[char, default: 0] += 1 } var window: [Character: Int] = [:] var matchCount = 0 while right < strs.count { let char = strs[right] right += 1 if need[char] != nil { window[char, default: 0] += 1 if need[char] == window[char] { matchCount += 1 } } while right - left >= s1.count { if matchCount == need.count { return true } let char = strs[left] left += 1 if need[char] == nil { continue } if need[char] == window[char] { matchCount -= 1 } window[char, default: 0] -= 1 } } return false }
mit
9735a1ee4e0e81e768ca2b42ee1c482b
23.520833
71
0.474936
3.923333
false
false
false
false
elslooo/hoverboard
OnboardKit/OnboardKit/OnboardItemCell.swift
1
10338
/* * Copyright (c) 2017 Tim van Elsloo * * 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 /** * The onboard item cell presents a single step. */ class OnboardItemCell : CollectionViewCell { /** * This is the title of the step that this cell represents. The title is * always visible. */ let titleLabel: NSTextField = { let textField = NSTextField() textField.isEditable = false textField.isSelectable = false textField.isBordered = false textField.drawsBackground = false textField.textColor = .labelColor textField.font = .systemFont(ofSize: 17.0) return textField }() /** * This is the description that corresponds to the step that this cell * represents. The description is only visible when the cell is expanded. */ let descriptionLabel: NSTextField = { let textField = NSTextField() textField.isEditable = false textField.isSelectable = false textField.isBordered = false textField.drawsBackground = false textField.textColor = .labelColor textField.font = .systemFont(ofSize: 14.0) textField.cell?.wraps = true textField.alphaValue = 0 return textField }() /** * This is the badge view that indicates the step. */ let badgeView = OnboardBadgeView(frame: NSRect( x: 31, y: 8, width: 32, height: 32 )) /** * This is the checkmark view that appears as soon as the step is completed. */ let checkmarkView: OnboardBadgeView = { let view = OnboardBadgeView(frame: NSRect( x: 0, y: 8, width: 32, height: 32 )) view.style = .checkmark return view }() required init() { super.init() self.addSubview(self.badgeView) self.addSubview(self.checkmarkView) self.addSubview(self.titleLabel) self.addSubview(self.descriptionLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** * This is an array of buttons that are added to the cell, one for each * button in the corresponding OnboardItem. */ private var buttons: [NSButton] = [] /** * This is an array of views that are added to the cell, one for each view * in the corresponding OnboardItem. These views are similar to accessory * views in UITableViewCells on iOS. */ private var views: [NSView] = [] /** * This property holds the onboard item that this cell should represent. * Upon changing this value, the cell updates its user interface state. */ internal var item: OnboardItem? { didSet { guard let item = self.item else { return } self.titleLabel.stringValue = item.title self.descriptionLabel.stringValue = item.description self.badgeView.text = "\(self.indexPath.item + 1)" self.layout() self.buttons.forEach { $0.removeFromSuperview() } self.buttons.removeAll() var y: CGFloat = 11 for (index, button) in item.buttons.enumerated() { let control = NSButton(frame: NSRect( x: self.bounds.width - 120, y: y, width: 100, height: 32 )) control.autoresizingMask = .viewMinXMargin control.bezelStyle = .rounded control.title = button.title // Add default key binding. if button.type == .default { control.keyEquivalent = "\r" } control.tag = index control.target = self control.action = #selector(buttonPressed) control.alphaValue = (self.expanded ? 1.0 : 0.0) self.buttons.append(control) self.addSubview(control) y += control.frame.size.height - 4 } self.views.forEach { $0.removeFromSuperview() } self.views.removeAll() for view in item.views { self.views.append(view) self.addSubview(view) } } } /** * This boolean indicates if the cell is expanded. In expanded state, the * cell displays the description and its buttons and views. */ internal var expanded: Bool = false { didSet { self.descriptionLabel.alphaValue = (self.expanded ? 1.0 : 0.0) self.badgeView.style = (self.expanded ? .focused : .transparent) self.buttons.forEach { (button) in button.alphaValue = (self.expanded ? 1.0 : 0.0) button.isEnabled = self.expanded } self.views.forEach { (view) in view.alphaValue = (self.expanded ? 1.0 : 0.0) } } } /** * This boolean indicates if the item is completed. In completed state, the * cell shows a checkmark. */ internal var completed: Bool = false { didSet { let scale = CGFloat(self.completed ? 1.0 : 2.0) self.checkmarkView.layer?.transform = CATransform3DMakeScale(scale, scale, 1) self.checkmarkView.alphaValue = (self.completed ? 1.0 : 0.0) } } override var isFlipped: Bool { return true } // MARK: - Layout /** * In a horizontal layout, the buttons are shown at the right of the cell. */ private func layoutHorizontally() { self.badgeView.frame.origin.x = 15 self.titleLabel.frame.origin.x = 15 self.titleLabel.frame.origin.y = 52 let size = self.descriptionLabel.sizeThatFits(NSSize( width: self.bounds.width - 15 - 15, height: 500 )) self.descriptionLabel.frame.size = size self.descriptionLabel.frame.origin.x = 15 self.descriptionLabel.frame.origin.y = self.titleLabel.frame.maxY + 4 self.separator.frame = NSRect( x: self.bounds.width - 1, y: 0, width: 1, height: self.bounds.height ) for (index, button) in self.buttons.reversed().enumerated() { button.frame.origin = NSPoint( x: self.bounds.midX - button.bounds.midX, y: self.bounds.height - 15 - 28 * CGFloat(index) - 32 ) } for view in self.views { view.frame.origin.x = 15 view.frame.size.width = self.bounds.width - 15 - 15 } } /** * In a vertical layout, the buttons are shown at the bottom of the cell. */ private func layoutVertically() { self.badgeView.frame.origin.x = (94 - 32) / 2 self.titleLabel.frame.origin.x = 94 self.titleLabel.frame.origin.y = 25 - self.titleLabel.bounds.midY let size = self.descriptionLabel.sizeThatFits(NSSize( width: 380, height: 500 )) self.descriptionLabel.frame.size = size self.descriptionLabel.frame.origin.x = 94 self.descriptionLabel.frame.origin.y = 46 for view in self.views { view.frame.origin.x = 94 view.frame.size.width = self.bounds.width - 94 - 15 } } /** * We override this function to reposition all of the subviews, depending on * the layout of the controller. */ override func layout() { super.layout() self.titleLabel.sizeToFit() if self.item?.controller?.direction == .horizontal { self.layoutHorizontally() } else { self.layoutVertically() } var y = CGFloat(0) for view in self.views { view.frame.origin.y = self.descriptionLabel.frame.maxY + y y += view.frame.size.height } self.checkmarkView.frame.origin.x = self.bounds.width - self.checkmarkView.frame.width - 20 + 2 let scale = CGFloat(self.completed ? 1.0 : 2.0) let transform = CATransform3DMakeScale(scale, scale, 1) self.checkmarkView.layer?.sublayerTransform = transform } // MARK: - Buttons /** * This function is called by a NSButton and propagates that event to the * action closure that correspond to that button. */ func buttonPressed(_ sender: NSButton) { guard let item = self.item, self.expanded else { return } guard let controller = item.controller else { return } let button = item.buttons[sender.tag] button.action(controller) } }
mit
b92dd54066d7d2addef3dba98ae0b5e0
31.819048
80
0.561327
4.740028
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_02/04_DevMisc/ARKitDevMisc/ViewController.swift
1
2971
// // ViewController.swift // ARDebug // // Created by Shuichi Tsutsumi on 2017/07/17. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import UIKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { private var virtualObjectNode: SCNNode? @IBOutlet var sceneView: ARSCNView! @IBOutlet var trackingStateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self // シーンを生成してARSCNViewにセット sceneView.scene = SCNScene() // セッションのコンフィギュレーションを生成 let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal configuration.isLightEstimationEnabled = true // デバッグオプション // sceneView.debugOptions = [.showBoundingBoxes] // sceneView.debugOptions = [.showWireframe] sceneView.debugOptions = [.renderAsWireframe] // セッション開始 sceneView.session.run(configuration) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func loadModel() -> SCNNode { guard let scene = SCNScene(named: "duck.scn", inDirectory: "models.scnassets/duck") else {fatalError()} let modelNode = SCNNode() for child in scene.rootNode.childNodes { modelNode.addChildNode(child) } return modelNode } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} print("anchor:\(anchor), node: \(node), node geometry: \(String(describing: node.geometry))") // 平面アンカーを可視化 planeAnchor.addPlaneNode(on: node, color: .bookYellow) // 仮想オブジェクトのノードを作成 let virtualObjectNode = loadModel() DispatchQueue.main.async(execute: { // 仮想オブジェクトを乗せる node.addChildNode(virtualObjectNode) }) } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} DispatchQueue.main.async(execute: { planeAnchor.updatePlaneNode(on: node) }) } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { print("\(self.classForCoder)/" + #function) } // MARK: - ARSessionObserver func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { print("trackingState: \(camera.trackingState)") trackingStateLabel.text = camera.trackingState.description } }
mit
df699054cb7ed756fd9d3369c3cb92bc
29.769231
111
0.640357
4.964539
false
true
false
false
xuduo/socket.io-push-ios
source/SocketIOClientSwift/SocketPacket.swift
5
9370
// // SocketPacket.swift // Socket.IO-Client-Swift // // Created by Erik Little on 1/18/15. // // 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 struct SocketPacket { private let placeholders: Int private var currentPlace = 0 private static let logType = "SocketPacket" let nsp: String let id: Int let type: PacketType enum PacketType: Int { case Connect, Disconnect, Event, Ack, Error, BinaryEvent, BinaryAck } var args: [AnyObject]? { var arr = data if data.count == 0 { return nil } else { if type == .Event || type == .BinaryEvent { arr.removeAtIndex(0) return arr } else { return arr } } } var binary: [NSData] var data: [AnyObject] var description: String { return "SocketPacket {type: \(String(type.rawValue)); data: " + "\(String(data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}" } var event: String { return data[0] as? String ?? String(data[0]) } var packetString: String { return createPacketString() } init(type: SocketPacket.PacketType, data: [AnyObject] = [AnyObject](), id: Int = -1, nsp: String, placeholders: Int = 0, binary: [NSData] = [NSData]()) { self.data = data self.id = id self.nsp = nsp self.type = type self.placeholders = placeholders self.binary = binary } mutating func addData(data: NSData) -> Bool { if placeholders == currentPlace { return true } binary.append(data) currentPlace++ if placeholders == currentPlace { currentPlace = 0 return true } else { return false } } private func completeMessage(var message: String, ack: Bool) -> String { if data.count == 0 { return message + "]" } for arg in data { if arg is NSDictionary || arg is [AnyObject] { do { let jsonSend = try NSJSONSerialization.dataWithJSONObject(arg, options: NSJSONWritingOptions(rawValue: 0)) let jsonString = NSString(data: jsonSend, encoding: NSUTF8StringEncoding) message += jsonString! as String + "," } catch { DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType) } } else if var str = arg as? String { str = str["\n"] ~= "\\\\n" str = str["\r"] ~= "\\\\r" message += "\"\(str)\"," } else if arg is NSNull { message += "null," } else { message += "\(arg)," } } if message != "" { message.removeAtIndex(message.endIndex.predecessor()) } return message + "]" } private func createAck() -> String { let msg: String if type == PacketType.Ack { if nsp == "/" { msg = "3\(id)[" } else { msg = "3\(nsp),\(id)[" } } else { if nsp == "/" { msg = "6\(binary.count)-\(id)[" } else { msg = "6\(binary.count)-\(nsp),\(id)[" } } return completeMessage(msg, ack: true) } private func createMessageForEvent() -> String { let message: String if type == PacketType.Event { if nsp == "/" { if id == -1 { message = "2[" } else { message = "2\(id)[" } } else { if id == -1 { message = "2\(nsp),[" } else { message = "2\(nsp),\(id)[" } } } else { if nsp == "/" { if id == -1 { message = "5\(binary.count)-[" } else { message = "5\(binary.count)-\(id)[" } } else { if id == -1 { message = "5\(binary.count)-\(nsp),[" } else { message = "5\(binary.count)-\(nsp),\(id)[" } } } return completeMessage(message, ack: false) } private func createPacketString() -> String { let str: String if type == PacketType.Event || type == PacketType.BinaryEvent { str = createMessageForEvent() } else { str = createAck() } return str } mutating func fillInPlaceholders() { for i in 0..<data.count { if let str = data[i] as? String, num = str["~~(\\d)"].groups() { // Fill in binary placeholder with data data[i] = binary[Int(num[1])!] } else if data[i] is NSDictionary || data[i] is NSArray { data[i] = _fillInPlaceholders(data[i]) } } } private mutating func _fillInPlaceholders(data: AnyObject) -> AnyObject { if let str = data as? String { if let num = str["~~(\\d)"].groups() { return binary[Int(num[1])!] } else { return str } } else if let dict = data as? NSDictionary { let newDict = NSMutableDictionary(dictionary: dict) for (key, value) in dict { newDict[key as! NSCopying] = _fillInPlaceholders(value) } return newDict } else if let arr = data as? NSArray { let newArr = NSMutableArray(array: arr) for i in 0..<arr.count { newArr[i] = _fillInPlaceholders(arr[i]) } return newArr } else { return data } } } extension SocketPacket { private static func findType(binCount: Int, ack: Bool) -> PacketType { switch binCount { case 0 where !ack: return PacketType.Event case 0 where ack: return PacketType.Ack case _ where !ack: return PacketType.BinaryEvent case _ where ack: return PacketType.BinaryAck default: return PacketType.Error } } static func packetFromEmit(items: [AnyObject], id: Int, nsp: String, ack: Bool) -> SocketPacket { let (parsedData, binary) = deconstructData(items) let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData, id: id, nsp: nsp, placeholders: -1, binary: binary) return packet } } private extension SocketPacket { static func shred(data: AnyObject, inout binary: [NSData]) -> AnyObject { if let bin = data as? NSData { let placeholder = ["_placeholder" :true, "num": binary.count] binary.append(bin) return placeholder } else if var arr = data as? [AnyObject] { for i in 0..<arr.count { arr[i] = shred(arr[i], binary: &binary) } return arr } else if let dict = data as? NSDictionary { let mutDict = NSMutableDictionary(dictionary: dict) for (key, value) in dict { mutDict[key as! NSCopying] = shred(value, binary: &binary) } return mutDict } else { return data } } static func deconstructData(var data: [AnyObject]) -> ([AnyObject], [NSData]) { var binary = [NSData]() for i in 0..<data.count { data[i] = shred(data[i], binary: &binary) } return (data, binary) } }
mit
97764de09eb35426a3c7850a960fbe0d
29.822368
114
0.490928
4.768448
false
false
false
false
rmg/scaffold-shootout
swift-blog/Sources/Generated/CommentResource.swift
1
8992
import Kitura import LoggerAPI import SwiftyJSON public class CommentResource { private let adapter: CommentAdapter private let path = "/api/Comments" private let pathWithID = "/api/Comments/:id" init(factory: AdapterFactory) throws { adapter = try factory.getCommentAdapter() } func setupRoutes(router: Router) { router.all("/*", middleware: BodyParser()) router.get(path, handler: handleIndex) router.post(path, handler: handleCreate) router.delete(path, handler: handleDeleteAll) router.get(pathWithID, handler: handleRead) router.put(pathWithID, handler: handleReplace) router.patch(pathWithID, handler: handleUpdate) router.delete(pathWithID, handler: handleDelete) } private func handleIndex(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("GET \(path)") // TODO: offset and limit adapter.findAll() { models, error in if let _ = error { // TODO: Send error object? Log.error("InternalServerError during handleIndex: \(error)") response.status(.internalServerError) } else { response.send(json: JSON(models.map { $0.toJSON() })) } next() } } private func handleCreate(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("POST \(path)") guard let contentType = request.headers["Content-Type"], contentType.hasPrefix("application/json") else { response.status(.unsupportedMediaType) response.send(json: JSON([ "error": "Request Content-Type must be application/json" ])) return next() } guard case .json(let json)? = request.body else { response.status(.badRequest) response.send(json: JSON([ "error": "Request body could not be parsed as JSON" ])) return next() } do { let model = try Comment(json: json) adapter.create(model) { storedModel, error in if let _ = error { // TODO: Handle model errors (eg id conflict) Log.error("InternalServerError during handleCreate: \(error)") response.status(.internalServerError) } else { response.send(json: storedModel!.toJSON()) } next() } } catch let error as ModelError { response.status(.unprocessableEntity) response.send(json: JSON([ "error": error.defaultMessage() ])) next() } catch { Log.error("InternalServerError during handleCreate: \(error)") response.status(.internalServerError) next() } } private func handleDeleteAll(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("DELETE \(path)") adapter.deleteAll() { error in if let _ = error { response.status(.internalServerError) } else { let result = JSON([]) response.send(json: result) } next() } } private func handleRead(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("GET \(pathWithID)") adapter.findOne(request.parameters["id"]) { model, error in if let error = error { switch error { case AdapterError.notFound: response.status(.notFound) default: response.status(.internalServerError) } } else { response.send(json: model!.toJSON()) } next() } } private func handleReplace(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("PUT \(pathWithID)") guard let contentType = request.headers["Content-Type"], contentType.hasPrefix("application/json") else { response.status(.unsupportedMediaType) response.send(json: JSON([ "error": "Request Content-Type must be application/json" ])) return next() } guard case .json(let json)? = request.body else { response.status(.badRequest) response.send(json: JSON([ "error": "Request body could not be parsed as JSON" ])) return next() } do { let model = try Comment(json: json) adapter.update(request.parameters["id"], with: model) { storedModel, error in if let error = error { switch error { case AdapterError.notFound: response.status(.notFound) case AdapterError.idConflict(let id): response.status(.conflict) response.send(json: JSON([ "error": "Cannot update id to a value that already exists (\(id))" ])) default: Log.error("InternalServerError during handleCreate: \(error)") response.status(.internalServerError) } } else { response.send(json: storedModel!.toJSON()) } next() } } catch let error as ModelError { response.status(.unprocessableEntity) response.send(json: JSON([ "error": error.defaultMessage() ])) next() } catch { Log.error("InternalServerError during handleReplace: \(error)") response.status(.internalServerError) next() } } private func handleUpdate(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("PATCH \(pathWithID)") guard let contentType = request.headers["Content-Type"], contentType.hasPrefix("application/json") else { response.status(.unsupportedMediaType) response.send(json: JSON([ "error": "Request Content-Type must be application/json" ])) return next() } guard case .json(let json)? = request.body else { response.status(.badRequest) response.send(json: JSON([ "error": "Request body could not be parsed as JSON" ])) return next() } adapter.findOne(request.parameters["id"]) { model, error in if let error = error { switch error { case AdapterError.notFound: response.status(.notFound) default: response.status(.internalServerError) } return next() } do { let updatedModel = try model!.updatingWith(json: json) self.adapter.update(request.parameters["id"], with: updatedModel) { storedModel, error in if let error = error { switch error { case AdapterError.notFound: response.status(.notFound) case AdapterError.idConflict(let id): response.status(.conflict) response.send(json: JSON([ "error": "Cannot update id to a value that already exists (\(id))" ])) default: Log.error("InternalServerError during handleUpdate: \(error)") response.status(.internalServerError) } } else { response.send(json: storedModel!.toJSON()) } next() } } catch let error as ModelError { response.status(.unprocessableEntity) response.send(json: JSON([ "error": error.defaultMessage() ])) next() } catch { Log.error("InternalServerError during handleUpdate: \(error)") response.status(.internalServerError) next() } } } private func handleDelete(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { Log.debug("DELETE \(pathWithID)") adapter.delete(request.parameters["id"]) { model, error in if let error = error { switch error { case AdapterError.notFound: response.send(json: JSON([ "count": 0 ])) default: response.status(.internalServerError) } } else { response.send(json: JSON([ "count": 1] )) } next() } } }
mit
e879df593ec62a949c675a59b51a29f9
39.687783
125
0.526134
5.243149
false
false
false
false
veselints/Birdy
Birdy2/Birdy2/LocationsViewController.swift
1
2063
// // LocationsViewController.swift // Birdy2 // // Created by veso on 2/5/16. // Copyright © 2016 veso. All rights reserved. // import UIKit import GoogleMaps @objc class LocationsViewController: UIViewController { var locations: Array<Coordinates>!; override func viewDidLoad() { super.viewDidLoad() let logoImage = UIImage(named: "scriptLogo") let scriptLogoView = UIImageView(image:logoImage) scriptLogoView.contentMode = UIViewContentMode.ScaleAspectFit; scriptLogoView.frame = CGRectMake(0, 0, 30.0, 30.0); self.navigationItem.titleView = scriptLogoView; let firstPointLat = (self.locations[0].latitude as NSString).doubleValue let firstPointLon = (self.locations[0].longitude as NSString).doubleValue let camera = GMSCameraPosition.cameraWithLatitude(firstPointLat, longitude: firstPointLon, zoom: 5) let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera) mapView.myLocationEnabled = true self.view = mapView for point in self.locations { let marker = GMSMarker() let latitude = (point.latitude as NSString).doubleValue let longitude = (point.longitude as NSString).doubleValue marker.position = CLLocationCoordinate2DMake(latitude, longitude) // marker.title = "Sydney" // marker.snippet = "Australia" marker.map = mapView } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6ccb56df1d71d559d31b89e414604cf2
32.258065
106
0.653734
5.078818
false
false
false
false
benlangmuir/swift
test/ClangImporter/objc_direct.swift
7
1369
// RUN: %target-swift-frontend-verify -typecheck %s -enable-objc-interop -import-objc-header %S/../Inputs/objc_direct.h // REQUIRES: objc_interop let _ = Bar(value: 4) // expected-error {{'init(value:)' is unavailable in Swift}} let _ = Bar.init(value: 5) // expected-error {{'init(value:)' is unavailable in Swift}} var something = Bar() as AnyObject something.directProperty = 123 // expected-error {{value of type 'AnyObject' has no member 'directProperty'}} let _ = something.directProperty // expected-error {{value of type 'AnyObject' has no member 'directProperty'}} something.directProperty2 = 456 // expected-error {{value of type 'AnyObject' has no member 'directProperty2'}} let _ = something.directProperty2 // expected-error {{value of type 'AnyObject' has no member 'directProperty2'}} let _ = something.directMethod() // expected-error {{value of type 'AnyObject' has no member 'directMethod'}} let _ = something.directMethod2() // expected-error {{value of type 'AnyObject' has no member 'directMethod2'}} class Foo { // Test that we can use a method with the same name as some `objc_direct` method. @objc func directProtocolMethod() -> String { "This is not a direct method." } } var otherThing = Foo() as AnyObject // We expect no error. let _ = otherThing.directProtocolMethod()
apache-2.0
b49824e2ef7ffec685bccc17f427a880
46.206897
119
0.691746
3.922636
false
false
false
false
svdo/swift-RichString
Pods/Nimble/Sources/Nimble/Matchers/SatisfyAllOf.swift
1
3415
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers /// provided in the variable list of matchers. public func satisfyAllOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> { return satisfyAllOf(predicates) } /// A Nimble matcher that succeeds when the actual value matches with all of the matchers /// provided in the variable list of matchers. @available(*, deprecated, message: "Use Predicate instead") public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T> where U: Matcher, U.ValueType == T { return satisfyAllOf(matchers.map { $0.predicate }) } internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> { return Predicate.define { actualExpression in var postfixMessages = [String]() var matches = true for predicate in predicates { let result = try predicate.satisfies(actualExpression) if result.toBoolean(expectation: .toNotMatch) { matches = false } postfixMessages.append("{\(result.message.expectedMessage)}") } var msg: ExpectationMessage if let actualValue = try actualExpression.evaluate() { msg = .expectedCustomValueTo( "match all of: " + postfixMessages.joined(separator: ", and "), actual: "\(actualValue)" ) } else { msg = .expectedActualValueTo( "match all of: " + postfixMessages.joined(separator: ", and ") ) } return PredicateResult(bool: matches, message: msg) } } public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> { return satisfyAllOf(left, right) } #if canImport(Darwin) import class Foundation.NSObject extension NMBPredicate { @objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate { return NMBPredicate { actualExpression in if matchers.isEmpty { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( fail: "satisfyAllOf must be called with at least one matcher" ) ) } var elementEvaluators = [Predicate<NSObject>]() for matcher in matchers { let elementEvaluator = Predicate<NSObject> { expression in if let predicate = matcher as? NMBPredicate { return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift() } else { let failureMessage = FailureMessage() let success = matcher.matches( // swiftlint:disable:next force_try { try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location ) return PredicateResult(bool: success, message: failureMessage.toExpectationMessage()) } } elementEvaluators.append(elementEvaluator) } return try satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC() } } } #endif
mit
38920c2eafea9b6cc751e8a54923a3b9
38.709302
128
0.581845
5.455272
false
false
false
false
ydi-core/nucleus-ios
Nucleus/Extensions/UIImage+AddBlendMode.swift
1
1290
// // UIImage+AddBlendMode.swift // Nucleus // // Created by Bezaleel Ashefor on 26/11/2017. // Copyright © 2017 Ephod. All rights reserved. // import UIKit extension UIImage { func tintedWithLinearGradientColors(colorsArr: [CGColor]) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale); guard let context = UIGraphicsGetCurrentContext() else { return UIImage() } context.translateBy(x: 0, y: self.size.height) context.scaleBy(x: 1, y: -1) context.setBlendMode(.colorBurn) let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height) // Create gradient let colors = colorsArr as CFArray let space = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: space, colors: colors, locations: nil) // Apply gradient context.clip(to: rect, mask: self.cgImage!) context.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: self.size.width, y: self.size.height), options: .drawsAfterEndLocation) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return gradientImage! } }
bsd-2-clause
218b862806781dce1f75972cc537a4b5
33.837838
162
0.647013
4.444828
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEEnhancedTransmitterTest.swift
1
2977
// // HCILEEnhancedTransmitterTest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Enhanced Transmitter Test Command /// /// This command is used to start a test where the DUT generates test reference packets /// at a fixed interval. The Controller shall transmit at maximum power. func lowEnergyEnhancedTransmitterTest(txChannel: LowEnergyTxChannel, lengthOfTestData: UInt8, packetPayload: LowEnergyPacketPayload, phy: HCILEEnhancedTransmitterTest.Phy, timeout: HCICommandTimeout = .default) async throws { let parameters = HCILEEnhancedTransmitterTest(txChannel: txChannel, lengthOfTestData: lengthOfTestData, packetPayload: packetPayload, phy: phy) try await deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Enhanced Transmitter Test Command /// /// This command is used to start a test where the DUT generates test reference packets /// at a fixed interval. The Controller shall transmit at maximum power. /// /// An LE Controller supporting the LE_Enhanced Transmitter_Test command shall support /// Packet_Payload values 0x00, 0x01 and 0x02. An LE Controller supporting the LE Coded PHY /// shall also support Packet_Payload value 0x04. An LE Controller may support other values /// of Packet_Payload. @frozen public struct HCILEEnhancedTransmitterTest: HCICommandParameter { public static let command = HCILowEnergyCommand.enhancedTransmitterTest //0x0034 /// N = (F – 2402) / 2 /// Range: 0x00 – 0x27. Frequency Range : 2402 MHz to 2480 MHz public let txChannel: LowEnergyTxChannel //RX_Channel /// Length in bytes of payload data in each packet public let lengthOfTestData: UInt8 public let packetPayload: LowEnergyPacketPayload public let phy: Phy public init(txChannel: LowEnergyTxChannel, lengthOfTestData: UInt8, packetPayload: LowEnergyPacketPayload, phy: Phy) { self.txChannel = txChannel self.lengthOfTestData = lengthOfTestData self.packetPayload = packetPayload self.phy = phy } public var data: Data { return Data([txChannel.rawValue, lengthOfTestData, packetPayload.rawValue, phy.rawValue]) } public enum Phy: UInt8 { /// Transmitter set to use the LE 1M PHY case le1MPhy = 0x01 /// Transmitter set to use the LE 2M PHY case le2MPhy = 0x02 /// Transmitter set to use the LE Coded PHY with S=8 data coding case leCodedPhywithS8 = 0x03 /// Transmitter set to use the LE Coded PHY with S=2 data coding case leCodedPhywithS2 = 0x04 } }
mit
53eab005da1f964951c0bd0af8bb1b43
34.380952
229
0.67362
4.409496
false
true
false
false
domenicosolazzo/practice-swift
AR/ARMeasureKit/ARMeasureKit/Apple/FocusSquare.swift
1
18592
/* See LICENSE folder for this sample’s licensing information. Code from Abstract: SceneKit node wrapper shows UI in the AR scene for placing virtual objects. */ import Foundation import ARKit class FocusSquare: SCNNode { ///////////////////////////////////////////////// // Variables to configure the focus square // Original size of the focus square in m. private let focusSquareSize: Float = 0.17 // Thickness of the focus square lines in m. private let focusSquareThickness: Float = 0.018 // Scale factor for the focus square when it is closed, w.r.t. the original size. private let scaleForClosedSquare: Float = 0.97 // Side length of the focus square segments when it is open (w.r.t. to a 1x1 square). private let sideLengthForOpenSquareSegments: CGFloat = 0.2 // Duration of the open/close animation private let animationDuration = 0.7 // Color of the focus square private let focusSquareColor = #colorLiteral(red: 1, green: 0.8288275599, blue: 0, alpha: 1) // base yellow private let focusSquareColorLight = #colorLiteral(red: 1, green: 0.9312674403, blue: 0.4846551418, alpha: 1) // light yellow // For scale adapdation based on the camera distance, see the `scaleBasedOnDistance(camera:)` method. ///////////////////////////////////////////////// var lastPositionOnPlane: SCNVector3? var lastPosition: SCNVector3? override init() { super.init() self.opacity = 0.0 self.addChildNode(focusSquareNode()) open() lastPositionOnPlane = nil lastPosition = nil recentFocusSquarePositions = [] anchorsOfVisitedPlanes = [] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(for position: SCNVector3, planeAnchor: ARPlaneAnchor?, camera: ARCamera?) { lastPosition = position if let anchor = planeAnchor { close(flash: !anchorsOfVisitedPlanes.contains(anchor)) lastPositionOnPlane = position anchorsOfVisitedPlanes.insert(anchor) } else { open() } updateTransform(for: position, camera: camera) } func hide() { if self.opacity == 1.0 { self.runAction(SCNAction.fadeOut(duration: 0.5)) } } func unhide() { if self.opacity == 0.0 { self.runAction(SCNAction.fadeIn(duration: 0.5)) } } // MARK: - Private private var isOpen = false // use average of recent positions to avoid jitter private var recentFocusSquarePositions = [SCNVector3]() private var anchorsOfVisitedPlanes: Set<ARAnchor> = [] private func updateTransform(for position: SCNVector3, camera: ARCamera?) { // add to list of recent positions recentFocusSquarePositions.append(position) // remove anything older than the last 8 recentFocusSquarePositions.keepLast(8) // move to average of recent positions to avoid jitter if let average = recentFocusSquarePositions.average { self.position = average self.setUniformScale(scaleBasedOnDistance(camera: camera)) } // Correct y rotation of camera square if let camera = camera { let tilt = abs(camera.eulerAngles.x) let threshold1: Float = Float.pi / 2 * 0.65 let threshold2: Float = Float.pi / 2 * 0.75 let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x) var angle: Float = 0 switch tilt { case 0..<threshold1: angle = camera.eulerAngles.y case threshold1..<threshold2: let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1)) let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw) angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange default: angle = yaw } self.rotation = SCNVector4Make(0, 1, 0, angle) } } private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float { // Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal var normalized = angle while abs(normalized - ref) > Float.pi / 4 { if angle > ref { normalized -= Float.pi / 2 } else { normalized += Float.pi / 2 } } return normalized } private func scaleBasedOnDistance(camera: ARCamera?) -> Float { if let camera = camera { let distanceFromCamera = (self.worldPosition - SCNVector3.positionFromTransform(camera.transform)).length() // This function reduces size changes of the focus square based on the distance by scaling it up if it far away, // and down if it is very close. // The values are adjusted such that scale will be 1 in 0.7 m distance (estimated distance when looking at a table), // and 1.2 in 1.5 m distance (estimated distance when looking at the floor). let newScale = distanceFromCamera < 0.7 ? (distanceFromCamera / 0.7) : (0.25 * distanceFromCamera + 0.825) return newScale } return 1.0 } private func pulseAction() -> SCNAction { let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5) let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5) pulseOutAction.timingMode = .easeInEaseOut pulseInAction.timingMode = .easeInEaseOut return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction])!)! } private func stopPulsing(for node: SCNNode?) { node?.removeAction(forKey: "pulse") node?.opacity = 1.0 } private var isAnimating: Bool = false private func open() { if isOpen || isAnimating { return } // Open animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = animationDuration / 4 entireSquare?.opacity = 1.0 self.segments?[0].open(direction: .left, newLength: sideLengthForOpenSquareSegments) self.segments?[1].open(direction: .right, newLength: sideLengthForOpenSquareSegments) self.segments?[2].open(direction: .up, newLength: sideLengthForOpenSquareSegments) self.segments?[3].open(direction: .up, newLength: sideLengthForOpenSquareSegments) self.segments?[4].open(direction: .down, newLength: sideLengthForOpenSquareSegments) self.segments?[5].open(direction: .down, newLength: sideLengthForOpenSquareSegments) self.segments?[6].open(direction: .left, newLength: sideLengthForOpenSquareSegments) self.segments?[7].open(direction: .right, newLength: sideLengthForOpenSquareSegments) SCNTransaction.completionBlock = { self.entireSquare?.runAction(self.pulseAction(), forKey: "pulse") } SCNTransaction.commit() // Scale/bounce animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = animationDuration / 4 entireSquare?.setUniformScale(focusSquareSize) SCNTransaction.commit() isOpen = true } private func close(flash: Bool = false) { if !isOpen || isAnimating { return } isAnimating = true stopPulsing(for: entireSquare) // Close animation SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = self.animationDuration / 2 entireSquare?.opacity = 0.99 SCNTransaction.completionBlock = { SCNTransaction.begin() SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) SCNTransaction.animationDuration = self.animationDuration / 4 self.segments?[0].close(direction: .right) self.segments?[1].close(direction: .left) self.segments?[2].close(direction: .down) self.segments?[3].close(direction: .down) self.segments?[4].close(direction: .up) self.segments?[5].close(direction: .up) self.segments?[6].close(direction: .right) self.segments?[7].close(direction: .left) SCNTransaction.completionBlock = { self.isAnimating = false } SCNTransaction.commit() } SCNTransaction.commit() // Scale/bounce animation entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x") entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y") entireSquare?.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z") // Flash if flash { let waitAction = SCNAction.wait(duration: animationDuration * 0.75) let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: animationDuration * 0.125) let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: animationDuration * 0.125) fillPlane?.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction])!) let flashSquareAction = flashAnimation(duration: animationDuration * 0.25) segments?[0].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[1].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[2].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[3].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[4].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[5].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[6].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) segments?[7].runAction(SCNAction.sequence([waitAction, flashSquareAction])!) } isOpen = false } private func flashAnimation(duration: TimeInterval) -> SCNAction { let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in // animate color from HSB 48/100/100 to 48/30/100 and back let elapsedTimePercentage = elapsedTime / CGFloat(duration) let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3 if let material = node.geometry?.firstMaterial { material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0) } } return action } private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath) let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let fs = focusSquareSize let ts = focusSquareSize * scaleForClosedSquare let values = [fs, fs * 1.15, fs * 1.15, ts * 0.97, ts] let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00] let timingFunctions = [easeOut, linear, easeOut, easeInOut] scaleAnimation.values = values scaleAnimation.keyTimes = keyTimes scaleAnimation.timingFunctions = timingFunctions scaleAnimation.duration = animationDuration return scaleAnimation } private var segments: [FocusSquareSegment]? { guard let s1 = childNode(withName: "s1", recursively: true) as? FocusSquareSegment, let s2 = childNode(withName: "s2", recursively: true) as? FocusSquareSegment, let s3 = childNode(withName: "s3", recursively: true) as? FocusSquareSegment, let s4 = childNode(withName: "s4", recursively: true) as? FocusSquareSegment, let s5 = childNode(withName: "s5", recursively: true) as? FocusSquareSegment, let s6 = childNode(withName: "s6", recursively: true) as? FocusSquareSegment, let s7 = childNode(withName: "s7", recursively: true) as? FocusSquareSegment, let s8 = childNode(withName: "s8", recursively: true) as? FocusSquareSegment else { return nil } return [s1, s2, s3, s4, s5, s6, s7, s8] } private var fillPlane: SCNNode? { return childNode(withName: "fillPlane", recursively: true) } private var entireSquare: SCNNode? { return self.childNodes.first } private func focusSquareNode() -> SCNNode { /* The focus square consists of eight segments as follows, which can be individually animated. s1 s2 _ _ s3 | | s4 s5 | | s6 - - s7 s8 */ let sl: Float = 0.5 // segment length let st = focusSquareThickness let c: Float = focusSquareThickness / 2 // correction to align lines perfectly let s1 = FocusSquareSegment(name: "s1", width: sl, thickness: st, color: focusSquareColor) let s2 = FocusSquareSegment(name: "s2", width: sl, thickness: st, color: focusSquareColor) let s3 = FocusSquareSegment(name: "s3", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s4 = FocusSquareSegment(name: "s4", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s5 = FocusSquareSegment(name: "s5", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s6 = FocusSquareSegment(name: "s6", width: sl, thickness: st, color: focusSquareColor, vertical: true) let s7 = FocusSquareSegment(name: "s7", width: sl, thickness: st, color: focusSquareColor) let s8 = FocusSquareSegment(name: "s8", width: sl, thickness: st, color: focusSquareColor) s1.position += SCNVector3Make(-(sl / 2 - c), -(sl - c), 0) s2.position += SCNVector3Make(sl / 2 - c, -(sl - c), 0) s3.position += SCNVector3Make(-sl, -sl / 2, 0) s4.position += SCNVector3Make(sl, -sl / 2, 0) s5.position += SCNVector3Make(-sl, sl / 2, 0) s6.position += SCNVector3Make(sl, sl / 2, 0) s7.position += SCNVector3Make(-(sl / 2 - c), sl - c, 0) s8.position += SCNVector3Make(sl / 2 - c, sl - c, 0) let fillPlane = SCNPlane(width: CGFloat(1.0 - st * 2 + c), height: CGFloat(1.0 - st * 2 + c)) let material = SCNMaterial.material(withDiffuse: focusSquareColorLight, respondsToLighting: false) fillPlane.materials = [material] let fillPlaneNode = SCNNode(geometry: fillPlane) fillPlaneNode.name = "fillPlane" fillPlaneNode.opacity = 0.0 let planeNode = SCNNode() planeNode.eulerAngles = SCNVector3Make(Float.pi / 2.0, 0, 0) // Horizontal planeNode.setUniformScale(focusSquareSize * scaleForClosedSquare) planeNode.addChildNode(s1) planeNode.addChildNode(s2) planeNode.addChildNode(s3) planeNode.addChildNode(s4) planeNode.addChildNode(s5) planeNode.addChildNode(s6) planeNode.addChildNode(s7) planeNode.addChildNode(s8) planeNode.addChildNode(fillPlaneNode) isOpen = false // Always render focus square on top planeNode.renderOnTop() return planeNode } } class FocusSquareSegment: SCNNode { enum Direction { case up case down case left case right } init(name: String, width: Float, thickness: Float, color: UIColor, vertical: Bool = false) { super.init() let material = SCNMaterial.material(withDiffuse: color, respondsToLighting: false) var plane: SCNPlane if vertical { plane = SCNPlane(width: CGFloat(thickness), height: CGFloat(width)) } else { plane = SCNPlane(width: CGFloat(width), height: CGFloat(thickness)) } plane.materials = [material] self.geometry = plane self.name = name } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func open(direction: Direction, newLength: CGFloat) { guard let p = self.geometry as? SCNPlane else { return } if direction == .left || direction == .right { p.width = newLength } else { p.height = newLength } switch direction { case .left: self.position.x -= Float(0.5 / 2 - p.width / 2) case .right: self.position.x += Float(0.5 / 2 - p.width / 2) case .up: self.position.y -= Float(0.5 / 2 - p.height / 2) case .down: self.position.y += Float(0.5 / 2 - p.height / 2) } } func close(direction: Direction) { guard let p = self.geometry as? SCNPlane else { return } var oldLength: CGFloat if direction == .left || direction == .right { oldLength = p.width p.width = 0.5 } else { oldLength = p.height p.height = 0.5 } switch direction { case .left: self.position.x -= Float(0.5 / 2 - oldLength / 2) case .right: self.position.x += Float(0.5 / 2 - oldLength / 2) case .up: self.position.y -= Float(0.5 / 2 - oldLength / 2) case .down: self.position.y += Float(0.5 / 2 - oldLength / 2) } } }
mit
08a7388b2b1a63c726ee571f244cfb7d
39.947137
128
0.611512
4.749617
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/GuidelinesViewController.swift
1
900
// // GuidelinesViewController.swift // Habitica // // Created by Phillip Thelen on 23.02.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Down class GuidelinesViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = L10n.Titles.guidelines let urlString = "https://s3.amazonaws.com/habitica-assets/mobileApp/endpoint/community-guidelines.md" guard let url = URL(string: urlString) else { return } if let text = try? String(contentsOf: url) { textView.attributedText = try? Down(markdownString: text).toHabiticaAttributedString() } } @IBAction func doneButtonTapped(_ sender: Any) { dismiss(animated: true, completion: nil) } }
gpl-3.0
47a746b3c7817884742e442dc5b56c7a
27.09375
109
0.650723
4.517588
false
false
false
false
stuart-grey/shinobicharts-style-guide
case-studies/StyleGuru/StyleGuru/sport/RunningChartData.swift
1
2637
// // Copyright 2015 Scott Logic // // 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 enum RunningChartSeries: Int { case Pace case Elevation } typealias SeriesAxisMapping = [RunningChartSeries : SChartAxis] func runningChartSeriesForAxis(mapping: SeriesAxisMapping, axis: SChartAxis) -> RunningChartSeries? { let series = filter(mapping) { (k,v) in return v === axis }.map { $0.0 } return series.first } class RunningChartDataSource: NSObject { let datapoints: [RunningChartSeries : [SChartData]] let axisMapping: SeriesAxisMapping init(data: [RunningTrackpoint], axisMapping: SeriesAxisMapping) { datapoints = [ .Elevation : data.map { $0.elevationDataPoint() }, .Pace : data.map { $0.paceDataPoint() } ] self.axisMapping = axisMapping super.init() } } extension RunningChartDataSource : SChartDatasource { func numberOfSeriesInSChart(chart: ShinobiChart!) -> Int { return datapoints.count } func sChart(chart: ShinobiChart!, seriesAtIndex index: Int) -> SChartSeries! { return SChartLineSeries() } func sChart(chart: ShinobiChart!, numberOfDataPointsForSeriesAtIndex seriesIndex: Int) -> Int { return datapoints[RunningChartSeries(rawValue: seriesIndex)!]?.count ?? 0 } func sChart(chart: ShinobiChart!, dataPointAtIndex dataIndex: Int, forSeriesAtIndex seriesIndex: Int) -> SChartData! { return datapoints[RunningChartSeries(rawValue: seriesIndex)!]?[dataIndex] } func sChart(chart: ShinobiChart!, dataPointsForSeriesAtIndex seriesIndex: Int) -> [AnyObject]! { return datapoints[RunningChartSeries(rawValue: seriesIndex)!] } func sChart(chart: ShinobiChart!, yAxisForSeriesAtIndex index: Int) -> SChartAxis! { return axisMapping[RunningChartSeries(rawValue: index)!] } } extension RunningChartDataSource { static func defaultData(axisMapping: SeriesAxisMapping) -> RunningChartDataSource? { if let runningData = RunningTrackpoint.loadDataFromDefaultPlist() { return RunningChartDataSource(data: runningData, axisMapping: axisMapping) } return .None } }
apache-2.0
bc094777f8c7414ab036a1a8121a9937
32.392405
120
0.732272
4.179081
false
false
false
false
mythkiven/DiffuseMenu_Swift
SDiffuseMenuDebugDemo/ViewController.swift
1
9032
import UIKit class ViewController: UIViewController, SDiffuseMenuDelegate { @IBOutlet weak var menuView: UIView! @IBOutlet weak var nearRadius: UISlider! @IBOutlet weak var farRadius: UISlider! @IBOutlet weak var endRadius: UISlider! @IBOutlet weak var timeOffSet: UISlider! @IBOutlet weak var menuWholeAngle: UISlider! @IBOutlet weak var animationDration: UISlider! @IBOutlet weak var rotateAngle: UISlider! @IBOutlet weak var isRotateAddButton: UISwitch! @IBOutlet weak var rotateAddButtonAngle: UISlider! @IBOutlet weak var isLineGrapyType: UISwitch! @IBOutlet weak var nearRadiusValue: UITextField! @IBOutlet weak var farRadiusValue: UITextField! @IBOutlet weak var endRadiusValue: UITextField! @IBOutlet weak var timeOffSetValue: UITextField! @IBOutlet weak var menuWholeAngleValue: UITextField! @IBOutlet weak var animationDrationValue: UITextField! @IBOutlet weak var rotateAddButtonAngleValue: UITextField! @IBOutlet weak var rotateAngleValue: UITextField! var menu: SDiffuseMenu! // MARK: - override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLoad() { super.viewDidLoad() guard let storyMenuItemImage = UIImage(named:"menuitem-normal.png") else { fatalError("图片加载失败") } guard let storyMenuItemImagePressed = UIImage(named:"menuitem-highlighted.png") else { fatalError("图片加载失败") } guard let starImage = UIImage(named:"star.png") else { fatalError("图片加载失败") } guard let starItemNormalImage = UIImage(named:"addbutton-normal.png") else { fatalError("图片加载失败") } guard let starItemLightedImage = UIImage(named:"addbutton-highlighted.png") else { fatalError("图片加载失败") } guard let starItemContentImage = UIImage(named:"plus-normal.png") else { fatalError("图片加载失败") } guard let starItemContentLightedImage = UIImage(named:"plus-highlighted.png") else { fatalError("图片加载失败") } // 选项数组 var menus = [SDiffuseMenuItem]() for _ in 0 ..< 6 { let starMenuItem = SDiffuseMenuItem(image: storyMenuItemImage, highlightedImage: storyMenuItemImagePressed, contentImage: starImage, highlightedContentImage: nil) menus.append(starMenuItem) } // 菜单按钮 let startItem = SDiffuseMenuItem(image: starItemNormalImage, highlightedImage: starItemLightedImage, contentImage: starItemContentImage, highlightedContentImage: starItemContentLightedImage ) let menuRect = CGRect.init(x: self.menuView.bounds.size.width/2, y: self.menuView.bounds.size.width/2, width: self.menuView.bounds.size.width, height: self.menuView.bounds.size.width) // 创建菜单 menu = SDiffuseMenu(frame: menuRect, startItem: startItem, menusArray: menus as NSArray, grapyType: SDiffuseMenu.SDiffuseMenuGrapyType.arc) menu.center = self.menuView.center menu.delegate = self self.menuView.addSubview(menu) // 配置动画 resetAnimation("") } // MARK: - @IBAction func resetAnimation(_ sender: Any){ if sender is UIButton { // 调试代码控制动画 // if menu.expanding == true { // menu.close() // }else{ // menu.open() // } } // print("菜单状态%@",menu.expanding == true ? "展开":"关闭") // 获取控件初始数据 nearRadiusDidChangeValue(nearRadius) farRadiusDidChangeValue(farRadius) endRadiusDidChangeValue(endRadius) timeOffSetDidChangeValue(timeOffSet) menuWholeAngleDidChangeValue(menuWholeAngle) animationDrationDidChangeValue(animationDration) rotateAddButtonAngleDidChangeValue(rotateAddButtonAngle) rotateAngleDidChangeValue(rotateAngle) // 动画配置: // 动画时长 menu.animationDuration = CFTimeInterval(animationDrationValue.text!) // 最小半径 menu.nearRadius = CGFloat((nearRadiusValue.text! as NSString).floatValue) // 结束半径 menu.endRadius = CGFloat((endRadiusValue.text! as NSString).floatValue) // 最大半径 menu.farRadius = CGFloat((farRadiusValue.text! as NSString).floatValue) // 单个动画间隔时间 menu.timeOffset = CFTimeInterval(timeOffSetValue.text!)! // 整体角度 menu.menuWholeAngle = CGFloat((menuWholeAngleValue.text! as NSString).floatValue) // 整体偏移角度 menu.rotateAngle = CGFloat((rotateAngleValue.text! as NSString).floatValue) // 展开时自旋角度 menu.expandRotation = CGFloat(M_PI) // 结束时自旋角度 menu.closeRotation = CGFloat(M_PI * 2) // 是否旋转菜单按钮 menu.rotateAddButton = isRotateAddButton.isOn // 菜单按钮旋转角度 menu.rotateAddButtonAngle = CGFloat((rotateAddButtonAngleValue.text! as NSString).floatValue) // 菜单展示的形状:直线 or 弧形 menu.sDiffuseMenuGrapyType = isLineGrapyType.isOn == true ? .line : .arc // 为方便使用,已枚举常见方位,可直接使用.无需再次设置 rotateAngle && menuWholeAngle // 若对于 rotateAngle\menuWholeAngle 不熟悉,建议查看 source 目录下的配置图片 // menu.sDiffuseMenuDirection = .above // 上方180° // menu.sDiffuseMenuDirection = .left // 左方180° // menu.sDiffuseMenuDirection = .below // 下方180° // menu.sDiffuseMenuDirection = .right // 右方180° // menu.sDiffuseMenuDirection = .upperRight // 右上方90° // menu.sDiffuseMenuDirection = .lowerRight // 右下方90° // menu.sDiffuseMenuDirection = .upperLeft // 左上方90° // menu.sDiffuseMenuDirection = .lowerLeft // 左下方90° // menu.sDiffuseMenuDirection = .other } @IBAction func nearRadiusDidChangeValue(_ sender: UISlider) { nearRadiusValue.text = String(format: "%.1f", sender.value) } @IBAction func farRadiusDidChangeValue(_ sender: UISlider) { farRadiusValue.text = String(format: "%.1f", sender.value) } @IBAction func endRadiusDidChangeValue(_ sender: UISlider) { endRadiusValue.text = String(format: "%.1f", sender.value) } @IBAction func animationDrationDidChangeValue(_ sender: UISlider) { animationDrationValue.text = String(format: "%.1f", sender.value) } @IBAction func menuWholeAngleDidChangeValue(_ sender: UISlider) { menuWholeAngleValue.text = String(format: "%.2f", sender.value) } @IBAction func rotateAddButtonAngleDidChangeValue(_ sender: UISlider) { rotateAddButtonAngleValue.text = String(format: "%.2f", sender.value) } @IBAction func rotateAngleDidChangeValue(_ sender: UISlider) { rotateAngleValue.text = String(format: "%.2f", sender.value) } @IBAction func timeOffSetDidChangeValue(_ sender: UISlider) { timeOffSetValue.text = String(format: "%.4f", sender.value) } // MARK: - 动画代理方法 func SDiffuseMenuDidSelectMenuItem(_ menu: SDiffuseMenu, didSelectIndex index: Int) { print("选中按钮at index:\(index) is: \(menu.menuItemAtIndex(index)) ") } func SDiffuseMenuDidClose(_ menu: SDiffuseMenu) { print("关闭动画关闭结束") } func SDiffuseMenuDidOpen(_ menu: SDiffuseMenu) { print("展开动画展开结束") } func SDiffuseMenuWillOpen(_ menu: SDiffuseMenu) { print("菜单将要展开") } func SDiffuseMenuWillClose(_ menu: SDiffuseMenu) { print("菜单将要关闭") } // MARK: - // override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // self.view.resignFirstResponder() // } }
mit
e76bfc1f0312e05b4598073f01d09e70
38.18894
125
0.588782
4.426861
false
false
false
false
merlos/iOS-Open-GPX-Tracker
Pods/MapCache/MapCache/Classes/Log.swift
1
2565
// // Log.swift // MapCache // // Created by merlos on 02/06/2019. // // Based on Haneke' Log File // https://github.com/Haneke/HanekeSwift/blob/master/Haneke/Log.swift // import Foundation /// /// For logging messages on console. /// /// The log format is `<tag><Level> <message> [with error <error>]`: /// Examples: /// ``` /// [MapCache][DEBUG] Welcome to MapCache /// [MapCache][ERROR] Could not download file with error Unknown address /// /// ``` /// /// public struct Log { /// The tag [MapCache] fileprivate static let tag = "[MapCache]" /// Log Levels fileprivate enum Level : String { /// `[Debug]` For displaying messages useful during development. case Debug = "[DEBUG]" /// `[ERROR]`For displaying messages of bad situations, very, very bad situations. case Error = "[ERROR]" } /// /// The actual method that prints. /// - Parameter level: log level to show /// - Parameter message: message to show /// - Parameter error: error to show if any on addition to the message. Uses the pattern `{message} with error {error}` fileprivate static func log(_ level: Level, _ message: @autoclosure () -> String, _ error: Error? = nil) { if let error = error { print("\(tag)\(level.rawValue) \(message()) with error \(error)") } else { print("\(tag)\(level.rawValue) \(message())") } } /// /// For displaying messages. Useful during development of this package. /// /// Example: /// ``` /// Log.debug("Hello world") // prints: [MapCache][DEBUG] Hello word /// ``` /// /// These messages are displayed only if DEBUG is defined. /// - Parameter message: message to display /// - Parameter error: error to display if any. static func debug(message: @autoclosure () -> String, error: Error? = nil) { #if DEBUG log(.Debug, message(), error) #endif } /// /// These messages are displayed independently of the debug mode. /// Used to provide useful information on exceptional situations to library users. /// Example: /// ``` /// Log.error("Could not download tile", error) // prints: [MapCache][ERROR] Could not download tile with error No internet connection. /// ``` /// /// - Parameter message: message to display /// - Parameter error: error to display static func error(message: @autoclosure () -> String, error: Error? = nil) { log(.Error, message(), error) } }
gpl-3.0
9783b3d1aeefeeb9d12147326389cbc3
29.535714
139
0.593372
4.246689
false
false
false
false
MLSDev/AppRouter
Tests/Reactive/AppRouterReactiveTests.swift
1
3617
// // AppRouterReactiveTests.swift // AppRouter // // Created by Antihevich on 8/9/16. // Copyright © 2016 Artem Antihevich. All rights reserved. // import XCTest import AppRouterRx import RxCocoa import RxSwift class AppRouterReactiveTests: XCTestCase { func testDidLoad() { let first = FirstController() let second = SecondController() let expectationOne = expectation(description: "") let expectationTwo = expectation(description: "") _ = FirstController.rx.onViewDidLoad().emit(onNext: { _ in expectationOne.fulfill() }) _ = first.rx.onViewDidLoad().emit(onNext: { expectationTwo.fulfill() }) second.viewDidLoad() first.viewDidLoad() waitForExpectations(timeout: 2, handler: nil) } func testWillAppear() { let first = FirstController() let second = SecondController() let expectationOne = expectation(description: "") let expectationTwo = expectation(description: "") _ = FirstController.rx.onViewWillAppear().emit(onNext: { (vc, animated) in XCTAssertTrue(animated) expectationOne.fulfill() }) _ = first.rx.onViewWillAppear().emit(onNext: { animated in XCTAssertTrue(animated) expectationTwo.fulfill() }) second.viewWillAppear(true) first.viewWillAppear(true) waitForExpectations(timeout: 2, handler: nil) } func testDidAppear() { let first = FirstController() let second = SecondController() let expectationOne = expectation(description: "") let expectationTwo = expectation(description: "") _ = FirstController.rx.onViewDidAppear().emit(onNext: { (vc, animated) in XCTAssertTrue(animated) expectationOne.fulfill() }) _ = first.rx.onViewDidAppear().emit(onNext: { animated in XCTAssertTrue(animated) expectationTwo.fulfill() }) second.viewDidAppear(true) first.viewDidAppear(true) waitForExpectations(timeout: 2, handler: nil) } func testWillDisappear() { let first = FirstController() let second = SecondController() let expectationOne = expectation(description: "") let expectationTwo = expectation(description: "") _ = FirstController.rx.onViewWillDisappear().emit(onNext: { (vc, animated) in XCTAssertTrue(animated) expectationOne.fulfill() }) _ = first.rx.onViewWillDisappear().emit(onNext: { animated in XCTAssertTrue(animated) expectationTwo.fulfill() }) second.viewWillDisappear(true) first.viewWillDisappear(true) waitForExpectations(timeout: 2, handler: nil) } func testDidDisappear() { let first = FirstController() let second = SecondController() let expectationOne = expectation(description: "") let expectationTwo = expectation(description: "") _ = FirstController.rx.onViewDidDisappear().emit(onNext: { (vc, animated) in XCTAssertTrue(animated) expectationOne.fulfill() }) _ = first.rx.onViewDidDisappear().emit(onNext: { animated in XCTAssertTrue(animated) expectationTwo.fulfill() }) second.viewDidDisappear(true) first.viewDidDisappear(true) waitForExpectations(timeout: 2, handler: nil) } }
mit
5c873b2ea7ae6b0a56c48310b7122548
31.285714
85
0.603706
5.165714
false
true
false
false
GustavoAlvarez/Universe-Atlas
Universe Atlas/PlanetsTable.swift
1
2720
// // PlanetsTable.swift // Universe Atlas // // Created by Gustavo Alvarez on 06/08/17. // Copyright © 2017 ParanoidDev. All rights reserved. // import UIKit class planetCell: UITableViewCell{ @IBOutlet weak var planetImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var systemLabel: UILabel! @IBOutlet weak var galaxyLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class PlanetsTable: UITableViewController { let planets = ["Earth", "Mars", "Saturn", "Venus", "Earth", "Mars", "Saturn", "Venus"] override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.barTintColor = hexStringToUIColor(hex: "262042") UIApplication.shared.statusBarStyle = .lightContent navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return planets.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:planetCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! planetCell let row = indexPath.row cell.planetImage.image = UIImage(named: planets[row]) cell.nameLabel.text = planets[row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("You tapped cell number \(indexPath.row).") } func hexStringToUIColor(hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
mit
2d71faa5abf67105be3253ce0d66d3fa
26.19
113
0.612357
4.899099
false
false
false
false
LawrenceHan/iOS-project-playground
Chatter/Chatter/ChatWindowController.swift
1
3560
// // ChatWindowController.swift // Chatter // // Created by Hanguang on 12/11/15. // Copyright © 2015 Hanguang. All rights reserved. // private let ChatWindowControllerDidSendMessageNotification = "com.bignerdranch.chatter.ChatwindowControllerDidSendMessageNotification" private let ChatWindowControllerMessageKey = "com.bignerdranch.chatter.ChatWindowControllerMessageKey" import Cocoa class ChatWindowController: NSWindowController { dynamic var log: NSAttributedString = NSAttributedString(string: "") dynamic var message: String? dynamic var username: String? let randomNumber = arc4random_uniform(1000) // NSTextView does not support weak references. @IBOutlet var textView: NSTextView! // MARK: - Lifecycle override var windowNibName: String { return "ChatWindowController" } override init(window: NSWindow?) { NSValueTransformer.setValueTransformer(IsNotEmptyTransformer(), forName: "IsNotEmptyTransformer") super.init(window: window) } required init?(coder: NSCoder) { NSValueTransformer.setValueTransformer(IsNotEmptyTransformer(), forName: "IsNotEmptyTransformer") super.init(coder: coder) } override func windowDidLoad() { super.windowDidLoad() let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector("receiveDidSendMessageNotification:"), name: ChatWindowControllerDidSendMessageNotification, object: nil) } deinit { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self) } // MARK: - Actions @IBAction func send(sender: NSButton) { sender.window?.endEditingFor(nil) if var message = message { var defaultName = "unknown_\(randomNumber):" if let name = username { defaultName = "\(name)_\(randomNumber):" } message = defaultName + message let userInfo = [ChatWindowControllerMessageKey : message] let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.postNotificationName(ChatWindowControllerDidSendMessageNotification, object: self, userInfo: userInfo) } message = "" } // MARK: - Notifications // ChatWindowControllerDidSendMessageNotification func receiveDidSendMessageNotification(note: NSNotification) { let mutableLog = log.mutableCopy() as! NSMutableAttributedString if log.length > 0 { mutableLog.appendAttributedString(NSAttributedString(string: "\n")) } let userInfo = note.userInfo! as! [String : String] let message = userInfo[ChatWindowControllerMessageKey]! var attributes = [String : NSColor]() if note.object! as! NSWindowController == self { attributes = [NSForegroundColorAttributeName : NSColor.blueColor()] } else { attributes = [NSForegroundColorAttributeName : NSColor.blackColor()] } let logLine = NSAttributedString(string: message, attributes: attributes) mutableLog.appendAttributedString(logLine) log = mutableLog.copy() as! NSAttributedString textView.scrollRangeToVisible(NSRange(location: log.length, length: 0)) } }
mit
d86574cd404aa5f5bd70151aee9a544c
33.892157
134
0.658893
5.731079
false
false
false
false
urbanthings/urbanthings-sdk-apple
UrbanThingsAPI/Internal/Response/UTTransitStopRTIReport.swift
1
1463
// // UTTransitStopRTIReport.swift // UrbanThingsAPI // // Created by Mark Woollard on 02/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation class UTTransitStopRTIReport : UTAttribution, TransitStopRTIReport { let reportName:String? let platformID:String? let upcomingCalls:[MonitoredStopCall] let disruptions:[Disruption] let noDataLabel:String? let sourceName:String let timestamp:Date? override init(json: [String : Any]) throws { self.reportName = try parse(optional: json, key: .ReportName, type: UTTransitStopRTIReport.self) self.platformID = try parse(optional: json, key: .PlatformID, type: UTTransitStopRTIReport.self) self.upcomingCalls = try parse(required:json, key: .UpcomingCalls, type:UTTransitStopRTIReport.self) { try [UTMonitoredStopCall](required:$0) }.map { $0 as MonitoredStopCall } self.disruptions = try parse(required:json, key: .Disruptions, type:UTTransitStopRTIReport.self) { try [UTDisruption](required:$0) }.map { $0 as Disruption } self.noDataLabel = try parse(optional: json, key: .NoDataLabel, type: UTTransitStopRTIReport.self) self.sourceName = try parse(required: json, key: .SourceName, type: UTTransitStopRTIReport.self) self.timestamp = try parse(optional:json, key: .Timestamp, type:UTDisruption.self) { try String(optional: $0)?.requiredDate() } try super.init(json: json) } }
apache-2.0
eaf19a5d0c581fce6d195f35f1934a6a
46.16129
183
0.718878
3.574572
false
false
false
false
AndrewBennet/readinglist
ReadingList/Startup/BuildInfo.swift
1
2958
import Foundation struct BuildInfo: Codable { enum BuildType: Int, Codable { case debug, testFlight, appStore //swiftlint:disable:this explicit_enum_raw_value } init(version: Version, buildNumber: Int, type: BuildType) { self.version = version self.buildNumber = buildNumber self.type = type } static var thisBuild: BuildInfo = { guard let bundleShortVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, let version = Version(bundleShortVersion) else { preconditionFailure() } guard let bundleVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, let buildNumber = Int(bundleVersion) else { preconditionFailure() } let buildType: BuildType #if DEBUG || arch(i386) || arch(x86_64) buildType = .debug #else if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" { buildType = .testFlight } else { buildType = .appStore } #endif return BuildInfo(version: version, buildNumber: buildNumber, type: buildType) }() let version: Version let buildNumber: Int let type: BuildType /// Returns the version suffixed with the build number if this is a Beta build var fullDescription: String { switch type { case .appStore: return "\(version)" case .testFlight: return "\(version) (Build \(buildNumber))" case .debug: return "\(version) Debug" } } /// Returns the version suffixed with Beta or Debug if this is a TestFlight or Debug build var versionAndConfiguration: String { switch type { case .appStore: return "\(version)" case .testFlight: return "\(version) (Beta)" case .debug: return "\(version) (Debug)" } } } struct Version: Equatable, Hashable, Comparable, CustomStringConvertible, Codable { let major: Int let minor: Int let patch: Int init(major: Int, minor: Int, patch: Int) { self.major = major self.minor = minor self.patch = patch } init?(_ versionString: String) { let components = versionString.components(separatedBy: ".") if components.count != 3 { return nil } let integerComponents = components.compactMap(Int.init) if integerComponents.count != 3 { return nil } self.major = integerComponents[0] self.minor = integerComponents[1] self.patch = integerComponents[2] } var description: String { "\(major).\(minor).\(patch)" } static func < (lhs: Version, rhs: Version) -> Bool { if lhs.major != rhs.major { return lhs.major < rhs.major } if lhs.minor != rhs.minor { return lhs.minor < rhs.minor } return lhs.patch < rhs.patch } }
gpl-3.0
e97e93d7bd1289eb9767b6c54e768262
29.8125
108
0.605477
4.665615
false
true
false
false
vl4298/mah-income
Mah Income/Mah Income/Scenes/Analyze/AnalyzeModelController.swift
1
1084
// // AnalyzeModelController.swift // Mah Income // // Created by Van Luu on 5/9/17. // Copyright © 2017 Van Luu. All rights reserved. // import UIKit import RealmSwift class AnalyzeModelController { weak var viewController: AnalyzeViewController! fileprivate lazy var paymentWorker: PaymentWorker? = { return PaymentWorker() }() func fetchAllPaymentWith(category: String, reason: String) { guard let worker = paymentWorker else { viewController.presentError(des: "Can not init") return } let payments = worker.getAllPaymentWith(category: category, reason: reason) viewController.paymentsWith(category: category, reason: reason, payments: payments) } func fetchAllPaymentWith(category: String, from date: Date) { guard let worker = paymentWorker else { viewController.presentError(des: "Can not init") return } let payments = worker.getAllPaymentsWith(category: category, from: date) viewController.paymentsWith(category: category, from: date, payments: payments) } }
mit
6eda331c87090cab9b117179f962c9e1
24.785714
87
0.700831
4.420408
false
false
false
false
nathawes/swift
test/stdlib/MultipliedFullWidth.swift
9
6784
//===--- MultipliedFullWidth.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var tests = TestSuite("MultipliedFullWidth") func testCase<T: FixedWidthInteger>( _ x: T, _ y: T, high: T, low: T.Magnitude, line: UInt = #line ) { let result = x.multipliedFullWidth(by: y) expectEqual(high, result.high, line: line) expectEqual(low, result.low, line: line) } func specialValues<T: FixedWidthInteger & SignedInteger>(_ type: T.Type) { let umin = T.Magnitude(truncatingIfNeeded: T.min) testCase(T.min, .min, high: -(.min >> 1), low: 0) testCase(T.min, -1, high: 0, low: umin) testCase(T.min, 0, high: 0, low: 0) testCase(T.min, 1, high: -1, low: umin) testCase(T.min, .max, high: .min >> 1, low: umin) testCase(T(-1), .min, high: 0, low: umin) testCase(T(-1), -1, high: 0, low: 1) testCase(T(-1), 0, high: 0, low: 0) testCase(T(-1), 1, high: -1, low: .max) testCase(T(-1), .max, high: -1, low: umin + 1) testCase(T(0), .min, high: 0, low: 0) testCase(T(0), -1, high: 0, low: 0) testCase(T(0), 0, high: 0, low: 0) testCase(T(0), 1, high: 0, low: 0) testCase(T(0), .max, high: 0, low: 0) testCase(T(1), .min, high: -1, low: umin) testCase(T(1), -1, high: -1, low: .max) testCase(T(1), 0, high: 0, low: 0) testCase(T(1), 1, high: 0, low: 1) testCase(T(1), .max, high: 0, low: .max >> 1) testCase(T.max, .min, high: .min >> 1, low: umin) testCase(T.max, -1, high: -1, low: umin + 1) testCase(T.max, 0, high: 0, low: 0) testCase(T.max, 1, high: 0, low: .max >> 1) testCase(T.max, .max, high: (.max >> 1), low: 1) } func specialValues<T: FixedWidthInteger & UnsignedInteger>(_ type: T.Type) { testCase(T(0), 0, high: 0, low: 0) testCase(T(0), 1, high: 0, low: 0) testCase(T(0), .max, high: 0, low: 0) testCase(T(1), 0, high: 0, low: 0) testCase(T(1), 1, high: 0, low: 1) testCase(T(1), .max, high: 0, low: .max) testCase(T.max, 0, high: 0, low: 0) testCase(T.max, 1, high: 0, low: .max) testCase(T.max, .max, high: .max-1, low: 1) } tests.test("Special Values") { specialValues(Int.self) specialValues(Int64.self) specialValues(Int32.self) specialValues(Int16.self) specialValues(Int8.self) specialValues(UInt.self) specialValues(UInt64.self) specialValues(UInt32.self) specialValues(UInt16.self) specialValues(UInt8.self) } tests.test("Random Values") { // Some extra coverage for the 64b integers, since they are the only users // of the default implementation (only on 32b systems): testCase(Int64(-5837700935641288840), -1537421853862307457, high: 486536212510185592, low: 3055263144559363208) testCase(Int64(1275671358463268836), 7781435829978284036, high: 538119614841437377, low: 14789118443021950864) testCase(Int64(4911382318934676967), -5753361984332212917, high: -1531812888571062585, low: 1722298197364104621) testCase(Int64(6581943526282064299), -8155192887281934825, high: -2909837032245044682, low: 16706127436327993437) testCase(Int64(4009108071534959395), 7605188192539249328, high: 1652867370329384990, low: 3839516780320392720) testCase(Int64(-1272471934452731280), -7713709059189882656, high: 532098144210826160, low: 4919265615377605120) testCase(Int64(-1290602245486355209), -6877877092931971073, high: 481201646472028302, low: 4015257672509033225) testCase(Int64(1966873427191941886), -7829903732960672311, high: -834858960925259072, low: 12998587081554941806) testCase(Int64(5459471085932887725), 7323207134727813062, high: 2167365549637832126, low: 5826569093894448334) testCase(Int64(-5681348775805725880), -6546051581806832250, high: 2016095739825622823, low: 7531931343377498032) testCase(Int64(3528630718229643203), 6780383198781339163, high: 1297002242834103876, low: 16845851682892995473) testCase(Int64(4386302929483327645), 756139473360675718, high: 179796324698125913, low: 13652654049648998702) testCase(Int64(-2864416372170195291), 5089997120359086926, high: -790376395292167927, low: 8341529919881354566) testCase(Int64(-252886279681789793), 1113918432442210295, high: -15270699648874904, low: 4582052466224525929) testCase(Int64(-7821806154093904666), -678157520322455918, high: 287553003647030877, low: 6476241133902266156) testCase(Int64(-7739162216163589826), 3946867172269483361, high: -1655871907247741938, low: 13863106094322986622) testCase(UInt64(4052776605025255999), 17841868768407320997, high: 3919884617339462744, low: 486827993115916699) testCase(UInt64(6242835766066895539), 14960190906716810460, high: 5062899690398282642, low: 14718350117826688468) testCase(UInt64(17427627038899386484), 13127734187148388607, high: 12402473540330496943, low: 11581729162526677900) testCase(UInt64(14992872905705044844), 12933105414992193421, high: 10511578899141219143, low: 7252341782600986236) testCase(UInt64(12642327504267244590), 10708397907431293358, high: 7338914274020844379, low: 8873679764824466756) testCase(UInt64(18257718462988034339), 17327659287939371125, high: 17150101049683916791, low: 14387647780301477119) testCase(UInt64(5589411463208969260), 14342285504591657788, high: 4345749834640583520, low: 12301233398332628560) testCase(UInt64(14319626538136147986), 2140855187369381019, high: 1661878466620705928, low: 2387587391530298086) testCase(UInt64(12737453267169023056), 10991462038848276938, high: 7589590526017326520, low: 4333382898129426208) testCase(UInt64(13832741301927421318), 7713698894698105596, high: 5784305396386691701, low: 6880744869607156712) testCase(UInt64(5299309970076755930), 12147554660789977612, high: 3489702967025088672, low: 8435073470527345208) testCase(UInt64(3775627568330760013), 12573993794040378591, high: 2573609598696611841, low: 11258650814777796627) testCase(UInt64(10163828939432769169), 11406425048812406036, high: 6284737975620258563, low: 8064735036375816276) testCase(UInt64(10553402338235046132), 16330771020588292162, high: 9342851854245941300, low: 7535126182307876584) testCase(UInt64(17113612905570890777), 11972779332523394977, high: 11107516322766487141, low: 955396679557657273) testCase(UInt64(10933450006210087838), 18204962163032170108, high: 10790145018498752040, low: 692054466472649864) } runAllTests()
apache-2.0
821ed2323ba3e555f74ce7b789bba400
52.417323
117
0.733933
2.696343
false
true
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Backend/Processing/LinearFocusFilter.swift
1
4258
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import CoreImage /** * Applies a linear focus to an instance of `CIImage`. */ @available(iOS 8, *) @objc(IMGLYLinearFocusFilter) public class LinearFocusFilter: CIFilter { // MARK: - Properties /// The input image. public var inputImage: CIImage? /// The first normalized control point of the focus. This control point should use the coordinate system of Core Image, which means that (0,0) is at the top left. public var inputNormalizedControlPoint1: NSValue? /// The second normalized control point of the focus. This control point should use the coordinate system of Core Image, which means that (0,0) is at the top left. public var inputNormalizedControlPoint2: NSValue? /// The blur radius to use for focus. Default is 4. public var inputRadius: NSNumber? // MARK: - CIFilter /** :nodoc: */ public override func setDefaults() { inputNormalizedControlPoint1 = NSValue(CGPoint: CGPoint.zero) inputNormalizedControlPoint2 = NSValue(CGPoint: CGPoint.zero) inputRadius = 10 } /// :nodoc: public override var outputImage: CIImage? { guard let inputImage = inputImage, inputNormalizedControlPoint1 = inputNormalizedControlPoint1, inputNormalizedControlPoint2 = inputNormalizedControlPoint2, inputRadius = inputRadius else { return nil } if inputRadius.floatValue < 0.16 { return inputImage } guard let blurFilter = CIFilter(name: "CIGaussianBlur", withInputParameters: [kCIInputRadiusKey: inputRadius, kCIInputImageKey: inputImage]) else { return inputImage } guard let blurredImage = blurFilter.outputImage?.imageByCroppingToRect(inputImage.extent) else { return inputImage } let opaqueColor = CIColor(red: 0, green: 1, blue: 0, alpha: 1) let transparentColor = CIColor(red: 0, green: 1, blue: 0, alpha: 0) let denormalizedControlPoint1 = CGPoint(x: inputNormalizedControlPoint1.CGPointValue().x * inputImage.extent.width, y: inputNormalizedControlPoint1.CGPointValue().y * inputImage.extent.height) let denormalizedControlPoint2 = CGPoint(x: inputNormalizedControlPoint2.CGPointValue().x * inputImage.extent.width, y: inputNormalizedControlPoint2.CGPointValue().y * inputImage.extent.height) let vector = CGVector(startPoint: denormalizedControlPoint1, endPoint: denormalizedControlPoint2) let controlPoint1Extension = denormalizedControlPoint1 - 0.3 * vector let controlPoint2Extension = denormalizedControlPoint2 + 0.3 * vector guard let gradient0 = CIFilter(name: "CILinearGradient", withInputParameters: ["inputPoint0": CIVector(CGPoint: controlPoint1Extension), "inputPoint1": CIVector(CGPoint: denormalizedControlPoint1), "inputColor0": opaqueColor, "inputColor1": transparentColor])?.outputImage else { return inputImage } guard let gradient1 = CIFilter(name: "CILinearGradient", withInputParameters: ["inputPoint0": CIVector(CGPoint: controlPoint2Extension), "inputPoint1": CIVector(CGPoint: denormalizedControlPoint2), "inputColor0": opaqueColor, "inputColor1": transparentColor])?.outputImage else { return inputImage } guard let maskImage = CIFilter(name: "CIAdditionCompositing", withInputParameters: [kCIInputImageKey: gradient0, kCIInputBackgroundImageKey: gradient1])?.outputImage else { return inputImage } guard let blendFilter = CIFilter(name: "CIBlendWithMask", withInputParameters: [kCIInputImageKey: blurredImage, kCIInputMaskImageKey: maskImage, kCIInputBackgroundImageKey: inputImage]) else { return inputImage } return blendFilter.outputImage } }
mit
e5306d21f6636c41f810347cb38f98e0
45.791209
287
0.722405
4.789651
false
false
false
false
timelessg/TLStoryCamera
TLStoryCameraFramework/TLStoryCameraFramework/Class/Views/TLStoryPhotoPreviewView.swift
1
1285
// // TLStoryPhotoPreviewView.swift // TLStoryCamera // // Created by garry on 2017/9/15. // Copyright © 2017年 com.garry. All rights reserved. // import UIKit import GPUImage class TLStoryPhotoPreviewView: UIView { public var gpuPicture:GPUImagePicture? = nil fileprivate var gpuView:GPUImageView? = nil deinit { gpuView?.removeFromSuperview() gpuPicture?.removeAllTargets() gpuPicture = nil } init(frame: CGRect, image:UIImage) { super.init(frame: frame) gpuView = GPUImageView.init(frame: self.bounds) gpuView?.fillMode = .preserveAspectRatio self.addSubview(gpuView!) gpuPicture = GPUImagePicture.init(image: image) gpuPicture?.addTarget(gpuView) gpuPicture?.processImage() } public func config(filter:GPUImageCustomLookupFilter?) { gpuPicture?.removeAllTargets() if let f = filter { gpuPicture?.addTarget(f) f.addTarget(gpuView!) }else { gpuPicture!.addTarget(gpuView) } gpuPicture?.processImage() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ad84716e8fe1fa63324a6cbb5e07a7e8
23.653846
60
0.607644
4.466899
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Editor/CropRectComponent.swift
1
7281
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** A `CropRectComponent` holds all the logic for the cropping view. */ @available(iOS 8, *) @objc(IMGLYCropRectComponent) public class CropRectComponent: NSObject { /// The currently visible cropping area. public var cropRect = CGRect.zero private var topLineView = UIView(frame: CGRect.zero) private var bottomLineView = UIView(frame: CGRect.zero) private var leftLineView = UIView(frame: CGRect.zero) private var rightLineView = UIView(frame: CGRect.zero) /// The top left anchor image view. public var topLeftAnchor: UIImageView? /// The top right anchor image view. public var topRightAnchor: UIImageView? /// The bottom left anchor image view. public var bottomLeftAnchor: UIImageView? /// The bottom right anchor image view. public var bottomRightAnchor: UIImageView? private var transparentView: UIView? private var parentView: UIView? private var showAnchors = true /** Call this in `viewDidLoad`. - parameter transparentView: A view that is userd as transperent overlay. - parameter parentView: The parent view. - parameter showAnchors: A bool that determines whether the anchors are visible or not. */ public func setup(transparentView: UIView, parentView: UIView, showAnchors: Bool) { self.transparentView = transparentView self.parentView = parentView self.showAnchors = showAnchors setupLineViews() setupAnchors() } /** Call this in `viewDidAppear`. */ public func present() { layoutViewsForCropRect() showViews() } private func setupLineViews() { cropRect = CGRect(x: 100, y: 100, width: 150, height: 100) setupLineView(topLineView) setupLineView(bottomLineView) setupLineView(leftLineView) setupLineView(rightLineView) } private func setupLineView(lineView: UIView) { lineView.backgroundColor = UIColor.whiteColor() lineView.hidden = true lineView.userInteractionEnabled = false parentView!.addSubview(lineView) } private func addMaskRectView() { let bounds = CGRect(x: 0, y: 0, width: transparentView!.frame.size.width, height: transparentView!.frame.size.height) let maskLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.fillColor = UIColor.blackColor().CGColor let path = UIBezierPath(rect: cropRect) path.appendPath(UIBezierPath(rect: bounds)) maskLayer.path = path.CGPath maskLayer.fillRule = kCAFillRuleEvenOdd transparentView!.layer.mask = maskLayer let cropRectElement = UIAccessibilityElement(accessibilityContainer: self) cropRectElement.isAccessibilityElement = true cropRectElement.accessibilityLabel = Localize("Cropping area") cropRectElement.accessibilityHint = Localize("Double-tap and hold to move cropping area") cropRectElement.accessibilityFrame = transparentView!.convertRect(cropRect, toView: nil) transparentView!.accessibilityElements = [cropRectElement] if let topLeftAnchor = topLeftAnchor { transparentView!.accessibilityElements?.append(topLeftAnchor) } if let topRightAnchor = topRightAnchor { transparentView!.accessibilityElements?.append(topRightAnchor) } if let bottomLeftAnchor = bottomLeftAnchor { transparentView!.accessibilityElements?.append(bottomLeftAnchor) } if let bottomRightAnchor = bottomRightAnchor { transparentView!.accessibilityElements?.append(bottomRightAnchor) } } private func setupAnchors() { let anchorImage = UIImage(named: "crop_anchor", inBundle: NSBundle.imglyKitBundle, compatibleWithTraitCollection:nil) topLeftAnchor = createAnchorWithImage(anchorImage) topLeftAnchor?.accessibilityLabel = Localize("Top left cropping handle") topRightAnchor = createAnchorWithImage(anchorImage) topRightAnchor?.accessibilityLabel = Localize("Top right cropping handle") bottomLeftAnchor = createAnchorWithImage(anchorImage) bottomLeftAnchor?.accessibilityLabel = Localize("Bottom left cropping handle") bottomRightAnchor = createAnchorWithImage(anchorImage) bottomRightAnchor?.accessibilityLabel = Localize("Bottom right cropping handle") } private func createAnchorWithImage(image: UIImage?) -> UIImageView { let anchor = UIImageView(image: image!) anchor.isAccessibilityElement = true anchor.accessibilityTraits &= ~UIAccessibilityTraitImage anchor.accessibilityHint = Localize("Double-tap and hold to adjust cropping area") anchor.contentMode = UIViewContentMode.Center anchor.frame = CGRect(x: 0, y: 0, width: 44, height: 44) anchor.hidden = true transparentView!.addSubview(anchor) return anchor } // MARK: - Layout /** Initially lays out all needed views for the crop rect. */ public func layoutViewsForCropRect() { layoutLines() layoutAnchors() addMaskRectView() } private func layoutLines() { let left = cropRect.origin.x + transparentView!.frame.origin.x let right = left + cropRect.size.width - 1.0 let top = cropRect.origin.y + transparentView!.frame.origin.y let bottom = top + cropRect.size.height - 1.0 let width = cropRect.size.width let height = cropRect.size.height leftLineView.frame = CGRect(x: left, y: top, width: 1, height: height) rightLineView.frame = CGRect(x: right, y: top, width: 1, height: height) topLineView.frame = CGRect(x: left, y: top, width: width, height: 1) bottomLineView.frame = CGRect(x: left, y: bottom, width: width, height: 1) } private func layoutAnchors() { let left = cropRect.origin.x let right = left + cropRect.size.width let top = cropRect.origin.y let bottom = top + cropRect.size.height topLeftAnchor!.center = CGPoint(x: left, y: top) topRightAnchor!.center = CGPoint(x: right, y: top) bottomLeftAnchor!.center = CGPoint(x: left, y: bottom) bottomRightAnchor!.center = CGPoint(x: right, y: bottom) } /** Makes all views visible. */ public func showViews() { if showAnchors { topLeftAnchor!.hidden = false topRightAnchor!.hidden = false bottomLeftAnchor!.hidden = false bottomRightAnchor!.hidden = false } leftLineView.hidden = false rightLineView.hidden = false topLineView.hidden = false bottomLineView.hidden = false } }
mit
403fab64ffd02366f00ef6e872fac672
36.725389
125
0.678616
4.870234
false
false
false
false
intelygenz/NetClient-iOS
Stub/NetStub.swift
1
4660
// // NetStub.swift // Net // // Created by Alex Rupérez on 24/1/18. // import Foundation open class NetStub: Net { public enum Result { case response(NetResponse), error(NetError) } public enum AsyncBehavior: Equatable { case immediate(DispatchQueue?), delayed(DispatchQueue?, DispatchTimeInterval) } public static var shared: Net = NetStub() var requestInterceptors = [InterceptorToken: RequestInterceptor]() var responseInterceptors = [InterceptorToken: ResponseInterceptor]() open var retryClosure: NetTask.RetryClosure? open var acceptableStatusCodes = defaultAcceptableStatusCodes open var nextResult: Result? open var asyncBehavior: AsyncBehavior public init(_ nextResult: Result? = nil, _ asyncBehavior: AsyncBehavior = .immediate(nil)) { self.nextResult = nextResult self.asyncBehavior = asyncBehavior } @discardableResult open func addRequestInterceptor(_ interceptor: @escaping RequestInterceptor) -> InterceptorToken { let token = InterceptorToken() requestInterceptors[token] = interceptor return token } @discardableResult open func addResponseInterceptor(_ interceptor: @escaping ResponseInterceptor) -> InterceptorToken { let token = InterceptorToken() responseInterceptors[token] = interceptor return token } @discardableResult open func removeInterceptor(_ token: InterceptorToken) -> Bool { guard requestInterceptors.removeValue(forKey: token) != nil else { return responseInterceptors.removeValue(forKey: token) != nil } return true } func stub(_ request: NetRequest? = nil) -> NetTask { var requestBuilder = request?.builder() if var builder = requestBuilder { requestInterceptors.values.forEach { interceptor in builder = interceptor(builder) } requestBuilder = builder } guard let nextResult = nextResult else { switch asyncBehavior { case .immediate(let queue): return NetTaskStub(request: requestBuilder?.build(), queue: queue) case .delayed(let queue, let delay): return NetTaskStub(request: requestBuilder?.build(), queue: queue, delay: delay) } } switch nextResult { case .response(let response): var responseBuilder = response.builder() responseInterceptors.values.forEach { interceptor in responseBuilder = interceptor(responseBuilder) } switch asyncBehavior { case .immediate(let queue): return NetTaskStub(request: requestBuilder?.build(), response: responseBuilder.build(), queue: queue) case .delayed(let queue, let delay): return NetTaskStub(request: requestBuilder?.build(), response: responseBuilder.build(), queue: queue, delay: delay) } case .error(let error): var retryCount: UInt = 0 while retryClosure?(nil, error, retryCount) == true { retryCount += 1 } switch asyncBehavior { case .immediate(let queue): return NetTaskStub(request: requestBuilder?.build(), error: error, retryCount: retryCount, queue: queue) case .delayed(let queue, let delay): return NetTaskStub(request: requestBuilder?.build(), error: error, retryCount: retryCount, queue: queue, delay: delay) } } } open func data(_ request: NetRequest) -> NetTask { return stub(request) } open func download(_ resumeData: Data) -> NetTask { return stub() } open func download(_ request: NetRequest) -> NetTask { return stub(request) } open func upload(_ streamedRequest: NetRequest) -> NetTask { return stub(streamedRequest) } open func upload(_ request: NetRequest, data: Data) -> NetTask { return stub(request) } open func upload(_ request: NetRequest, fileURL: URL) -> NetTask { return stub(request) } #if !os(watchOS) @available(iOS 9.0, macOS 10.11, *) open func stream(_ netService: NetService) -> NetTask { return stub() } @available(iOS 9.0, macOS 10.11, *) open func stream(_ domain: String, type: String, name: String, port: Int32?) -> NetTask { return stub() } @available(iOS 9.0, macOS 10.11, *) open func stream(_ hostName: String, port: Int) -> NetTask { return stub() } #endif }
mit
b0baf60f465df04b888ddb28c70a3f60
32.042553
134
0.623524
4.858186
false
false
false
false
cuzv/PullToRefresh
Sources/RefreshContainerView.swift
2
11004
// // RefreshContainerView.swift // PullToRefresh // // Created by Shaw on 6/21/15. // Copyright © 2015 ReadRain. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //////////////////////////////////////////////////////// // // Copyright (c) 2014, Beamly // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Beamly nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL BEAMLY BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import UIKit // MARK: - Const public let DefaultResetContentInsetAnimationDuration: TimeInterval = 0.3 // MARK: - RefreshContainerViewState @objc public enum RefreshContainerViewState: Int { case none = 0 case triggered case loading } @objc public enum PullToRefreshType: Int { case loosenRefresh case infiniteScroll } // MARK: - RefreshContainerViewDelegate @objc public protocol RefreshContainerViewDelegate { @objc optional func refreshContainerView(_ containerView: RefreshContainerView, didChangeState state: RefreshContainerViewState) -> Void @objc optional func refreshContainerView(_ containerView: RefreshContainerView, didChangeTriggerStateProgress progress: CGFloat) -> Void } // MARK: - RefreshContainerViewSubclassDelegate @objc internal protocol RefreshContainerViewSubclassDelegate { func resetFrame() -> Void func didSetEnable(_ enable: Bool) -> Void func observeValue(forContentInset inset: UIEdgeInsets) -> Void func scrollViewDidScroll(toContentOffSet offSet: CGPoint) -> Void func beginRefreshing() -> Void func endRefreshing() -> Void } // MARK: - RefreshActionHandler public typealias RefreshActionHandler = ((_ scrollView: UIScrollView) -> Void) // MARK: - RefreshContainerView open class RefreshContainerView: UIView { open var state: RefreshContainerViewState = .none open weak var delegate: RefreshContainerViewDelegate? open var actionHandler: RefreshActionHandler? open var preserveContentInset: Bool = false { didSet { if bounds.size.height > 0.0 { subclass.resetFrame() } } } open var enable: Bool = true { didSet { if enable == oldValue { return } if enable { subclass.resetFrame() } else { subclass.endRefreshing() } subclass.didSetEnable(enable) } } internal unowned let scrollView: UIScrollView internal var externalContentInset: UIEdgeInsets internal var updatingScrollViewContentInset: Bool = false internal let pullToRefreshType: PullToRefreshType private weak var subclass: RefreshContainerViewSubclassDelegate! // MARK: Initializers public init(height: CGFloat, scrollView: UIScrollView, pullToRefreshType: PullToRefreshType) { externalContentInset = scrollView.contentInset self.scrollView = scrollView self.pullToRefreshType = pullToRefreshType let frame = CGRect(x: 0, y: 0, width: 0, height: height) super.init(frame: frame) subclass = self as? RefreshContainerViewSubclassDelegate assert(nil != subclass, "Self's Subclasses must conformsToProtocol `RefreshContainerViewSubclassDelegate`") autoresizingMask = .flexibleWidth subclass.resetFrame() } override init(frame: CGRect) { fatalError("init(frame:) has not been implemented, use init(height:scrollView)") } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented, use init(height:scrollView)") } #if DEBUG deinit { debugPrint("\(#file):\(#line):\(type(of: self)):\(#function)") } #endif // MARK: - Internal internal func changeState(_ state: RefreshContainerViewState) -> Void { if self.state == state { return } self.state = state delegate?.refreshContainerView?(self, didChangeState: state) } // MARK: UIScrollView internal func resetScrollViewContentInsetWithCompletion(_ completion: ((_ finished: Bool) -> Void)?) { resetScrollViewContentInsetWithCompletion(completion, animated: true) } internal func resetScrollViewContentInsetWithCompletion(_ completion: ((_ finished: Bool) -> Void)?, animated: Bool) { if animated { let options: UIView.AnimationOptions = [.allowUserInteraction, .beginFromCurrentState] UIView.animate(withDuration: DefaultResetContentInsetAnimationDuration, delay: 0, options: options, animations: { self.setScrollViewContentInset(self.externalContentInset) }, completion: completion) } else { setScrollViewContentInset(self.externalContentInset) completion?(true) } } internal func setScrollViewContentInset(_ inset: UIEdgeInsets) -> Void { let alreadyUpdating = updatingScrollViewContentInset if !alreadyUpdating { updatingScrollViewContentInset = true } scrollView.contentInset = inset if !alreadyUpdating { updatingScrollViewContentInset = false } } internal func setScrollViewContentInset(_ inset: UIEdgeInsets, forLoadingAnimated animated: Bool, completion: ((_ finished: Bool) -> Void)?) -> Void { let updateClosure: () -> Void = { () -> Void in self.setScrollViewContentInset(inset) } if animated { let options: AnimationOptions = [.allowUserInteraction, .beginFromCurrentState] UIView.animate(withDuration: DefaultResetContentInsetAnimationDuration, delay: 0, options: options, animations: updateClosure, completion: completion) } else { UIView.performWithoutAnimation(updateClosure) if nil != completion { completion?(true) } } } // MARK: Observing open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if let superview = superview { removeObserversFromView(superview) } if let newSuperview = newSuperview { addScrollViewObservers(newSuperview) } } private func removeObserversFromView(_ view: UIView) -> Void { assert(nil != view as? UIScrollView, "Self's superview must be kind of `UIScrollView`") view.removeObserver(self, forKeyPath: "contentOffset") view.removeObserver(self, forKeyPath: "contentSize") view.removeObserver(self, forKeyPath: "frame") view.removeObserver(self, forKeyPath: "contentInset") } private func addScrollViewObservers(_ view: UIView) -> Void { assert(nil != view as? UIScrollView, "Self's superview must be kind of `UIScrollView`") view.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) view.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil) view.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil) view.addObserver(self, forKeyPath: "contentInset", options: NSKeyValueObservingOptions.new, context: nil) } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if !enable { return } // let value = change?[NSKeyValueChangeNewKey] // debugPrint("\(keyPath): \(value)") if keyPath == "contentOffset" { guard let offSet = ((change?[NSKeyValueChangeKey.newKey]) as AnyObject).cgPointValue else { return } subclass.scrollViewDidScroll(toContentOffSet: offSet) } else if keyPath == "contentSize" { layoutSubviews() subclass.resetFrame() } else if keyPath == "frame" { layoutSubviews() } else if keyPath == "contentInset" { if !updatingScrollViewContentInset { guard let contentInset = ((change?[NSKeyValueChangeKey.newKey]) as AnyObject).uiEdgeInsetsValue else { return } subclass.observeValue(forContentInset: contentInset) } } } }
mit
3820e7cfffc551cdbabecb0ded4092ff
38.437276
162
0.667
5.25956
false
false
false
false
thapapratyush/TipSome
Tipsome/ViewController.swift
1
1155
// // ViewController.swift // Tipsome // // Created by Aarya BC on 1/1/17. // Copyright © 2017 Pratyush Thapa. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: AnyObject) { let tipPercent = [0.13, 0.18, 0.20, 0.25] let bill = Double(billField.text!) ?? 0 let tip = bill * tipPercent[tipControl.selectedSegmentIndex] let total = bill + tip tipLabel.text=String(format:"$%.2f", tip) totalLabel.text=String(format:"$%.2f", total) } }
apache-2.0
d55cdb893478e23f14d96c45bf2982df
25.837209
80
0.637782
4.227106
false
false
false
false
brentsimmons/Evergreen
Widget/Widget Views/TodayWidget.swift
1
3015
// // TodayWidget.swift // NetNewsWire Widget Extension // // Created by Stuart Breckenridge on 18/11/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import WidgetKit import SwiftUI struct TodayWidgetView : View { @Environment(\.widgetFamily) var family: WidgetFamily @Environment(\.sizeCategory) var sizeCategory: ContentSizeCategory var entry: Provider.Entry var body: some View { if entry.widgetData.todayArticles.count == 0 { inboxZero .widgetURL(WidgetDeepLink.today.url) } else { GeometryReader { metrics in HStack { VStack { todayImage .padding(.vertical, 12) .padding(.leading, 8) Spacer() } } .frame(width: metrics.size.width * 0.15) Spacer() VStack(alignment:.leading, spacing: 0) { ForEach(0..<maxCount(), content: { i in if i != 0 { Divider() ArticleItemView(article: entry.widgetData.todayArticles[i], deepLink: WidgetDeepLink.todayArticle(id: entry.widgetData.todayArticles[i].id).url) .padding(.top, 8) .padding(.bottom, 4) } else { ArticleItemView(article: entry.widgetData.todayArticles[i], deepLink: WidgetDeepLink.todayArticle(id: entry.widgetData.todayArticles[i].id).url) .padding(.bottom, 4) } }) Spacer() } .padding(.leading, metrics.size.width * 0.175) .padding([.bottom, .trailing]) .padding(.top, 12) .overlay( VStack { Spacer() HStack { Spacer() if entry.widgetData.currentTodayCount - maxCount() > 0 { Text(L10n.todayCount(entry.widgetData.currentTodayCount - maxCount())) .font(.caption2) .bold() .foregroundColor(.secondary) } } } .padding(.horizontal) .padding(.bottom, 6) ) }.widgetURL(WidgetDeepLink.today.url) } } var todayImage: some View { Image(systemName: "sun.max.fill") .resizable() .frame(width: 30, height: 30, alignment: .center) .cornerRadius(4) .foregroundColor(.orange) } func maxCount() -> Int { var reduceAccessibilityCount: Int = 0 if SizeCategories().isSizeCategoryLarge(category: sizeCategory) { reduceAccessibilityCount = 1 } if family == .systemLarge { return entry.widgetData.todayArticles.count >= 7 ? (7 - reduceAccessibilityCount) : entry.widgetData.todayArticles.count } return entry.widgetData.todayArticles.count >= 3 ? (3 - reduceAccessibilityCount) : entry.widgetData.todayArticles.count } var inboxZero: some View { VStack(alignment: .center) { Spacer() Image(systemName: "sun.max.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 30) .foregroundColor(.orange) Text(L10n.todayWidgetNoItemsTitle) .font(.headline) .foregroundColor(.primary) Text(L10n.todayWidgetNoItems) .font(.caption) .foregroundColor(.gray) Spacer() } .multilineTextAlignment(.center) .padding() } }
mit
4c2814e96afc0fafd800416b28072cec
23.704918
123
0.642336
3.436716
false
false
false
false
bazelbuild/tulsi
src/TulsiGenerator/ProcessRunner.swift
1
13030
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Darwin import Foundation /// Encapsulates functionality to launch and manage Processes. public final class ProcessRunner { /// Information retrieved through execution of a process. public struct CompletionInfo { /// The process that was executed. public let process: Process /// The commandline that was executed, suitable for pasting in terminal to reproduce. public let commandlineString: String /// The process's standard output. public let stdout: Data /// The process's standard error. public let stderr: Data /// The exit status for the process. public var terminationStatus: Int32 { return process.terminationStatus } } /// Coordinates logging with Process lifetime to accurately report when a given process started. final class TimedProcessRunnerObserver: NSObject { /// Observer for KVO on the process. private var processObserver: NSKeyValueObservation? /// Mapping between Processes and LogSessionHandles created for each. /// /// - Warning: Do not access directly; use `accessPendingLogHandles` instead. /// - SeeAlso: `accessPendingLogHandles` private var pendingLogHandles = Dictionary<Process, LocalizedMessageLogger.LogSessionHandle>() /// Lock to serialize access to `pendingLogHandles`. /// /// We use `os_unfair_lock` because it is efficient when contention is rare, which should be /// the case in this situation. private var pendingLogHandlesLock = os_unfair_lock() /// Provides thread-safe access to `pendingLogHandles`. /// /// We need to access `pendingLogHandles` in a thread-safe way because /// `TimedProcessRunnerObserver` can be used concurrently by multiple threads. /// /// - Parameter usePendingLogHandles: The critical section that reads from or writes to /// `pendingLogHandles`. Minimize the code in the critical /// section to avoid unnecessary lock contention. private func accessPendingLogHandles<T>(usePendingLogHandles: (inout Dictionary<Process, LocalizedMessageLogger.LogSessionHandle>) throws -> T) rethrows -> T { os_unfair_lock_lock(&pendingLogHandlesLock) defer { os_unfair_lock_unlock(&pendingLogHandlesLock) } return try usePendingLogHandles(&pendingLogHandles) } /// Start logging the given Process with KVO to determine the time when it starts running. fileprivate func startLoggingProcessTime(process: Process, loggingIdentifier: String, messageLogger: LocalizedMessageLogger) { let logSessionHandle = messageLogger.startProfiling(loggingIdentifier) accessPendingLogHandles { pendingLogHandles in pendingLogHandles[process] = logSessionHandle } processObserver = process.observe(\.isRunning, options: .new) { [unowned self] process, change in guard change.newValue == true else { return } self.accessPendingLogHandles { pendingLogHandles in pendingLogHandles[process]?.resetStartTime() } } } /// Report the time this process has taken, and cleanup its logging handle and KVO observer. fileprivate func stopLogging(process: Process, messageLogger: LocalizedMessageLogger) { if let logHandle = self.pendingLogHandles[process] { messageLogger.logProfilingEnd(logHandle) processObserver?.invalidate() accessPendingLogHandles { pendingLogHandles in _ = pendingLogHandles.removeValue(forKey: process) } } } } public typealias CompletionHandler = (CompletionInfo) -> Void private static var defaultInstance: ProcessRunner = { ProcessRunner() }() /// The outstanding processes. private var pendingProcesses = Set<Process>() private let processReader: ProcessOutputReader /// Handle KVO around processes to determine when a process starts running. private let timedProcessRunnerObserver = TimedProcessRunnerObserver() /// Prepares a Process using the given launch binary with the given arguments that will collect /// output and passing it to a terminationHandler. static func createProcess(_ launchPath: String, arguments: [String], environment: [String: String]? = nil, messageLogger: LocalizedMessageLogger? = nil, loggingIdentifier: String? = nil, terminationHandler: @escaping CompletionHandler) -> Process { return defaultInstance.createProcess(launchPath, arguments: arguments, environment: environment, messageLogger: messageLogger, loggingIdentifier: loggingIdentifier, terminationHandler: terminationHandler) } /// Creates and launches a Process using the given launch binary with the given arguments that /// will run synchronously to completion and return a CompletionInfo. static func launchProcessSync(_ launchPath: String, arguments: [String], environment: [String: String]? = nil, messageLogger: LocalizedMessageLogger? = nil, loggingIdentifier: String? = nil, currentDirectoryURL: URL? = nil ) -> CompletionInfo { let semaphore = DispatchSemaphore(value: 0) var completionInfo: CompletionInfo! = nil let process = defaultInstance.createProcess(launchPath, arguments: arguments, environment: environment, messageLogger: messageLogger, loggingIdentifier: loggingIdentifier) { processCompletionInfo in completionInfo = processCompletionInfo semaphore.signal() } if currentDirectoryURL != nil { process.currentDirectoryURL = currentDirectoryURL } process.launch() _ = semaphore.wait(timeout: DispatchTime.distantFuture) return completionInfo } // MARK: - Private methods private init() { processReader = ProcessOutputReader() processReader.start() } deinit { processReader.stop() } private func createProcess(_ launchPath: String, arguments: [String], environment: [String: String]? = nil, messageLogger: LocalizedMessageLogger? = nil, loggingIdentifier: String? = nil, terminationHandler: @escaping CompletionHandler) -> Process { let process = Process() process.launchPath = launchPath process.arguments = arguments if let environment = environment { process.environment = environment } // Construct a string suitable for cutting and pasting into the commandline. let commandlineArguments = arguments.map { $0.escapingForShell }.joined(separator: " ") let commandlineRunnableString = "\(launchPath.escapingForShell) \(commandlineArguments)" // If the localizedMessageLogger was passed as an arg, start logging the runtime of the process. if let messageLogger = messageLogger { timedProcessRunnerObserver.startLoggingProcessTime(process: process, loggingIdentifier: (loggingIdentifier ?? launchPath), messageLogger: messageLogger) messageLogger.infoMessage("Running \(commandlineRunnableString)") } let dispatchGroup = DispatchGroup() let notificationCenter = NotificationCenter.default func registerAndStartReader(_ fileHandle: FileHandle, outputData: NSMutableData) -> NSObjectProtocol { let observer = notificationCenter.addObserver(forName: NSNotification.Name.NSFileHandleReadToEndOfFileCompletion, object: fileHandle, queue: nil) { (notification: Notification) in defer { dispatchGroup.leave() } if let err = notification.userInfo?["NSFileHandleError"] as? NSNumber { assertionFailure("Read from pipe failed with error \(err)") } guard let data = notification.userInfo?[NSFileHandleNotificationDataItem] as? Data else { assertionFailure("Unexpectedly received no data in read handler") return } outputData.append(data) } dispatchGroup.enter() // The docs for readToEndOfFileInBackgroundAndNotify are unclear as to exactly what work is // done on the calling thread. By observation, it appears that data will not be read if the // main queue is in event tracking mode. let selector = #selector(FileHandle.readToEndOfFileInBackgroundAndNotify as (FileHandle) -> () -> Void) fileHandle.perform(selector, on: processReader.thread, with: nil, waitUntilDone: true) return observer } let stdoutData = NSMutableData() process.standardOutput = Pipe() let stdoutObserver = registerAndStartReader((process.standardOutput! as AnyObject).fileHandleForReading, outputData: stdoutData) let stderrData = NSMutableData() process.standardError = Pipe() let stderrObserver = registerAndStartReader((process.standardError! as AnyObject).fileHandleForReading, outputData: stderrData) process.terminationHandler = { (process: Process) -> Void in // The termination handler's thread is used to allow the caller's callback to do off-main work // as well. assert(!Thread.isMainThread, "Process termination handler unexpectedly called on main thread.") _ = dispatchGroup.wait(timeout: DispatchTime.distantFuture) // If the localizedMessageLogger was an arg, report total runtime of this process + cleanup. if let messageLogger = messageLogger { self.timedProcessRunnerObserver.stopLogging(process: process, messageLogger: messageLogger) } terminationHandler(CompletionInfo(process: process, commandlineString: commandlineRunnableString, stdout: stdoutData as Data, stderr: stderrData as Data)) Thread.doOnMainQueue { notificationCenter.removeObserver(stdoutObserver) notificationCenter.removeObserver(stderrObserver) assert(self.pendingProcesses.contains(process), "terminationHandler called with unexpected process") self.pendingProcesses.remove(process) } } Thread.doOnMainQueue { self.pendingProcesses.insert(process) } return process } // MARK: - ProcessOutputReader // Provides a thread/runloop that may be used to read Process output pipes. private class ProcessOutputReader: NSObject { lazy var thread: Thread = { [unowned self] in let value = Thread(target: self, selector: #selector(threadMain(_:)), object: nil) value.name = "com.google.Tulsi.ProcessOutputReader" return value }() private var continueRunning = false func start() { assert(!thread.isExecuting, "Start called twice without a stop") thread.start() } func stop() { perform(#selector(ProcessOutputReader.stopThread), on:thread, with:nil, waitUntilDone: false) } // MARK: - Private methods @objc private func threadMain(_ object: AnyObject) { let runLoop = RunLoop.current // Add a dummy port to prevent the runloop from returning immediately. runLoop.add(NSMachPort(), forMode: RunLoop.Mode.default) while !thread.isCancelled { runLoop.run(mode: RunLoop.Mode.default, before: Date.distantFuture) } } @objc private func stopThread() { thread.cancel() } } }
apache-2.0
489d56018a1da89a46098227add5167a
41.305195
163
0.642287
5.523527
false
false
false
false
niklassaers/PackStream-Swift
Sources/PackStream/String.swift
1
6827
import Foundation extension String: PackProtocol { struct Constants { static let shortStringMinMarker: Byte = 0x80 static let shortStringMaxMarker: Byte = 0x8F static let eightBitByteMarker: Byte = 0xD0 static let sixteenBitByteMarker: Byte = 0xD1 static let thirtytwoBitByteMarker: Byte = 0xD2 } public func pack() throws -> [Byte] { guard let data = self.data(using: .utf8, allowLossyConversion: false) else { throw PackError.notPackable } var bytes = [Byte]() data.withUnsafeBytes { (p: UnsafeRawBufferPointer) -> Void in for byte in p { bytes.append(byte) } } let n = UInt(bytes.count) if n == 0 { return [ 0x80 ] } else if n <= 15 { return try packShortString(bytes) } else if n <= 255 { return try pack8BitString(bytes) } else if n <= 65535 { return try pack16BitString(bytes) } else if n <= 4294967295 as UInt { return try pack32BitString(bytes) } throw PackError.notPackable } private func packShortString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.shortStringMinMarker + UInt8(bytes.count) return [marker] + bytes } private func pack8BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.eightBitByteMarker return [marker, UInt8(bytes.count) ] + bytes } private func pack16BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.sixteenBitByteMarker let size = try UInt16(bytes.count).pack()[0...1] return [marker] + size + bytes } private func pack32BitString(_ bytes: [Byte]) throws -> [Byte] { let marker = Constants.thirtytwoBitByteMarker let size = try UInt32(bytes.count).pack()[0...3] return [marker] + size + bytes } public static func unpack(_ bytes: ArraySlice<Byte>) throws -> String { if bytes.count == 0 { return "" } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return try unpackShortString(bytes) case Constants.eightBitByteMarker: return try unpack8BitString(bytes) case Constants.sixteenBitByteMarker: return try unpack16BitString(bytes) case Constants.thirtytwoBitByteMarker: return try unpack32BitString(bytes) default: throw UnpackError.unexpectedByteMarker } } static func markerSizeFor(bytes: ArraySlice<Byte>) throws -> Int { if bytes.count == 0 { return 0 } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return 1 case Constants.eightBitByteMarker: return 2 case Constants.sixteenBitByteMarker: return 3 case Constants.thirtytwoBitByteMarker: return 5 default: throw UnpackError.unexpectedByteMarker } } static func sizeFor(bytes: ArraySlice<Byte>) throws -> Int { if bytes.count == 0 { return 0 } guard let firstByte = bytes.first else { throw UnpackError.incorrectNumberOfBytes } let bytes = Array(bytes) switch firstByte { case Constants.shortStringMinMarker...Constants.shortStringMaxMarker: return Int(firstByte) - Int(Constants.shortStringMinMarker) case Constants.eightBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 2 return Int(try UInt8.unpack(bytes[start..<end])) case Constants.sixteenBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 3 return Int(try UInt16.unpack(bytes[start..<end])) case Constants.thirtytwoBitByteMarker: let start = bytes.startIndex + 1 let end = bytes.startIndex + 5 return Int(try UInt32.unpack(bytes[start..<end])) default: throw UnpackError.unexpectedByteMarker } } private static func unpackShortString(_ bytes: ArraySlice<Byte>) throws -> String { let size = bytes[bytes.startIndex] - Constants.shortStringMinMarker let start = bytes.startIndex + 1 if bytes.count != Int(size) + 1 { let alt = try bytesToString(Array(bytes[start..<bytes.endIndex])) print("Found \(alt)") throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } let end = bytes.endIndex return try bytesToString(Array(bytes[start..<end])) } private static func bytesToString(_ bytes: [Byte]) throws -> String { let data = Data(bytes) guard let string = String(data: data, encoding: .utf8) else { throw UnpackError.incorrectValue } return string } private static func unpack8BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 2 let size = try UInt8.unpack(bytes[start..<end]) if bytes.count != Int(size) + 2 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 2)..<bytes.endIndex])) } private static func unpack16BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 3 let size = try UInt16.unpack(bytes[start..<end]) if bytes.count != Int(size) + 3 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 3)..<bytes.endIndex])) } private static func unpack32BitString(_ bytes: ArraySlice<Byte>) throws -> String { let start = bytes.startIndex + 1 let end = bytes.startIndex + 5 let size = try UInt32.unpack(bytes[start..<end]) if bytes.count != Int(size) + 5 { throw UnpackError.incorrectNumberOfBytes } if size == 0 { return "" } return try bytesToString(Array(bytes[(bytes.startIndex + 5)..<bytes.endIndex])) } }
bsd-3-clause
d76f6aff551e8cb01b3641c8310e698b
28.812227
87
0.589424
4.521192
false
false
false
false
egnwd/ic-bill-hack
quick-split/Pods/Alamofire/Source/Request.swift
71
20129
// Request.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`. */ public class Request { // MARK: - Properties /// The delegate for the underlying task. public let delegate: TaskDelegate /// The underlying task. public var task: NSURLSessionTask { return delegate.task } /// The session belonging to the underlying task. public let session: NSURLSession /// The request sent or to be sent to the server. public var request: NSURLRequest? { return task.originalRequest } /// The response received from the server, if any. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } /// The progress of the request lifecycle. public var progress: NSProgress { return delegate.progress } var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? // MARK: - Lifecycle init(session: NSURLSession, task: NSURLSessionTask) { self.session = session switch task { case is NSURLSessionUploadTask: delegate = UploadTaskDelegate(task: task) case is NSURLSessionDataTask: delegate = DataTaskDelegate(task: task) case is NSURLSessionDownloadTask: delegate = DownloadTaskDelegate(task: task) default: delegate = TaskDelegate(task: task) } delegate.queue.addOperationWithBlock { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: - Authentication /** Associates an HTTP Basic credential with the request. - parameter user: The user. - parameter password: The password. - parameter persistence: The URL credential persistence. `.ForSession` by default. - returns: The request. */ public func authenticate( user user: String, password: String, persistence: NSURLCredentialPersistence = .ForSession) -> Self { let credential = NSURLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /** Associates a specified credential with the request. - parameter credential: The credential. - returns: The request. */ public func authenticate(usingCredential credential: NSURLCredential) -> Self { delegate.credential = credential return self } // MARK: - Progress /** Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write. - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read. - parameter closure: The code to be executed periodically during the lifecycle of the request. - returns: The request. */ public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { if let uploadDelegate = delegate as? UploadTaskDelegate { uploadDelegate.uploadProgress = closure } else if let dataDelegate = delegate as? DataTaskDelegate { dataDelegate.dataProgress = closure } else if let downloadDelegate = delegate as? DownloadTaskDelegate { downloadDelegate.downloadProgress = closure } return self } /** Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. This closure returns the bytes most recently received from the server, not including data from previous calls. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`. - parameter closure: The code to be executed periodically during the lifecycle of the request. - returns: The request. */ public func stream(closure: (NSData -> Void)? = nil) -> Self { if let dataDelegate = delegate as? DataTaskDelegate { dataDelegate.dataStream = closure } return self } // MARK: - State /** Resumes the request. */ public func resume() { if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidResume, object: task) } /** Suspends the request. */ public func suspend() { task.suspend() NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidSuspend, object: task) } /** Cancels the request. */ public func cancel() { if let downloadDelegate = delegate as? DownloadTaskDelegate, downloadTask = downloadDelegate.downloadTask { downloadTask.cancelByProducingResumeData { data in downloadDelegate.resumeData = data } } else { task.cancel() } NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidCancel, object: task) } // MARK: - TaskDelegate /** The task delegate is responsible for handling all delegate callbacks for the underlying task as well as executing all operations attached to the serial operation queue upon task completion. */ public class TaskDelegate: NSObject { /// The serial operation queue used to execute all operations after the task completes. public let queue: NSOperationQueue let task: NSURLSessionTask let progress: NSProgress var data: NSData? { return nil } var error: NSError? var initialResponseTime: CFAbsoluteTime? var credential: NSURLCredential? init(task: NSURLSessionTask) { self.task = task self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true if #available(OSX 10.10, *) { operationQueue.qualityOfService = NSQualityOfService.Utility } return operationQueue }() } deinit { queue.cancelAllOperations() queue.suspended = false } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest?) -> Void)) { var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } else { if challenge.previousFailureCount > 0 { disposition = .CancelAuthenticationChallenge } else { credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) if credential != nil { disposition = .UseCredential } } } completionHandler(disposition, credential) } func URLSession( session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) { var bodyStream: NSInputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { self.error = error if let downloadDelegate = self as? DownloadTaskDelegate, userInfo = error.userInfo as? [String: AnyObject], resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData { downloadDelegate.resumeData = resumeData } } queue.suspended = false } } } // MARK: - DataTaskDelegate class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } private var totalBytesReceived: Int64 = 0 private var mutableData: NSMutableData override var data: NSData? { if dataStream != nil { return nil } else { return mutableData } } private var expectedContentLength: Int64? private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? private var dataStream: ((data: NSData) -> Void)? override init(task: NSURLSessionTask) { mutableData = NSMutableData() super.init(task: task) } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? // MARK: Delegate Methods func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data: data) } else { mutableData.appendData(data) } totalBytesReceived += data.length let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived dataProgress?( bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpected ) } } func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse?) -> Void)) { var cachedResponse: NSCachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /** The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received. */ public var description: String { var components: [String] = [] if let HTTPMethod = request?.HTTPMethod { components.append(HTTPMethod) } if let URLString = request?.URL?.absoluteString { components.append(URLString) } if let response = response { components.append("(\(response.statusCode))") } return components.joinWithSeparator(" ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, URL = request.URL, host = URL.host else { return "$ curl command could not be created" } if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" { components.append("-X \(HTTPMethod)") } if let credentialStorage = self.session.configuration.URLCredentialStorage { let protectionSpace = NSURLProtectionSpace( host: host, port: URL.port?.integerValue ?? 0, `protocol`: URL.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.HTTPShouldSetCookies { if let cookieStorage = session.configuration.HTTPCookieStorage, cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" } components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"") } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields { switch field { case "Cookie": continue default: components.append("-H \"\(field): \(value)\"") } } } if let additionalHeaders = session.configuration.HTTPAdditionalHeaders { for (field, value) in additionalHeaders { switch field { case "Cookie": continue default: components.append("-H \"\(field): \(value)\"") } } } if let HTTPBodyData = request.HTTPBody, HTTPBody = String(data: HTTPBodyData, encoding: NSUTF8StringEncoding) { let escapedBody = HTTPBody.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(URL.absoluteString)\"") return components.joinWithSeparator(" \\\n\t") } /// The textual representation used when written to an output stream, in the form of a cURL command. public var debugDescription: String { return cURLRepresentation() } }
mit
e58480718e865063db58bdbfd60a27a4
35.461957
162
0.619914
6.37132
false
false
false
false
SpectralDragon/LightRoute
Sources/TransitionNodes/CloseTransitionNode.swift
1
6919
// // CloseTransitionNode.swift // LiteRoute // // Copyright © 2016-2020 Vladislav Prusakov <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit /// Responds style how controller will be close. public enum CloseTransitionStyle { /// Make default dismiss controller action. case `default` /// Make custom navigation controller close action. case navigation(style: NavigationStyle) /// Responds transition case how navigation controller will be close. public enum NavigationStyle { /// Make pop to view controller for you controller. case pop(to: UIViewController) /// Make default pop on one controller back. case simplePop /// Make pop to root action. case toRoot /// Return you to finded controller in navigation stack. /// - Note: Fot this style, you should be complete method `find(pop:)` case findedPop } } public final class CloseTransitionNode { // Main transition data. internal unowned var root: UIViewController /// Shows animated this transition or not. public var isAnimated: Bool { return animated } // MARK: Private /// Set and get current transition animate state. internal var animated: Bool = true /// Wait transition post action. internal var postLinkAction: TransitionPostLinkAction? internal var findPopController: UIViewController? // MARK: - // MARK: Initialize /// /// Initialize transition node for current transition. /// /// - Parameters: /// - root: The root view controller. /// - destination: The view controller at which the jump occurs. /// - type: The argument which checks the specified type and controller type for compatibility, and returns this type in case of success. /// init(root: UIViewController) { self.root = root } /// /// This method find controller in navigation stack, for popToViewController method. /// /// - Note: You should be call CloseTransitionNavigationStyle.findedPop for complete this action. /// /// - Parameter completionHandler: /// - Returns: Return current transition context. /// - Throws: Throw error, if parent view controller not navigation controller. /// public func find(pop completionHandler: (UIViewController) -> Bool) throws -> CloseTransitionNode { guard let parent = root.parent, let navigationController = parent as? UINavigationController else { throw LiteRouteError.viewControllerWasNil("Navigation") } self.findPopController = navigationController.children.first(where: completionHandler) return self } /// /// This method select preffered transition close style. /// /// - Parameter style: Set preffered style to close. /// - Returns: Return current transition node /// - Throws: Throw error, if root or navigation controllers was nil. /// public func preferred(style: CloseTransitionStyle) throws -> CloseTransitionNode { // Remove old link action self.postLinkAction = nil self.postLinkAction { [weak self] in guard let root = self?.root, let animated = self?.isAnimated else { throw LiteRouteError.viewControllerWasNil("Root") } switch style { case .navigation(style: let navStyle): guard let parent = root.parent, let navigationController = parent as? UINavigationController else { throw LiteRouteError.viewControllerWasNil("Navigation") } switch navStyle { case .pop(to: let controller): navigationController.popToViewController(controller, animated: animated) case .simplePop: if navigationController.children.count > 1 { guard let controller = navigationController.children.dropLast().last else { return } navigationController.popToViewController(controller, animated: animated) } else { throw LiteRouteError.customError("Can't do popToViewController(:animated), because childViewControllers < 1") } case .toRoot: navigationController.popToRootViewController(animated: animated) case .findedPop: guard let findedController = self?.findPopController else { throw LiteRouteError.customError("Finded controller can't be nil!") } navigationController.popToViewController(findedController, animated: animated) } case .default: root.dismiss(animated: animated, completion: nil) } } return self } /// /// This method perform close module. /// - Throws: Throw error, if something went wrong. /// public func perform() throws { try self.postLinkAction?() } /// /// Turn on or off animate for current transition. /// - Note: By default this transition is animated. /// /// - Parameter animate: Animate or not current transition ifneeded. /// public func transition(animate: Bool) -> CloseTransitionNode { self.animated = animate return self } // MARK: - // MARK: Private methods /// /// This method waits to be able to fire. /// - parameter completion: Whait push action from `TransitionPromise` class. /// func postLinkAction( _ completion: @escaping TransitionPostLinkAction) { self.postLinkAction = completion } }
mit
022a6478551d87cc4d50bd750448298a
37.010989
143
0.640648
5.205418
false
false
false
false
kosiara/swift-basic-example
FireLampades/FireLampades/AppDelegate.swift
1
4695
// // AppDelegate.swift // FireLampades // // Created by Bartosz Kosarzycki on 1/11/17. // Copyright © 2017 Bartosz Kosarzycki. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. // self.saveContext() } // MARK: - Core Data stack // // lazy var persistentContainer: NSPersistentContainer = { // /* // The persistent container for the application. This implementation // creates and returns a container, having loaded the store for the // application to it. This property is optional since there are legitimate // error conditions that could cause the creation of the store to fail. // */ // let container = NSPersistentContainer(name: "FireLampades") // container.loadPersistentStores(completionHandler: { (storeDescription, error) in // if let error = error as NSError? { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // // /* // Typical reasons for an error here include: // * The parent directory does not exist, cannot be created, or disallows writing. // * The persistent store is not accessible, due to permissions or data protection when the device is locked. // * The device is out of space. // * The store could not be migrated to the current model version. // Check the error message to determine what the actual problem was. // */ // fatalError("Unresolved error \(error), \(error.userInfo)") // } // }) // return container // }() // MARK: - Core Data Saving support // func saveContext () { // let context = persistentContainer.viewContext // if context.hasChanges { // do { // try context.save() // } catch { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // let nserror = error as NSError // fatalError("Unresolved error \(nserror), \(nserror.userInfo)") // } // } // } }
mit
7dac642ab0dd98602e103a1049c344c3
49.473118
285
0.675117
5.346241
false
false
false
false
MukeshKumarS/Swift
test/SILGen/statements.swift
1
18102
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -verify %s | FileCheck %s class MyClass { func foo() { } } func markUsed<T>(t: T) {} func marker_1() {} func marker_2() {} func marker_3() {} class BaseClass {} class DerivedClass : BaseClass {} var global_cond: Bool = false func bar(x: Int) {} func foo(x: Int, _ y: Bool) {} @noreturn func abort() { abort() } func assignment(x: Int, y: Int) { var x = x var y = y x = 42 y = 57 _ = x _ = y (x, y) = (1,2) } // CHECK-LABEL: sil hidden @{{.*}}assignment // CHECK: integer_literal $Builtin.Int2048, 42 // CHECK: assign // CHECK: integer_literal $Builtin.Int2048, 57 // CHECK: assign func if_test(x: Int, y: Bool) { if (y) { bar(x); } bar(x); } // CHECK-LABEL: sil hidden @_TF10statements7if_test func if_else(x: Int, y: Bool) { if (y) { bar(x); } else { foo(x, y); } bar(x); } // CHECK-LABEL: sil hidden @_TF10statements7if_else func nested_if(x: Int, y: Bool, z: Bool) { if (y) { if (z) { bar(x); } } else { if (z) { foo(x, y); } } bar(x); } // CHECK-LABEL: sil hidden @_TF10statements9nested_if func nested_if_merge_noret(x: Int, y: Bool, z: Bool) { if (y) { if (z) { bar(x); } } else { if (z) { foo(x, y); } } } // CHECK-LABEL: sil hidden @_TF10statements21nested_if_merge_noret func nested_if_merge_ret(x: Int, y: Bool, z: Bool) -> Int { if (y) { if (z) { bar(x); } return 1; } else { if (z) { foo(x, y); } } return 2; } // CHECK-LABEL: sil hidden @_TF10statements19nested_if_merge_ret func else_break(x: Int, y: Bool, z: Bool) { while z { if y { } else { break } } } // CHECK-LABEL: sil hidden @_TF10statements10else_break func loop_with_break(x: Int, _ y: Bool, _ z: Bool) -> Int { while (x > 2) { if (y) { bar(x); break; } } } // CHECK-LABEL: sil hidden @_TF10statements15loop_with_break func loop_with_continue(x: Int, y: Bool, z: Bool) -> Int { while (x > 2) { if (y) { bar(x); continue; } loop_with_break(x, y, z); } bar(x); } // CHECK-LABEL: sil hidden @_TF10statements18loop_with_continue func do_loop_with_continue(x: Int, y: Bool, z: Bool) -> Int { repeat { if (x < 42) { bar(x); continue; } loop_with_break(x, y, z); } while (x > 2); bar(x); } // CHECK-LABEL: sil hidden @_TF10statements21do_loop_with_continue // CHECK-LABEL: sil hidden @{{.*}}for_loops1 func for_loops1(x: Int, c: Bool) { var x = x for i in 1..<100 { markUsed(i) } for ; x < 40; { markUsed(x) x += 1 } for var i = 0; i < 100; ++i { } for let i = 0; i < 100; i { } } // CHECK-LABEL: sil hidden @{{.*}}for_loops2 func for_loops2() { // rdar://problem/19316670 // CHECK: [[NEXT:%[0-9]+]] = function_ref @_TFVs17IndexingGenerator4next // CHECK-NEXT: alloc_stack $Optional<MyClass> // CHECK-NEXT: apply [[NEXT]]<Array<MyClass>, // CHECK: class_method [[OBJ:%[0-9]+]] : $MyClass, #MyClass.foo!1 let objects = [MyClass(), MyClass() ] for obj in objects { obj.foo() } return } func void_return() { let b:Bool if b { return } } // CHECK-LABEL: sil hidden @_TF10statements11void_return // CHECK: cond_br {{%[0-9]+}}, [[BB1:bb[0-9]+]], [[BB2:bb[0-9]+]] // CHECK: [[BB1]]: // CHECK: br [[EPILOG:bb[0-9]+]] // CHECK: [[BB2]]: // CHECK: br [[EPILOG]] // CHECK: [[EPILOG]]: // CHECK: [[R:%[0-9]+]] = tuple () // CHECK: return [[R]] func foo() {} // <rdar://problem/13549626> // CHECK-LABEL: sil hidden @_TF10statements14return_from_if func return_from_if(a: Bool) -> Int { // CHECK: bb0(%0 : $Bool): // CHECK: cond_br {{.*}}, [[THEN:bb[0-9]+]], [[ELSE:bb[0-9]+]] if a { // CHECK: [[THEN]]: // CHECK: br [[EPILOG:bb[0-9]+]]({{%.*}}) return 1 } else { // CHECK: [[ELSE]]: // CHECK: br [[EPILOG]]({{%.*}}) return 0 } // CHECK-NOT: function_ref @foo // CHECK: [[EPILOG]]([[RET:%.*]] : $Int): // CHECK: return [[RET]] foo() // expected-warning {{will never be executed}} } class C {} func use(c: C) {} func for_each_loop(x: [C]) { for i in x { use(i) } _ = 0 } // CHECK-LABEL: sil hidden @{{.*}}test_break func test_break(i : Int) { switch i { case (let x) where x != 17: if x == 42 { break } markUsed(x) default: break } } // <rdar://problem/19150249> Allow labeled "break" from an "if" statement // CHECK-LABEL: sil hidden @_TF10statements13test_if_breakFGSqCS_1C_T_ func test_if_break(c : C?) { label1: // CHECK: switch_enum %0 : $Optional<C>, case #Optional.Some!enumelt.1: [[TRUE:bb[0-9]+]], default [[FALSE:bb[0-9]+]] if let x = c { // CHECK: [[TRUE]]({{.*}} : $C): // CHECK: apply foo() // CHECK: strong_release // CHECK: br [[FALSE:bb[0-9]+]] break label1 use(x) // expected-warning {{will never be executed}} } // CHECK: [[FALSE]]: // CHECK: return } // CHECK-LABEL: sil hidden @_TF10statements18test_if_else_breakFGSqCS_1C_T_ func test_if_else_break(c : C?) { label2: // CHECK: switch_enum %0 : $Optional<C>, case #Optional.Some!enumelt.1: [[TRUE:bb[0-9]+]], default [[FALSE:bb[0-9]+]] if let x = c { // CHECK: [[TRUE]]({{.*}} : $C): use(x) // CHECK: br [[CONT:bb[0-9]+]] } else { // CHECK: [[FALSE]]: // CHECK: apply // CHECK: br [[CONT]] foo() break label2 foo() // expected-warning {{will never be executed}} } // CHECK: [[CONT]]: // CHECK: return } // CHECK-LABEL: sil hidden @_TF10statements23test_if_else_then_breakFTSbGSqCS_1C__T_ func test_if_else_then_break(a : Bool, _ c : C?) { label3: // CHECK: switch_enum %1 : $Optional<C>, case #Optional.Some!enumelt.1: [[TRUE:bb[0-9]+]], default [[FALSE:bb[0-9]+]] if let x = c { // CHECK: [[TRUE]]({{.*}} : $C): use(x) // CHECK: br [[CONT:bb[0-9]+]] } else if a { // CHECK: [[FALSE]]: // CHECK: cond_br {{.*}}, [[TRUE2:bb[0-9]+]], [[FALSE2:bb[0-9]+]] // CHECK: apply // CHECK: br [[CONT]] foo() break label3 foo() // expected-warning {{will never be executed}} } // CHECK: [[FALSE2]]: // CHECK: br [[CONT]] // CHECK: [[CONT]]: // CHECK: return } // CHECK-LABEL: sil hidden @_TF10statements13test_if_breakFSbT_ func test_if_break(a : Bool) { // CHECK: br [[LOOP:bb[0-9]+]] // CHECK: [[LOOP]]: // CHECK: function_ref @_TFSb21_getBuiltinLogicValue // CHECK-NEXT: apply // CHECK-NEXT: cond_br {{.*}}, [[LOOPTRUE:bb[0-9]+]], [[OUT:bb[0-9]+]] while a { if a { foo() break // breaks out of while, not if. } foo() } // CHECK: [[LOOPTRUE]]: // CHECK: function_ref @_TFSb21_getBuiltinLogicValue // CHECK-NEXT: apply // CHECK-NEXT: cond_br {{.*}}, [[IFTRUE:bb[0-9]+]], [[IFFALSE:bb[0-9]+]] // [[IFTRUE]]: // CHECK: function_ref statements.foo // CHECK: br [[OUT]] // CHECK: [[IFFALSE]]: // CHECK: function_ref statements.foo // CHECK: br [[LOOP]] // CHECK: [[OUT]]: // CHECK: return } // CHECK-LABEL: sil hidden @_TF10statements7test_doFT_T_ func test_do() { // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: apply [[BAR]]( bar(0) // CHECK-NOT: br bb do { // CHECK: [[CTOR:%.*]] = function_ref @_TFC10statements7MyClassC // CHECK: [[OBJ:%.*]] = apply [[CTOR]]( let obj = MyClass() _ = obj // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 1 // CHECK: apply [[BAR]]( bar(1) // CHECK-NOT: br bb // CHECK: strong_release [[OBJ]] // CHECK-NOT: br bb } // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 2 // CHECK: apply [[BAR]]( bar(2) } // CHECK-LABEL: sil hidden @_TF10statements15test_do_labeledFT_T_ func test_do_labeled() { // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: apply [[BAR]]( bar(0) // CHECK: br bb1 // CHECK: bb1: lbl: do { // CHECK: [[CTOR:%.*]] = function_ref @_TFC10statements7MyClassC // CHECK: [[OBJ:%.*]] = apply [[CTOR]]( let obj = MyClass() _ = obj // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 1 // CHECK: apply [[BAR]]( bar(1) // CHECK: [[GLOBAL:%.*]] = function_ref @_TF10statementsau11global_condSb // CHECK: cond_br {{%.*}}, bb2, bb3 if (global_cond) { // CHECK: bb2: // CHECK: strong_release [[OBJ]] // CHECK: br bb1 continue lbl } // CHECK: bb3: // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 2 // CHECK: apply [[BAR]]( bar(2) // CHECK: [[GLOBAL:%.*]] = function_ref @_TF10statementsau11global_condSb // CHECK: cond_br {{%.*}}, bb4, bb5 if (global_cond) { // CHECK: bb4: // CHECK: strong_release [[OBJ]] // CHECK: br bb6 break lbl } // CHECK: bb5: // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 3 // CHECK: apply [[BAR]]( bar(3) // CHECK: strong_release [[OBJ]] // CHECK: br bb6 } // CHECK: [[BAR:%.*]] = function_ref @_TF10statements3barFSiT_ // CHECK: integer_literal $Builtin.Int2048, 4 // CHECK: apply [[BAR]]( bar(4) } func callee1() {} func callee2() {} func callee3() {} // CHECK-LABEL: sil hidden @_TF10statements11defer_test1FT_T_ func defer_test1() { defer { callee1() } defer { callee2() } callee3() // CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3FT_T_ // CHECK: apply [[C3]] // CHECK: [[C2:%.*]] = function_ref @{{.*}}_TFF10statements11defer_test1FT_T_L0_6$deferFT_T_ // CHECK: apply [[C2]] // CHECK: [[C1:%.*]] = function_ref @{{.*}}_TFF10statements11defer_test1FT_T_L_6$deferFT_T_ // CHECK: apply [[C1]] } // CHECK: sil shared @_TFF10statements11defer_test1FT_T_L_6$deferFT_T_ // CHECK: function_ref @{{.*}}callee1FT_T_ // CHECK: sil shared @_TFF10statements11defer_test1FT_T_L0_6$deferFT_T_ // CHECK: function_ref @{{.*}}callee2FT_T_ // CHECK-LABEL: sil hidden @_TF10statements11defer_test2FSbT_ func defer_test2(cond : Bool) { // CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3FT_T_ // CHECK: apply [[C3]] // CHECK: br [[LOOP:bb[0-9]+]] callee3() // CHECK: [[LOOP]]: // test the condition. // CHECK: [[CONDTRUE:%.*]] = apply {{.*}}(%0) // CHECK: cond_br [[CONDTRUE]], [[BODY:bb[0-9]+]], [[EXIT:bb[0-9]+]] while cond { // CHECK: [[BODY]]: // CHECK: [[C2:%.*]] = function_ref @{{.*}}callee2FT_T_ // CHECK: apply [[C2]] // CHECK: [[C1:%.*]] = function_ref @_TFF10statements11defer_test2FSbT_L_6$deferFT_T_ // CHECK: apply [[C1]] // CHECK: br [[EXIT]] defer { callee1() } callee2() break } // CHECK: [[EXIT]]: // CHECK: [[C3:%.*]] = function_ref @{{.*}}callee3FT_T_ // CHECK: apply [[C3]] callee3() } func generic_callee_1<T>(_: T) {} func generic_callee_2<T>(_: T) {} func generic_callee_3<T>(_: T) {} // CHECK-LABEL: sil hidden @_TF10statements16defer_in_generic func defer_in_generic<T>(x: T) { // CHECK: [[C3:%.*]] = function_ref @_TF10statements16generic_callee_3 // CHECK: apply [[C3]]<T> // CHECK: [[C2:%.*]] = function_ref @_TFF10statements16defer_in_generic // CHECK: apply [[C2]]<T> // CHECK: [[C1:%.*]] = function_ref @_TFF10statements16defer_in_generic // CHECK: apply [[C1]]<T> defer { generic_callee_1(x) } defer { generic_callee_2(x) } generic_callee_3(x) } // CHECK-LABEL: sil hidden @_TF10statements13defer_mutableFSiT_ func defer_mutable(x: Int) { var x = x // CHECK: [[BOX:%.*]] = alloc_box $Int // CHECK-NOT: [[BOX]]#0 // CHECK: function_ref @_TFF10statements13defer_mutableFSiT_L_6$deferfT_T_ : $@convention(thin) (@inout_aliasable Int) -> () // CHECK-NOT: [[BOX]]#0 // CHECK: strong_release [[BOX]]#0 defer { _ = x } } protocol StaticFooProtocol { static func foo() } func testDeferOpenExistential(b: Bool, type: StaticFooProtocol.Type) { defer { type.foo() } if b { return } return } // CHECK-LABEL: sil hidden @_TF10statements22testRequireExprPatternFSiT_ func testRequireExprPattern(a : Int) { marker_1() // CHECK: [[M1:%[0-9]+]] = function_ref @_TF10statements8marker_1FT_T_ : $@convention(thin) () -> () // CHECK-NEXT: apply [[M1]]() : $@convention(thin) () -> () // CHECK: function_ref static Swift.~= infix <A where A: Swift.Equatable> (A, A) -> Swift.Bool // CHECK: cond_br {{.*}}, bb1, bb2 guard case 4 = a else { marker_2(); return } // Fall through case comes first. // CHECK: bb1: // CHECK: [[M3:%[0-9]+]] = function_ref @_TF10statements8marker_3FT_T_ : $@convention(thin) () -> () // CHECK-NEXT: apply [[M3]]() : $@convention(thin) () -> () // CHECK-NEXT: br bb3 marker_3() // CHECK: bb2: // CHECK: [[M2:%[0-9]+]] = function_ref @_TF10statements8marker_2FT_T_ : $@convention(thin) () -> () // CHECK-NEXT: apply [[M2]]() : $@convention(thin) () -> () // CHECK-NEXT: br bb3 // CHECK: bb3: // CHECK-NEXT: tuple () // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_TF10statements20testRequireOptional1FGSqSi_Si // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.Some!enumelt.1: bb1, default bb2 func testRequireOptional1(a : Int?) -> Int { // CHECK: bb1(%3 : $Int): // CHECK-NEXT: debug_value %3 : $Int, let, name "t" // CHECK-NEXT: return %3 : $Int guard let t = a else { abort() } // CHECK: bb2: // CHECK-NEXT: // function_ref statements.abort () -> () // CHECK-NEXT: %6 = function_ref @_TF10statements5abortFT_T_ // CHECK-NEXT: %7 = apply %6() : $@convention(thin) @noreturn () -> () // CHECK-NEXT: unreachable return t } // CHECK-LABEL: sil hidden @_TF10statements20testRequireOptional2FGSqSS_SS // CHECK: bb0(%0 : $Optional<String>): // CHECK-NEXT: debug_value %0 : $Optional<String>, let, name "a" // CHECK-NEXT: retain_value %0 : $Optional<String> // CHECK-NEXT: switch_enum %0 : $Optional<String>, case #Optional.Some!enumelt.1: bb1, default bb2 func testRequireOptional2(a : String?) -> String { guard let t = a else { abort() } // CHECK: bb1(%4 : $String): // CHECK-NEXT: debug_value %4 : $String, let, name "t" // CHECK-NEXT: release_value %0 : $Optional<String> // CHECK-NEXT: return %4 : $String // CHECK: bb2: // CHECK-NEXT: // function_ref statements.abort () -> () // CHECK-NEXT: %8 = function_ref @_TF10statements5abortFT_T_ // CHECK-NEXT: %9 = apply %8() // CHECK-NEXT: unreachable return t } enum MyOpt<T> { case None, Some(T) } // CHECK-LABEL: sil hidden @_TF10statements28testAddressOnlyEnumInRequire // CHECK: bb0(%0 : $*T, %1 : $*MyOpt<T>): // CHECK-NEXT: debug_value_addr %1 : $*MyOpt<T>, let, name "a" // CHECK-NEXT: %3 = alloc_stack $T, let, name "t" // CHECK-NEXT: %4 = alloc_stack $MyOpt<T> // CHECK-NEXT: copy_addr %1 to [initialization] %4#1 : $*MyOpt<T> // CHECK-NEXT: switch_enum_addr %4#1 : $*MyOpt<T>, case #MyOpt.Some!enumelt.1: bb2, default bb1 func testAddressOnlyEnumInRequire<T>(a : MyOpt<T>) -> T { // CHECK: bb1: // CHECK-NEXT: dealloc_stack %4#0 // CHECK-NEXT: dealloc_stack %3#0 // CHECK-NEXT: br bb3 guard let t = a else { abort() } // CHECK: bb2: // CHECK-NEXT: %10 = unchecked_take_enum_data_addr %4#1 : $*MyOpt<T>, #MyOpt.Some!enumelt.1 // CHECK-NEXT: copy_addr [take] %10 to [initialization] %3#1 : $*T // CHECK-NEXT: dealloc_stack %4#0 // CHECK-NEXT: copy_addr [take] %3#1 to [initialization] %0 : $*T // CHECK-NEXT: dealloc_stack %3#0 // CHECK-NEXT: destroy_addr %1 : $*MyOpt<T> // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: bb3: // CHECK-NEXT: // function_ref statements.abort () -> () // CHECK-NEXT: %18 = function_ref @_TF10statements5abortFT_T_ // CHECK-NEXT: %19 = apply %18() : $@convention(thin) @noreturn () -> () // CHECK-NEXT: unreachable return t } // CHECK-LABEL: sil hidden @_TF10statements19testCleanupEmission // <rdar://problem/20563234> let-else problem: cleanups for bound patterns shouldn't be run in the else block protocol MyProtocol {} func testCleanupEmission<T>(x: T) { // SILGen shouldn't crash/verify abort on this example. guard let x2 = x as? MyProtocol else { return } _ = x2 } // CHECK-LABEL: sil hidden @_TF10statements15test_is_patternFCS_9BaseClassT_ func test_is_pattern(y : BaseClass) { // checked_cast_br %0 : $BaseClass to $DerivedClass guard case is DerivedClass = y else { marker_1(); return } marker_2() } // CHECK-LABEL: sil hidden @_TF10statements15test_as_patternFCS_9BaseClassCS_12DerivedClass func test_as_pattern(y : BaseClass) -> DerivedClass { // checked_cast_br %0 : $BaseClass to $DerivedClass guard case let result as DerivedClass = y else { } // CHECK: bb{{.*}}({{.*}} : $DerivedClass): // CHECK: bb{{.*}}([[PTR:%[0-9]+]] : $DerivedClass): // CHECK-NEXT: debug_value [[PTR]] : $DerivedClass, let, name "result" // CHECK-NEXT: strong_release %0 : $BaseClass // CHECK-NEXT: return [[PTR]] : $DerivedClass return result } // CHECK-LABEL: sil hidden @_TF10statements22let_else_tuple_bindingFGSqTSiSi__Si func let_else_tuple_binding(a : (Int, Int)?) -> Int { // CHECK: bb0(%0 : $Optional<(Int, Int)>): // CHECK-NEXT: debug_value %0 : $Optional<(Int, Int)>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<(Int, Int)>, case #Optional.Some!enumelt.1: bb1, default bb2 guard let (x, y) = a else { } _ = y return x // CHECK: bb1(%3 : $(Int, Int)): // CHECK-NEXT: %4 = tuple_extract %3 : $(Int, Int), 0 // CHECK-NEXT: debug_value %4 : $Int, let, name "x" // CHECK-NEXT: %6 = tuple_extract %3 : $(Int, Int), 1 // CHECK-NEXT: debug_value %6 : $Int, let, name "y" // CHECK-NEXT: return %4 : $Int }
apache-2.0
2cabd9cdcb99a325dd50d8a4ee0ee4b7
25.121212
126
0.577063
2.932448
false
true
false
false
Ossey/WeiBo
XYWeiBo/XYWeiBo/Classes/Compose(发布)/Controller/XYComposeViewController.swift
1
9386
// // XYComposeViewController.swift // XYWeiBo // // Created by mofeini on 16/10/2. // Copyright © 2016年 sey. All rights reserved. // import UIKit import SVProgressHUD class XYComposeViewController: UIViewController { // MARK:- 控件 @IBOutlet weak var textView: XYComposeTextView! @IBOutlet weak var picPikerView: XYPicPickerCollectionView! // MARK:- 约束 @IBOutlet weak var toolBarBottomConstr: NSLayoutConstraint! @IBOutlet weak var picPikerViewHeightConstr: NSLayoutConstraint! // MARK:- 懒加载属性 lazy var titleView : XYComposeTitleView = XYComposeTitleView.titleViewFromNib() lazy var images : [UIImage] = [UIImage]() // 存放所有选择的图片 lazy var emoticonVc : XYEmoticonViewController = XYEmoticonViewController {[weak self] (emoticonItem) in // 给textView插入输入的表情 self?.textView.insertEmoticon(emoticonItem: emoticonItem) // 手动触发textView的代理方法:输入表情也是等于输入文字 self?.textViewDidChange((self?.textView)!) } // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() // 监听键盘frame发送改变的通知 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotification), name: .UIKeyboardWillChangeFrame, object: nil) // 监听点击了添加图片按钮的点击事件 NotificationCenter.default.addObserver(self, selector: #selector(clickAddPictureButton(notification:)), name: XYClickAddPictureButtonNotification, object: nil) // 监听点击了删除图片按钮的点击事件 NotificationCenter.default.addObserver(self, selector: #selector(clickRemovePictureButton(notification:)), name: XYClickRemovePictureButtonNotification, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.textView.becomeFirstResponder() } deinit { NotificationCenter.default.removeObserver(self) print("发布控制器已释放") } } // MARK:- 设置UI界面 extension XYComposeViewController { func setupNavigationBar() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(composeCloseBtnClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(composeBtnClick)) navigationItem.rightBarButtonItem?.isEnabled = false titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) navigationItem.titleView = titleView textView.delegate = self } } // MARK:- 事件监听 extension XYComposeViewController { /// 关闭按钮的点击事件 func composeCloseBtnClick() { self.textView.resignFirstResponder() dismiss(animated: true, completion: nil) } /// 发布按钮的点击事件: 发布微博 func composeBtnClick() { // 1.发布文本微博 // 1.获取textView上表情的字符串 let emoticonStr = textView.getEmoticonString() // 2.定义一个闭包 let finishedCallBack = { (isSucces: Bool) -> () in if isSucces { // 发送微博成功 SVProgressHUD.showSuccess(withStatus: "发布微博成功") self.dismiss(animated: true, completion: nil) return } // 发送微博失败 SVProgressHUD.showError(withStatus: "发布微博失败") } // 发布微博注意:图片微博:由于权限问题只能发一张图片 // 2.1通过判断用户发送的微博有没有图片,决定使用什么接口发送微博 if let image = images.first { // 用户发布的微博有图片,就使用有图片接口发送 XYNetworkTools.shareInstace.senderStatus(statusText: emoticonStr, image: image, isSuccesCallBack: finishedCallBack) } else { // 用户发布的微博没有图片,使用文本接口发送 XYNetworkTools.shareInstace.senderStatus(statusText: emoticonStr, isSuccesCallBck: finishedCallBack) } } /// 监听键盘frame即将发送改变的通知 func keyboardWillChangeFrameNotification(notification: Notification) { // 获取键盘的动画时间 let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval // 获取键盘出现后的frame let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let keyboardY = keyboardFrame.origin.y // 计算键盘出现后toolBar的底部约束 toolBarBottomConstr.constant = UIScreen.main.bounds.size.height - keyboardY UIView .animate(withDuration: duration) { self.view.layoutIfNeeded() } } /// 点击工具栏上emoticon表情时调用 @IBAction func emoticonItemClick(_ sender: AnyObject) { // 退出第一响应者 textView.resignFirstResponder() // 切换键盘 textView.inputView = textView.inputView == nil ? emoticonVc.view : nil // 成为第一响应者 textView.becomeFirstResponder() } /// 点击照片选择按钮的点击事件 @IBAction func picPickerButtonClick() { // 设置照片选择器view的高度约束 self.picPikerViewHeightConstr.constant = UIScreen.main.bounds.size.height * 0.65 self.textView.resignFirstResponder() UIView.animate(withDuration: 0.5) { self.view.layoutIfNeeded() } } /// 当接收到点击添加图片按钮的通知后调用 func clickAddPictureButton(notification: Notification) { // 添加图片 addPicture() } /// 当接收到点击删除图片按钮的通知后调用 func clickRemovePictureButton(notification: Notification) { // 删除图片 removePicture(notification: notification) } } // MARK:- 添加和删除照片 extension XYComposeViewController { /// 添加图片 func addPicture() { // 1.判断数据源是否可用 if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { return // 照片资源库不可用时直接返回 } // 2.创建照片选择控制器 let imagePickVc = UIImagePickerController() // 3.设置照片的来源 imagePickVc.sourceType = .photoLibrary // 4.设置代理 imagePickVc.delegate = self // 设置modal的弹出样式为自定义 // 目的:弹出后不让上一个控制器的view消失,因为我在上一控制器的显示完成的方法中让键盘弹出了,所以每次view显示都会弹出,这样不好,设置为custom后,modal出新的控制器后,上一控制器的view也不会消失,退出modal会所以也不会调用view显示的方法 imagePickVc.modalPresentationStyle = .custom // 5.弹出照片选择控制器 present(imagePickVc, animated: true, completion: nil) } /// 删除图片 func removePicture(notification: Notification) { // 1.获取点击删除上的图片 guard let imaage = notification.object as? UIImage else { return } // 2.获取图片在images数组中的下标值 guard let index = images.index(of: imaage) else { return } // 3.从数组中删除这个图片 images.remove(at: index) // 4.重新给collectionView中的images赋值,当collectionView中的images监听到值发送改变时就会刷新数据 picPikerView.images = images } } extension XYComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { // 每次选择照片时调用 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 1.获取选择的照片 let image = info[UIImagePickerControllerOriginalImage] as! UIImage // 2.将选中的照片添加到数组中 images.append(image) // 3.将照片数组传递出去 picPikerView.images = images // 4.退出照片选中器 dismiss(animated: true, completion: nil) } } extension XYComposeViewController : UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.textView.placeHodlerLabel.isHidden = textView.hasText navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } } extension XYComposeViewController : UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { self.textView.resignFirstResponder() } }
apache-2.0
58237ff239446ffdbe832f1dadeaf1f0
27.98913
173
0.628546
4.7625
false
false
false
false
baottran/nSURE
nSURE/RepairAddImageViewController.swift
1
6211
// // RepairAddImageViewController.swift // nSURE // // Created by Bao Tran on 8/24/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit import MBProgressHUD class RepairAddImageViewController: UIViewController, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate { @IBOutlet weak var imageCollection: UICollectionView! @IBOutlet weak var imageCountLabel: UILabel! @IBOutlet weak var savingIndicator: UIActivityIndicatorView! @IBOutlet weak var notesField: UITextView! let imagePicker = UIImagePickerController() var imageArray: [UIImage] = [] var repairObj: PFObject! var activityObj: PFObject! var activityType: String! var delegate: RepairActivityDetailViewControllerDelegate! var savePushed = false override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(imageCollection) imageCollection.dataSource = self imagePicker.delegate = self imagePicker.sourceType = .Camera notesField.delegate = self notesField.text = "Notes (optional) ..." notesField.textColor = UIColor.lightGrayColor() // presentViewController(imagePicker, animated: true, completion: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } func keyboardWillShow(sender: NSNotification) { self.view.frame.origin.y -= 200 } func keyboardWillHide(sender: NSNotification) { self.view.frame.origin.y += 200 } func textViewDidBeginEditing(textView: UITextView) { if textView.textColor == UIColor.lightGrayColor() { textView.text = nil textView.textColor = UIColor.blackColor() } } func textViewDidEndEditing(textView: UITextView) { if textView.text.isEmpty { textView.text = "Notes (optional)..." textView.textColor = UIColor.lightGrayColor() } } override func viewDidAppear(animated: Bool) { if imageArray == [] { takePicture() } } func setLabel(){ if imageArray.count == 1 { imageCountLabel.text = "1 Image" } else { imageCountLabel.text = "\(imageArray.count) Images" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancel(){ dismissViewControllerAnimated(true, completion: nil) } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! RepairImageCollectionViewCell cell.repairImage.image = imageArray[indexPath.row] return cell } @IBAction func takePicture(){ presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let imageTaken = info[UIImagePickerControllerOriginalImage] as! UIImage imageArray.append(imageTaken) imageCollection.reloadData() setLabel() dismissViewControllerAnimated(true, completion: nil) } @IBAction func saveMsg(sender: AnyObject) { if savePushed == false { savePushed = true let progressModal = MBProgressHUD.showHUDAddedTo(self.view, animated: true) progressModal.labelText = "Saving Pictures" let message = PFObject(className: "Message") message["type"] = "Images" message["text"] = notesField.text message["activity"] = activityObj message["activityType"] = activityType let currentUser = PFUser.currentUser() message["createdBy"] = currentUser message["repair"] = repairObj for image in imageArray { let imageFile = resizeImage(image) message.addObject(imageFile, forKey: "images") } message.saveInBackgroundWithBlock{ success, error in if success { print("message successfully saved", terminator: "") self.view.endEditing(true) MBProgressHUD.hideAllHUDsForView(self.view, animated: true) self.dismissViewControllerAnimated(true, completion: { self.delegate.reloadMessagesTable() }) } else { print("error saving message", terminator: "") self.savePushed = false print(error, terminator: "") } } } } func resizeImage(image: UIImage) -> PFFile { let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(0.5, 0.5)) let hasAlpha = false let scale:CGFloat = 0.5 UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale) image.drawInRect(CGRect(origin: CGPointZero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageData = UIImagePNGRepresentation(scaledImage) let imageFile = PFFile(data: imageData!) return imageFile } }
mit
c6e409bdcca9f361ca5c89e40c942883
33.314917
167
0.62985
5.864967
false
false
false
false
dtrauger/Charts
Source/Charts/Data/Implementations/Standard/LineChartDataSet.swift
1
6192
// // LineChartDataSet.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 open class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet { @objc(LineChartMode) public enum Mode: Int { case linear case stepped case cubicBezier case horizontalBezier } fileprivate func initialize() { // default color circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) } public required init() { super.init() initialize() } public override init(values: [ChartDataEntry]?, label: String?) { super.init(values: values, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// The drawing mode for this line dataset /// /// **default**: Linear open var mode: Mode = Mode.linear fileprivate var _cubicIntensity = CGFloat(0.2) /// Intensity for cubic lines (min = 0.05, max = 1) /// /// **default**: 0.2 open var cubicIntensity: CGFloat { get { return _cubicIntensity } set { _cubicIntensity = newValue if _cubicIntensity > 1.0 { _cubicIntensity = 1.0 } if _cubicIntensity < 0.05 { _cubicIntensity = 0.05 } } } @available(*, deprecated, message: "Use `mode` instead.") open var drawCubicEnabled: Bool { get { return mode == .cubicBezier } set { mode = newValue ? LineChartDataSet.Mode.cubicBezier : LineChartDataSet.Mode.linear } } @available(*, deprecated, message: "Use `mode` instead.") open var isDrawCubicEnabled: Bool { return drawCubicEnabled } @available(*, deprecated, message: "Use `mode` instead.") open var drawSteppedEnabled: Bool { get { return mode == .stepped } set { mode = newValue ? LineChartDataSet.Mode.stepped : LineChartDataSet.Mode.linear } } @available(*, deprecated, message: "Use `mode` instead.") open var isDrawSteppedEnabled: Bool { return drawSteppedEnabled } /// The radius of the drawn circles. open var circleRadius = CGFloat(8.0) /// The hole radius of the drawn circles open var circleHoleRadius = CGFloat(4.0) open var circleColors = [NSUIColor]() /// - returns: The color at the given index of the DataSet's circle-color array. /// Performs a IndexOutOfBounds check by modulus. open func getCircleColor(atIndex index: Int) -> NSUIColor? { let size = circleColors.count let index = index % size if index >= size { return nil } return circleColors[index] } /// Sets the one and ONLY color that should be used for this DataSet. /// Internally, this recreates the colors array and adds the specified color. open func setCircleColor(_ color: NSUIColor) { circleColors.removeAll(keepingCapacity: false) circleColors.append(color) } open func setCircleColors(_ colors: NSUIColor...) { circleColors.removeAll(keepingCapacity: false) circleColors.append(contentsOf: colors) } /// Resets the circle-colors array and creates a new one open func resetCircleColors(_ index: Int) { circleColors.removeAll(keepingCapacity: false) } /// If true, drawing circles is enabled open var drawCirclesEnabled = true /// - returns: `true` if drawing circles for this DataSet is enabled, `false` ifnot open var isDrawCirclesEnabled: Bool { return drawCirclesEnabled } /// The color of the inner circle (the circle-hole). open var circleHoleColor: NSUIColor? = NSUIColor.white /// `true` if drawing circles for this DataSet is enabled, `false` ifnot open var drawCircleHoleEnabled = true /// - returns: `true` if drawing the circle-holes is enabled, `false` ifnot. open var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled } /// This is how much (in pixels) into the dash pattern are we starting from. open var lineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] open var lineDashLengths: [CGFloat]? /// Line cap type, default is CGLineCap.Butt open var lineCapType = CGLineCap.butt /// formatter for customizing the position of the fill-line fileprivate var _fillFormatter: IFillFormatter = DefaultFillFormatter() /// Sets a custom IFillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic. open var fillFormatter: IFillFormatter? { get { return _fillFormatter } set { if newValue == nil { _fillFormatter = DefaultFillFormatter() } else { _fillFormatter = newValue! } } } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! LineChartDataSet copy.circleColors = circleColors copy.circleRadius = circleRadius copy.cubicIntensity = cubicIntensity copy.lineDashPhase = lineDashPhase copy.lineDashLengths = lineDashLengths copy.lineCapType = lineCapType copy.drawCirclesEnabled = drawCirclesEnabled copy.drawCircleHoleEnabled = drawCircleHoleEnabled copy.mode = mode return copy } }
apache-2.0
8ccad9bd6b6393097ef5de587e9b8e5e
27.534562
155
0.595123
4.981496
false
false
false
false
spacedrabbit/100-days
One00Days/One00Days/CloudAnimationView.swift
1
3176
// // CloudAnimationView.swift // One00Days // // Created by Louis Tur on 4/30/16. // Copyright © 2016 SRLabs. All rights reserved. // import Foundation import UIKit class CloudAnimationView: UIView { // MARK: - Init // ------------------------------------------------------------ override init(frame: CGRect) { super.init(frame: frame) self.setupViewHierarchy() self.configureConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Emitter Setup // ------------------------------------------------------------ internal func startCloudEmitter() { self.layoutIfNeeded() // needed right before positioning to get correct sizes cloudEmitterNode.emitterMode = kCAEmitterLayerPoints cloudEmitterNode.position = self.cloudGeneratorView.center cloudEmitterNode.emitterShape = kCAEmitterLayerCircle cloudEmitterNode.emitterSize = self.cloudGeneratorView.frame.size let foregroundCells = self.makeCloudCellForPosition(.foreGround) let midgroundCells = self.makeCloudCellForPosition(.midGround) let backgroundCells = self.makeCloudCellForPosition(.backGround) cloudEmitterNode.emitterCells = [foregroundCells, midgroundCells, backgroundCells] self.cloudGeneratorView.layer.addSublayer(self.cloudEmitterNode) } fileprivate func makeCloudCellForPosition(_ position: ScenePosition) -> CAEmitterCell { let cell = CAEmitterCell() cell.emissionRange = CGFloat(0.0) cell.emissionLatitude = CGFloat(M_PI) cell.emissionLongitude = CGFloat(0.0) cell.contents = Cloud(withRelativePosition: position).image?.cgImage switch position { case .foreGround: cell.scale = 2.0 cell.birthRate = 1.0 cell.velocity = 750.0 cell.alphaRange = 0.0 cell.lifetime = 10.0 case .midGround: cell.scale = 0.50 cell.birthRate = 0.25 cell.velocity = 50.0 cell.alphaRange = 0.5 cell.alphaSpeed = 10.0 cell.lifetime = 20.0 case .backGround: cell.scale = 0.15 cell.birthRate = 0.1 cell.velocity = 20.0 cell.lifetime = 100.0 } return cell } // MARK: - Layout // ------------------------------------------------------------ internal func configureConstraints() { self.trackView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self) } self.cloudGeneratorView.snp.makeConstraints { (make) -> Void in make.left.equalTo(self.trackView.snp.right) make.top.bottom.equalTo(self.trackView) make.width.greaterThanOrEqualTo(100.0) } } internal func setupViewHierarchy() { self.addSubviews([trackView, cloudGeneratorView]) } // MARK: - Lazy // ------------------------------------------------------------ lazy var trackView: UIView = { let view: UIView = UIView() return view }() lazy var cloudGeneratorView: UIView = { let view: UIView = UIView() return view }() lazy var cloudEmitterNode: CAEmitterLayer = { let emitter: CAEmitterLayer = CAEmitterLayer() return emitter }() }
mit
a88210c30e655e9d320f395a143d9d6a
26.136752
89
0.619213
4.490806
false
false
false
false
mitsuyoshi-yamazaki/SwarmChemistry
Demo_ScreenSaver/ConfigureWindow.swift
1
2152
// // ConfigureWindow.swift // SwarmChemistry // // Created by mitsuyoshi.yamazaki on 2017/08/24. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // import Cocoa import SwarmChemistry protocol ConfigureWindowDelegate: AnyObject { func configureWindow(_ window: ConfigureWindow, didSelect recipe: Recipe) } final final class ConfigureWindow: NSWindow, IBInstantiatable { weak var configureWindowDelegate: ConfigureWindowDelegate? var selectedRecipe: Recipe? fileprivate let recipeList = Recipe.presetRecipes override func awakeFromNib() { super.awakeFromNib() } // MARK: - @IBAction private func ok(sender: Any) { NSApp.endSheet(self) // endSheet(self) // Doesn't work } @IBAction private func cancel(sender: Any) { NSApp.endSheet(self) // endSheet(self) // Doesn't work } } extension ConfigureWindow: NSTableViewDataSource { private enum ColumnIdentifier: String { case selected = "Selected" case recipeName = "RecipeName" } func numberOfRows(in tableView: NSTableView) -> Int { return recipeList.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { guard let tableColumn = tableColumn else { Swift.print("No tableColumn specified") return nil } let recipe = recipeList[row] let isSelected = recipe.name == selectedRecipe?.name Swift.print("\(recipe.name): \(isSelected)") switch ColumnIdentifier(rawValue: tableColumn.identifier) { case .selected: return isSelected ? "✔︎" : "" case .recipeName: return recipe.name case nil: fatalError("Index out of range") } } } extension ConfigureWindow: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { guard let tableView = notification.object as? NSTableView else { fatalError("Unexpected notification object \(notification.object)") } let recipe = recipeList[tableView.selectedRow] selectedRecipe = recipe configureWindowDelegate?.configureWindow(self, didSelect: recipe) tableView.reloadData() } }
mit
eb0ec9227008dbd31a09090959da05ba
25.506173
106
0.710293
4.529536
false
true
false
false
GabrielMassana/ColorWithHSL-iOS
ColorWithHSLTests/ColorWithHSLTests.swift
1
3101
// // ColorWithHSLTests.swift // ColorWithHSLTests // // Created by GabrielMassana on 02/04/2016. // Copyright © 2016 GabrielMassana. All rights reserved. // import XCTest @testable import ColorWithHSL class ColorWithHSLTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } //MARK: - Valid func test_colorWithHex_newObjectReturned_minimum() { let color = UIColor.colorWithHSL(hue: 0.0, saturation: 0.0, lightness: 0.0) XCTAssertNotNil(color, "A valid Color object wasn't created"); } func test_colorWithHex_newObjectReturned_maximum() { let color = UIColor.colorWithHSL(hue: 360.0, saturation: 1.0, lightness: 1.0) XCTAssertNotNil(color, "A valid Color object wasn't created"); } //MARK: - NoValid func test_colorWithHex_outOfRangeHue_over() { let color = UIColor.colorWithHSL(hue: 361.0, saturation: 0.5, lightness: 0.5) XCTAssertNil(color, "A valid Color object was created"); } func test_colorWithHex_outOfRangeHue_under() { let color = UIColor.colorWithHSL(hue: -1.0, saturation: 0.5, lightness: 0.5) XCTAssertNil(color, "A valid Color object was created"); } func test_colorWithHex_outOfRangeSaturation_over() { let color = UIColor.colorWithHSL(hue: 180.0, saturation: 1.1, lightness: 0.5) XCTAssertNil(color, "A valid Color object was created"); } func test_colorWithHex_outOfRangeSaturation_under() { let color = UIColor.colorWithHSL(hue: 180.0, saturation: -0.1, lightness: 0.5) XCTAssertNil(color, "A valid Color object was created"); } func test_colorWithHex_outOfRangeLightness_over() { let color = UIColor.colorWithHSL(hue: 180.0, saturation: 0.5, lightness: 1.1) XCTAssertNil(color, "A valid Color object was created"); } func test_colorWithHex_outOfRangeLightness_under() { let color = UIColor.colorWithHSL(hue: 180.0, saturation: 0.5, lightness: -0.1) XCTAssertNil(color, "A valid Color object was created"); } //MARK: - SpecificColor func test_colorWithHex_red() { let redColor = UIColor.colorWithHSL(hue: 0.0, saturation: 1.0, lightness: 0.5) XCTAssertEqual(redColor, UIColor.redColor(), "A red Color object wasn't created"); } func test_colorWithHex_green() { let greenColor = UIColor.colorWithHSL(hue: 120.0, saturation: 1.0, lightness: 0.5) XCTAssertEqual(greenColor, UIColor.greenColor(), "A green Color object wasn't created"); } func test_colorWithHex_blue() { let blueColor = UIColor.colorWithHSL(hue: 240.0, saturation: 1.0, lightness: 0.5) XCTAssertEqual(blueColor, UIColor.blueColor(), "A blue Color object wasn't created"); } }
mit
c4c2dbe221d661527bb81f45572b6cc6
27.703704
96
0.609677
4.223433
false
true
false
false
joseph-zhong/CommuterBuddy-iOS
SwiftSideMenu/Utility/NSURLExtensions.swift
4
9956
// // NSURLExtensions.swift // EZSwiftExtensions // // Created by furuyan on 2016/01/11. // Copyright (c) 2016 Goktug Yilmaz. All rights reserved. // import UIKit extension URL { /// EZSE: Returns convert query to Dictionary public var queryParameters: [String: String]? { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return nil } var parameters = [String: String]() for item in queryItems { parameters[item.name] = item.value } return parameters } /// EZSE: Returns remote size of url, don't use it in main thread public func remoteSize(_ completionHandler: @escaping ((_ contentLength: Int64) -> Void), timeoutInterval: TimeInterval = 30) { var request = URLRequest(url: self, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval) request.httpMethod = "HEAD" request.setValue("", forHTTPHeaderField: "Accept-Encoding") URLSession.shared.dataTask(with: request) { (data, response, error) in let contentLength: Int64 = response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown DispatchQueue.global(qos: .default).async(execute: { completionHandler(contentLength) }) }.resume() } /// EZSE: Returns server supports resuming or not, don't use it in main thread public func supportsResume(_ completionHandler: @escaping ((_ doesSupport: Bool) -> Void), timeoutInterval: TimeInterval = 30) { var request = URLRequest(url: self, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutInterval) request.httpMethod = "HEAD" request.setValue("bytes=5-10", forHTTPHeaderField: "Range") URLSession.shared.dataTask(with: request) { (_, response, _) -> Void in let responseCode = (response as? HTTPURLResponse)?.statusCode ?? -1 DispatchQueue.global(qos: .default).async(execute: { completionHandler(responseCode == 206) }) }.resume() } /// EZSE: Compare two URLs public func isSameWithURL(_ url: URL) -> Bool { if self == url { return true } if self.scheme?.lowercased() != url.scheme?.lowercased() { return false } if let host1 = self.host, let host2 = url.host { let whost1 = host1.hasPrefix("www.") ? host1 : "www." + host1 let whost2 = host2.hasPrefix("www.") ? host2 : "www." + host2 if whost1 != whost2 { return false } } let pathdelimiter = CharacterSet(charactersIn: "/") if self.path.lowercased().trimmingCharacters(in: pathdelimiter) != url.path.lowercased().trimmingCharacters(in: pathdelimiter) { return false } if (self as NSURL).port != (url as NSURL).port { return false } if self.query?.lowercased() != url.query?.lowercased() { return false } return true } /// EZSE: Returns true if given file is a directory public var fileIsDirectory: Bool { var isdirv: AnyObject? do { try (self as NSURL).getResourceValue(&isdirv, forKey: URLResourceKey.isDirectoryKey) } catch _ { } return isdirv?.boolValue ?? false } /// EZSE: File modification date, nil if file doesn't exist public var fileModifiedDate: Date? { get { var datemodv: AnyObject? do { try (self as NSURL).getResourceValue(&datemodv, forKey: URLResourceKey.contentModificationDateKey) } catch _ { } return datemodv as? Date } set { do { try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.contentModificationDateKey) } catch _ { } } } /// EZSE: File creation date, nil if file doesn't exist public var fileCreationDate: Date? { get { var datecreatev: AnyObject? do { try (self as NSURL).getResourceValue(&datecreatev, forKey: URLResourceKey.creationDateKey) } catch _ { } return datecreatev as? Date } set { do { try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.creationDateKey) } catch _ { } } } /// EZSE: Returns last file access date, nil if file doesn't exist or not yet accessed public var fileAccessDate: Date? { _ = URLResourceKey.customIconKey var dateaccessv: AnyObject? do { try (self as NSURL).getResourceValue(&dateaccessv, forKey: URLResourceKey.contentAccessDateKey) } catch _ { } return dateaccessv as? Date } /// EZSE: Returns file size, -1 if file doesn't exist public var fileSize: Int64 { var sizev: AnyObject? do { try (self as NSURL).getResourceValue(&sizev, forKey: URLResourceKey.fileSizeKey) } catch _ { } return sizev?.int64Value ?? -1 } /// EZSE: File is hidden or not, don't care about files beginning with dot public var fileIsHidden: Bool { get { var ishiddenv: AnyObject? do { try (self as NSURL).getResourceValue(&ishiddenv, forKey: URLResourceKey.isHiddenKey) } catch _ { } return ishiddenv?.boolValue ?? false } set { do { try (self as NSURL).setResourceValue(newValue, forKey: URLResourceKey.isHiddenKey) } catch _ { } } } /// EZSE: Checks if file is writable public var fileIsWritable: Bool { var isdirv: AnyObject? do { try (self as NSURL).getResourceValue(&isdirv, forKey: URLResourceKey.isWritableKey) } catch _ { } return isdirv?.boolValue ?? false } #if (OSX) @available(OSX 10.10, *) internal var fileThumbnailsDictionary: [String: NSImage]? { get { var thumbsData: AnyObject? do { try self.getResourceValue(&thumbsData, forKey: NSURLThumbnailDictionaryKey) } catch _ { } return thumbsData as? [String: NSImage] } set { do { let dic = NSDictionary(dictionary: newValue ?? [:]) try self.setResourceValue(dic, forKey: NSURLThumbnailDictionaryKey) } catch _ { } } } /// EZSE: File thubmnail saved in system or iCloud in form of 1024pxx1024px @available(OSX 10.10, *) public var fileThumbnail1024px: NSImage? { get { return fileThumbnailsDictionary?[NSThumbnail1024x1024SizeKey] } set { assert(newValue == nil || (newValue?.size.height == 1024 && newValue?.size.width == 1024), "Image size set in fileThumbnail1024px is not 1024x1024") fileThumbnailsDictionary?[NSThumbnail1024x1024SizeKey] = newValue } } #else @available(iOS 8.0, *) internal var fileThumbnailsDictionary: [String: UIImage]? { get { var thumbsData: AnyObject? do { try (self as NSURL).getResourceValue(&thumbsData, forKey: URLResourceKey.thumbnailDictionaryKey) } catch _ { } return thumbsData as? [String: UIImage] } set { do { let dic = NSDictionary(dictionary: newValue ?? [:]) try (self as NSURL).setResourceValue(dic, forKey: URLResourceKey.thumbnailDictionaryKey) } catch _ { } } } /// EZSE: File thubmnail saved in system or iCloud in form of 1024pxx1024px @available(iOS 8.0, *) var fileThumbnail1024px: UIImage? { get { return fileThumbnailsDictionary?[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue] } set { assert(newValue == nil || (newValue?.size.height == 1024 && newValue?.size.width == 1024), "Image size set in fileThumbnail1024px is not 1024x1024") fileThumbnailsDictionary?[URLThumbnailDictionaryItem.NSThumbnail1024x1024SizeKey.rawValue] = newValue } } #endif /// EZSE: Set SkipBackup attrubute of file or directory in iOS. return current state if no value is set public func skipBackupAttributeToItemAtURL(_ skip: Bool? = nil) -> Bool { let keys = [URLResourceKey.isDirectoryKey, URLResourceKey.fileSizeKey] let enumOpt = FileManager.DirectoryEnumerationOptions() if FileManager.default.fileExists(atPath: self.path) { if skip != nil { if self.fileIsDirectory { let filesList = (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: keys, options: enumOpt)) ?? [] for fileURL in filesList { _ = fileURL.skipBackupAttributeToItemAtURL(skip) } } do { try (self as NSURL).setResourceValue(NSNumber(value: skip!), forKey: .isExcludedFromBackupKey) return true } catch _ { return false } } else { let dict = try? (self as NSURL).resourceValues(forKeys: [URLResourceKey.isExcludedFromBackupKey]) if let key: AnyObject = dict?[URLResourceKey.isExcludedFromBackupKey] as AnyObject? { return key.boolValue } return false } } return false } }
mit
fb54dce60fb1fc0596ae133940afd1a6
35.874074
160
0.580655
4.926274
false
false
false
false
a2/Oberholz
Oberholz/Classes/OberholzViewController.swift
1
3017
import UIKit public protocol OberholzViewControllerDelegate: class { } public final class OberholzViewController: UIViewController, UIViewControllerTransitioningDelegate { public var masterViewController: UIViewController public var detailViewController: UIViewController public weak var delegate: OberholzViewControllerDelegate? let detailContainerView = UIView() var detailTopLayoutConstraint: NSLayoutConstraint? let handleView = OberholzHandleView() public init(masterViewController: UIViewController, detailViewController: UIViewController) { self.masterViewController = masterViewController self.detailViewController = detailViewController super.init(nibName: nil, bundle: nil) self.addChildViewController(masterViewController) self.addChildViewController(detailViewController) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: // MARK: View Life Cycle public override func viewDidLoad() { super.viewDidLoad() view.addSubview(masterViewController.view) masterViewController.view.frame = view.bounds switch detailViewController.preferredStatusBarStyle() { case .LightContent: handleView.fillColor = UIColor(white: 1, alpha: 0.5) default: handleView.fillColor = UIColor(white: 0, alpha: 0.5) } detailContainerView.addSubview(detailViewController.view) detailContainerView.addSubview(handleView) view.addSubview(detailContainerView) detailContainerView.frame = view.bounds.divide(100, fromEdge: .MaxYEdge).slice handleView.frame = detailContainerView.bounds.divide(20, fromEdge: .MinYEdge).slice handleView.autoresizingMask = [.FlexibleWidth, .FlexibleBottomMargin] detailViewController.view.frame = detailContainerView.bounds detailViewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] } public override func updateViewConstraints() { super.updateViewConstraints() if detailTopLayoutConstraint == nil { let isHeightConstraint: (NSLayoutConstraint) -> Bool = { constraint in return constraint.firstAttribute == .Height && constraint.secondAttribute == .NotAnAttribute } // THIS IS HACKZ // As long as we adknowledge that this is a hack, then it's fine, right? // At least we didn't use private APIs. ;) if let topLayoutView = detailViewController.topLayoutGuide as? UIView, constraint = topLayoutView.constraintsAffectingLayoutForAxis(.Vertical).lazy.filter(isHeightConstraint).first { constraint.active = false detailTopLayoutConstraint = constraint detailViewController.topLayoutGuide.heightAnchor.constraintEqualToConstant(20).active = true } } } }
mit
5c4bce9aef10efb0173f9f7fd86c7b99
37.189873
194
0.705336
5.671053
false
false
false
false
OscarSwanros/swift
test/SILGen/enum_resilience.swift
3
2490
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_enum // Resilient enums are always address-only, and switches must include // a default case // CHECK-LABEL: sil hidden @_T015enum_resilience15resilientSwitchy0c1_A06MediumOF : $@convention(thin) (@in Medium) -> () // CHECK: [[BOX:%.*]] = alloc_stack $Medium // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] // CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5 // CHECK: bb1: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb3: // CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]] // CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]] // CHECK-NEXT: destroy_value [[INDIRECT]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb5: // CHECK-NEXT: unreachable // CHECK: bb6: // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] func resilientSwitch(_ m: Medium) { switch m { case .Paper: () case .Canvas: () case .Pamphlet: () case .Postcard: () } } // Indirect enums are still address-only, because the discriminator is stored // as part of the value, so we cannot resiliently make assumptions about the // enum's size // CHECK-LABEL: sil hidden @_T015enum_resilience21indirectResilientEnumy010resilient_A016IndirectApproachOF : $@convention(thin) (@in IndirectApproach) -> () func indirectResilientEnum(_ ia: IndirectApproach) {}
apache-2.0
6d7d120d43b01c2b4129b17ec395aa21
45.111111
209
0.663855
3.346774
false
false
false
false
adam-p/psiphon-tunnel-core
MobileLibrary/iOS/SampleApps/TunneledWebView/TunneledWebView/AppDelegate.swift
1
7701
// // AppDelegate.swift // TunneledWebView // /* Licensed under Creative Commons Zero (CC0). https://creativecommons.org/publicdomain/zero/1.0/ */ import UIKit import PsiphonTunnel @UIApplicationMain @objc class AppDelegate: UIResponder, UIApplicationDelegate, JAHPAuthenticatingHTTPProtocolDelegate { var window: UIWindow? var socksProxyPort: Int = 0 var httpProxyPort: Int = 0 // The instance of PsiphonTunnel we'll use for connecting. var psiphonTunnel: PsiphonTunnel? class func sharedDelegate() -> AppDelegate { var delegate: AppDelegate? if (Thread.isMainThread) { delegate = UIApplication.shared.delegate as? AppDelegate } else { DispatchQueue.main.sync { delegate = UIApplication.shared.delegate as? AppDelegate } } return delegate! } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Set the class delegate and register NSURL subclass // JAHPAuthenticatingHTTPProtocol with NSURLProtocol. // See comments for `setDelegate` and `start` in // JAHPAuthenticatingHTTPProtocol.h /*******************************************************/ /***** *****/ /***** !!! WARNING !!! *****/ /***** *****/ /*******************************************************/ /***** *****/ /***** This methood of proxying UIWebView is not *****/ /***** officially supported and requires extra *****/ /***** steps to proxy audio / video content. *****/ /***** Otherwise audio / video fetching may be *****/ /***** untunneled! *****/ /***** *****/ /***** It is strongly advised that you read the *****/ /***** "Caveats" section of README.md before *****/ /***** using PsiphonTunnel to proxy UIWebView *****/ /***** traffic. *****/ /***** *****/ /*******************************************************/ JAHPAuthenticatingHTTPProtocol.setDelegate(self) JAHPAuthenticatingHTTPProtocol.start() self.psiphonTunnel = PsiphonTunnel.newPsiphonTunnel(self) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. DispatchQueue.global(qos: .default).async { // Start up the tunnel and begin connecting. // This could be started elsewhere or earlier. NSLog("Starting tunnel") guard let success = self.psiphonTunnel?.start(true), success else { NSLog("psiphonTunnel.start returned false") return } // The Psiphon Library exposes reachability functions, which can be used for detecting internet status. let reachability = Reachability.forInternetConnection() let networkStatus = reachability?.currentReachabilityStatus() NSLog("Internet is reachable? \(networkStatus != NotReachable)") } } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Clean up the tunnel NSLog("Stopping tunnel") self.psiphonTunnel?.stop() } } // MARK: TunneledAppDelegate implementation // See the protocol definition for details about the methods. // Note that we're excluding all the optional methods that we aren't using, // however your needs may be different. extension AppDelegate: TunneledAppDelegate { func getPsiphonConfig() -> Any? { // In this example, we're going to retrieve our Psiphon config from a file in the app bundle. // Alternatively, it could be a string literal in the code, or whatever makes sense. guard let psiphonConfigUrl = Bundle.main.url(forResource: "psiphon-config", withExtension: "json") else { NSLog("Error getting Psiphon config resource file URL!") return nil } do { return try String.init(contentsOf: psiphonConfigUrl) } catch { NSLog("Error reading Psiphon config resource file!") return nil } } /// Read the Psiphon embedded server entries resource file and return the contents. /// * returns: The string of the contents of the file. func getEmbeddedServerEntries() -> String? { guard let psiphonEmbeddedServerEntriesUrl = Bundle.main.url(forResource: "psiphon-embedded-server-entries", withExtension: "txt") else { NSLog("Error getting Psiphon embedded server entries resource file URL!") return nil } do { return try String.init(contentsOf: psiphonEmbeddedServerEntriesUrl) } catch { NSLog("Error reading Psiphon embedded server entries resource file!") return nil } } func onDiagnosticMessage(_ message: String, withTimestamp timestamp: String) { NSLog("onDiagnosticMessage(%@): %@", timestamp, message) } func onConnected() { NSLog("onConnected") DispatchQueue.main.sync { let urlString = "https://freegeoip.app/" let url = URL.init(string: urlString)! let mainView = self.window?.rootViewController as! ViewController mainView.loadUrl(url) } } func onListeningSocksProxyPort(_ port: Int) { DispatchQueue.main.async { JAHPAuthenticatingHTTPProtocol.resetSharedDemux() self.socksProxyPort = port } } func onListeningHttpProxyPort(_ port: Int) { DispatchQueue.main.async { JAHPAuthenticatingHTTPProtocol.resetSharedDemux() self.httpProxyPort = port } } }
gpl-3.0
8b6c17c4f569b9b1a81d57438b925423
41.546961
285
0.608103
5.408006
false
false
false
false
BGDigital/mckuai2.0
mckuai/mckuai/community/HttpUrl.swift
1
796
// // HttpUrl.swift // mckuai // // Created by 陈强 on 15/4/30. // Copyright (c) 2015年 XingfuQiu. All rights reserved. // import Foundation let forum_url = URL_MC+"act=forumList" let talk_url = URL_MC+"act=talkList" let webView_url = URL_MC+"act=talkOne" let addTalk_url = URL_MC+"act=addTalk" let followTalk_url = URL_MC+"act=followTalk" let replyTalk_url = URL_MC+"act=replyTalk" let login_url = URL_MC+"act=userLogin" let qqlogin_url = URL_MC+"act=login" let register_url = URL_MC+"act=register" let toCollect_url = URL_MC+"act=toCollect" let isCollect_url = URL_MC+"act=isCollect" let cancleCollect_url = URL_MC+"act=cancleCollect" let getUser_url = URL_MC+"act=getUser" let saveUser_url = URL_MC+"act=saveUser" let daShang_url = URL_MC+"act=daShang" class HttpUrl { }
mit
17b07813ec0d1fc8bcc42da7901d1ad8
20.378378
55
0.702532
2.581699
false
false
false
false
ifels/swiftDemo
RealmDemo/RealmDemo/model/Person.swift
1
802
// // Person.swift // LearningSnapKit // // Created by 聂鑫鑫 on 16/11/14. // Copyright © 2016年 melorriaga. All rights reserved. // import Foundation import RealmSwift class Person: Object { dynamic var name = "" let dogs = List<Dog>() dynamic var id = UUID().uuidString override static func primaryKey() ->String?{ return "id" } // func IncrementaID() -> Int { // let realm = try! Realm() // let RetNext: NSArray = Array(realm.objects(Person).sorted("id")) // let last = RetNext.lastObject // if RetNext.count > 0 { // let valor = last?.valueForKey("id") as? Int // return valor! + 1 // } else { // return 1 // } // } }
apache-2.0
3ae73497f8097e177b75c289e03a20d8
22.323529
78
0.513241
3.830918
false
false
false
false
gottesmm/swift
test/SILGen/objc_bridging.swift
4
27121
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu // REQUIRES: objc_interop import Foundation import Appliances func getDescription(_ o: NSObject) -> String { return o.description } // CHECK-LABEL: sil hidden @_TF13objc_bridging14getDescription // CHECK: bb0({{%.*}} : $NSObject): // CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] {{%.*}} : {{.*}}, #NSObject.description!getter.1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]({{%.*}}) // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]], // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK:} func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // CHECK-LABEL: sil hidden @_TF13objc_bridging18getUppercaseString // CHECK: bb0({{%.*}} : $NSString): // -- The 'self' argument of NSString methods doesn't bridge. // CHECK-NOT: function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK-NOT: function_ref @swift_StringToNSString // CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] {{%.*}} : {{.*}}, #NSString.uppercase!1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]({{%.*}}) // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK: } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { var s = s f.setFoo(s) } // CHECK-LABEL: sil hidden @_TF13objc_bridging6setFoo // CHECK: bb0({{%.*}} : $Foo, {{%.*}} : $String): // CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[F:%.*]] : {{.*}}, #Foo.setFoo!1.foreign // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: select_enum [[OPT_NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data [[OPT_NATIVE]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[NATIVE]]) // CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], %0) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } // @interface Foo -(BOOL) zim; @end func getZim(_ f: Foo) -> Bool { return f.zim() } // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-i386: } // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-watchos-i386: [[BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-watchos-i386: return [[BOOL]] : $Bool // CHECK-watchos-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-ios-x86_64: [[SWIFT_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-ios-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-arm64: [[SWIFT_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-arm64: return [[SWIFT_BOOL]] : $Bool // CHECK-arm64: } // @interface Foo -(void) setZim: (BOOL)b; @end func setZim(_ f: Foo, b: Bool) { f.setZim(b) } // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]({{%.*}}) : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: apply {{%.*}}([[OBJC_BOOL]], {{%.*}}) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-ios-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]({{%.*}}) : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: apply {{%.*}}([[OBJC_BOOL]], {{%.*}}) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-ios-x86_64: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-ios-x86_64: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-arm64: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-arm64: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-arm64: } // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-watchos-i386: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-watchos-i386: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-watchos-i386: } // @interface Foo -(_Bool) zang; @end func getZang(_ f: Foo) -> Bool { return f.zang() } // CHECK-LABEL: sil hidden @_TF13objc_bridging7getZangFCSo3FooSb // CHECK: [[BOOL:%.*]] = apply {{%.*}}(%0) : $@convention(objc_method) (Foo) -> Bool // CHECK: return [[BOOL]] // @interface Foo -(void) setZang: (_Bool)b; @end func setZang(_ f: Foo, _ b: Bool) { f.setZang(b) } // CHECK-LABEL: sil hidden @_TF13objc_bridging7setZangFTCSo3FooSb_T_ // CHECK: apply {{%.*}}(%1, %0) : $@convention(objc_method) (Bool, Foo) -> () // NSString *bar(void); func callBar() -> String { return bar() } // CHECK-LABEL: sil hidden @_TF13objc_bridging7callBar // CHECK: bb0: // CHECK: [[BAR:%.*]] = function_ref @bar // CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK: } // void setBar(NSString *s); func callSetBar(_ s: String) { var s = s setBar(s) } // CHECK-LABEL: sil hidden @_TF13objc_bridging10callSetBar // CHECK: bb0({{%.*}} : $String): // CHECK: [[SET_BAR:%.*]] = function_ref @setBar // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: select_enum [[OPT_NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data [[OPT_NATIVE]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[NATIVE]]) // CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]]) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } var NSS: NSString // -- NSString methods don't convert 'self' extension NSString { var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSStringg13nsstrFakePropS0_ // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSStrings13nsstrFakePropS0_ // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSString11nsstrResult // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSString8nsstrArg // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } } class Bas : NSObject { // -- Bridging thunks for String properties convert between NSString var strRealProp: String = "Hello" // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg11strRealPropSS : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas // CHECK: // function_ref objc_bridging.Bas.strRealProp.getter // CHECK: [[PROPIMPL:%.*]] = function_ref @_TFC13objc_bridging3Basg11strRealPropSS // CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[PROP_COPY]]) // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Basg11strRealPropSS // CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp // CHECK: [[PROP:%.*]] = load [copy] [[PROP_ADDR]] // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass11strRealPropSS : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[VALUE:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]] // CHECK: [[SETIMPL:%.*]] = function_ref @_TFC13objc_bridging3Bass11strRealPropSS // CHECK: apply [[SETIMPL]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bass11strRealPropSS' // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Bass11strRealPropSS // CHECK: bb0(%0 : $String, %1 : $Bas): // CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp // CHECK: assign {{.*}} to [[STR_ADDR]] // CHECK: } var strFakeProp: String { get { return "" } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg11strFakePropSS : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[GETTER:%.*]] = function_ref @_TFC13objc_bridging3Basg11strFakePropSS // CHECK: [[STR:%.*]] = apply [[GETTER]]([[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[STR]]) // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass11strFakePropSS : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[SETTER:%.*]] = function_ref @_TFC13objc_bridging3Bass11strFakePropSS // CHECK: apply [[SETTER]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bass11strFakePropSS' // -- Bridging thunks for explicitly NSString properties don't convert var nsstrRealProp: NSString var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg13nsstrRealPropCSo8NSString : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass13nsstrRealPropCSo8NSString : $@convention(objc_method) (NSString, Bas) -> // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // -- Bridging thunks for String methods convert between NSString func strResult() -> String { return "" } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas9strResult // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[METHOD:%.*]] = function_ref @_TFC13objc_bridging3Bas9strResult // CHECK: [[STR:%.*]] = apply [[METHOD]]([[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[STR]]) // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } func strArg(_ s: String) { } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas6strArg // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[METHOD:%.*]] = function_ref @_TFC13objc_bridging3Bas6strArg // CHECK: apply [[METHOD]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bas6strArgfSST_' // -- Bridging thunks for explicitly NSString properties don't convert func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas11nsstrResult // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Bas8nsstrArg // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } init(str: NSString) { nsstrRealProp = str super.init() } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas8arrayArg{{.*}} : $@convention(objc_method) (NSArray, Bas) -> () // CHECK: bb0([[NSARRAY:%[0-9]+]] : $NSArray, [[SELF:%[0-9]+]] : $Bas): // CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_TZFE10FoundationSa36_unconditionallyBridgeFromObjectiveCfGSqCSo7NSArray_GSax_ // CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type // CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]]) // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC13objc_bridging3Bas{{.*}} : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: destroy_value [[SELF_COPY]] : $Bas // CHECK: return [[RESULT]] : $() func arrayArg(_ array: [AnyObject]) { } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas11arrayResult{{.*}} : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK: bb0([[SELF:%[0-9]+]] : $Bas): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC13objc_bridging3Bas11arrayResult{{.*}} : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_TFE10FoundationSa19_bridgeToObjectiveCfT_CSo7NSArray // CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: destroy_value [[ARRAY]] // CHECK: return [[NSARRAY]] func arrayResult() -> [AnyObject] { return [] } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg9arrayPropGSaSS_ : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass9arrayPropGSaSS_ : $@convention(objc_method) (NSArray, Bas) -> () var arrayProp: [String] = [] } // CHECK-LABEL: sil hidden @_TF13objc_bridging16applyStringBlock{{.*}} : func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : $String): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BLOCK_COPY]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[STRING_COPY]]) // CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]] // CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: destroy_value [[NSSTR]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: destroy_value [[STRING]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] : $String return f(x) } // CHECK: } // end sil function '_TF13objc_bridging16applyStringBlock{{.*}}' // CHECK-LABEL: sil hidden @_TF13objc_bridging15bridgeCFunction func bridgeCFunction() -> (String!) -> (String!) { // CHECK: [[THUNK:%.*]] = function_ref @_TTOFSC18NSStringFromStringFGSQSS_GSQSS_ : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String> // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: return [[THICK]] return NSStringFromString } func forceNSArrayMembers() -> (NSArray, NSArray) { let x = NSArray(objects: nil, count: 0) return (x, x) } // Check that the allocating initializer shim for initializers that take pointer // arguments lifetime-extends the bridged pointer for the right duration. // <rdar://problem/16738050> // CHECK-LABEL: sil shared @_TFCSo7NSArrayC // CHECK: [[SELF:%.*]] = alloc_ref_dynamic // CHECK: [[METHOD:%.*]] = function_ref @_TTOFCSo7NSArrayc // CHECK: [[RESULT:%.*]] = apply [[METHOD]] // CHECK: return [[RESULT]] // Check that type lowering preserves the bool/BOOL distinction when bridging // imported C functions. // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool // FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks // at the underlying Clang decl of the bridged decl to decide whether it needs // bridging. // // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool func bools(_ x: Bool) -> (Bool, Bool) { useBOOL(x) useBool(x) return (getBOOL(), getBool()) } // CHECK-LABEL: sil hidden @_TF13objc_bridging9getFridge // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse): func getFridge(_ home: APPHouse) -> Refrigerator { // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[HOME]]) // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TZFV10Appliances12Refrigerator36_unconditionallyBridgeFromObjectiveC // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]]) // CHECK: destroy_value [[HOME]] : $APPHouse // CHECK: return [[RESULT]] : $Refrigerator return home.fridge } // CHECK-LABEL: sil hidden @_TF13objc_bridging16updateFridgeTemp // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double): func updateFridgeTemp(_ home: APPHouse, delta: Double) { // += // CHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_TFsoi2peFTRSdSd_T_ // Temporary fridge // CHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator // Get operation // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[HOME]]) // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_TZFV10Appliances12Refrigerator36_unconditionallyBridgeFromObjectiveC // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]]) // Addition // CHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature // CHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]]) // Setter // CHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator // CHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign // CHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_TFV10Appliances12Refrigerator19_bridgeToObjectiveCfT_CSo15APPRefrigerator // CHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]]) // CHECK: apply [[SETTER]]([[OBJC_ARG]], [[HOME]]) home.fridge.temperature += delta }
apache-2.0
77b4fd267652de629a49e6385d9e6551
52.489152
247
0.636675
3.389028
false
false
false
false
hongxinhope/UIImageEffects
UIImageEffects/UIImageEffects.swift
1
11870
/* Abstract: This class contains methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ /* UIImageEffects.swift This extension is based on Apple's UIImage category in sample code "Blurring and Tinting an Image": https://developer.apple.com/library/ios/samplecode/UIImageEffects/Introduction/Intro.html#//apple_ref/doc/uid/DTS40013396 Created by Xin Hong on 15/12/5. https://github.com/hongxinhope/UIImageEffects */ import UIKit import Accelerate public extension UIImage { public func applyLightEffect() -> UIImage? { let tintColor = UIColor(white: 1, alpha: 0.3) return applyBlur(radius: 60, tintColor: tintColor, saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { let tintColor = UIColor(white: 0.97, alpha: 0.82) return applyBlur(radius: 40, tintColor: tintColor, saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { let tintColor = UIColor(white: 0.11, alpha: 0.73) return applyBlur(radius: 40, tintColor: tintColor, saturationDeltaFactor: 1.8) } public func applyTintEffect(with tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0 if tintColor.getRed(&r, green: &g, blue: &b, alpha: nil) { effectColor = UIColor(red: r, green: g, blue: b, alpha: effectColorAlpha) } } return applyBlur(radius: 20, tintColor: effectColor, saturationDeltaFactor: -1) } public func applyBlur(radius blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { func preconditionsValid() -> Bool { if size.width < 1 || size.height < 1 { print("error: invalid image size: (\(size.width, size.height). Both width and height must >= 1)") return false } if cgImage == nil { print("error: image must be backed by a CGImage") return false } if let maskImage = maskImage { if maskImage.cgImage == nil { print("error: effectMaskImage must be backed by a CGImage") return false } } return true } guard preconditionsValid() else { return nil } let hasBlur = blurRadius > CGFloat(FLT_EPSILON) let hasSaturationChange = fabs(saturationDeltaFactor - 1) > CGFloat(FLT_EPSILON) let inputCGImage = cgImage! let inputImageScale = scale let inputImageBitmapInfo = inputCGImage.bitmapInfo let inputImageAlphaInfo = CGImageAlphaInfo(rawValue: inputImageBitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) let outputImageSizeInPoints = size let outputImageRectInPoints = CGRect(origin: CGPoint.zero, size: outputImageSizeInPoints) let useOpaqueContext = inputImageAlphaInfo == .none || inputImageAlphaInfo == .noneSkipLast || inputImageAlphaInfo == .noneSkipFirst UIGraphicsBeginImageContextWithOptions(outputImageRectInPoints.size, useOpaqueContext, inputImageScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1, y: -1) outputContext?.translateBy(x: 0, y: -outputImageRectInPoints.height) if hasBlur || hasSaturationChange { var effectInBuffer = vImage_Buffer() var scratchBuffer1 = vImage_Buffer() var inputBuffer: UnsafeMutablePointer<vImage_Buffer> var outputBuffer: UnsafeMutablePointer<vImage_Buffer> let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) var format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: nil, bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: .defaultIntent) let error = vImageBuffer_InitWithCGImage(&effectInBuffer, &format, nil, inputCGImage, vImage_Flags(kvImagePrintDiagnosticsToConsole)) if error != kvImageNoError { print("error: vImageBuffer_InitWithCGImage returned error code \(error)") UIGraphicsEndImageContext() return nil } vImageBuffer_Init(&scratchBuffer1, effectInBuffer.height, effectInBuffer.width, format.bitsPerPixel, vImage_Flags(kvImageNoFlags)) inputBuffer = withUnsafeMutablePointer(to: &effectInBuffer, { (address) -> UnsafeMutablePointer<vImage_Buffer> in return address }) outputBuffer = withUnsafeMutablePointer(to: &scratchBuffer1, { (address) -> UnsafeMutablePointer<vImage_Buffer> in return address }) if hasBlur { var inputRadius = blurRadius * inputImageScale if inputRadius - 2 < CGFloat(FLT_EPSILON) { inputRadius = 2 } var radius = UInt32(floor((inputRadius * CGFloat(3) * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5) / 2)) radius |= 1 let flags = vImage_Flags(kvImageGetTempBufferSize) | vImage_Flags(kvImageEdgeExtend) let tempBufferSize: Int = vImageBoxConvolve_ARGB8888(inputBuffer, outputBuffer, nil, 0, 0, radius, radius, nil, flags) let tempBuffer = malloc(tempBufferSize) vImageBoxConvolve_ARGB8888(inputBuffer, outputBuffer, tempBuffer, 0, 0, radius, radius, nil, vImage_Flags(kvImageEdgeExtend)) vImageBoxConvolve_ARGB8888(outputBuffer, inputBuffer, tempBuffer, 0, 0, radius, radius, nil, vImage_Flags(kvImageEdgeExtend)) vImageBoxConvolve_ARGB8888(inputBuffer, outputBuffer, tempBuffer, 0, 0, radius, radius, nil, vImage_Flags(kvImageEdgeExtend)) free(tempBuffer) let temp = inputBuffer inputBuffer = outputBuffer outputBuffer = temp } if hasSaturationChange { let s = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1, ] let divisor: Int32 = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](repeating: 0, count: matrixSize) for i in 0..<matrixSize { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * CGFloat(divisor))) } vImageMatrixMultiply_ARGB8888(inputBuffer, outputBuffer, saturationMatrix, divisor, nil, nil, vImage_Flags(kvImageNoFlags)) let temp = inputBuffer inputBuffer = outputBuffer outputBuffer = temp } let cleanupBuffer: @convention(c) (UnsafeMutableRawPointer?, UnsafeMutableRawPointer?) -> Void = {(userData, buf_data) -> Void in free(buf_data) } var effectCGImage = vImageCreateCGImageFromBuffer(inputBuffer, &format, cleanupBuffer, nil, vImage_Flags(kvImageNoAllocate), nil) if effectCGImage == nil { effectCGImage = vImageCreateCGImageFromBuffer(inputBuffer, &format, nil, nil, vImage_Flags(kvImageNoFlags), nil) free(inputBuffer.pointee.data) } if let _ = maskImage { outputContext?.draw(inputCGImage, in: outputImageRectInPoints) } outputContext?.saveGState() if let maskImage = maskImage { outputContext?.clip(to: outputImageRectInPoints, mask: maskImage.cgImage!) } outputContext?.draw(effectCGImage!.takeRetainedValue(), in: outputImageRectInPoints) outputContext?.restoreGState() free(outputBuffer.pointee.data) } else { outputContext?.draw(inputCGImage, in: outputImageRectInPoints) } if let tintColor = tintColor { outputContext?.saveGState() outputContext?.setFillColor(tintColor.cgColor) outputContext?.fill(outputImageRectInPoints) outputContext?.restoreGState() } let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
mit
6b64048bbc45c612349c048f8bc6bb49
46.662651
147
0.640125
5.102322
false
false
false
false
grandiere/box
box/Model/GridVisor/Render/Main/MGridVisorRenderFinder.swift
1
2058
import Foundation import MetalKit class MGridVisorRenderFinder:MetalRenderableProtocol { weak var render:MGridVisorRender! private weak var algoItem:MGridAlgoItem? private var colourBuffer:MTLBuffer? private let sequence:MGridVisorRenderFinderSequence private let spatialSquare:MetalSpatialShapeSquarePositive private let positionBuffer:MTLBuffer private let kSize:Float = 220 init( device:MTLDevice, textureLoader:MTKTextureLoader) { let position:MetalPosition = MetalPosition.zero() positionBuffer = device.generateBuffer(bufferable:position) spatialSquare = MetalSpatialShapeSquarePositive( device:device, width:kSize, height:kSize) sequence = MGridVisorRenderFinderSequence(textureLoader:textureLoader) } //MARK: renderable Protocol func render(manager:MetalRenderManager) { guard let rotationBuffer:MTLBuffer = render.rotationBuffer else { return } if let algoItem:MGridAlgoItem = render.controller.targeting { if colourBuffer == nil || algoItem !== self.algoItem { self.algoItem = algoItem colourBuffer = MetalColour.color( device:manager.device, originalColor:algoItem.overlayColour) } guard let texture:MTLTexture = sequence.current(), let colourBuffer:MTLBuffer = self.colourBuffer else { return } manager.renderColour( vertex:spatialSquare.vertexBuffer, position:positionBuffer, rotation:rotationBuffer, colour:colourBuffer, texture:texture) } else { sequence.restart() } } }
mit
a0f03973cffc6f2c86caf65d175dcd60
27.191781
78
0.562196
5.716667
false
false
false
false
acchou/RxGmail
Example/RxGmail/ThreadsViewController.swift
1
1403
import UIKit import RxSwift import RxCocoa class ThreadsViewController: UITableViewController { let disposeBag = DisposeBag() var selectedLabel: Label! var mode: ThreadsQueryMode! override func viewDidLoad() { super.viewDidLoad() let inputs = ThreadsViewModelInputs ( selectedLabel: selectedLabel, mode: mode ) tableView.dataSource = nil let outputs = global.threadsViewModel(inputs) outputs.threadHeaders.bindTo(tableView.rx.items(cellIdentifier: "ThreadCell")) { index, thread, cell in cell.textLabel?.text = thread.subject cell.detailTextLabel?.text = thread.sender } .disposed(by: disposeBag) tableView.rx .modelSelected(Thread.self) .asObservable() .subscribe(onNext: { self.performSegue(withIdentifier: "ShowThreadMessages", sender: $0) }) .disposed(by: disposeBag) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let threadMessagesVC = segue.destination as! ThreadMessagesViewController let selectedThread = sender as! Thread threadMessagesVC.threadId = selectedThread.identifier } }
mit
cd58671e8d52237cbcc7cc3b73b82dfb
30.177778
111
0.650748
5.196296
false
false
false
false