repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
roecrew/AudioKit
AudioKit/Common/Playgrounds/Filters.playground/Pages/Low Pass Butterworth Filter.xcplaygroundpage/Contents.swift
1
1367
//: ## Low Pass Butterworth Filter //: A low-pass filter takes an audio signal as an input, and cuts out the //: high-frequency components of the audio signal, allowing for the //: lower frequency components to "pass through" the filter. //: import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var filter = AKLowPassButterworthFilter(player) filter.cutoffFrequency = 500 // Hz AudioKit.output = filter AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Low Pass Butterworth Filter") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: filtersPlaygroundFiles)) addSubview(AKBypassButton(node: filter)) addSubview(AKPropertySlider( property: "Cutoff Frequency", format: "%0.1f Hz", value: filter.cutoffFrequency, minimum: 20, maximum: 22050, color: AKColor.greenColor() ) { sliderValue in filter.cutoffFrequency = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
57acc1a4d04d75f9c88ffbdb0bb6e97d
28.717391
73
0.686174
4.989051
false
false
false
false
adamontherun/Study-iOS-With-Adam-Live
DragDropData/DragDropData/Dog.swift
1
2413
//Some text. import UIKit import MobileCoreServices let dogTypeIdentifier = "com.wooffactory.test" final class Dog: NSObject { let maxBarkVolume: Int? var image: UIImage init(image: UIImage, maxBarkVolume: Int?) { self.maxBarkVolume = maxBarkVolume self.image = image } } extension Dog: NSItemProviderReading { static var readableTypeIdentifiersForItemProvider: [String] { return [dogTypeIdentifier, kUTTypePNG as String] } static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self { switch typeIdentifier { case dogTypeIdentifier: guard let dog = NSKeyedUnarchiver.unarchiveObject(with: data) as? Dog else { throw DogError.cantMakeDog } return self.init(image: dog.image, maxBarkVolume: dog.maxBarkVolume) case kUTTypePNG as NSString as String: guard let image = UIImage(data: data) else { throw DogError.cantMakeDog } return self.init(image: image, maxBarkVolume: nil) default: throw DogError.cantMakeDog } } } extension Dog: NSItemProviderWriting { static var writableTypeIdentifiersForItemProvider: [String] { return [dogTypeIdentifier, kUTTypePNG as String] } func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? { switch typeIdentifier { case dogTypeIdentifier: let data = NSKeyedArchiver.archivedData(withRootObject: self) completionHandler(data, nil) case kUTTypePNG as NSString as String: completionHandler(UIImagePNGRepresentation(image), nil) default: completionHandler(nil, DogError.cantMakeDog) } return nil } } extension Dog: NSCoding { func encode(with aCoder: NSCoder) { aCoder.encode(image, forKey: "image") if let maxBarkVolume = maxBarkVolume {aCoder.encode(maxBarkVolume, forKey: "maxBarkVolume")} } convenience init?(coder aDecoder: NSCoder) { guard let dogImage = aDecoder.decodeObject(forKey: "image") as? UIImage else { return nil } let maxBarkVolume = aDecoder.decodeInteger(forKey: "maxBarkVolume") self.init(image: dogImage, maxBarkVolume: maxBarkVolume) } }
mit
b10b71859ecbb3fd7c04677875ef03e2
32.054795
162
0.670535
4.518727
false
false
false
false
cikelengfeng/HTTPIDL
Sources/Runtime/Tool/MultipartFormData.swift
1
25231
// // MultipartFormData.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 #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(macOS) import CoreServices #endif public enum MultipartFormDataEncodeError: HIError { case bodyPartURLInvalid(url: URL) case bodyPartFilenameInvalid(in: URL) case bodyPartFileNotReachable(at: URL) case bodyPartFileNotReachableWithError(atURL: URL, error: Error) case bodyPartFileIsDirectory(at: URL) case bodyPartFileSizeNotAvailable(at: URL) case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) case bodyPartInputStreamCreationFailed(for: URL) case outputStreamCreationFailed(for: URL) case outputStreamFileAlreadyExists(at: URL) case outputStreamURLInvalid(url: URL) case outputStreamWriteFailed(error: Error) case inputStreamReadFailed(error: Error) } /// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode /// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead /// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the /// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for /// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. /// /// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well /// and the w3 form documentation. /// /// - https://www.ietf.org/rfc/rfc2388.txt /// - https://www.ietf.org/rfc/rfc2045.txt /// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 open class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func randomBoundary() -> String { return String(format: "httpidl.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { case .initial: boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" case .encapsulated: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" case .final: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } class BodyPart { let headers: [String: String] let bodyStream: InputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: InputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: MultipartFormDataEncodeError? private let streamBufferSize: Int // MARK: - Lifecycle /// Creates a multipart form data object. /// /// - returns: The multipart form data object. public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /// /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more /// information, please refer to the following article: /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html /// self.streamBufferSize = 1024 } // MARK: - Body Parts /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. public func append(_ data: Data, withName name: String) { let headers = contentHeaders(withName: name) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, mimeType: String) { let headers = contentHeaders(withName: name, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the /// system associated MIME type. /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. public func append(_ fileURL: URL, withName name: String) { let fileName = fileURL.lastPathComponent let pathExtension = fileURL.pathExtension if !fileName.isEmpty && !pathExtension.isEmpty { let mime = mimeType(forPathExtension: pathExtension) append(fileURL, withName: name, fileName: fileName, mimeType: mime) } else { setBodyPartError(error: .bodyPartFilenameInvalid(in: fileURL)) } } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) /// - Content-Type: #{mimeType} (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.isFileURL else { setBodyPartError(error: .bodyPartURLInvalid(url: fileURL)) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ do { let isReachable = try fileURL.checkPromisedItemIsReachable() guard isReachable else { setBodyPartError(error: .bodyPartFileNotReachable(at: fileURL)) return } } catch { setBodyPartError(error: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false let path = fileURL.path guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { setBodyPartError(error: .bodyPartFileIsDirectory(at: fileURL)) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ let bodyContentLength: UInt64 do { guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { setBodyPartError(error: .bodyPartFileSizeNotAvailable(at: fileURL)) return } bodyContentLength = fileSize.uint64Value } catch { setBodyPartError(error: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = InputStream(url: fileURL) else { setBodyPartError(error: .bodyPartInputStreamCreationFailed(for: fileURL)) return } append(stream, withLength: bodyContentLength, headers: headers) } /// Creates a body part from the stream and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. public func append( _ stream: InputStream, withLength length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) append(stream, withLength: length, headers: headers) } /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - HTTP headers /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter headers: The HTTP headers for the body part. public func append(_ stream: InputStream, withLength length: UInt64, headers: [String: String]) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /// Encodes all the appended body parts into a single `Data` value. /// /// It is important to note that this method will load all the appended body parts into memory all at the same /// time. This method should only be used when the encoded data will have a small memory footprint. For large data /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. /// /// - throws: An `AFError` if encoding encounters an error. /// /// - returns: The encoded `Data` if encoding is successful. public func encode() throws -> Data { if let bodyPartError = bodyPartError { throw bodyPartError } var encoded = Data() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encode(bodyPart) encoded.append(encodedData) } return encoded } /// Writes the appended body parts into the given file URL. /// /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, /// this approach is very memory efficient and should be used for large body part data. /// /// - parameter fileURL: The file URL to write the multipart form data into. /// /// - throws: An `AFError` if encoding encounters an error. public func writeEncodedData(to fileURL: URL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if FileManager.default.fileExists(atPath: fileURL.path) { throw MultipartFormDataEncodeError.outputStreamFileAlreadyExists(at: fileURL) } else if !fileURL.isFileURL { throw MultipartFormDataEncodeError.outputStreamURLInvalid(url: fileURL) } guard let outputStream = OutputStream(url: fileURL, append: false) else { throw MultipartFormDataEncodeError.outputStreamCreationFailed(for: fileURL) } outputStream.open() defer { outputStream.close() } self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try write(bodyPart, to: outputStream) } } // MARK: - Private - Body Part Encoding private func encode(_ bodyPart: BodyPart) throws -> Data { var encoded = Data() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.append(initialData) let headerData = encodeHeaders(for: bodyPart) encoded.append(headerData) let bodyStreamData = try encodeBodyStream(for: bodyPart) encoded.append(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.append(finalBoundaryData()) } return encoded } private func encodeHeaders(for bodyPart: BodyPart) -> Data { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.crlf)" } headerText += EncodingCharacters.crlf return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let error = inputStream.streamError { throw MultipartFormDataEncodeError.inputStreamReadFailed(error: error) } if bytesRead > 0 { encoded.append(buffer, count: bytesRead) } else { break } } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { try writeInitialBoundaryData(for: bodyPart, to: outputStream) try writeHeaderData(for: bodyPart, to: outputStream) try writeBodyStream(for: bodyPart, to: outputStream) try writeFinalBoundaryData(for: bodyPart, to: outputStream) } private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try write(initialData, to: outputStream) } private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let headerData = encodeHeaders(for: bodyPart) return try write(headerData, to: outputStream) } private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw MultipartFormDataEncodeError.inputStreamReadFailed(error: streamError) } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } try write(&buffer, to: outputStream) } else { break } } } private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { if bodyPart.hasFinalBoundary { return try write(finalBoundaryData(), to: outputStream) } } // MARK: - Private - Writing Buffered Data to Output Stream private func write(_ data: Data, to outputStream: OutputStream) throws { var buffer = [UInt8](repeating: 0, count: data.count) data.copyBytes(to: &buffer, count: data.count) return try write(&buffer, to: outputStream) } private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws { var bytesToWrite = buffer.count while bytesToWrite > 0, outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let error = outputStream.streamError { throw MultipartFormDataEncodeError.outputStreamWriteFailed(error: error) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } } // MARK: - Private - Mime Type private func mimeType(forPathExtension pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { var disposition = "form-data; name=\"\(name)\"" if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } var headers = ["Content-Disposition": disposition] if let mimeType = mimeType { headers["Content-Type"] = mimeType } return headers } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) } private func encapsulatedBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) } private func finalBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(error: MultipartFormDataEncodeError) { guard bodyPartError == nil else { return } bodyPartError = error } func stream() -> InputStream { self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true let partStream = self.bodyParts.flatMap { (part) -> [InputStream] in var ss = [InputStream]() let initialData = part.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() let headerData = encodeHeaders(for: part) ss.append(InputStream(data: initialData)) ss.append(InputStream(data: headerData)) ss.append(part.bodyStream) if part.hasFinalBoundary { let finalData = finalBoundaryData() ss.append(InputStream(data: finalData)) } return ss } let compoundStream = CompoundInputStream.create(withSubStream: partStream) return compoundStream } }
mit
faa80a746eec1019fa935fc46a859b97
39.695161
142
0.637311
4.950167
false
false
false
false
imclean/JLDishWashers
JLDishwasher/Options.swift
1
2453
// // Options.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class Options { public var dateMessage : String? public var id : Int? public var price : Double? public var trialMessage : String? public var standardDescription : String? public var date : String? public var shortDescription : String? public var currency : String? /** Returns an array of models based on given dictionary. Sample usage: let options_list = Options.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of Options Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [Options] { var models:[Options] = [] for item in array { models.append(Options(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let options = Options(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: Options Instance. */ required public init?(dictionary: NSDictionary) { dateMessage = dictionary["dateMessage"] as? String id = dictionary["id"] as? Int price = dictionary["price"] as? Double trialMessage = dictionary["trialMessage"] as? String standardDescription = dictionary["standardDescription"] as? String date = dictionary["date"] as? String shortDescription = dictionary["shortDescription"] as? String currency = dictionary["currency"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.dateMessage, forKey: "dateMessage") dictionary.setValue(self.id, forKey: "id") dictionary.setValue(self.price, forKey: "price") dictionary.setValue(self.trialMessage, forKey: "trialMessage") dictionary.setValue(self.standardDescription, forKey: "standardDescription") dictionary.setValue(self.date, forKey: "date") dictionary.setValue(self.shortDescription, forKey: "shortDescription") dictionary.setValue(self.currency, forKey: "currency") return dictionary } }
gpl-3.0
da7f8e62f78c671e05f15c87db57d3ee
28.542169
89
0.694127
4.450091
false
false
false
false
nasust/LeafViewer
LeafViewer/classes/ImageFileManager/ImageFileSystemManager.swift
1
5602
// // Created by hideki on 2017/06/20. // Copyright (c) 2017 hideki. All rights reserved. // import Foundation import Cocoa class ImageFileSystemManager: ImageFileManagerProto { static let typeExtensions: [String] = ["jpg", "jpeg", "png", "gif", "bmp"] static func isTargetFile(fileName: String) -> Bool { let fileManager = FileManager.default var isDir: ObjCBool = false if fileManager.fileExists(atPath: fileName, isDirectory: &isDir) { if isDir.boolValue { do { let files = try fileManager.contentsOfDirectory(atPath: fileName) for file in files { for fileType in ImageFileSystemManager.typeExtensions { if NSString(string: file).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame { return true } } } } catch { return false } } else { for fileType in typeExtensions { if NSString(string: fileName).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame { return true } } } } return false } private var directoryImageFiles = [String]() private var currentImageIndex = 0 var currentImage: NSImage? { get { if self.directoryImageFiles.count > 0 { let image = NSImage(contentsOfFile: directoryImageFiles[currentImageIndex]) var width = 0 var height = 0 for imageRep in image!.representations { if imageRep.pixelsWide > width { width = imageRep.pixelsWide } if imageRep.pixelsHigh > height { height = imageRep.pixelsHigh } } let viewImage = NSImage(size: NSMakeSize(CGFloat(width), CGFloat(height))) viewImage.addRepresentations(image!.representations) return viewImage } else { return nil } } } var currentImageFileName: String? { get { if self.directoryImageFiles.count > 0 { return directoryImageFiles[currentImageIndex] } else { return nil } } } var currentIndex: Int { get { return self.currentImageIndex } } var totalCount: Int { get { return self.directoryImageFiles.count } } func doNext() -> Bool { if (self.currentImageIndex + 1 < directoryImageFiles.count) { self.currentImageIndex += 1 return true } return false } func doPrev() -> Bool { if (self.currentImageIndex - 1 >= 0) { self.currentImageIndex -= 1 return true } return false } func doFirst() -> Bool { if self.directoryImageFiles.count > 0 { self.currentImageIndex = 0 return true } return true } func doLast() -> Bool { if self.directoryImageFiles.count > 0 { self.currentImageIndex = self.directoryImageFiles.count - 1 return true } return true } func hasNext() -> Bool { return self.currentImageIndex + 1 < directoryImageFiles.count } func hasPrev() -> Bool { return self.currentImageIndex - 1 >= 0 } init() { } func processFile(fileName: String) -> Bool { let fileManager = FileManager.default var isDir: ObjCBool = false if fileManager.fileExists(atPath: fileName, isDirectory: &isDir) { if isDir.boolValue { return self.processImageDirectory(directory: fileName) } else { return self.processImageFile(fileName: fileName) } } return false } private func processImageFile(fileName: String) -> Bool { let directoryPath = NSString(string: fileName).deletingLastPathComponent if self.processImageDirectory(directory: directoryPath) { self.currentImageIndex = self.directoryImageFiles.index(of: fileName)! return true } return false } private func processImageDirectory(directory: String) -> Bool { let fileManager = FileManager.default var currentDirectoryImageFiles = [String]() do { let files = try fileManager.contentsOfDirectory(atPath: directory) for file in files { var hit = false; for fileType in ImageFileSystemManager.typeExtensions { if NSString(string: file).pathExtension.caseInsensitiveCompare(fileType) == .orderedSame { hit = true break } } if hit { currentDirectoryImageFiles.append(directory + "/" + file) } } } catch { return false } self.directoryImageFiles = currentDirectoryImageFiles.sorted() self.currentImageIndex = 0 return true } func imageData(fileName: String) -> Data?{ return NSData(contentsOfFile: fileName) as Data! } }
gpl-3.0
8106953c1dd248c745c15b1320ebcb7a
26.732673
118
0.52517
5.524655
false
false
false
false
tungvoduc/DTPhotoViewerController
DTPhotoViewerController/Classes/DTPhotoCollectionViewCell.swift
1
7619
// // DTPhotoCollectionViewCell.swift // Pods // // Created by Admin on 17/01/2017. // // import UIKit public protocol DTPhotoCollectionViewCellDelegate: NSObjectProtocol { func collectionViewCellDidZoomOnPhoto(_ cell: DTPhotoCollectionViewCell, atScale scale: CGFloat) func collectionViewCellWillZoomOnPhoto(_ cell: DTPhotoCollectionViewCell) func collectionViewCellDidEndZoomingOnPhoto(_ cell: DTPhotoCollectionViewCell, atScale scale: CGFloat) } open class DTPhotoCollectionViewCell: UICollectionViewCell { public private(set) var scrollView: DTScrollView! public private(set) var imageView: UIImageView! // default is 1.0 open var minimumZoomScale: CGFloat = 1.0 { willSet { if imageView.image == nil { scrollView.minimumZoomScale = 1.0 } else { scrollView.minimumZoomScale = newValue } } didSet { correctCurrentZoomScaleIfNeeded() } } // default is 3.0. open var maximumZoomScale: CGFloat = 3.0 { willSet { if imageView.image == nil { scrollView.maximumZoomScale = 1.0 } else { scrollView.maximumZoomScale = newValue } } didSet { correctCurrentZoomScaleIfNeeded() } } weak var delegate: DTPhotoCollectionViewCellDelegate? public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } open override func prepareForReuse() { super.prepareForReuse() scrollView.zoomScale = 1.0 } private func commonInit() { backgroundColor = UIColor.clear isUserInteractionEnabled = true scrollView = DTScrollView(frame: CGRect.zero) scrollView.minimumZoomScale = minimumZoomScale scrollView.maximumZoomScale = 1.0 // Not allow zooming when there is no image let imageView = DTImageView(frame: CGRect.zero) // Layout subviews every time getting new image imageView.imageChangeBlock = { [weak self] image in // Update image frame whenever image changes if let strongSelf = self { if image == nil { strongSelf.scrollView.minimumZoomScale = 1.0 strongSelf.scrollView.maximumZoomScale = 1.0 } else { strongSelf.scrollView.minimumZoomScale = strongSelf.minimumZoomScale strongSelf.scrollView.maximumZoomScale = strongSelf.maximumZoomScale strongSelf.setNeedsLayout() } strongSelf.correctCurrentZoomScaleIfNeeded() } } imageView.contentMode = .scaleAspectFit self.imageView = imageView scrollView.delegate = self contentView.addSubview(scrollView) scrollView.addSubview(imageView) if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } } private func correctCurrentZoomScaleIfNeeded() { if scrollView.zoomScale < scrollView.minimumZoomScale { scrollView.zoomScale = scrollView.minimumZoomScale } if scrollView.zoomScale > scrollView.maximumZoomScale { scrollView.zoomScale = scrollView.maximumZoomScale } } override open func layoutSubviews() { super.layoutSubviews() scrollView.frame = bounds //Set the aspect ration of the image if let image = imageView.image { let size = image.size let horizontalScale = size.width / scrollView.frame.width let verticalScale = size.height / scrollView.frame.height let factor = max(horizontalScale, verticalScale) //Divide the size by the greater of the vertical or horizontal shrinkage factor let width = size.width / factor let height = size.height / factor if scrollView.zoomScale != 1 { // If current zoom scale is not at default value, we need to maintain // imageView's size while laying out subviews // Calculate new zoom scale corresponding to current default size to maintain // imageView's size let newZoomScale = scrollView.zoomScale * imageView.bounds.width / width // Update scrollView's maximumZoomScale or minimumZoomScale if needed // in order to ensure that updating its zoomScale works. if newZoomScale > scrollView.maximumZoomScale { scrollView.maximumZoomScale = newZoomScale } else if newZoomScale < scrollView.minimumZoomScale { scrollView.minimumZoomScale = newZoomScale } // Reset scrollView's maximumZoomScale or minimumZoomScale if needed if newZoomScale <= maximumZoomScale, scrollView.maximumZoomScale > maximumZoomScale { scrollView.maximumZoomScale = maximumZoomScale } if newZoomScale >= minimumZoomScale, scrollView.minimumZoomScale < minimumZoomScale { scrollView.minimumZoomScale = minimumZoomScale } // After updating scrollView's zoomScale, imageView's size will be updated // We need to revert it back to its original size. let imageViewSize = imageView.frame.size scrollView.setZoomScale(newZoomScale, animated: false) imageView.frame.size = imageViewSize // CGSize(width: width * newZoomScale, height: height * newZoomScale) scrollView.contentSize = imageViewSize } else { // If current zoom scale is at default value, just update imageView's size let x = (scrollView.frame.width - width) / 2 let y = (scrollView.frame.height - height) / 2 imageView.frame = CGRect(x: x, y: y, width: width, height: height) } } } } //MARK: - UIScrollViewDelegate extension DTPhotoCollectionViewCell: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { delegate?.collectionViewCellWillZoomOnPhoto(self) } public func scrollViewDidZoom(_ scrollView: UIScrollView) { updateImageViewFrameForSize(frame.size) delegate?.collectionViewCellDidZoomOnPhoto(self, atScale: scrollView.zoomScale) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { } public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { delegate?.collectionViewCellDidEndZoomingOnPhoto(self, atScale: scale) } fileprivate func updateImageViewFrameForSize(_ size: CGSize) { let y = max(0, (size.height - imageView.frame.height) / 2) let x = max(0, (size.width - imageView.frame.width) / 2) imageView.frame.origin = CGPoint(x: x, y: y) } }
mit
7049e1040698d619290ab4516ad7d6dd
36.717822
122
0.606904
5.943058
false
false
false
false
ytfhqqu/iCC98
iCC98/iCC98/MeTableViewController.swift
1
9892
// // MeTableViewController.swift // iCC98 // // Created by Duo Xu on 5/1/17. // Copyright © 2017 Duo Xu. // // 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 Alamofire import SVProgressHUD import FLAnimatedImage import CC98Kit class MeTableViewController: UITableViewController { @IBOutlet weak var accountCell: UITableViewCell! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var genderLabel: UILabel! @IBOutlet weak var portraitImageView: FLAnimatedImageView! @IBOutlet weak var openEasyConnectCell: UITableViewCell! @IBOutlet weak var signOutCell: UITableViewCell! @IBOutlet weak var messagesButtonItem: UIBarButtonItem! @IBOutlet weak var loginButtonItem: UIBarButtonItem! // MARK: - Data /// 用户的信息。 private var userInfo: UserInfo? { didSet { updateUI() } } /// 获取数据。 private func fetchData(accessToken: String) { _ = CC98API.getInfoOfCurrentUser(accessToken: accessToken) { [weak self] result in switch result { case .success(_, let data): if let userInfo = data { self?.userInfo = userInfo } case .failure(let status, let message): SVProgressHUD.showError(statusCode: status, message: message) case .noResponse: SVProgressHUD.showNoResponseError() } } } // MARK: - UI // 更新 UI private func updateUI() { accountCell?.accessoryType = .disclosureIndicator if let userName = userInfo?.name, let gender = userInfo?.gender { // 用户名 userNameLabel?.text = userName // 性别 if gender == CC98Kit.Constants.UserGender.male.rawValue { genderLabel?.text = "♂" genderLabel?.textColor = Constants.maleColor } else { genderLabel?.text = "♀" genderLabel?.textColor = Constants.femaleColor } } // 加载头像 if let portraitUrl = userInfo?.portraitUrl { Constants.alamofireSessionManager.request(portraitUrl).responseData { [weak self] response in // 处理响应 switch response.result { case .success(let value): // 有响应 if let statusCode = response.response?.statusCode { switch statusCode { case 200..<300: // HTTP 2xx,表示成功的状态码 // 展示图像 if response.response?.mimeType == "image/gif" { self?.portraitImageView?.animatedImage = FLAnimatedImage(animatedGIFData: value) } else { self?.portraitImageView?.image = UIImage(data: value) } default: // 其余的 HTTP 状态码均认为是失败,包括 4xx、5xx 和 3xx 等 break } } else { fallthrough } case .failure: // 无响应 break } } } } // 把 UI 复位到未登录的状态 private func resetUINotSignedIn() { // 复位账号信息单元格 accountCell?.accessoryType = .none userNameLabel?.text = "登录" genderLabel?.text = " " portraitImageView?.image = #imageLiteral(resourceName: "AvatarPlaceholder") // 隐藏“退出登录”单元格 signOutCell?.isHidden = true // “消息”按钮不可用 messagesButtonItem?.isEnabled = false } // 把 UI 调整为已登录的状态 private func resetUISignedIn(accessToken: String) { // 获取账号信息 fetchData(accessToken: accessToken) // 显示“退出登录”单元格 signOutCell?.isHidden = false // “消息”按钮可用 messagesButtonItem?.isEnabled = true } // MARK: - View controller lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if OAuthUtility.accessTokenIsValid { resetUISignedIn(accessToken: OAuthUtility.accessToken!) } else { resetUINotSignedIn() } } // MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 按下特定的单元格会触发操作 if indexPath.section == 2 { // 第三节是打开“EasyConnect”单元格 if let easyConnectScheme = URL(string: "ioseasyconnect://") { if UIApplication.shared.canOpenURL(easyConnectScheme) { if #available(iOS 10, *) { UIApplication.shared.open(easyConnectScheme, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(easyConnectScheme) } } else { // 创建并展示一个确认对话框 let alertController = UIAlertController(title: "未安装 EasyConnect", message: "在 App Store 搜索“EasyConnect”下载安装。", preferredStyle: .alert) let okAction = UIAlertAction(title: "确定", style: .default) alertController.addAction(okAction) self.present(alertController, animated: true) } } // 单元格恢复为未选中的状态 tableView.deselectRow(at: indexPath, animated: true) } else if indexPath.section == 3 { // 第四节是“退出登录”单元格 // 创建并展示一个上拉菜单(iPhone)或弹框(iPad) let alertControllerStyle: UIAlertControllerStyle switch UIDevice.current.userInterfaceIdiom { case .phone: alertControllerStyle = .actionSheet default: alertControllerStyle = .alert } let alertController = UIAlertController(title: nil, message: "退出登录后,部分版面将无法访问,发帖、短消息等功能将无法使用。", preferredStyle: alertControllerStyle) let cancelAction = UIAlertAction(title: "取消", style: .cancel) let destroyAction = UIAlertAction(title: "退出登录", style: .destructive) { [weak self] action in // 选择“退出登录”后的操作 // 清除所有令牌信息 OAuthUtility.signOut() // UI 恢复为尚未登录的状态 self?.resetUINotSignedIn() } alertController.addAction(cancelAction) alertController.addAction(destroyAction) self.present(alertController, animated: true) // 单元格恢复为未选中的状态 tableView.deselectRow(at: indexPath, animated: true) } } // 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?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "Account", let userInfoTVC = segue.destination as? UserInfoTableViewController { userInfoTVC.setData(id: userInfo?.id ?? 0) } else if segue.identifier == "Messages", let messageTVC = segue.destination as? MessageTableViewController { messageTVC.setData(userName: userInfo?.name ?? "") } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "Account" && !OAuthUtility.accessTokenIsValid { // 令牌无效时,需要登录并授权 OAuthUtility.authorize(displaySafariOn: self) { [weak self] result in switch result { case .success(token: let tokenInfo): self?.resetUISignedIn(accessToken: tokenInfo.accessToken!) default: break } } // 不能查看自己的账号信息 return false } return true } }
mit
4561b59c4ead387a542b998c43e8901c
38.04661
154
0.570049
5.130846
false
false
false
false
bengottlieb/marcel
Source/Marcel/Header.swift
1
2832
// // MIMEMessage.Part.Header.swift // Marcel // // Created by Ben Gottlieb on 9/1/17. // Copyright © 2017 Stand Alone, inc. All rights reserved. // import Foundation extension MIMEMessage.Part { public struct Header: CustomStringConvertible, CustomDebugStringConvertible { public enum Kind: String { case returnPath = "return-path" case received = "received" case authenticationResults = "authentication-results" case receivedSPF = "received-spf" case subject, from, to, date, sender case replyTo = "reply-to" case messageID = "message-id" case mailer = "x-mailer" case listUnsubscribe = "list-unsubscribe" case contentType = "content-type" case contentTransferEncoding = "content-transfer-encoding" case dkimSignature = "DKIM-Signature" } let raw: String let name: String let kind: Kind? let body: String var cleanedBody: String { return self.body.decodedFromUTF8Wrapping } init(_ string: String) { let components = string.components(separatedBy: ":") self.name = components.first ?? "" self.body = Array(components[1...]).joined(separator: ":").trimmingCharacters(in: .whitespaces) self.kind = Kind(rawValue: self.name.lowercased()) self.raw = string } var keyValues: [String: String] { let trimThese = CharacterSet(charactersIn: "\"").union(.whitespacesAndNewlines) let commaComponents = self.body.components(separatedBy: ",") let seimcolonComponents = self.body.components(separatedBy: ";") let components = seimcolonComponents.count > 1 ? seimcolonComponents : commaComponents var results: [String: String] = [:] for component in components { let pieces = component.components(separatedBy: "=") guard pieces.count >= 2 else { continue } let key = pieces[0].trimmingCharacters(in: trimThese).components(separatedBy: .whitespaces).last! results[key] = Array(pieces[1...]).joined(separator: "=").trimmingCharacters(in: trimThese) } return results } var boundaryValue: String? { for (key, value) in self.keyValues { if key.contains("boundary") { return value } } return nil } public var description: String { if let kind = self.kind { return "\(kind.rawValue): \(self.body)" } return "\"\(self.name)\": \(self.body)" } public var debugDescription: String { return self.description } } } extension Array where Element == MIMEMessage.Part.Header { func allHeaders(ofKind kind: MIMEMessage.Part.Header.Kind) -> [MIMEMessage.Part.Header] { return self.filter { header in return header.kind == kind } } subscript(_ kind: MIMEMessage.Part.Header.Kind) -> MIMEMessage.Part.Header? { for header in self { if header.kind == kind { return header }} return nil } } extension CharacterSet { static let quotes = CharacterSet(charactersIn: "\"'") }
mit
b32ff9a126c268ca0785fdad6c3b6adb
30.455556
101
0.695161
3.662354
false
false
false
false
jwfriese/Fleet
Fleet/CoreExtensions/TableView/UITableViewRowAction+Fleet.swift
1
1500
import UIKit import ObjectiveC private var handlerAssociatedKey: UInt = 0 @objc private class ObjectifiedBlock: NSObject { var block: ((UITableViewRowAction, IndexPath) -> Void)? init(block: ((UITableViewRowAction, IndexPath) -> Void)?) { self.block = block } } extension UITableViewRowAction { var handler: ((UITableViewRowAction, IndexPath) -> Void)? { get { return fleet_property_handler } } fileprivate var fleet_property_handler: ((UITableViewRowAction, IndexPath) -> Void)? { get { let block = objc_getAssociatedObject(self, &handlerAssociatedKey) as? ObjectifiedBlock return block?.block } set { let block = ObjectifiedBlock(block: newValue) objc_setAssociatedObject(self, &handlerAssociatedKey, block, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } @objc class func swizzleInit() { Fleet.swizzle( originalSelector: Selector(("_initWithStyle:title:handler:")), swizzledSelector: #selector(UITableViewRowAction.fleet_init(withStyle:title:handler:)), forClass: self ) } @objc func fleet_init(withStyle style: UITableViewRowAction.Style, title: String?, handler: @escaping ((UITableViewRowAction, IndexPath) -> Swift.Void)) -> UITableViewRowAction { fleet_property_handler = handler return fleet_init(withStyle: style, title: title, handler: handler) } }
apache-2.0
c0a55e46c7f0315d5eaed2d2be299bc9
32.333333
182
0.656
4.918033
false
false
false
false
shalex9154/XCGLogger-Firebase
XCGLogger+Firebase/FirebaseDestination.swift
1
6898
// // FirebaseDestination.swift // XCGLogger+Firebase // // Created by Oleksii Shvachenko on 9/27/17. // Copyright © 2017 oleksii. All rights reserved. // import Foundation import XCGLogger import FirebaseCommunity import CryptoSwift struct LogDecorator { let log: LogDetails let deviceOS: String let deviceName: String let deviceID: String private let formatter = ISO8601DateFormatter() init(log: LogDetails) { self.log = log let device = UIDevice.current deviceID = device.identifierForVendor!.uuidString deviceName = device.modelName deviceOS = "\(device.systemName) \(device.systemVersion)" } var json: [String: Any] { let tagsKey = XCGLogger.Constants.userInfoKeyTags let result: [String] if let tags = log.userInfo[tagsKey] as? [String] { result = tags } else if let tags = log.userInfo[tagsKey] as? String { result = [tags] } else { result = [] } return [ "level": log.level.description, "date": formatter.string(from: log.date), "message": log.message, "functionName": log.functionName, "fileName": log.fileName, "lineNumber": log.lineNumber, "deviceID": deviceID, "deviceName": deviceName, "deviceOS": deviceOS, "tags": result ] } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator" default: return identifier } } } private protocol DataSaver { func save(logDetails: LogDecorator, message: String) } private class EncryptedFirebaseDataSaver: DataSaver { private let firebaseRef: DatabaseReference private let aesEncoder: AES init(firebaseRef: DatabaseReference, aesEncoder: AES) { self.firebaseRef = firebaseRef self.aesEncoder = aesEncoder } func save(logDetails: LogDecorator, message: String) { let data = try! JSONSerialization.data(withJSONObject: logDetails.json, options: JSONSerialization.WritingOptions(rawValue: 0)) let raw = try! aesEncoder.encrypt(data.bytes) let encryptedData = Data(bytes: raw) firebaseRef.child(message.md5()).setValue(encryptedData.toHexString()) } } public class FirebaseDestination: BaseDestination { public struct EncryptionParams { let key: String let iv: String init(key: String, iv: String) { precondition(key.count == iv.count, "Key and iv should have the same length of 16 characters") self.key = key self.iv = iv } } private let dataSaver: DataSaver /** Designated initialization - Parameter encryptionKey: key to use in AES 128 encryption. - Parameter firebaseSettingsPath: path to plist generated by goole, Bundle.main.path(forResource: "FirebaseSetting", ofType: "plist"). */ public init?(firebaseSettingsPath: String, encryptionParams: EncryptionParams) { guard let options = FirebaseOptions(contentsOfFile: firebaseSettingsPath) else { return nil } guard let aesEncoder = try? AES(key: encryptionParams.key, iv: encryptionParams.iv) else { return nil } FirebaseApp.configure(name: "FirebaseLogs", options: options) let app = FirebaseApp.app(name: "FirebaseLogs")! let database = Database.database(app: app) database.isPersistenceEnabled = true let firebaseRef = Database.database(app: app).reference().child("Logs") dataSaver = EncryptedFirebaseDataSaver(firebaseRef: firebaseRef, aesEncoder: aesEncoder) } public override func output(logDetails: LogDetails, message: String) { var logDetails = logDetails var message = message // Apply filters, if any indicate we should drop the message, we abort before doing the actual logging guard !self.shouldExclude(logDetails: &logDetails, message: &message) else { return } self.applyFormatters(logDetails: &logDetails, message: &message) //store log detail let logDecorator = LogDecorator(log: logDetails) dataSaver.save(logDetails: logDecorator, message: message) } }
mit
f58a38e57a88fba51fd36f711b73ade1
38.867052
137
0.606786
3.982102
false
false
false
false
carambalabs/UnsplashKit
Example/Unsplash.playground/Pages/API.xcplaygroundpage/Contents.swift
1
1291
//: [Previous](@previous) import Foundation import UnsplashKit import XCPlayground /*: # Unsplash Official API */ /*: ## Creating the client The first thing we have to do is create an API client that will execute the resources against the API and return the parsed responses asynchronously. > UnsplashClient supports passing a closure that returns extra headers to be inserted in a given request. For example, these headers can contain the user authentication in the Authorization header. */ var token = "" var client = UnsplashClient { request -> [String: String] in return [ "Authorization": "Bearer \(token)"] } /*: ## Requests Models expose the requests that can be executed as resources. A resource contains the request, and how the response should be parsed. For example `User.me` returns the resource to fetch the authenticated user. */ client.execute(resource: User.me) { (result) in if let userFirstName = result.value?.object.firstName { print("📷 User name: \(userFirstName)") } } /*: Some examples of these resources could be: */ let searchPhotos = Search.photos(query: "mountain") let curatedCollections = Collection.curated() let curatedPhotos = Photo.curated() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [Next](@next)
mit
fb8ceeeee65448ef60fef6b867737965
28.272727
209
0.744565
4.264901
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardScan/UI/VideoFeed.swift
1
8449
import AVKit import VideoToolbox protocol AfterPermissions { func permissionDidComplete(granted: Bool, showedPrompt: Bool) } class VideoFeed { private enum SessionSetupResult { case success case notAuthorized case configurationFailed } let session = AVCaptureSession() private var isSessionRunning = false private let sessionQueue = DispatchQueue(label: "session queue") private var setupResult: SessionSetupResult = .success var videoDeviceInput: AVCaptureDeviceInput! var videoDevice: AVCaptureDevice? var videoDeviceConnection: AVCaptureConnection? var torch: Torch? func pauseSession() { self.sessionQueue.suspend() } func requestCameraAccess(permissionDelegate: AfterPermissions?) { switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: self.sessionQueue.resume() DispatchQueue.main.async { permissionDelegate?.permissionDidComplete(granted: true, showedPrompt: false) } break case .notDetermined: AVCaptureDevice.requestAccess( for: .video, completionHandler: { granted in if !granted { self.setupResult = .notAuthorized } self.sessionQueue.resume() DispatchQueue.main.async { permissionDelegate?.permissionDidComplete( granted: granted, showedPrompt: true ) } } ) default: // The user has previously denied access. self.setupResult = .notAuthorized DispatchQueue.main.async { permissionDelegate?.permissionDidComplete(granted: false, showedPrompt: false) } } } func setup( captureDelegate: AVCaptureVideoDataOutputSampleBufferDelegate, initialVideoOrientation: AVCaptureVideoOrientation, completion: @escaping ((_ success: Bool) -> Void) ) { sessionQueue.async { self.configureSession( captureDelegate: captureDelegate, initialVideoOrientation: initialVideoOrientation, completion: completion ) } } func configureSession( captureDelegate: AVCaptureVideoDataOutputSampleBufferDelegate, initialVideoOrientation: AVCaptureVideoOrientation, completion: @escaping ((_ success: Bool) -> Void) ) { if setupResult != .success { DispatchQueue.main.async { completion(false) } return } session.beginConfiguration() do { var defaultVideoDevice: AVCaptureDevice? // Choose the back dual camera if available, otherwise default to a wide angle camera. if let dualCameraDevice = AVCaptureDevice.default( .builtInDualCamera, for: .video, position: .back ) { defaultVideoDevice = dualCameraDevice } else if let backCameraDevice = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .back ) { // If the back dual camera is not available, default to the back wide angle camera. defaultVideoDevice = backCameraDevice } else if let frontCameraDevice = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .front ) { // In some cases where users break their phones, the back wide angle camera is not available. // In this case, we should default to the front wide angle camera. defaultVideoDevice = frontCameraDevice } guard let myVideoDevice = defaultVideoDevice else { setupResult = .configurationFailed session.commitConfiguration() DispatchQueue.main.async { completion(false) } return } self.videoDevice = myVideoDevice self.torch = Torch(device: myVideoDevice) let videoDeviceInput = try AVCaptureDeviceInput(device: myVideoDevice) self.setupVideoDeviceDefaults() if session.canAddInput(videoDeviceInput) { session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput } else { setupResult = .configurationFailed session.commitConfiguration() DispatchQueue.main.async { completion(false) } return } let videoDeviceOutput = AVCaptureVideoDataOutput() videoDeviceOutput.videoSettings = [ kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: Int( kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ) ] videoDeviceOutput.alwaysDiscardsLateVideoFrames = true let captureSessionQueue = DispatchQueue(label: "camera output queue") videoDeviceOutput.setSampleBufferDelegate(captureDelegate, queue: captureSessionQueue) guard session.canAddOutput(videoDeviceOutput) else { setupResult = .configurationFailed session.commitConfiguration() DispatchQueue.main.async { completion(false) } return } session.addOutput(videoDeviceOutput) if session.canSetSessionPreset(.high) { session.sessionPreset = .high } self.videoDeviceConnection = videoDeviceOutput.connection(with: .video) if self.videoDeviceConnection?.isVideoOrientationSupported ?? false { self.videoDeviceConnection?.videoOrientation = initialVideoOrientation } } catch { setupResult = .configurationFailed session.commitConfiguration() DispatchQueue.main.async { completion(false) } return } session.commitConfiguration() DispatchQueue.main.async { completion(true) } } func setupVideoDeviceDefaults() { guard let videoDevice = self.videoDevice else { return } guard let _ = try? videoDevice.lockForConfiguration() else { return } if videoDevice.isFocusModeSupported(.continuousAutoFocus) { videoDevice.focusMode = .continuousAutoFocus if videoDevice.isSmoothAutoFocusSupported { videoDevice.isSmoothAutoFocusEnabled = true } } if videoDevice.isExposureModeSupported(.continuousAutoExposure) { videoDevice.exposureMode = .continuousAutoExposure } if videoDevice.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) { videoDevice.whiteBalanceMode = .continuousAutoWhiteBalance } if videoDevice.isLowLightBoostSupported { videoDevice.automaticallyEnablesLowLightBoostWhenAvailable = true } videoDevice.unlockForConfiguration() } //MARK: -Torch Logic func toggleTorch() { self.torch?.toggle() } func isTorchOn() -> Bool { return self.torch?.state == Torch.State.on } func hasTorchAndIsAvailable() -> Bool { let hasTorch = self.torch?.device?.hasTorch ?? false let isTorchAvailable = self.torch?.device?.isTorchAvailable ?? false return hasTorch && isTorchAvailable } func setTorchLevel(level: Float) { self.torch?.level = level } //MARK: -VC Lifecycle Logic func willAppear() { sessionQueue.async { switch self.setupResult { case .success: self.session.startRunning() self.isSessionRunning = self.session.isRunning case _: break } } } func willDisappear() { sessionQueue.async { if self.setupResult == .success { self.session.stopRunning() self.isSessionRunning = self.session.isRunning } } } }
mit
d3fb8588b6b52ccb39e779db8ea13c04
33.345528
109
0.589537
6.185212
false
true
false
false
vchuo/Photoasis
Photoasis/Classes/Models/API/Client/POAPIClient.swift
1
3004
// // POAPIClient.swift // APIクライエント。 // // Created by Vernon Chuo Chian Khye on 2017/02/25. // Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved. // import Foundation import RxSwift import ChuoUtil class POAPIClient { // MARK: - Public Properties var responseReceivedCallbacks = POAPIClientResponseReceivedCallbacks() var errorReceivedCallbacks = POAPIClientErrorReceivedCallbacks() // MARK: - Private Properties private let disposeBag = DisposeBag() // MARK: - Public Properties /** リクエストを送る。 - parameter router: ルーター */ func sendRequest<T: RequestProtocol>(router: T) { CUAPIClient.rx_sendRequest(router).subscribe( onNext: { response in self.processServerResponse(response.isSuccess, responseValue: response.value as! AnyObject) }, onError: { error in self.processError(error) } ).addDisposableTo(disposeBag) } // MARK: - Private Functions /** サーバレスポンスをプロセス。 - parameter responseValue: サーバレスポンス */ private func processServerResponse(isSuccess: Bool, responseValue: AnyObject) { // isSuccess == true && self.responseReceivedCallbacks.success != nil if isSuccess { if let callback = self.responseReceivedCallbacks.success { callback(responseValue); return } } // isSuccess == false || self.responseReceivedCallbacks.success == nil if let callback = responseReceivedCallbacks.catchAll { callback(responseValue) } } /** エラーが発生する場合。 - parameter error: エラー */ private func processError(error: ErrorType) { print("[POAPIClient] Connection attempt with server failed. Error code: \((error as NSError).code).") switch (error as NSError).code { case NSURLErrorNotConnectedToInternet: if let callback = errorReceivedCallbacks.noInternetConnection { callback(error); return } default: break } if let callback = errorReceivedCallbacks.catchAll { callback(error) } } } struct POAPIClientResponseReceivedCallbacks { var success: (AnyObject -> Void)? = nil var catchAll: (AnyObject -> Void)? = nil init(success: (AnyObject -> Void)? = nil, catchAll: (AnyObject -> Void)? = nil) { self.success = success self.catchAll = catchAll } } struct POAPIClientErrorReceivedCallbacks { var noInternetConnection: (ErrorType? -> Void)? = nil var catchAll: (ErrorType? -> Void)? = nil init(noInternetConnection: (ErrorType? -> Void)? = nil, catchAll: (ErrorType? -> Void)? = nil) { self.noInternetConnection = noInternetConnection self.catchAll = catchAll } }
mit
369d4611c1ff710632620a3d3d53822c
28.5
109
0.619509
4.662903
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/Common/View/BasePeekAndPopViewController.swift
1
3421
import UIKit import Marshroute class BasePeekAndPopViewController: BaseViewController { // MARK: - Internal properties let peekAndPopUtility: PeekAndPopUtility // MARK: - Init init(peekAndPopUtility: PeekAndPopUtility) { self.peekAndPopUtility = peekAndPopUtility super.init() } // MARK: - Override point var peekSourceViews: [UIView] { return [] } @available(iOS 9.0, *) func startPeekWith( previewingContext: UIViewControllerPreviewing, location: CGPoint) { // You can override this method to adjust `sourceRect` of a `previewingContext`. // Default implementation finds an interactable `UIControl` matching the `location` and simulates a `touchUpInside` // // If one of your `peekSourceViews` is `UITableView` or any other collection, you should override this method // to find view data matching the `location` and invoke its callback, // so that `Presenter` can ask `Router` to perform some transition // // Do not forget to invoke `super` implementation unless your custom implementation succeeds guard let interactableControl = previewingContext.sourceView.interactableControlAt(location: location) else { return } let interactableControlFrameInSourceView = interactableControl.convert( interactableControl.bounds, to: previewingContext.sourceView ) // Improve animations via deselecting the control interactableControl.isHighlighted = false interactableControl.isSelected = false // Adjust `sourceRect` to provide non-blur area of `peek` animation previewingContext.sourceRect = interactableControlFrameInSourceView // Simulate user interaction interactableControl.sendActions(for: .touchUpInside) } // MARK: - Lifecycle override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) reregisterForPeekAndPopIfAvailable() } override func didMove(toParent parent: UIViewController?) { super.didMove(toParent: parent) reregisterForPeekAndPopIfAvailable() } // MARK: - Private private func reregisterForPeekAndPopIfAvailable() { if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .available { registerForPeekAndPop() } else { unregisterFromPeekAndPop() } } } @available(iOS 9.0, *) private func registerForPeekAndPop() { for peekSourceView in peekSourceViews { peekAndPopUtility.register( viewController: self, forPreviewingInSourceView: peekSourceView, onPeek: { [weak self] (previewingContext, location) in self?.startPeekWith( previewingContext: previewingContext, location: location ) }, onPreviewingContextChange: nil ) } } @available(iOS 9.0, *) private func unregisterFromPeekAndPop() { peekAndPopUtility.unregisterViewControllerFromPreviewing(self) } }
mit
8d12dc0a6e5e658e9dc34bb51c7fa3b3
34.268041
123
0.631102
5.589869
false
false
false
false
SteveBarnegren/TweenKit
TweenKit/TweenKit/BezierAction.swift
1
1861
// // BezierAction.swift // TweenKit // // Created by Steven Barnegren on 27/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation /** Action for animating over a bezier path */ public class BezierAction<T: Tweenable2DCoordinate>: FiniteTimeAction { // MARK: - Public /** Create with a BezierPath instance - Parameter path: The path to animate over - Parameter duration: Duration of the animation - Parameter update: Callback with position and rotation */ public init(path: BezierPath<T>, duration: Double, update: @escaping (T, Lazy<Double>) -> ()) { self.duration = duration self.path = path self.updateHandler = update } public var easing = Easing.linear public var duration: Double public var reverse = false public var onBecomeActive: () -> () = {} public var onBecomeInactive: () -> () = {} // MARK: - Properties let path: BezierPath<T> let updateHandler: (T, Lazy<Double>) -> () // MARK: - Methods public func willBecomeActive() { onBecomeActive() } public func didBecomeInactive() { onBecomeInactive() } public func willBegin() { } public func didFinish() { update(t: reverse ? 0.0 : 1.0) } public func update(t: CFTimeInterval) { let t = easing.apply(t: t) let value = path.valueAt(t: t) let rotation = Lazy<Double> { [unowned self] in let diff = 0.001 let beforeValue = self.path.valueAt(t: t - diff) let afterValue = self.path.valueAt(t: t + diff) return beforeValue.angle(to: afterValue) } updateHandler(value, rotation) } }
mit
969f41cb9c0095d87a2b772722d62b9d
23.8
99
0.569892
4.386792
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/Classes/Home/QRCode/JKQRCodeVC.swift
1
7434
// // JKQRCodeVC.swift // sinaWeibo // // Created by 张俊凯 on 6/30/16. // Copyright © 2016 张俊凯. All rights reserved. // import UIKit import AVFoundation class JKQRCodeVC: UIViewController,UITabBarDelegate { //容器视图高度 @IBOutlet weak var containerHeightCons: NSLayoutConstraint! //冲击波视图 @IBOutlet weak var scanLineView: UIImageView! //冲击波视图顶部约束 @IBOutlet weak var scanLineCons: NSLayoutConstraint! @IBOutlet weak var messageLabel: UILabel! //底部tabbar @IBOutlet weak var customTabBar: UITabBar! //关闭按钮点击事件 @IBAction func closeBtnClick(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } //我的名片点击推出控制器 @IBAction func myCardClick(sender: UIButton) { let cardVC = JKQRCodeCardVC() navigationController?.pushViewController(cardVC, animated: true) } override func viewDidLoad() { super.viewDidLoad() customTabBar.selectedItem = customTabBar.items![0] customTabBar.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //开始动画 startAnimation() //开始扫描 startScan() } //开始扫描 func startScan(){ //判断是否能够将输入添加到会话中 if !session.canAddInput(deviceInput) { return } //判断是否能够将输出添加到会话中 if !session.canAddOutput(output) { return } //将输入和输出都添加到会话中 session.addInput(deviceInput) print(output.availableMetadataObjectTypes) session.addOutput(output) print(output.availableMetadataObjectTypes) //设置输出能够解析的数据类型 //一定要在输出对象添加到会员之后设置,否则会报错 output.metadataObjectTypes = output.availableMetadataObjectTypes print(output.availableMetadataObjectTypes) //设置输出对象的代理,只要解析成功就会通知代理 output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) //添加预览图层 view.layer.insertSublayer(previewLayer, atIndex:0) //将绘制图层添加到预览图层上 previewLayer.addSublayer(drawLayer) //告诉session开始扫描 session.startRunning() } func startAnimation(){ //让约束从顶部开始 self.scanLineCons.constant = -self.containerHeightCons.constant self.scanLineView.layoutIfNeeded() //执行冲击波动画 UIView.animateWithDuration(2.0,animations: { () -> Void in self.scanLineCons.constant = self.containerHeightCons.constant //设置动画指定的次数 UIView.setAnimationRepeatCount(MAXFLOAT) //强制更新画面 self.scanLineView.layoutIfNeeded() }) } //MARK: - UITabBarDelagate func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { print(item.tag) if item.tag == 1 { self.containerHeightCons.constant = 300 }else{ self.containerHeightCons.constant = 150 } //停止动画 self.scanLineView.layer.removeAllAnimations() //重新开始动画 startAnimation() } //MARK: - 懒加载 视频会话 private lazy var session : AVCaptureSession = AVCaptureSession() //拿到输入设备 private lazy var deviceInput : AVCaptureDeviceInput? = { let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do{ let input = try AVCaptureDeviceInput(device: device) return input }catch{ print(error) return nil } }() //拿到输出对象 private lazy var output : AVCaptureMetadataOutput = AVCaptureMetadataOutput() //创建预览图层 private lazy var previewLayer:AVCaptureVideoPreviewLayer = { let layer = AVCaptureVideoPreviewLayer(session: self.session) layer.frame = UIScreen.mainScreen().bounds return layer }() //创建用于绘制边线的图层 private lazy var drawLayer : CALayer = { let layer = CALayer() layer.frame = UIScreen.mainScreen().bounds return layer }() } extension JKQRCodeVC:AVCaptureMetadataOutputObjectsDelegate{ //只要解析到数据就会调用 func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { //清空图册 clearConers() //获取到扫描的数据 //注意要使用stingValue print(metadataObjects.last?.stringValue) messageLabel.text = metadataObjects.last?.stringValue messageLabel.sizeToFit() //获取扫描到的二维码位置 for object in metadataObjects { //判断当前获取到的数据是否是机器可识别的类型 if object is AVMetadataMachineReadableCodeObject { //将坐标转换成界面可识别的坐标 let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject //绘制图形 drawConers(codeObject) } } } //绘制图形 private func drawConers(codeObject:AVMetadataMachineReadableCodeObject){ if codeObject.corners.isEmpty { return } //创建一个图层 let layer = CAShapeLayer() layer.lineWidth = 4 layer.strokeColor = UIColor.redColor().CGColor layer.fillColor = UIColor.clearColor().CGColor //创建路径 let path = UIBezierPath() var point = CGPointZero var index :Int = 0 //从corner数组中取出第0个元素,将这个字典的xy赋值给point CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point) path.moveToPoint(point) //移动到其他的点 while index < codeObject.corners.count { CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point) path.addLineToPoint(point) } //关闭路径 path.closePath() //绘制路径 layer.path = path.CGPath //将绘制好的图层添加到drawLayer上 drawLayer.addSublayer(layer) } //用来清空边线 private func clearConers(){ //判断drawLayer上是否有其他图层 if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0{ return } //移除所有子图层 for sublayer in drawLayer.sublayers! { sublayer.removeFromSuperlayer() } } }
mit
99243147476b9a14244518efb042d7cc
25.893878
162
0.598725
5.175962
false
false
false
false
treejames/firefox-ios
Sync/SyncStateMachine.swift
3
33745
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import XCGLogger private let log = Logger.syncLogger private let ShortCircuitMissingMetaGlobal = true // Do this so we don't exercise 'recovery' code. private let ShortCircuitMissingCryptoKeys = true // Do this so we don't exercise 'recovery' code. private let StorageVersionCurrent = 5 private let DefaultEngines: [String: Int] = ["tabs": 1] private let DefaultDeclined: [String] = [String]() private func getDefaultEngines() -> [String: EngineMeta] { return mapValues(DefaultEngines, { EngineMeta(version: $0, syncID: Bytes.generateGUID()) }) } public typealias TokenSource = () -> Deferred<Result<TokenServerToken>> public typealias ReadyDeferred = Deferred<Result<Ready>> // See docs in docs/sync.md. // You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine // does. Well, such a client is pinned to a particular server, and this state machine must // acknowledge that a Sync client occasionally must migrate between two servers, preserving // some state from the last. // The resultant 'Ready' will be able to provide a suitably initialized storage client. public class SyncStateMachine { private class func scratchpadPrefs(prefs: Prefs) -> Prefs { return prefs.branch("scratchpad") } public class func getInfoCollections(authState: SyncAuthState, prefs: Prefs) -> Deferred<Result<InfoCollections>> { log.debug("Fetching info/collections in state machine.") let token = authState.token(NSDate.now(), canBeExpired: true) return chainDeferred(token, { (token, kB) in // TODO: the token might not be expired! Check and selectively advance. log.debug("Got token from auth state. Advancing to InitialWithExpiredToken.") let state = InitialWithExpiredToken(scratchpad: Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: self.scratchpadPrefs(prefs)), token: token) return state.getInfoCollections() }) } public class func clearStateFromPrefs(prefs: Prefs) { log.debug("Clearing all Sync prefs.") Scratchpad.clearFromPrefs(self.scratchpadPrefs(prefs)) prefs.clearAll() } public class func toReady(authState: SyncAuthState, prefs: Prefs) -> ReadyDeferred { let token = authState.token(NSDate.now(), canBeExpired: false) return chainDeferred(token, { (token, kB) in log.debug("Got token from auth state. Server is \(token.api_endpoint).") let scratchpadPrefs = self.scratchpadPrefs(prefs) let prior = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKB(kB)) if prior == nil { log.info("No persisted Sync state. Starting over.") } let scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKB(kB), persistingTo: scratchpadPrefs) log.info("Advancing to InitialWithLiveToken.") let state = InitialWithLiveToken(scratchpad: scratchpad, token: token) return advanceSyncState(state) }) } } public enum SyncStateLabel: String { case Stub = "STUB" // For 'abstract' base classes. case InitialWithExpiredToken = "initialWithExpiredToken" case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo" case InitialWithLiveToken = "initialWithLiveToken" case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo" case ResolveMetaGlobal = "resolveMetaGlobal" case NewMetaGlobal = "newMetaGlobal" case HasMetaGlobal = "hasMetaGlobal" case Restart = "restart" // Go around again... once only, perhaps. case Ready = "ready" case ChangedServer = "changedServer" case MissingMetaGlobal = "missingMetaGlobal" case MissingCryptoKeys = "missingCryptoKeys" case MalformedCryptoKeys = "malformedCryptoKeys" case SyncIDChanged = "syncIDChanged" static let allValues: [SyncStateLabel] = [ InitialWithExpiredToken, InitialWithExpiredTokenAndInfo, InitialWithLiveToken, InitialWithLiveTokenAndInfo, ResolveMetaGlobal, NewMetaGlobal, HasMetaGlobal, Restart, Ready, ChangedServer, MissingMetaGlobal, MissingCryptoKeys, MalformedCryptoKeys, SyncIDChanged, ] } /** * States in this state machine all implement SyncState. * * States are either successful main-flow states, or (recoverable) error states. * Errors that aren't recoverable are simply errors. * Main-flow states flow one to one. * * (Terminal failure states might be introduced at some point.) * * Multiple error states (but typically only one) can arise from each main state transition. * For example, parsing meta/global can result in a number of different non-routine situations. * * For these reasons, and the lack of useful ADTs in Swift, we model the main flow as * the success branch of a Result, and the recovery flows as a part of the failure branch. * * We could just as easily use a ternary Either-style operator, but thanks to Swift's * optional-cast-let it's no saving to do so. * * Because of the lack of type system support, all RecoverableSyncStates must have the same * signature. That signature implies a possibly multi-state transition; individual states * will have richer type signatures. */ public protocol SyncState { var label: SyncStateLabel { get } } /* * Base classes to avoid repeating initializers all over the place. */ public class BaseSyncState: SyncState { public var label: SyncStateLabel { return SyncStateLabel.Stub } public let client: Sync15StorageClient! let token: TokenServerToken // Maybe expired. var scratchpad: Scratchpad // TODO: 304 for i/c. public func getInfoCollections() -> Deferred<Result<InfoCollections>> { return chain(self.client.getInfoCollections(), { return $0.value }) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } public func synchronizer<T: Synchronizer>(synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs) -> T { return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs) } // This isn't a convenience initializer 'cos subclasses can't call convenience initializers. public init(scratchpad: Scratchpad, token: TokenServerToken) { let workQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) let resultQueue = dispatch_get_main_queue() let backoff = scratchpad.backoffStorage let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff) self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } } public class BaseSyncStateWithInfo: BaseSyncState { public let info: InfoCollections init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(client: client, scratchpad: scratchpad, token: token) } init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(scratchpad: scratchpad, token: token) } } /* * Error types. */ public protocol SyncError: ErrorType {} public class UnknownError: SyncError { public var description: String { return "Unknown error." } } public class CouldNotFetchMetaGlobalError: SyncError { public var description: String { return "Could not fetch meta/global." } } public class CouldNotFetchKeysError: SyncError { public var description: String { return "Could not fetch crypto/keys." } } public class StubStateError: SyncError { public var description: String { return "Unexpectedly reached a stub state. This is a coding error." } } public class UpgradeRequiredError: SyncError { let targetStorageVersion: Int public init(target: Int) { self.targetStorageVersion = target } public var description: String { return "Upgrade required to work with storage version \(self.targetStorageVersion)." } } public class InvalidKeysError: SyncError { let keys: Keys public init(_ keys: Keys) { self.keys = keys } public var description: String { return "Downloaded crypto/keys, but couldn't parse them." } } public class MissingMetaGlobalAndUnwillingError: SyncError { public var description: String { return "No meta/global on server, and we're unwilling to create one." } } public class MissingCryptoKeysAndUnwillingError: SyncError { public var description: String { return "No crypto/keys on server, and we're unwilling to create one." } } /* * Error states. These are errors that can be recovered from by taking actions. */ public protocol RecoverableSyncState: SyncState, SyncError { // All error states must be able to advance to a usable state. func advance() -> Deferred<Result<SyncState>> } /** * Recovery: discard our local timestamps and sync states; discard caches. * Be prepared to handle a conflict between our selected engines and the new * server's meta/global; if an engine is selected locally but not declined * remotely, then we'll need to upload a new meta/global and sync that engine. */ public class ChangedServerError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.ChangedServer } public var description: String { return "Token destination changed to \(self.newToken.api_endpoint)/\(self.newToken.uid)." } let newToken: TokenServerToken let newScratchpad: Scratchpad public init(scratchpad: Scratchpad, token: TokenServerToken) { self.newToken = token self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs) } public func advance() -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken) return Deferred(value: Result(success: state)) } } /** * Recovery: same as for changed server, but no need to upload a new meta/global. */ public class SyncIDChangedError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged } public var description: String { return "Global sync ID changed." } private let previousState: BaseSyncStateWithInfo private let newMetaGlobal: Fetched<MetaGlobal> public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) { self.previousState = previousState self.newMetaGlobal = newMetaGlobal } public func advance() -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint() let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info) return Deferred(value: Result(success: state)) } } /** * Recovery: wipe the server (perhaps unnecessarily), upload a new meta/global, * do a fresh start. */ public class MissingMetaGlobalError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal } public var description: String { return "Missing meta/global." } private let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } // TODO: this needs EnginePreferences. private class func createMetaGlobal(previous: MetaGlobal?, scratchpad: Scratchpad) -> MetaGlobal { return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: getDefaultEngines(), declined: DefaultDeclined) } private func onWiped(resp: StorageResponse<JSON>, s: Scratchpad) -> Deferred<Result<SyncState>> { // Upload a new meta/global. // Note that we discard info/collections -- we just wiped storage. return Deferred(value: Result(success: InitialWithLiveToken(client: self.previousState.client, scratchpad: s, token: self.previousState.token))) } private func advanceFromWiped(wipe: Deferred<Result<StorageResponse<JSON>>>) -> Deferred<Result<SyncState>> { // TODO: mutate local storage to allow for a fresh start. // Note that we discard the previous global and keys -- after all, we just wiped storage. let s = self.previousState.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() return chainDeferred(wipe, { self.onWiped($0, s: s) }) } public func advance() -> Deferred<Result<SyncState>> { return self.advanceFromWiped(self.previousState.client.wipeStorage()) } } // TODO public class MissingCryptoKeysError: RecoverableSyncState { public var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys } public var description: String { return "Missing crypto/keys." } public func advance() -> Deferred<Result<SyncState>> { return Deferred(value: Result(failure: MissingCryptoKeysAndUnwillingError())) } } /* * Non-error states. */ public class InitialWithExpiredToken: BaseSyncState { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithExpiredToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } func advanceWithInfo(info: InfoCollections) -> InitialWithExpiredTokenAndInfo { return InitialWithExpiredTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } public func advanceIfNeeded(previous: InfoCollections?, collections: [String]?) -> Deferred<Result<InitialWithExpiredTokenAndInfo?>> { return chain(getInfoCollections(), { info in // Unchanged or no previous state? Short-circuit. if let previous = previous { if info.same(previous, collections: collections) { return nil } } // Changed? Move to the next state with the fetched info. return self.advanceWithInfo(info) }) } } public class InitialWithExpiredTokenAndInfo: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithExpiredTokenAndInfo } public func advanceWithToken(liveTokenSource: TokenSource) -> Deferred<Result<InitialWithLiveTokenAndInfo>> { return chainResult(liveTokenSource(), { token in if self.token.sameDestination(token) { return Result(success: InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: token, info: self.info)) } // Otherwise, we're screwed: we need to start over. // Pass in the new token, of course. return Result(failure: ChangedServerError(scratchpad: self.scratchpad, token: token)) }) } } public class InitialWithLiveToken: BaseSyncState { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } // This looks totally redundant, but try taking it out, I dare you. public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { super.init(client: client, scratchpad: scratchpad, token: token) } func advanceWithInfo(info: InfoCollections) -> InitialWithLiveTokenAndInfo { return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } public func advance() -> Deferred<Result<InitialWithLiveTokenAndInfo>> { return chain(getInfoCollections(), self.advanceWithInfo) } } /** * Each time we fetch a new meta/global, we need to reconcile it with our * current state. * * It might be identical to our current meta/global, in which case we can short-circuit. * * We might have no previous meta/global at all, in which case this state * simply configures local storage to be ready to sync according to the * supplied meta/global. (Not necessarily datatype elections: those will be per-device.) * * Or it might be different. In this case the previous m/g and our local user preferences * are compared to the new, resulting in some actions and a final state. * * This state is similar in purpose to GlobalSession.processMetaGlobal in Android Sync. * TODO */ public class ResolveMetaGlobal: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } public override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobal } class func fromState(state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobal { return ResolveMetaGlobal(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } func advanceAfterWipe(resp: StorageResponse<JSON>) -> ReadyDeferred { // This will only be called on a successful response. // Upload a new meta/global by advancing to an initial state. // Note that we discard info/collections -- we just wiped storage. let s = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() let initial: InitialWithLiveToken = InitialWithLiveToken(client: self.client, scratchpad: s, token: self.token) return advanceSyncState(initial) } func advance() -> ReadyDeferred { // TODO: detect when an individual collection syncID has changed, and make sure that // collection is reset. // First: check storage version. let v = fetched.value.storageVersion if v > StorageVersionCurrent { log.info("Client upgrade required for storage version \(v)") return Deferred(value: Result(failure: UpgradeRequiredError(target: v))) } if v < StorageVersionCurrent { log.info("Server storage version \(v) is outdated.") // Wipe the server and upload. // TODO: if we're connecting for the first time, and this is an old server, try // to salvage old preferences from the old meta/global -- e.g., datatype elections. // This doesn't need to be implemented until we rev the storage format, which // might never happen. return chainDeferred(client.wipeStorage(), self.advanceAfterWipe) } // Second: check syncID and contents. if let previous = self.scratchpad.global?.value { // Do checks that only apply when we're coming from a previous meta/global. if previous.syncID != fetched.value.syncID { // Global syncID changed. Reset for every collection, and also throw away any cached keys. return resetStateWithGlobal(fetched) } // TODO: Check individual collections, resetting them as necessary if their syncID has changed! // For now, we just adopt the new meta/global, adjust our engines to match, and move on. // This means that if a per-engine syncID changes, *we won't do the right thing*. let withFetchedGlobal = self.scratchpad.withGlobal(fetched) return applyEngineChoicesAndAdvance(withFetchedGlobal) } // No previous meta/global. We know we need to do a fresh start sync. // This function will do the right thing if there's no previous meta/global. return resetStateWithGlobal(fetched) } /** * In some cases we downloaded a new meta/global, and we recognize that we need * a blank slate. This method makes one from our scratchpad, applies any necessary * changes to engine elections from the downloaded meta/global, uploads a changed * meta/global if we must, and then moves to HasMetaGlobal and on to Ready. * TODO: reset all local collections. */ private func resetStateWithGlobal(fetched: Fetched<MetaGlobal>) -> ReadyDeferred { let fresh = self.scratchpad.freshStartWithGlobal(fetched) return applyEngineChoicesAndAdvance(fresh) } private func applyEngineChoicesAndAdvance(newScratchpad: Scratchpad) -> ReadyDeferred { // When we adopt a new meta global, we might update our local enabled/declined // engine lists (which are stored in the scratchpad itself), or need to add // some to meta/global. This call asks the scratchpad to return a possibly new // scratchpad, and optionally a meta/global to upload. // If this upload fails, we abort, of course. let previousMetaGlobal = self.scratchpad.global?.value let (withEnginesApplied: Scratchpad, toUpload: MetaGlobal?) = newScratchpad.applyEngineChoices(previousMetaGlobal) if let toUpload = toUpload { // Upload the new meta/global. // The provided scratchpad *does not reflect this new meta/global*: you need to // get the timestamp from the upload! let upload = self.client.uploadMetaGlobal(toUpload, ifUnmodifiedSince: fetched.timestamp) return chainDeferred(upload, { resp in let postUpload = withEnginesApplied.checkpoint() // TODO: add the timestamp! return HasMetaGlobal.fromState(self, scratchpad: postUpload).advance() }) } // If the meta/global was quietly applied, great; roll on with what we were given. return HasMetaGlobal.fromState(self, scratchpad: withEnginesApplied.checkpoint()).advance() } } public class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo } private func processFailure(failure: ErrorType?) -> ErrorType { if let failure = failure as? ServerInBackoffError { return failure } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<StorageResponse<GlobalEnvelope>> { // Be passive. return failure } if let failure = failure as? BadRequestError<StorageResponse<GlobalEnvelope>> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } // For now, avoid the risky stuff. if ShortCircuitMissingMetaGlobal { return MissingMetaGlobalAndUnwillingError() } if let failure = failure as? NotFound<StorageResponse<GlobalEnvelope>> { // OK, this is easy. // This state is responsible for creating the new m/g, uploading it, and // restarting with a clean scratchpad. return MissingMetaGlobalError(previousState: self) } log.error("Unexpected failure. \(failure?.description)") return failure ?? UnknownError() } // This method basically hops over HasMetaGlobal, because it's not a state // that we expect consumers to know about. func advance() -> ReadyDeferred { // Either m/g and c/k are in our local cache, and they're up-to-date with i/c, // or we need to fetch them. // Cached and not changed in i/c? Use that. // This check would be inaccurate if any other fields were stored in meta/; this // has been the case in the past, with the Sync 1.1 migration indicator. if let global = self.scratchpad.global { if let metaModified = self.info.modified("meta") { // The record timestamp *should* be no more recent than the current collection. // We don't check that (indeed, we don't even store it!). // We also check the last fetch timestamp for the record, and that can be // later than the collection timestamp. All we care about here is if the // server might have a newer record. if global.timestamp >= metaModified { log.info("Using cached meta/global.") // Strictly speaking we can avoid fetching if this condition is not true, // but if meta/ is modified for a different reason -- store timestamps // for the last collection fetch. This will do for now. return HasMetaGlobal.fromState(self).advance() } } } // Fetch. return self.client.getMetaGlobal().bind { result in if let resp = result.successValue { if let fetched = resp.value.toFetched() { // We bump the meta/ timestamp because, though in theory there might be // other records in that collection, even if there are we don't care about them. self.scratchpad.collectionLastFetched["meta"] = resp.metadata.lastModifiedMilliseconds return ResolveMetaGlobal.fromState(self, fetched: fetched).advance() } // This should not occur. log.error("Unexpectedly no meta/global despite a successful fetch.") } // Otherwise, we have a failure state. return Deferred(value: Result(failure: self.processFailure(result.failureValue))) } } } public class HasMetaGlobal: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal } class func fromState(state: BaseSyncStateWithInfo) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } class func fromState(state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info) } private func processFailure(failure: ErrorType?) -> ErrorType { // For now, avoid the risky stuff. if ShortCircuitMissingCryptoKeys { return MissingCryptoKeysAndUnwillingError() } if let failure = failure as? NotFound<StorageResponse<KeysPayload>> { // This state is responsible for creating the new c/k, uploading it, and // restarting with a clean scratchpad. // But we haven't implemented it yet. return MissingCryptoKeysError() } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<StorageResponse<KeysPayload>> { // Be passive. return failure } if let failure = failure as? BadRequestError<StorageResponse<KeysPayload>> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description)") return failure ?? UnknownError() } func advance() -> ReadyDeferred { // Fetch crypto/keys, unless it's present in the cache already. if let keys = self.scratchpad.keys where keys.value.valid { if let cryptoModified = self.info.modified("crypto") { // Both of these are server timestamps. If the record we stored has the // same modified time as the server collection, and we're fetching from the // same server, then the record must be identical, and we can use it directly. // If the server timestamp is newer, there might be new keys. // If the server timestamp is older, something horribly wrong has occurred. if cryptoModified == keys.timestamp { log.debug("Using cached collection keys for ready state.") let ready = Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: keys.value) return Deferred(value: Result(success: ready)) } log.warning("Cached keys with timestamp \(keys.timestamp) disagree with server modified \(cryptoModified).") // Re-fetch keys and check to see if the actual contents differ. // If the keys are the same, we can ignore this change. If they differ, // we need to re-sync any collection whose keys just changed. // TODO TODO TODO: do that work. log.error("Unable to handle key evolution. Sorry.") return Deferred(value: Result(failure: InvalidKeysError(keys.value))) } else { // No known modified time for crypto/. That likely means the server has no keys. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local keys found timestamped \(keys.timestamp), but no crypto collection on server. Dropping cached keys.") self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint() // TODO: we need to do a full sync when we have new keys. } } // // N.B., we assume that if the server has a meta/global, we don't have a cached crypto/keys, // and the server doesn't have crypto/keys, that the server was wiped. // // This assumption is basically so that we don't get trapped in a cycle of seeing this situation, // blanking the server, trying to upload meta/global, getting interrupted, and so on. // // I think this is pretty safe. TODO: verify this assumption by reading a-s and desktop code. // // TODO: detect when the keys have changed, and scream and run away if so. // TODO: upload keys if necessary, then go to Restart. let syncKey = Keys(defaultBundle: self.scratchpad.syncKeyBundle) let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0 }) let encrypter = syncKey.encrypter("keys", encoder: encoder) let client = self.client.clientForCollection("crypto", encrypter: encrypter) // TODO: this assumes that there are keys on the server. Check first, and if there aren't, // go ahead and go to an upload state without having to fail. return client.get("keys").bind { result in if let resp = result.successValue { let collectionKeys = Keys(payload: resp.value.payload) if (!collectionKeys.valid) { log.error("Unexpectedly invalid crypto/keys during a successful fetch.") return Deferred(value: Result(failure: InvalidKeysError(collectionKeys))) } // setKeys bumps the crypto/ timestamp because, though in theory there might be // other records in that collection, even if there are we don't care about them. let fetched = Fetched(value: collectionKeys, timestamp: resp.value.modified) let s = self.scratchpad.evolve().setKeys(fetched).build().checkpoint() let ready = Ready(client: self.client, scratchpad: s, token: self.token, info: self.info, keys: collectionKeys) log.info("Arrived in Ready state.") return Deferred(value: Result(success: ready)) } // Otherwise, we have a failure state. // Much of this logic is shared with the meta/global fetch. return Deferred(value: Result(failure: self.processFailure(result.failureValue))) } } } public class Ready: BaseSyncStateWithInfo { public override var label: SyncStateLabel { return SyncStateLabel.Ready } let collectionKeys: Keys public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } } /* * Because a strongly typed state machine is incompatible with protocols, * we use function dispatch to ape a protocol. */ func advanceSyncState(s: InitialWithLiveToken) -> ReadyDeferred { return chainDeferred(s.advance(), { $0.advance() }) } func advanceSyncState(s: HasMetaGlobal) -> ReadyDeferred { return s.advance() }
mpl-2.0
f0016cca43d97c541c1a6a2c257f72fa
42.097063
153
0.673967
4.860291
false
false
false
false
myTargetSDK/mytarget-ios
myTargetDemoSwift/myTargetDemo/Controllers/Native/NativeViewController.swift
1
11080
// // NativeViewController.swift // myTargetDemo // // Created by Alexander Vorobyev on 12.08.2022. // Copyright © 2022 Mail.ru Group. All rights reserved. // import UIKit import MyTargetSDK final class NativeViewController: UIViewController { private enum CellType { case ad(view: UIView) case general } private let slotId: UInt private let query: [String: String]? private lazy var notificationView: NotificationView = .create(view: view) private lazy var refreshControl: UIRefreshControl = .init() private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.alwaysBounceVertical = true collectionView.register(GeneralCollectionCell.self, forCellWithReuseIdentifier: GeneralCollectionCell.reuseIdentifier) collectionView.register(AdCollectionCell.self, forCellWithReuseIdentifier: AdCollectionCell.reuseIdentifier) collectionView.register(LoadingReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: LoadingReusableView.reuseIdentifier) collectionView.delegate = self collectionView.dataSource = self return collectionView }() private var content: [CellType] = [] private var nativeAds: [MTRGNativeAd] = [] private var loadableNativeAd: MTRGNativeAd? private var isLoading: Bool = false init(slotId: UInt, query: [String: String]? = nil) { self.slotId = slotId self.query = query super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Native Ads" view.backgroundColor = .backgroundColor() view.addSubview(collectionView) refreshControl.addTarget(self, action: #selector(refreshControlTriggered), for: .valueChanged) collectionView.refreshControl = refreshControl reloadContent() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate { [weak self] _ in self?.collectionView.collectionViewLayout.invalidateLayout() } } // MARK: - Native Ad private func loadNativeAd() { loadableNativeAd = MTRGNativeAd(slotId: slotId) query?.forEach { loadableNativeAd?.customParams.setCustomParam($0.value, forKey: $0.key) } loadableNativeAd?.delegate = self loadableNativeAd?.load() notificationView.showMessage("Loading...") } private func loadMultipleNativeAds() { let nativeAdLoader = MTRGNativeAdLoader(forCount: 3, slotId: slotId) query?.forEach { nativeAdLoader.customParams.setCustomParam($0.value, forKey: $0.key) } nativeAdLoader.load { [weak self] nativeAds in guard let self = self else { return } self.renderContent(with: nativeAds, shouldPreClean: true) self.notificationView.showMessage("Loaded \(nativeAds.count) ads") } notificationView.showMessage("Loading...") } private func createNativeView(from promoBanner: MTRGNativePromoBanner) -> UIView { let nativeAdView = MTRGNativeViewsFactory.createNativeAdView() nativeAdView.banner = promoBanner nativeAdView.mediaAdView.delegate = self let nativeAdContainer = MTRGNativeAdContainer.create(withAdView: nativeAdView) nativeAdContainer.ageRestrictionsView = nativeAdView.ageRestrictionsLabel nativeAdContainer.advertisingView = nativeAdView.adLabel nativeAdContainer.titleView = nativeAdView.titleLabel nativeAdContainer.descriptionView = nativeAdView.descriptionLabel nativeAdContainer.iconView = nativeAdView.iconAdView nativeAdContainer.mediaView = nativeAdView.mediaAdView nativeAdContainer.domainView = nativeAdView.domainLabel nativeAdContainer.categoryView = nativeAdView.categoryLabel nativeAdContainer.disclaimerView = nativeAdView.disclaimerLabel nativeAdContainer.ratingView = nativeAdView.ratingStarsLabel nativeAdContainer.votesView = nativeAdView.votesLabel nativeAdContainer.ctaView = nativeAdView.buttonView return nativeAdContainer } // MARK: - Actions @objc private func refreshControlTriggered() { reloadContent() } // MARK: - Private private func reloadContent() { guard !isLoading else { return } isLoading = true loadMultipleNativeAds() } private func loadMoreContent() { guard !isLoading else { return } isLoading = true loadNativeAd() } private func renderContent(with nativeAds: [MTRGNativeAd], shouldPreClean: Bool = false) { isLoading = false refreshControl.endRefreshing() let nativeViews = nativeAds.compactMap { nativeAd -> UIView? in guard let banner = nativeAd.banner else { return nil } let adView = createNativeView(from: banner) nativeAd.register(adView, with: self) return adView } if shouldPreClean { self.nativeAds = nativeAds content.removeAll() } else { self.nativeAds.append(contentsOf: nativeAds) } let batchCount = 16 for index in 0..<nativeViews.count * batchCount { // every third cell in a batch will be an ad let cellType: CellType = index % batchCount - 2 == 0 ? .ad(view: nativeViews[index / batchCount]) : .general content.append(cellType) } collectionView.reloadData() } } // MARK: - MTRGNativeAdDelegate extension NativeViewController: MTRGNativeAdDelegate { func onLoad(with promoBanner: MTRGNativePromoBanner, nativeAd: MTRGNativeAd) { loadableNativeAd.map { renderContent(with: [$0]) } loadableNativeAd = nil notificationView.showMessage("onLoad() called") } func onNoAd(withReason reason: String, nativeAd: MTRGNativeAd) { loadableNativeAd.map { renderContent(with: [$0]) } loadableNativeAd = nil notificationView.showMessage("onNoAd(\(reason)) called") } func onAdShow(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onAdShow() called") } func onAdClick(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onAdClick() called") } func onShowModal(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onShowModal() called") } func onDismissModal(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onDismissModal() called") } func onLeaveApplication(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onLeaveApplication() called") } func onVideoPlay(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onVideoPlay() called") } func onVideoPause(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onVideoPause() called") } func onVideoComplete(with nativeAd: MTRGNativeAd) { notificationView.showMessage("onVideoComplete() called") } } // MARK: - MTRGMediaAdViewDelegate extension NativeViewController: MTRGMediaAdViewDelegate { func onImageSizeChanged(_ mediaAdView: MTRGMediaAdView) { collectionView.reloadData() } } // MARK: - UICollectionViewDelegate extension NativeViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { guard elementKind == UICollectionView.elementKindSectionFooter else { return } loadMoreContent() } } // MARK: - UICollectionViewDataSource extension NativeViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return content.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch content[indexPath.row] { case .ad(let view): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AdCollectionCell.reuseIdentifier, for: indexPath) (cell as? AdCollectionCell)?.adView = view return cell case .general: return collectionView.dequeueReusableCell(withReuseIdentifier: GeneralCollectionCell.reuseIdentifier, for: indexPath) } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionFooter else { return UICollectionReusableView() } let loadingView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: LoadingReusableView.reuseIdentifier, for: indexPath) return loadingView } } // MARK: - UICollectionViewDelegateFlowLayout extension NativeViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch content[indexPath.row] { case .ad(let view): return view.sizeThatFits(collectionView.frame.size) case .general: let dummyCell = GeneralCollectionCell() return dummyCell.sizeThatFits(collectionView.frame.size) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return content.isEmpty ? .zero : CGSize(width: collectionView.bounds.size.width, height: 32) } }
lgpl-3.0
c218230369639fe6da3f42162d2b5314
34.060127
183
0.662785
5.56454
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Utility/Pilot/TrainingQueue.swift
2
6929
// // TrainingQueue.swift // Neocom // // Created by Artem Shimanski on 12/2/19. // Copyright © 2019 Artem Shimanski. All rights reserved. // import Foundation import CoreData import Expressible class TrainingQueue { struct Item: Hashable { let skill: Pilot.Skill let targetLevel: Int let startSP: Int let finishSP: Int } let pilot: Pilot var queue: [Item] = [] init(pilot: Pilot) { self.pilot = pilot } init(pilot: Pilot, skillPlan: SkillPlan) { self.pilot = pilot add(skillPlan) } func add(_ skillType: SDEInvType, level: Int) { guard let skill = Pilot.Skill(type: skillType) else {return} addRequiredSkills(for: skillType) let typeID = Int(skillType.typeID) let trainedLevel = pilot.trainedSkills[typeID]?.trainedSkillLevel ?? 0 guard trainedLevel < level else {return} let queuedLevels = IndexSet(queue.filter({$0.skill.typeID == typeID}).map{$0.targetLevel}) for i in (trainedLevel + 1)...level { if !queuedLevels.contains(i) { let sp = pilot.skillQueue.first(where: {$0.skill.typeID == skill.typeID && $0.queuedSkill.finishedLevel == i})?.skillPoints queue.append(Item(skill: skill, targetLevel: i, startSP: sp)) } } } func add(_ mastery: SDECertMastery) { mastery.skills?.forEach { guard let skill = $0 as? SDECertSkill else {return} guard let type = skill.type else {return} add(type, level: max(Int(skill.skillLevel), 1)) } } func addRequiredSkills(for type: SDEInvType) { type.requiredSkills?.forEach { guard let requiredSkill = ($0 as? SDEInvTypeRequiredSkill) else {return} guard let type = requiredSkill.skillType else {return} add(type, level: Int(requiredSkill.skillLevel)) } } func addRequiredSkills(for activity: SDEIndActivity) { activity.requiredSkills?.forEach { guard let requiredSkill = ($0 as? SDEIndRequiredSkill) else {return} guard let type = requiredSkill.skillType else {return} add(type, level: Int(requiredSkill.skillLevel)) } } func add(_ skillPlan: SkillPlan) { skillPlan.skills?.compactMap { skill in (skill as? SkillPlanSkill).flatMap{ skill in (try? skill.managedObjectContext?.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(skill.typeID)).first()).map{($0, skill.level)} } }.forEach { (type, level) in add(type, level: Int(level)) } } func add(_ skillQueue: [Pilot.SkillQueueItem], managedObjectContext: NSManagedObjectContext) { let skills = Dictionary(skillQueue.map{($0.queuedSkill.skillID, $0.queuedSkill.finishedLevel)}, uniquingKeysWith: {a, b in max(a, b)}) for (typeID, level) in skills { guard let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(typeID)).first() else {continue} add(type, level: level) } } func remove(_ item: TrainingQueue.Item) { let indexes = IndexSet(queue.enumerated().filter {$0.element.skill.typeID == item.skill.typeID && $0.element.targetLevel >= item.targetLevel}.map{$0.offset}) indexes.reversed().forEach {queue.remove(at: $0)} indexes.rangeView.reversed().forEach { queue.removeSubrange($0) } } func trainingTime() -> TimeInterval { return trainingTime(with: pilot.attributes) } func trainingTime(with attributes: Pilot.Attributes) -> TimeInterval { return queue.map {$0.trainingTime(with: attributes)}.reduce(0, +) } } extension TrainingQueue.Item { init(skill: Pilot.Skill, targetLevel: Int, startSP: Int?) { self.skill = skill self.targetLevel = targetLevel let finishSP = skill.skillPoints(at: targetLevel) self.startSP = min(startSP ?? skill.skillPoints(at: targetLevel - 1), finishSP) self.finishSP = finishSP } func trainingTime(with attributes: Pilot.Attributes) -> TimeInterval { return Double(finishSP - startSP) / skill.skillPointsPerSecond(with: attributes) } } extension Pilot.Attributes { struct Key: Hashable { let primary: SDEAttributeID let secondary: SDEAttributeID } init(optimalFor trainingQueue: TrainingQueue) { if trainingQueue.queue.isEmpty { self = .default } else { var skillPoints: [Key: Int] = [:] for item in trainingQueue.queue { let sp = item.finishSP - item.startSP let key = Key(primary: item.skill.primaryAttributeID, secondary: item.skill.secondaryAttributeID) skillPoints[key, default: 0] += sp } let basePoints = 17 let bonusPoints = 14 let maxPoints = 27 let totalMaxPoints = basePoints * 5 + bonusPoints var minTrainingTime = TimeInterval.greatestFiniteMagnitude var optimal = Pilot.Attributes.default for intelligence in basePoints...maxPoints { for memory in basePoints...maxPoints { for perception in basePoints...maxPoints { guard intelligence + memory + perception < totalMaxPoints - basePoints * 2 else {break} for willpower in basePoints...maxPoints { guard intelligence + memory + perception + willpower < totalMaxPoints - basePoints else {break} let charisma = totalMaxPoints - (intelligence + memory + perception + willpower) guard charisma <= maxPoints else {continue} let attributes = Pilot.Attributes(intelligence: intelligence, memory: memory, perception: perception, willpower: willpower, charisma: charisma) let trainingTime = skillPoints.reduce(0) { (t, i) -> TimeInterval in let primary = attributes[i.key.primary] let secondary = attributes[i.key.secondary] return t + TimeInterval(i.value) / (TimeInterval(primary) + TimeInterval(secondary) / 2) } if trainingTime < minTrainingTime { minTrainingTime = trainingTime optimal = attributes } } } } } self = optimal } } }
lgpl-2.1
6c744adccb803ca60f933b0323d9b63e
37.921348
171
0.574192
4.582011
false
false
false
false
donnellyk/ARKitDemo
ARKitDemo/SimpleTrackingViewController.swift
1
1814
import UIKit import ARKit import SceneKit extension UIViewController { } class SimpleTrackingViewController : BaseARKitViewController { weak var trackingButton:UIButton! var isTracking:Bool = false override func viewDidLoad() { super.viewDidLoad() setupTrackingButton() detectPlanes = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) debugOptions = [ARSCNDebugOptions.showFeaturePoints] } @objc func trackingTapped(_ sender:AnyObject) { guard !busyView.isAnimating else { return } isTracking = !isTracking if isTracking { trackingButton.setTitle("Stop tracking", for: .normal) } else { trackingButton.setTitle("Start tracking", for: .normal) } } func session(_ session: ARSession, didUpdate frame: ARFrame) { guard isTracking else { return } addPoint(fromTransform: frame.camera.transform) } } private extension SimpleTrackingViewController { func setupTrackingButton() { let trackingButton = UIButton() trackingButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(trackingButton) trackingButton.setTitle("Start tracking", for: .normal) trackingButton.addTarget(self, action: #selector(trackingTapped), for: .touchUpInside) trackingButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true trackingButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true self.trackingButton = trackingButton } func addPoint(fromTransform transform:matrix_float4x4) { let position = SCNVector3.positionFrom(matrix: transform) let point = SphereNode(position: position) sceneView.scene.rootNode.addChildNode(point) } }
mit
90958c750bb97cb915e05b177d77f441
26.484848
106
0.727674
4.798942
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGenKit/Parsers/Yaml/YamlFile.swift
1
958
// // SwiftGenKit // Copyright © 2020 SwiftGen // MIT Licence // import Foundation import PathKit import Yams public extension Yaml { struct File { let path: Path let name: String let documents: [Any] init(path: Path, relativeTo parent: Path? = nil) throws { guard let string: String = try? path.read() else { throw ParserError.invalidFile(path: path, reason: "Unable to read file") } self.path = parent.flatMap { path.relative(to: $0) } ?? path self.name = path.lastComponentWithoutExtension do { var items = try Yams.load_all(yaml: string) var result: [Any] = [] while let item = items.next() { result.append(item) } self.documents = result if let error = items.error { throw error } } catch let error { throw ParserError.invalidFile(path: path, reason: error.localizedDescription) } } } }
mit
75240490c5006f00d9479898e2a1897f
21.785714
85
0.599791
4.125
false
false
false
false
mikezone/EffectiveSwift
EffectiveSwift/Extension/UIKit/UIApplication+SE.swift
1
3933
// // UIApplication+MKAdd.swift // SwiftExtension // // Created by Mike on 17/1/26. // Copyright © 2017年 Mike. All rights reserved. // import UIKit public extension UIApplication { public var documentsURL: URL? { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last } public var documentsPath: String? { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first } public var cachesURL: URL? { return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).last } public var cachesPath: String? { return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first } public var libraryURL: URL? { return FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last } public var libraryPath: String? { return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first } public var isPirated: Bool { if UIDevice.current.isSimulator { return true } // Simulator is not from appstore if getgid() <= 10 { return true } // process ID shouldn't be root if Bundle.main.infoDictionary?["SignerIdentity"] != nil { return true} if !_fileExist("_CodeSignature") { return true} if !_fileExist("SC_Info") { return true } //if someone really want to crack your app, this method is useless.. //you may change this method's name, encrypt the code and do more check.. return false } private func _fileExist(_ fileName: String, _ inMainBundle: Void = ()) -> Bool { let bundlePath = Bundle.main.bundlePath let path = String(format: "%s/%s", bundlePath, fileName) return FileManager.default.fileExists(atPath: path) } public var appBundleName: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String } public var appBundleID: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as? String } public var appVersion: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String } public var appBuildVersion: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String } public var isBeingDebugged: Bool { var size = MemoryLayout<kinfo_proc>.size var info: kinfo_proc = kinfo_proc() memset(&info, 0, MemoryLayout<kinfo_proc>.size) let name = UnsafeMutablePointer<Int32>.allocate(capacity: 4) name[0] = CTL_KERN name[1] = KERN_PROC name[2] = KERN_PROC_PID name[3] = getpid() let ret: Int32 = 0 if ret == sysctl(name, 4, &info, &size, nil, 0) { return ret != 0 } return (info.kp_proc.p_flag & P_TRACED) != 0 } // public var memoryUsage: UInt64? { // var info = task_basic_info() // var size = MemoryLayout<task_basic_info>.size // //// var info: task_info_t = UnsafeMutablePointer<Int32>.allocate(capacity: size) // // var usize = UInt32(size) //// var size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<task_basic_info>.size) // // let kern = task_info(mach_task_self_, task_flavor_t(TASK_BASIC_INFO), info, &usize) // // return kern != KERN_SUCCESS ? nil : info // } // public var cpuUsage: UInt64 { // // } public static var isAppExtension: Bool { if Bundle.main.bundlePath.hasSuffix(".appex") { return true } guard let clazz = NSClassFromString("UIApplication") else { return true } return !clazz.responds(to: Selector(("shared"))) } }
gpl-3.0
fde130930fc8ae191b74b5a8a28e1f63
33.173913
105
0.622137
4.276387
false
false
false
false
DianQK/Flix
Example/Example/CalendarEvent/Location/GeolocationService.swift
1
1654
// // GeolocationService.swift // RxExample // // Created by Carlos García on 19/01/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import CoreLocation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class GeolocationService { static let instance = GeolocationService() private (set) var authorized: Driver<Bool> private (set) var location: Driver<CLLocation?> private let locationManager = CLLocationManager() private init() { locationManager.distanceFilter = kCLDistanceFilterNone locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation authorized = Observable.deferred { [weak locationManager] in let status = CLLocationManager.authorizationStatus() guard let locationManager = locationManager else { return Observable.just(status) } return locationManager .rx.didChangeAuthorizationStatus .startWith(status) } .asDriver(onErrorJustReturn: CLAuthorizationStatus.notDetermined) .map { switch $0 { case .authorizedAlways, .authorizedWhenInUse: return true default: return false } } location = locationManager.rx.didUpdateLocations .asDriver(onErrorJustReturn: []) .map { $0.last } locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } }
mit
a772b162ad8f9f5ec713134e630911ff
29.036364
78
0.59322
6.210526
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Common/Cells/GridCell.swift
1
1594
// // MIT License // Copyright (c) Gathering Hall Studios // // TODO: This shouldn't have to inherit from CustomCell, fix when CustomCell is made a protocol import UIKit class GridCell<T>: CustomCell<T> { let colStack = UIStackView(axis: .horizontal, spacing: 0) var columns = [LabelStack]() init() { super.init(style: .default, reuseIdentifier: "idontcare") initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews() { contentView.addSubview(colStack) colStack.matchParent(top: 5, left: nil, bottom: 5, right: nil) NSLayoutConstraint(item: contentView, attribute: .centerX, relatedBy: .equal, toItem: colStack, attribute: .centerX, multiplier: 1, constant: 0).isActive = true } func add(imageNames: [String]) { let attributeStrings = imageNames.map { $0.attributedImage } add(values: attributeStrings) } func add(values: [Any]) { if columns.count == 0 { for _ in 0 ... values.count - 1 { let column = LabelStack(axis: .vertical) column.showSeparator = true colStack.addArrangedSubview(column) columns.append(column) } } for i in 0 ... columns.count - 1 { let columnStack = columns[i] let value = values[i] columnStack.add(value: value) } } }
mit
52afe6de9aedaa1e22293f15afb54ad0
27.464286
95
0.557089
4.490141
false
false
false
false
kjifw/Senses
senses-client/Senses/Senses/Models/Extensions/PartyDetailsModelExtensions.swift
1
1065
// // PartyDetailsModelExtensions.swift // Senses // // Created by Jeff on 3/30/17. // Copyright © 2017 Telerik Academy. All rights reserved. // import Foundation extension PartyDetailsModel { convenience init(withDict item: Dictionary<String, Any>) { var invitees:[Any] = [] var participants:[Any] = [] if(item["inviteesList"] != nil) { invitees = item["inviteesList"] as! [Any] } if(item["participantsList"] != nil) { participants = item["participantsList"] as! [Any] } self.init(withName: item["name"] as! String, id: "\(item["uniqueId"]!)", Location: item["location"] as! String, StartAt: item["startDateTime"] as! String, withHost: item["host"] as! String, withType: item["partyType"] as! String, withImage: item["image"] as! String, withInvitees: invitees, withParticipants: participants) } }
mit
f97bf627304ea9022049af1cd18ee8a7
30.294118
62
0.532895
4.307692
false
false
false
false
protoman92/SwiftUtilities
SwiftUtilitiesTests/test/localization/LocalizationTest.swift
1
1617
// // LocalizationTest.swift // SwiftUtilitiesTests // // Created by Hai Pham on 14/12/17. // Copyright © 2017 Holmusk. All rights reserved. // import XCTest @testable import SwiftUtilities public final class LocalizationTest: XCTestCase { fileprivate var bundle: Bundle! fileprivate var tables: [String]! fileprivate var localizer: LocalizerType! override public func setUp() { super.setUp() bundle = Bundle(for: LocalizationTest.self) tables = ["Localizable1", "Localizable2"] localizer = Localizer.builder() .add(bundle: bundle!) .add(bundle: Bundle.main) .add(tables: tables!) .build() continueAfterFailure = false } public func test_localizeStrings_shouldWorkCorrectly() { /// Setup let strings = [ "string1_test1", "string1_test2", "string2_test1", "string2_test2" ] let wrongString = "wrongString" /// When for string in strings { let localized1 = localizer.localize(string) let localized2 = string.localize(bundle, tables) /// Then XCTAssertNotEqual(string, localized1) XCTAssertEqual(localized1, localized2) } XCTAssertEqual(wrongString.localize(bundle, tables), wrongString) XCTAssertEqual(localizer.localize(wrongString), wrongString) } public func test_localizeWithFormat_shouldWork() { /// Setup let formatString = "string1_test3" /// When let localized = localizer.localize(formatString, 1) /// Then XCTAssertNotEqual(formatString, localized) XCTAssertEqual(localized, "This is a test 1 with format") } }
apache-2.0
4d4ce1f89fde1f8b782fac41e588b4c2
23.119403
69
0.676361
4.219321
false
true
false
false
prine/ROThumbnailGenerator
Source/PDFThumbnailGenerator.swift
1
2310
// // PDFThumbnailGenerator.swift // RASCOpublic // // Created by Robin Oster on 30/04/15. // Copyright (c) 2015 Rascor International AG. All rights reserved. // import UIKit class PDFThumbnailGenerator : ROThumbnailGenerator { var supportedExtensions:Array<String> = ["pdf"] func getThumbnail(_ url:URL, pageNumber:Int, width:CGFloat) -> UIImage { if let pdf:CGPDFDocument = CGPDFDocument(url as CFURL) { if let firstPage = pdf.page(at: pageNumber) { var pageRect:CGRect = firstPage.getBoxRect(CGPDFBox.mediaBox) let pdfScale:CGFloat = width/pageRect.size.width pageRect.size = CGSize(width: pageRect.size.width*pdfScale, height: pageRect.size.height*pdfScale) pageRect.origin = CGPoint.zero UIGraphicsBeginImageContext(pageRect.size) if let context:CGContext = UIGraphicsGetCurrentContext() { // White BG context.setFillColor(red: 1.0,green: 1.0,blue: 1.0,alpha: 1.0) context.fill(pageRect) context.saveGState() // Next 3 lines makes the rotations so that the page look in the right direction context.translateBy(x: 0.0, y: pageRect.size.height) context.scaleBy(x: 1.0, y: -1.0) context.concatenate((firstPage.getDrawingTransform(CGPDFBox.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))) context.drawPDFPage(firstPage) context.restoreGState() if let thm = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext(); return thm; } } } } return UIImage() } func getThumbnail(_ url:URL, pageNumber:Int) -> UIImage { return self.getThumbnail(url, pageNumber: pageNumber, width: 240.0) } func getThumbnail(_ url:URL) -> UIImage { return self.getThumbnail(url, pageNumber: 1, width: 240.0) } }
mit
c9c3148b53831368cd8fa1866fce588a
36.868852
145
0.541558
4.989201
false
false
false
false
adevelopers/PeriodicTableView
PeriodicTable/PeriodicTable/ElementView/ElementDetailImageViewController.swift
1
1246
// // ElementDetailImageViewController.swift // PeriodicTable // // Created by Kirill Khudyakov on 22.10.17. // Copyright © 2017 adeveloper. All rights reserved. // import UIKit class ElementDetailImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var viewModel: ElementTableModel? convenience init(model: ElementTableModel) { self.init(nibName: "ElementDetailImageViewController", bundle: nil) self.viewModel = model } override func viewDidLoad() { super.viewDidLoad() configureBackButton() if let viewModel = viewModel { imageView.image = UIImage(named: viewModel.symbol) imageView.contentMode = .scaleAspectFit imageView.backgroundColor = .black } } fileprivate func configureBackButton() { title = viewModel?.name self.navigationController?.navigationBar.topItem?.titleView?.tintColor = .white let backButton = UIBarButtonItem() backButton.setTitlePositionAdjustment(UIOffset.zero, for: .compact) backButton.title = "" self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton } }
mit
b959e13d20dcc785475063fcf03a35b3
27.953488
88
0.672289
5.275424
false
false
false
false
andreamazz/Tropos
Sources/Tropos/Controllers/AcknowledgementsParser.swift
1
926
import Foundation struct AcknowledgementsParser { let propertyList: [String: Any] init?(fileURL: URL) { if let plist = NSDictionary(contentsOf: fileURL) as? [String: Any] { propertyList = plist } else { return nil } } func displayString() -> String { let acknowledgements = propertyList["PreferenceSpecifiers"] as? [[String: String]] ?? [] return acknowledgements.reduce("") { string, acknowledgement in return string + displayStringForAcknowledgement(acknowledgement) } } private func displayStringForAcknowledgement(_ acknowledgement: [String: String]) -> String { let appendNewline: (String) -> String = { "\($0)\n" } let title = acknowledgement["Title"].map(appendNewline) ?? "" let footer = acknowledgement["FooterText"].map(appendNewline) ?? "" return title + footer } }
mit
bb9ad0c4e368cb88a75094ebd5e04563
32.071429
97
0.62095
4.978495
false
false
false
false
ktmswzw/FeelingClientBySwift
Pods/ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController/AnimationController.swift
6
2750
// // AnimationController.swift // ImagePickerSheet // // Created by Laurin Brandner on 25/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit class AnimationController: NSObject { let imagePickerSheetController: ImagePickerSheetController let presenting: Bool // MARK: - Initialization init(imagePickerSheetController: ImagePickerSheetController, presenting: Bool) { self.imagePickerSheetController = imagePickerSheetController self.presenting = presenting } // MARK: - Animation private func animatePresentation(context: UIViewControllerContextTransitioning) { guard let containerView = context.containerView() else { return } containerView.addSubview(imagePickerSheetController.view) let sheetOriginY = imagePickerSheetController.sheetCollectionView.frame.origin.y imagePickerSheetController.sheetCollectionView.frame.origin.y = containerView.bounds.maxY imagePickerSheetController.backgroundView.alpha = 0 UIView.animateWithDuration(transitionDuration(context), delay: 0, options: .CurveEaseOut, animations: { () -> Void in self.imagePickerSheetController.sheetCollectionView.frame.origin.y = sheetOriginY self.imagePickerSheetController.backgroundView.alpha = 1 }, completion: { _ in context.completeTransition(true) }) } private func animateDismissal(context: UIViewControllerContextTransitioning) { guard let containerView = context.containerView() else { return } UIView.animateWithDuration(transitionDuration(context), delay: 0, options: .CurveEaseIn, animations: { () -> Void in self.imagePickerSheetController.sheetCollectionView.frame.origin.y = containerView.bounds.maxY self.imagePickerSheetController.backgroundView.alpha = 0 }, completion: { _ in self.imagePickerSheetController.view.removeFromSuperview() context.completeTransition(true) }) } } // MARK: - UIViewControllerAnimatedTransitioning extension AnimationController: UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { guard #available(iOS 9, *) else { return 0.3 } return 0.25 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if presenting { animatePresentation(transitionContext) } else { animateDismissal(transitionContext) } } }
mit
9ea1ede6bf17d42e2d6eabbbc9242406
33.375
125
0.681455
5.939525
false
false
false
false
jwelton/BreweryDB
BreweryDB/Ingredient.swift
1
2580
// // Ingredient.swift // BreweryDB // // Created by Jake Welton on 3/23/17. // Copyright © 2017 Jake Welton. All rights reserved. // import Foundation public class Ingredient { public let identifier: Int public var category: String? public var categoryDisplay: String? public var name: String? public var summary: String? public var countryOfOrigin: String? public var alphaAcidMin: Float? public var betaAcidMin: Float? public var betaAcidMax: Float? public var humuleneMin: Float? public var humuleneMax: Float? public var caryophylleneMin: Float? public var caryophylleneMax: Float? public var cohumuloneMin: Float? public var cohumuloneMax: Float? public var myrceneMin: Float? public var myrceneMax: Float? public var farneseneMin: Float? public var farneseneMax: Float? public init(identifier: Int) { self.identifier = identifier } } extension Ingredient: JSONParserEntity { public static func map(json: json) -> AnyObject? { guard let identifier = json["id"] as? Int else { return nil } let ingredient = Ingredient(identifier: identifier) ingredient.name = json["name"] as? String ingredient.category = json["category"] as? String ingredient.categoryDisplay = json["categoryDisplay"] as? String ingredient.summary = json["description"] as? String ingredient.countryOfOrigin = json["countryOfOrigin"] as? String ingredient.alphaAcidMin = json["alphaAcidMin"] as? Float ingredient.betaAcidMin = json["betaAcidMin"] as? Float ingredient.betaAcidMax = json["betaAcidMax"] as? Float ingredient.humuleneMin = json["humuleneMin"] as? Float ingredient.humuleneMax = json["humuleneMax"] as? Float ingredient.caryophylleneMin = json["caryophylleneMin"] as? Float ingredient.caryophylleneMax = json["caryophylleneMax"] as? Float ingredient.cohumuloneMin = json["cohumuloneMin"] as? Float ingredient.cohumuloneMax = json["cohumuloneMax"] as? Float ingredient.myrceneMin = json["myrceneMin"] as? Float ingredient.myrceneMax = json["myrceneMax"] as? Float ingredient.farneseneMin = json["farneseneMin"] as? Float ingredient.farneseneMax = json["farneseneMax"] as? Float return ingredient } } extension Ingredient: CustomStringConvertible { public var description: String { return "Identifier: \(identifier), name: \(name), category: \(category)" } }
mit
b7d7b409c285854d03f965f64b7cdeb5
35.323944
80
0.678945
4.312709
false
false
false
false
aiaio/DesignStudioExpress
DesignStudioExpress/ViewModels/DetailDesignStudioViewModel.swift
1
4921
// // DetailDesignStudioViewModel.swift // DesignStudioExpress // // Created by Kristijan Perusko on 11/15/15. // Copyright © 2015 Alexander Interactive. All rights reserved. // import Foundation import RealmSwift class DetailDesignStudioViewModel { enum FieldName { case Title case Duration } let newStudioButtonText = "CREATE" let editStudioButtonText = "CONTINUE" lazy var realm = try! Realm() private var data: DesignStudio! private var isNew = false var title: String { get { return self.data.title } set { try! self.realm.write { self.data.title = newValue } } } var duration: String { get { return "\(data.duration)" } set { /* Duration on DesignStudio is now a sum of all durations from activities * functionality is left commented so that we can revert this decision * in future phases * try! realm.write { self.data.duration = Int(newValue) ?? 0 } */ } } var challenges: String { get { let challengesCount = data.challenges.count // handle plural version of the label var challengeLabel = "challenge" if (challengesCount != 1) { challengeLabel += "s" } return "(\(challengesCount) \(challengeLabel))" } } var buttonTitle: String { get { if self.isNew { return newStudioButtonText } return editStudioButtonText } } var editIconImage: String { get { if self.editingEnabled { return "Pencil_Icon_Blue" } return "Lock_icon_White" } } var editingEnabled: Bool { get { return !self.data.started && !self.data.template } } init () { self.createNewDesignStudio() } func setDesignStudio(newDesignStudio: DesignStudio?) { if let designStudio = newDesignStudio { self.data = designStudio isNew = false self.fixDesignStudioState() } else { // create new DS, but don't save it until we segue to next screen createNewDesignStudio() } } // in case the the design studio is started, but not finished // this will fix the state private func fixDesignStudioState() { // if it's not finished and if it's not currently running if self.data.started && !self.data.finished && AppDelegate.designStudio.currentDesignStudio?.id != self.data.id { do { try realm.write { self.data.finished = true } } catch let error as NSError { print("Couldn't save design studio: " + error.localizedDescription) } } } private func createNewDesignStudio() { let ds = DesignStudio() self.data = ds self.isNew = true } func openDesignStudio(title: String, duration: String) -> DesignStudio { // save the design studio when we're moving to the next screen if self.isNew { do { try realm.write { self.realm.add(self.data) self.isNew = false } } catch let error as NSError { print("Couldn't save a new design studio: " + error.localizedDescription) } } else { // in case user clicks continue while the keyboard is still active // save the title self.title = title } return self.data } func copyDesignStudio() -> DesignStudio? { if let copyDS = self.data.makeACopy() { do { let realm = try Realm() try realm.write { realm.add(copyDS) } } catch let error as NSError { print("Couldn't save the Design Studio copy: " + error.localizedDescription) return nil } return copyDS } return nil } private func checkMaxLength(textFieldLength: Int, range: NSRange, replacementStringLength: Int, maxAllowedLength: Int) -> Bool { // prevents Undo bug // check http://stackoverflow.com/a/1773257/515053 for reference if (range.length + range.location > textFieldLength ) { return false; } let newLength = textFieldLength + replacementStringLength - range.length return newLength <= maxAllowedLength } }
mit
58715685f7d0a3d44bff65ed8b9f6e7e
27.275862
132
0.522967
5.025536
false
false
false
false
huangboju/Moots
Examples/波浪/WaterWave/WaterWave/Views/PullToRefreshWave/UIScrollView+Extension.swift
1
1420
// // UIScrollView+Extension.swift // WaterWave // // Created by 伯驹 黄 on 2016/10/15. // Copyright © 2016年 xiAo_Ju. All rights reserved. // import UIKit var hh_associatePullToRefreshViewKey = "hh_associatePullToRefreshViewKey" extension UIScrollView { var pullToRefreshView: PullToRefreshWaveView? { set { objc_setAssociatedObject(self, &hh_associatePullToRefreshViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, &hh_associatePullToRefreshViewKey) as? PullToRefreshWaveView } } func hh_addRefreshViewWithAction(handler: (() -> Void)?) { let refreshWaveView = PullToRefreshWaveView() addSubview(refreshWaveView) pullToRefreshView = refreshWaveView refreshWaveView.actionHandler = handler refreshWaveView.observe(scrollView: self) } func hh_removeRefreshView() { if pullToRefreshView == nil { return; } pullToRefreshView?.invalidateWave() pullToRefreshView?.removeObserver(scrollView: self) pullToRefreshView?.removeFromSuperview() } func hh_setRefreshViewTopWaveFill(color: UIColor) { pullToRefreshView?.topWaveColor = color } func hh_setRefreshViewBottomWaveFill(color: UIColor) { pullToRefreshView?.bottomWaveColor = color } }
mit
bbefef03f8d1d28ef889ad5deeda2f25
27.795918
123
0.674699
4.832192
false
false
false
false
yosan/AwsChat
AwsChat/ChatRoomsViewController.swift
1
4556
// // ChatRoomsViewController.swift // AwsChat // // Created by Takahashi Yosuke on 2016/08/12. // Copyright © 2016年 Yosan. All rights reserved. // import UIKit /// List view of chat rooms. User can create, select, delete them. class ChatRoomsViewController: UITableViewController { /// Logined user var user: AWSChatUser! /// User's chat rooms var rooms: [AWSChatRoom]? /// Service for chat rooms fileprivate let roomsService = ChatRoomsService() // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() reloadRooms() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rooms?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RoomCell", for: indexPath) if let roomId = rooms?[(indexPath as NSIndexPath).row].RoomId as? String { cell.textLabel?.text = roomId } return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // Delete button is shown by cell swipe. if editingStyle == .delete { guard let rooms = rooms else { return } deleteChatRoom(rooms[(indexPath as NSIndexPath).row]) } } // MARK: - Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier , identifier == "EnterRoom" else { fatalError() } guard let chatVC = segue.destination as? ChatViewController else { fatalError() } guard let selectedRow = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row else { fatalError() } chatVC.user = user chatVC.room = rooms![selectedRow] } /** Called when create new room button clicked - parameter sender: button */ @IBAction func onNewRoomButtonTapped(_ sender: AnyObject) { let alert = getCreateRoomAlert() present(alert, animated: true, completion: nil) } } // MARK: - Private private extension ChatRoomsViewController { /** Get chat rooms from server and reload */ func reloadRooms() { roomsService.getChatRooms(user) { (rooms, error) in guard error == nil else { print(error) return } self.rooms = rooms self.tableView.reloadData() } } /** Create UIAlertController to create chat room - returns: UIAlertController */ func getCreateRoomAlert() -> UIAlertController { let alert = UIAlertController(title: "Create Chat Room", message: "Input room ID and Name", preferredStyle: .alert) /// User can input "Room ID" and "Room Name". !!!: "Room Name" is not used yet. let textFieldNames = [ "Room ID", "Room Name" ] textFieldNames.forEach { (textFieldName) in alert.addTextField { (textField) in textField.placeholder = textFieldName } } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in // If create button is cliced, start process of creating chat room. if let textFields = alert.textFields , textFields.count == textFieldNames.count { guard let roomId = textFields[0].text, let roomName = textFields[1].text else { fatalError() } self.roomsService.createChatRoom(roomId, roomName: roomName, user: self.user, completion: { (room, error) in guard error == nil else { return } self.reloadRooms() }) } })) return alert } /** Delete chat room - parameter room: the room to deleate */ func deleteChatRoom(_ room: AWSChatRoom) { roomsService.deleteChatRoom(room) { (error) in self.reloadRooms() } } }
mit
e57761fca7f7f4acdea2da7aff68aca5
31.992754
136
0.609488
4.927489
false
false
false
false
KellenYangs/KLSwiftTest_05_05
KLBlurViewTest/KLBlurViewTest/ViewController.swift
1
940
// // ViewController.swift // KLBlurViewTest // // Created by bcmac3 on 16/7/27. // Copyright © 2016年 KellenYangs. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var blurView: KLBlurView! override func viewDidLoad() { super.viewDidLoad() blurView.blurProgress = 0.2 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func radiusChange(sender: UISlider) { blurView.blurProgress = sender.value } @IBAction func pan(sender: UIPanGestureRecognizer) { if ((sender.state == .Began) || (sender.state == .Changed)) { let moveP = sender.translationInView(view) blurView.transform = CGAffineTransformMakeTranslation(moveP.x, moveP.y) } else { blurView.transform = CGAffineTransformIdentity } } }
mit
4b500f4897d0e6872c69259302a99c98
21.853659
83
0.629669
4.593137
false
false
false
false
lieonCX/Live
Live/ViewModel/Common/LocationViewModel.swift
1
2769
// // LocationViewModel.swift // Live // // Created by lieon on 2017/7/10. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import Foundation private let shareInstance = LocationViewModel() class LocationViewModel: NSObject { var latitude: CLLocationDegrees = 0.0 var longitude: CLLocationDegrees = 0.0 var cityName: String = "" static let share: LocationViewModel = shareInstance /// 定位对象 fileprivate lazy var llocationManager: CLLocationManager = CLLocationManager() func startLocate() { if CLLocationManager.locationServicesEnabled() { LocationViewModel.share.llocationManager.delegate = LocationViewModel.share LocationViewModel.share.llocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation LocationViewModel.share.llocationManager.requestWhenInUseAuthorization() LocationViewModel.share.llocationManager.startUpdatingLocation() } } } extension LocationViewModel: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let currentLocation: CLLocation = locations.last { let location: CLLocation = locations[0] let coordinate2D: CLLocationCoordinate2D = location.coordinate let baidu: CLLocationCoordinate2D = Utils.bd09(fromGCJ02: coordinate2D) LocationViewModel.share.latitude = baidu.latitude LocationViewModel.share.longitude = baidu.longitude let geocoder: CLGeocoder = CLGeocoder() geocoder.reverseGeocodeLocation(currentLocation, completionHandler: { (arr, error) in guard let arr = arr else { return } if !arr.isEmpty { if let placemark: CLPlacemark = arr.first { var currentCity: String = "" if let city: String = placemark.locality { currentCity = city } else { guard let arrea = placemark.administrativeArea else { return } currentCity = arrea } // print("currentCity : \(currentCity)") LocationViewModel.share.cityName = currentCity if !LocationViewModel.share.cityName.isEmpty { LocationViewModel.share.llocationManager.stopUpdatingLocation() } } } }) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { // print("error:\(error.localizedDescription)") } }
mit
2a4afc5d76d0d1ea54dc49662fdb0861
42.09375
108
0.617114
5.855626
false
false
false
false
SiddharthChopra/KahunaSocialMedia
KahunaSocialMedia/Classes/Facebook/FacebookFeedsJsonParser.swift
1
6092
// // FacebookFeedsJsonParser.swift // MyCity311 // // Created by Piyush on 6/10/16. // Copyright © 2016 Kahuna Systems. All rights reserved. // import UIKit class FacebookFeedsJsonParser: NSObject { override init() { } deinit { print("** FacebookFeedsJsonParser deinit called **") } func parseData(feedsData: NSData) -> NSArray? { let feedsArray = NSMutableArray() autoreleasepool() { let stringData = String(data: feedsData as Data, encoding: String.Encoding.utf8) let feedsDict = readFileFromPathAndSerializeIt(stringData: stringData!) var fbFromName = SocialOperationHandler.sharedInstance.fbFromName as NSString fbFromName = fbFromName.replacingOccurrences(of: "\\u2019", with: "'") as NSString fbFromName = fbFromName.replacingOccurrences(of: "\\u2019", with: "'") as NSString if let myArray = feedsDict!["data"], myArray != nil, let arrayFeeds = myArray as? NSArray { for i in 0 ..< arrayFeeds.count { let innerFeedsDict = arrayFeeds[i] as! NSDictionary let fromDict = innerFeedsDict["from"] as! NSDictionary var message = innerFeedsDict["message"] as? String if message == nil { message = innerFeedsDict["description"] as? String } var pictureURL = "" var linkURL = "" if let picture = innerFeedsDict["picture"] as? String { pictureURL = picture } if let link = innerFeedsDict["link"] as? String { linkURL = link } if (message != nil && (message?.count)! > 0) || pictureURL.count > 0 || linkURL.count > 0 { let coreDataObj: FacebookFeedDataInfo? = FacebookFeedDataInfo() var authorName = fromDict["name"] as! NSString authorName = authorName.replacingOccurrences(of: "\\u2019", with: "'") as NSString authorName = authorName.replacingOccurrences(of: "\\u2019", with: "'") as NSString coreDataObj?.fbAuthorName = authorName as String if let userId = fromDict["id"] as? String { coreDataObj?.fbUserId = userId } if let msg = message { let returnDescString = self.replaceOccuranceOfString(inputString: msg) coreDataObj?.fbDescription = returnDescString coreDataObj?.fbMessage = returnDescString } coreDataObj?.fbPostPictureLink = pictureURL coreDataObj?.fbVideoLink = linkURL if let icon = innerFeedsDict["icon"] as? String { coreDataObj?.fbUserIcon = icon } if let type = innerFeedsDict["type"] as? String { coreDataObj?.fbPostType = type } if innerFeedsDict["updated_time"] != nil { if let updated_time = innerFeedsDict["updated_time"] as? String { coreDataObj?.fbUpdatedTime = updated_time } } else { if let created_time = innerFeedsDict["created_time"] as? String { coreDataObj?.fbUpdatedTime = created_time } } if let created_time = innerFeedsDict["created_time"] as? String { coreDataObj?.fbCreatedTime = created_time } if let fbFeedId = innerFeedsDict["id"] as? String { coreDataObj?.fbFeedId = fbFeedId } if let tempDic = innerFeedsDict["shares"] as? NSDictionary { if let count = tempDic["count"] as? String { coreDataObj?.fbLikesCount = count } if let count = tempDic["count"] as? String { coreDataObj?.fbCommentsCount = count } } feedsArray.add(coreDataObj!) } } } } return feedsArray } //MARK:- Read file from path and Serialize it func readFileFromPathAndSerializeIt(stringData: String) -> AnyObject? { let data = stringData.data(using: String.Encoding.utf8) do { let jsonArray = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) return jsonArray as AnyObject? } catch let error as NSError { print("Error in reading Facebook fetch JSON File\(error.description)") } return nil } func replaceOccuranceOfString(inputString: String) -> String { print("\n ************* FB Desc Input \(inputString)") var replaceString = inputString as NSString _ = NSMakeRange(0, (replaceString.length)) replaceString = replaceString.replacingOccurrences(of: "&amp;", with: "&") as NSString replaceString = replaceString.replacingOccurrences(of: "&apos;", with: "'") as NSString replaceString = replaceString.replacingOccurrences(of: "&quot;", with: "\"") as NSString replaceString = replaceString.replacingOccurrences(of: "&gt;", with: ">") as NSString replaceString = replaceString.replacingOccurrences(of: "&lt;", with: "<") as NSString replaceString = replaceString.replacingOccurrences(of: "&#39;", with: "'") as NSString return replaceString as String } }
mit
28643a5348e3fbd7e77eee67d881ca08
48.520325
131
0.518962
5.487387
false
false
false
false
sodascourse/swift-introduction
Swift-Introduction.playground/Pages/Collections - Array.xcplaygroundpage/Contents.swift
1
5406
/*: # Collections Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. - Arrays are **ordered** collections of values. - Sets are **unordered** collections of **unique values**. - Dictionaries are **unordered** collections of **key-value associations**. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake. It also means you can be confident about the type of values you will retrieve from a collection. If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. You can change the collection by adding, removing, or changing items in the collection. If you assign an array, a set, or a dictionary to a constant, that collection is immutable, and its size and contents cannot be changed. */ /*: ## Arrays An array stores values of _the same type_ in **an ordered list**. The same value can appear in an array multiple times at different positions. ### Array creation Arrays could be created by using Array's initializers or with the array literals. An array literal is written as a list of values, separated by commas, surrounded by a pair of square brackets. */ let names = ["Peter", "Annie", "Matt", "Spencer", "Alvin"] let zeros = Array(repeating: 0, count: 10) var emptyStringArray = [String]() var emptyDoubleArray = Array<Double>() /*: ### Array Type The type of a Swift array is written in full as `Array<Element>`, where `Element` is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as `[Element]`. The shorthand form is preferred and is used throughout this guide when referring to the type of an array. */ let fruits: Array<String> = ["apple", "banana", "orange"] let numbers: [Int] = [1, 2, 3, 4, 5] /*: ### Array and Operators - Arrays could be joined by `+` operator. - We use bracket operator (`[]`) to access the content of an array by a given index or a range. */ var japaneseFoods = ["寿司", "カツ丼", "うどん"] let taiwaneseFoods = ["大腸麵線", "蚵仔煎", "珍珠奶茶", "小籠湯包"] let asianFoods = japaneseFoods + taiwaneseFoods let 烏龍麵 = asianFoods[2] //japaneseFoods[3] // Try to uncomment the above line to see what Xcode yields let noodles = asianFoods[2..<4] /*: ### Properties and Methods of Arrays */ asianFoods.isEmpty japaneseFoods.count let sushi = japaneseFoods.first let doubleOptionalValue = emptyDoubleArray.last // Try to use "option+click" to see the type of above two constants. japaneseFoods.append("牛丼") japaneseFoods.insert("Rib eye steak", at: 2) //taiwaneseFoods.append("魯肉飯") // Try to uncomment the above line to see what Xcode yields let indexOf肉骨茶 = japaneseFoods.index(of: "肉骨茶") let indexOfRibEyeSteak = japaneseFoods.index(of: "Rib eye steak")! // Try to use "option+click" to see the type of above two constants. //let indexOfPhở = japaneseFoods.index(of: "Phở")! // Try to uncomment the above line to see what Xcode yields japaneseFoods.remove(at: indexOfRibEyeSteak) japaneseFoods if let indexOfBurrito = japaneseFoods.index(of: "Burrito") { japaneseFoods.remove(at: indexOfBurrito) } //japaneseFoods.remove(at: indexOf肉骨茶) // Try to uncomment the above line to see what Xcode yields /*: ### Array and Control flows The `for-in` loop is great to enumerate elements in an array */ for japaneseFood in japaneseFoods { "\(japaneseFood) is a delicious." } // `enumerated` method would return an `interator` with pairs (tuples) of index and value. for (index, taiwaneseFood) in taiwaneseFoods.enumerated() { "The food at \(index) is \(taiwaneseFood)." } /*: In Swift, we have a convention that functions and methods which alter the data structure itself (in place) would be named in plain form, like `sort` and `filter`. And since these methods alters the object itself, it's only available to mutable instances (variables). For method named with past tense, like `sorted` and `filtered`, they return a copy of the original one */ let unorderedNumbers = [4, 1, 5, -10, 12, 6, 3, 7, 2] let sortedNumbers = unorderedNumbers.sorted() unorderedNumbers var unorderedNumbers2 = [1, 2, -1, 4, 3, 5] unorderedNumbers2.sort() unorderedNumbers2 /*: ## Array is a generic type The `Array` type could hold another type as its `Element` type. This concept is called **Generic**. We say that Array is a generic collection type. The syntax of denoting a generic type is by angle brackets (`<>`). Types in properties and methods of a generic type may be changed. */ let emptyDoubleOptional = emptyDoubleArray.first let emptyStringOptional = emptyStringArray.first // Try to use "option+click" to see the type of above two constants. emptyDoubleArray.append(42.0) emptyStringArray.append("String") // Try to append different types into these arrays, like: //emptyStringArray.append(10) let removedDouble = emptyDoubleArray.removeLast() let removedString = emptyStringArray.removeFirst() // Try to use "option+click" to see the type of above two constants. //: --- //: //: [<- Previous](@previous) | [Next ->](@next) //:
apache-2.0
1eb933f25d01edcab993ca55209615b7
30.122807
107
0.725667
3.711297
false
false
false
false
shahan312/turbo-api
User.swift
1
13012
// // Users.swift // TurboApi // // Created by Shahan Khan on 9/21/14. // Copyright (c) 2014 Shahan Khan. All rights reserved. // import Foundation struct SimpleUserModel { var id = "" var firstName = "" var lastName = "" var username = "" var avatarUrl: String? init() { } func getUserModel(success: ((UserModel)->())?, error: ((APIError)->())?) { User.getById(id, success: success, error: error) } static func serialize(model: SimpleUserModel) -> Dictionary<String, AnyObject> { var dictionary: Dictionary<String, AnyObject> = [ "_id" : model.id as AnyObject, "firstName" : model.firstName as AnyObject, "lastName" : model.lastName as AnyObject, "username" : model.username as AnyObject] if let avatarUrl = model.avatarUrl { dictionary["avatarUrl"] = avatarUrl as AnyObject } return dictionary } static func serializeArray(models: [SimpleUserModel]) -> [Dictionary<String, AnyObject>] { var array: [Dictionary<String, AnyObject>] = [] for model in models { array.append(SimpleUserModel.serialize(model)) } return array } static func unserialize(dictionary: Dictionary<String, AnyObject>) -> SimpleUserModel { var model = SimpleUserModel() if let value = ((dictionary["_id"] as AnyObject?) as? String) { model.id = value } if let value = ((dictionary["username"] as AnyObject?) as? String) { model.username = value } if let value = ((dictionary["avatarUrl"] as AnyObject?) as? String) { model.avatarUrl = value } if let value = ((dictionary["firstName"] as AnyObject?) as? String) { model.firstName = value } if let value = ((dictionary["lastName"] as AnyObject?) as? String) { model.lastName = value } return model } static func unserializeArray(array: [Dictionary<String, AnyObject>]) -> [SimpleUserModel] { var models: [SimpleUserModel] = [] for dictionary in array { models.append(unserialize(dictionary)) } return models } static func arrayContainsUser(models: [SimpleUserModel], user: SimpleUserModel) -> Bool { // Checks an array of SimpleUserModels for a given user for model in models { if model.id == user.id { return true } } return false } static func arrayWithRemovedUser(models: [SimpleUserModel], removeUser: SimpleUserModel) -> [SimpleUserModel] { var array: [SimpleUserModel] = [] array = models for (index, model) in enumerate(array) { if model.id == removeUser.id { array.removeAtIndex(index) } } return array } static func indexOfUserInArray(models: [SimpleUserModel], user: SimpleUserModel) -> Int? { var modelsCopy: [SimpleUserModel] = [] modelsCopy = models for (index, model) in enumerate(modelsCopy) { if model.id == user.id { return index } } return nil } } class UserModel { var id = "" var firstName = "" var lastName = "" var username = "" var password: String? var email = "" var phone = "" var facebookId: String? var facebookToken: String? var avatarUrl: String? var coverUrl: String? init() { } // converts the UserModel into SimpleUserModel func toSimpleUser() -> SimpleUserModel { var simpleUser = SimpleUserModel() simpleUser.id = id simpleUser.firstName = firstName simpleUser.lastName = lastName simpleUser.username = username simpleUser.avatarUrl = avatarUrl return simpleUser } // make the current user in user follow this user func follow(success: (()->())?, error: ((APIError)->())?) { API.postArrayString("/users/\(id)/follow", parameters: nil, success: { (array) in success?() return }, error: error) Analytics.track("Followed a user") } // make the current user unfollow this user func unfollow(success: (()->())?, error: ((APIError)->())?) { API.delete("/users/\(id)/unfollow", success: { (array) in success?() return }, error: error) Analytics.track("Unfollowed a user") } func save(success: (()->())?, error: ((APIError)->())?) { // if user already exists if id != "" { API.put("/users/\(id)", parameters: serialize(), success: { (dictionary) in success?() return }, error: error) return } // if new users, use POST API.post("/users", parameters: serialize(), success: { (dictionary) in let model = User.unserialize(dictionary) self.id = model.id success?() }, error: error) Analytics.track("Created an account") } func serialize() -> Dictionary<String, AnyObject> { return User.serialize(self) } func isFollowing(userId: String) -> Bool { return contains(following, userId) ? true : false } func getFacebookCover(success:(()->())?, error: ((APIError)->())?) { let manager = API.manager() if facebookId != nil { let fbCoverUrl = "http://graph.facebook.com/" + facebookId! + "?fields=cover" manager.GET(fbCoverUrl, parameters: nil, success: { (operation, data) in let dict = data as Dictionary<String, AnyObject> if let coverDict = ((dict["cover"] as AnyObject?) as? Dictionary<String, AnyObject>) { if let value = ((coverDict["source"] as AnyObject?) as? String) { self.coverUrl = value } } success?() return }, failure: { (task, err) in API.handleError(task, error: err, callback: error) return }) } } } class User { class func savePushToken(token: String) { if let userId = currentUserId() { if let authToken = NSUserDefaults.standardUserDefaults().stringForKey("authToken") { API.put("/users/\(userId)/devices/\(authToken)", parameters: ["pushToken": token], nil, nil) } } } class func loggedIn() -> Bool { let userId = NSUserDefaults.standardUserDefaults().stringForKey("userId") let authToken = NSUserDefaults.standardUserDefaults().stringForKey("authToken") if userId == nil || authToken == nil { return false } return true } class func login(username: String, password: String, success: (()->())?, error: ((APIError)->())?) { // TODO: Login - device uuid let params: [String: AnyObject] = ["username": username, "password": password, "type": "ios", "uuid": "unknown"] API.post("/login", parameters: params, success: { (dictionary) in // get userId and authToken from json dictionary let userId = (dictionary["id"] as AnyObject?) as? String let authToken = (dictionary["authToken"] as AnyObject?) as? String // save login info NSUserDefaults.standardUserDefaults().setObject(userId!, forKey: "userId") NSUserDefaults.standardUserDefaults().setObject(authToken!, forKey: "authToken") NSUserDefaults.standardUserDefaults().synchronize() // Reupdate analytics Analytics.setup() Analytics.track("Logged in", properties: ["type": "email"]) success?() return }, error: error) } class func loginFacebook(id: String, token: String, success: (()->())?, error: ((APIError)->())?) { // TODO: Login - device uuid let params: [String: AnyObject] = ["facebookId": id, "facebookToken": token, "type": "ios", "uuid": "unknown"] API.post("/login", parameters: params, success: { (dictionary) in // get userId and authToken from json dictionary let userId = (dictionary["id"] as AnyObject?) as? String let authToken = (dictionary["authToken"] as AnyObject?) as? String if userId == nil || authToken == nil { NSLog("Did not fetch correct authentication tokens.") error?(APIError.ServerError) return } // save login info NSUserDefaults.standardUserDefaults().setObject(userId!, forKey: "userId") NSUserDefaults.standardUserDefaults().setObject(authToken!, forKey: "authToken") NSUserDefaults.standardUserDefaults().synchronize() // Reupdate analytics Analytics.setup() Analytics.track("Logged in", properties: ["type": "facebook"]) success?() return }, error: error) } class func logout() { // TODO: delete token from server // clear token from device Analytics.track("Logged out") NSUserDefaults.standardUserDefaults().removeObjectForKey("userId") NSUserDefaults.standardUserDefaults().removeObjectForKey("authToken") // Reupdate analytics Analytics.setup() // TODO: clear facebook token } class func currentUser(success: ((UserModel)->())? = nil, error: ((APIError)->())? = nil) { let userId = NSUserDefaults.standardUserDefaults().stringForKey("userId") if userId == nil { error?(.NotAuthenticated) return } getById(userId!, success, error) } class func currentUserId() -> String? { return NSUserDefaults.standardUserDefaults().stringForKey("userId") } // get current user's facebook friends (that are Linx users) class func getFacebookFriends(success: (([SimpleUserModel])->())?, error: ((APIError)->())?) { if let userId = currentUserId() { API.getArray("/users/\(userId)/facebookFriends", success: { (array) in success?(SimpleUserModel.unserializeArray(array)) return }, error: error) } else { error?(.NotAuthenticated) } Analytics.track("Viewed Facebook Friends on Linx") } class func getFriendsFromContacts(phoneNumbers: [String], success: (([SimpleUserModel])->())?, error: ((APIError)->())?) { if let userId = currentUserId() { let params: [String: AnyObject] = ["phoneNumbers": phoneNumbers as AnyObject] API.postArray("/users/\(userId)/findFriendsFromContacts", parameters: params, success: { (array) in success?(SimpleUserModel.unserializeArray(array)) return }, error: error) } else { error?(.NotAuthenticated) } Analytics.track("Viewed friends from contacts") } class func getById(userId: String, success: ((UserModel)->())?, error: ((APIError)->())?) { API.get("/users/\(userId)", success: { (dictionary) in success?(User.unserialize(dictionary)) return }, error: error) } class func getByUserName(username: String, success: (([SimpleUserModel])->())?, error: ((APIError)->())?) { API.getArray("/users?username=\(username)", success: { (array) in success?(SimpleUserModel.unserializeArray(array)) return }, error: error) } class func getByIds(userIds: [String], success: (([SimpleUserModel])->())?, error: ((APIError)->())?) { let params: [String: AnyObject] = ["userIds": userIds] API.postArray("/populate/users", parameters: params, success: { (array) in success?(SimpleUserModel.unserializeArray(array)) return }, error: error) } class func searchByUsername(username: String, success: (([SimpleUserModel])->())?, error: ((APIError)->())?) { API.getArray("/users?username=\(username)", success: { (array) in success?(SimpleUserModel.unserializeArray(array)) return }, error: error) Analytics.track("Searched by username") } class func serialize(model: UserModel) -> Dictionary<String, AnyObject> { var dictionary: [String: AnyObject] = [ "_id": model.id as AnyObject, "firstName": model.firstName as AnyObject, "lastName": model.lastName as AnyObject, "username": model.username as AnyObject ] if model.email != "" { dictionary["email"] = model.email as AnyObject } if model.phone != "" { dictionary["phone"] = model.phone as AnyObject } if let password = model.password { dictionary["password"] = password as AnyObject } if let avatarUrl = model.avatarUrl { dictionary["avatarUrl"] = avatarUrl as AnyObject } if let coverUrl = model.coverUrl { dictionary["coverUrl"] = coverUrl as AnyObject } if let facebookId = model.facebookId { dictionary["facebookId"] = facebookId as AnyObject } if let facebookToken = model.facebookToken { dictionary["facebookToken"] = facebookToken as AnyObject } return dictionary } class func unserialize(dictionary: Dictionary<String, AnyObject>) -> UserModel { var model = UserModel() if let value = ((dictionary["firstName"] as AnyObject?) as? String) { model.firstName = value } if let value = ((dictionary["lastName"] as AnyObject?) as? String) { model.lastName = value } if let value = ((dictionary["username"] as AnyObject?) as? String) { model.username = value } if let value = ((dictionary["_id"] as AnyObject?) as? String) { model.id = value } if let value = ((dictionary["email"] as AnyObject?) as? String) { model.email = value } if let value = ((dictionary["phone"] as AnyObject?) as? String) { model.phone = value } if let value = ((dictionary["facebookToken"] as AnyObject?) as? String) { model.facebookToken = value } if let value = ((dictionary["facebookId"] as AnyObject?) as? String) { model.facebookId = value } if let value = ((dictionary["avatarUrl"] as AnyObject?) as? String) { if value != "" { model.avatarUrl = value } } if let value = ((dictionary["coverUrl"] as AnyObject?) as? String) { if value != "" { model.coverUrl = value } } return model } }
mit
775a4e32bcc650bdf383090244836955
25.288889
123
0.654396
3.742307
false
false
false
false
sishenyihuba/ClipsButton
ClipsButtonDemo/Pods/ClipsButton/ClipsButton/ClipsButton.swift
2
3290
// // ClipsButton.swift // ClipsButton // // Created by macache on 2017/8/24. // Copyright © 2017年 dxl. All rights reserved. // import UIKit @IBDesignable public class ClipsButton: UIButton { // MARK: - pubic properties @IBInspectable public var clipsColor : UIColor = #colorLiteral(red: 0.9568627451, green: 0.2, blue: 0.1960784314, alpha: 1) { didSet { innerLayer.fillColor = clipsColor.cgColor } } @IBInspectable public var innerInset : CGFloat = 5.0 { didSet { innerLayer.path = UIBezierPath(roundedRect: bounds.insetBy(dx: innerInset, dy: innerInset), cornerRadius: bounds.height / 2).cgPath } } public var innerScale : CGFloat = 10.0 //when we highlight the button ,the property changed public override var isHighlighted: Bool { didSet { guard oldValue != isHighlighted else { return } animationClipsButton() } } // MARK: - private properties private var innerLayer : CAShapeLayer! // MARK: - public initializers public override init(frame: CGRect) { super.init(frame: frame) setupUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } // MARK: - private Method private func setupUI() { setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal) setTitleColor(#colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 0), for: .highlighted) layer.cornerRadius = bounds.height / 2 layer.borderWidth = 2 layer.borderColor = UIColor.white.cgColor innerLayer = CAShapeLayer() innerLayer.frame = bounds innerLayer.path = UIBezierPath(roundedRect: bounds.insetBy(dx: innerInset, dy: innerInset), cornerRadius: bounds.height / 2).cgPath innerLayer.fillColor = clipsColor.cgColor layer.addSublayer(innerLayer) } private func animationClipsButton() { let scaleX = 1 - (innerScale / innerLayer.bounds.width) let scaleY = 1 - (innerScale / innerLayer.bounds.height) let animationX = initAnimationWithKeyPath("transform.scale.x") let animationY = initAnimationWithKeyPath("transform.scale.y") if isHighlighted { animationX .toValue = scaleX innerLayer.add(animationX, forKey: "scale.x") animationY.toValue = scaleY innerLayer.add(animationY, forKey: "scale.y") } else { animationX.fromValue = scaleX animationX.toValue = 1.0 innerLayer.add(animationX, forKey: "scale.x") animationY.fromValue = scaleY animationY.toValue = 1.0 innerLayer.add(animationY, forKey: "scale.y") } } private func initAnimationWithKeyPath(_ path : String) -> CABasicAnimation{ let animation = CABasicAnimation(keyPath: path) animation.duration = 0.25 animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) return animation } }
mit
d519224a5cfa67429a659f76f07bea93
31.22549
143
0.628232
4.597203
false
false
false
false
seivan/ScalarArithmetic
TestsAndSample/Tests/TestsIntComparable.swift
1
3889
// // TestsIntComparable.swift // TestsAndSample // // Created by Seivan Heidari on 01/07/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import XCTest class TestsIntComparable: SuperTestsScalarComparable, ScalarComparableTesting { func testEqual() { XCTAssert(self.intValue == self.doubleValue); XCTAssert(self.intValue == self.cgFloatValue); XCTAssert(self.intValue == self.int16Value); XCTAssert(self.intValue == self.int32Value); XCTAssert(self.intValue == self.int64Value); XCTAssert(self.intValue == self.uInt16Value); XCTAssert(self.intValue == self.uInt16Value); XCTAssert(self.intValue == self.uInt16Value); } func testNotEqual() { XCTAssertFalse(self.intValue != self.doubleValue); XCTAssertFalse(self.intValue != self.cgFloatValue); XCTAssertFalse(self.intValue != self.int16Value); XCTAssertFalse(self.intValue != self.int32Value); XCTAssertFalse(self.intValue != self.int64Value); XCTAssertFalse(self.intValue != self.uInt16Value); XCTAssertFalse(self.intValue != self.uInt16Value); XCTAssertFalse(self.intValue != self.uInt16Value); } func testLessThanOrEqual() { XCTAssert(self.intValue <= self.doubleValue); XCTAssert(self.intValue <= self.cgFloatValue); XCTAssert(self.intValue <= self.int16Value); XCTAssert(self.intValue <= self.int32Value); XCTAssert(self.intValue <= self.int64Value); XCTAssert(self.intValue <= self.uInt16Value); XCTAssert(self.intValue <= self.uInt16Value); XCTAssert(self.intValue <= self.uInt16Value); self.intValue = -1 XCTAssert(self.intValue <= self.doubleValue); XCTAssert(self.intValue <= self.cgFloatValue); XCTAssert(self.intValue <= self.int16Value); XCTAssert(self.intValue <= self.int32Value); XCTAssert(self.intValue <= self.int64Value); XCTAssert(self.intValue <= self.uInt16Value); XCTAssert(self.intValue <= self.uInt16Value); XCTAssert(self.intValue <= self.uInt16Value); } func testLessThan() { self.intValue = -1 XCTAssert(self.intValue < self.doubleValue); XCTAssert(self.intValue < self.cgFloatValue); XCTAssert(self.intValue < self.int16Value); XCTAssert(self.intValue < self.int32Value); XCTAssert(self.intValue < self.int64Value); XCTAssert(self.intValue < self.uInt16Value); XCTAssert(self.intValue < self.uInt16Value); XCTAssert(self.intValue < self.uInt16Value); } func testGreaterThanOrEqual() { XCTAssert(self.intValue >= self.doubleValue); XCTAssert(self.intValue >= self.cgFloatValue); XCTAssert(self.intValue >= self.int16Value); XCTAssert(self.intValue >= self.int32Value); XCTAssert(self.intValue >= self.int64Value); XCTAssert(self.intValue >= self.uInt16Value); XCTAssert(self.intValue >= self.uInt16Value); XCTAssert(self.intValue >= self.uInt16Value); self.intValue = -1 XCTAssertFalse(self.intValue >= self.doubleValue); XCTAssertFalse(self.intValue >= self.cgFloatValue); XCTAssertFalse(self.intValue >= self.int16Value); XCTAssertFalse(self.intValue >= self.int32Value); XCTAssertFalse(self.intValue >= self.int64Value); XCTAssertFalse(self.intValue >= self.uInt16Value); XCTAssertFalse(self.intValue >= self.uInt16Value); XCTAssertFalse(self.intValue >= self.uInt16Value); } func testGreaterThan() { self.intValue = -1 XCTAssertFalse(self.intValue > self.doubleValue); XCTAssertFalse(self.intValue > self.cgFloatValue); XCTAssertFalse(self.intValue > self.int16Value); XCTAssertFalse(self.intValue > self.int32Value); XCTAssertFalse(self.intValue > self.int64Value); XCTAssertFalse(self.intValue > self.uInt16Value); XCTAssertFalse(self.intValue > self.uInt16Value); XCTAssertFalse(self.intValue > self.uInt16Value); } }
mit
1c13a8cdd9c660f82007dc7bc12cc2cf
33.114035
79
0.711751
4.085084
false
true
false
false
el-hoshino/NotAutoLayout
Playground.playground/Sources/ContentsView.swift
1
2781
import UIKit import NotAutoLayout private let padding: NotAutoLayout.Float = 10 public class ContentsView: UIView { private let contentsLabel: UILabel private let timeStampView: UILabel private let dateFormatter: DateFormatter public var contents: String? { get { return self.contentsLabel.text } set { self.contentsLabel.text = newValue } } public var timeStamp: Date? { get { return self.timeStampView.text.map { self.dateFormatter.date(from: $0) } ?? nil } set { newValue.map { self.timeStampView.text = self.dateFormatter.string(from: $0) } } } public override init(frame: CGRect) { self.contentsLabel = UILabel() self.timeStampView = UILabel() self.dateFormatter = DateFormatter() super.init(frame: frame) self.setupContentsLabel() self.setupTimeStampLabel() self.setupDateFormatter() } public convenience init() { self.init(frame: .zero) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func sizeThatFits(_ size: CGSize) -> CGSize { let fittingSize = CGSize(width: size.width, height: 0) let contentsLabelFittedSize = self.contentsLabel.sizeThatFits(fittingSize) let timeStampViewFittedSize = self.timeStampView.sizeThatFits(fittingSize) let fittedWidth = max(contentsLabelFittedSize.width, timeStampViewFittedSize.width) let fittedHeight = contentsLabelFittedSize.height + timeStampViewFittedSize.height + (padding.cgValue * 3) return CGSize(width: fittedWidth, height: fittedHeight) } public override func layoutSubviews() { super.layoutSubviews() self.placeContentsLabel() self.placeTimeStampView() } } extension ContentsView { private func setupContentsLabel() { let view = self.contentsLabel view.clipsToBounds = true view.numberOfLines = 0 view.font = .systemFont(ofSize: UIFont.labelFontSize) view.textColor = .black self.addSubview(view) } private func setupTimeStampLabel() { let view = self.timeStampView view.clipsToBounds = true view.font = .systemFont(ofSize: UIFont.smallSystemFontSize) view.textColor = .darkGray self.addSubview(view) } private func setupDateFormatter() { let formatter = self.dateFormatter formatter.dateFormat = "yyyy/MM/dd HH:mm" } } extension ContentsView { private func placeContentsLabel() { self.nal.layout(self.contentsLabel, by: { $0 .setTopCenter(by: { $0.topCenter }) .setWidth(by: { $0.width }) .fitHeight() }) } private func placeTimeStampView() { self.nal.layout(self.timeStampView) { $0 .pinTopCenter(to: self.contentsLabel, with: { $0.bottomCenter }) .setWidth(by: { $0.width }) .fitHeight() .movingY(by: padding) } } }
apache-2.0
7627cdaac2187ff10f8919ef2058df6f
20.726563
108
0.711615
3.493719
false
false
false
false
nickswalker/ASCIIfy
Example/iOS/Source/ViewController.swift
1
4830
// // Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of // project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright // for ASCIIfy are held by Nick Walker, 2016. // // 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 ASCIIfy class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var fontSizeSlider: UISlider! @IBOutlet weak var fontSizeLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! fileprivate var imagePicker: UIImagePickerController? fileprivate var inputImage: UIImage? fileprivate var outputImage: UIImage? { didSet(oldValue) { if displayingOutput { imageView.image = outputImage } } } fileprivate var colorMode: ASCIIConverter.ColorMode = .color { didSet(oldValue) { processInput() } } fileprivate var displayingOutput = true { didSet(oldValue){ if displayingOutput { imageView.image = outputImage } else { imageView.image = inputImage } } } override func viewDidLoad() { super.viewDidLoad() // Configure demo image let bundle = Bundle(for: type(of: self)) let path = bundle.path(forResource: "flower", ofType: "jpg")! inputImage = UIImage(contentsOfFile: path) processInput() fontSizeLabel.text = "\(Int(fontSizeSlider.value))" } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { inputImage = info[UIImagePickerControllerEditedImage] as? UIImage imagePicker?.dismiss(animated: true, completion: nil) processInput() } fileprivate func processInput() { let font = ASCIIConverter.defaultFont.withSize(CGFloat(fontSizeSlider.value)) activityIndicator.startAnimating() inputImage?.fy_asciiImageWith(font, colorMode: colorMode) { image in self.activityIndicator.stopAnimating() self.outputImage = image } } // MARK: Interaction @IBAction func pickNewImage(_ sender: UIBarButtonItem) { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.sourceType = .photoLibrary self.imagePicker = picker present(picker, animated: true, completion: nil) } @IBAction func didShare(_ sender: UIBarButtonItem) { guard let outputImage = outputImage else { return } let controller = UIActivityViewController(activityItems: [outputImage], applicationActivities: nil) present(controller, animated: true, completion: nil) } @IBAction func didPressDown(_ sender: UIButton) { displayingOutput = false } @IBAction func didRelease(_ sender: UIButton) { displayingOutput = true } @IBAction func fontSizeChanged(_ sender: UISlider) { fontSizeLabel.text = "\(Int(fontSizeSlider.value))" processInput() } // MARK: Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "options" { let navController = (segue.destination as? UINavigationController) let optionsController = navController?.childViewControllers[0] as? OptionsController optionsController?.modeChangeHandler = { self.colorMode = $0} optionsController?.mode = colorMode } } @IBAction func prepareForUnwind(_ segue: UIStoryboardSegue) { } }
mit
97ef370e95d4b23967bb5344e3ac4aa0
35.568182
119
0.676818
5.081053
false
false
false
false
ronaldmannak/ConnectedDrive
Example/iOS/ConnectedDriveiOS/AppDelegate.swift
1
3813
// // AppDelegate.swift // ConnectedDriveiOS // // Created by Ronald Mannak on 12/26/15. // Copyright © 2015 Ronald Mannak. All rights reserved. // import UIKit import ConnectedDrive @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Locator.connectedDrive.delegate = self Locator.connectedDrive.autoLogin { result in switch result { case .Success(_): // AppDelegate is connectedDrive delegate and break case .Failure(let error): print("Auto login error: \(error)") } } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate: ConnectedDriveDelegate { func startedFetchingData() { } func finshedFetchingData() { } func shouldPresentLoginWindow() { setInitialViewControllerOfStoryboardToRootViewController("Login") } func didLogin() { setInitialViewControllerOfStoryboardToRootViewController("Main") } func didLogout() { setInitialViewControllerOfStoryboardToRootViewController("Login") } func setInitialViewControllerOfStoryboardToRootViewController(storyboardName: String) { let storyboard = UIStoryboard(name: storyboardName, bundle: nil) let viewController = storyboard.instantiateInitialViewController() UIView.transitionWithView(self.window!, duration: 0.3, options: .TransitionCrossDissolve, animations: { () -> Void in self.window?.rootViewController = viewController }, completion: nil) // [UIView transitionWithView:self.window // duration:0.5 // options:UIViewAnimationOptionTransitionFlipFromLeft // animations:^{ self.window.rootViewController = newViewController; } // completion:nil]; // UIApplication.sharedApplication().keyWindow?.rootViewController = viewController } }
mit
0f04d9387619e41712f5d49a9923578e
38.298969
285
0.700157
5.655786
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinUI/CoinView/CoinView.swift
1
15026
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import BlockchainNamespace import Combine import ComposableArchitecture import ComposableArchitectureExtensions import FeatureCoinDomain import Localization import SwiftUI import ToolKit public struct CoinView: View { let store: Store<CoinViewState, CoinViewAction> @ObservedObject var viewStore: ViewStore<CoinViewState, CoinViewAction> @BlockchainApp var app @Environment(\.context) var context public init(store: Store<CoinViewState, CoinViewAction>) { self.store = store _viewStore = .init(initialValue: ViewStore(store)) } typealias Localization = LocalizationConstants.Coin public var body: some View { VStack(alignment: .leading, spacing: 0) { ScrollView { header() accounts() about() Color.clear .frame(height: Spacing.padding2) } if viewStore.accounts.isNotEmpty, viewStore.actions.isNotEmpty { actions() } } .primaryNavigation( leading: navigationLeadingView, title: viewStore.currency.name, trailing: { dismiss() } ) .frame(maxWidth: .infinity, maxHeight: .infinity) .onAppear { viewStore.send(.onAppear) } .onDisappear { viewStore.send(.onDisappear) } .bottomSheet( item: viewStore.binding(\.$account).animation(.spring()), content: { account in AccountSheet( account: account, isVerified: viewStore.kycStatus != .unverified, onClose: { viewStore.send(.set(\.$account, nil), animation: .spring()) } ) .context( [ blockchain.ux.asset.account.id: account.id, blockchain.ux.asset.account: account ] ) } ) .bottomSheet( item: viewStore.binding(\.$explainer).animation(.spring()), content: { account in AccountExplainer( account: account, onClose: { viewStore.send(.set(\.$explainer, nil), animation: .spring()) } ) .context( [ blockchain.ux.asset.account.id: account.id, blockchain.ux.asset.account: account ] ) } ) } @ViewBuilder func header() -> some View { GraphView( store: store.scope(state: \.graph, action: CoinViewAction.graph) ) } @ViewBuilder func totalBalance() -> some View { TotalBalanceView( currency: viewStore.currency, accounts: viewStore.accounts, trailing: { WithViewStore(store) { viewStore in if let isFavorite = viewStore.isFavorite { IconButton(icon: isFavorite ? .favorite : .favoriteEmpty) { viewStore.send(isFavorite ? .removeFromWatchlist : .addToWatchlist) } } else { ProgressView() .progressViewStyle(.circular) .frame(width: 28, height: 28) } } } ) } @ViewBuilder func accounts() -> some View { VStack { if viewStore.error == .failedToLoad { AlertCard( title: Localization.Accounts.Error.title, message: Localization.Accounts.Error.message, variant: .error, isBordered: true ) .padding([.leading, .trailing, .top], Spacing.padding2) } else if viewStore.currency.isTradable { totalBalance() if let status = viewStore.kycStatus { AccountListView( accounts: viewStore.accounts, currency: viewStore.currency, interestRate: viewStore.interestRate, kycStatus: status ) if let swapAction = viewStore.swapButton { PrimaryButton(title: swapAction.title) { swapAction.icon } action: { app.post(event: swapAction.event[].ref(to: context), context: context) } .disabled(swapAction.disabled) .padding(.top, Spacing.padding2) .padding(.horizontal, Spacing.padding2) } } } else { totalBalance() AlertCard( title: Localization.Label.Title.notTradable.interpolating( viewStore.currency.name, viewStore.currency.displayCode ), message: Localization.Label.Title.notTradableMessage.interpolating( viewStore.currency.name, viewStore.currency.displayCode ) ) .padding([.leading, .trailing], Spacing.padding2) } } } @State private var isExpanded: Bool = false @ViewBuilder func about() -> some View { if viewStore.assetInformation?.description.nilIfEmpty == nil, viewStore.assetInformation?.website == nil { EmptyView() } else { HStack { VStack(alignment: .leading, spacing: Spacing.padding1) { Text( Localization.Label.Title.aboutCrypto .interpolating(viewStore.currency.name) ) .foregroundColor(.semantic.title) .typography(.body2) if let about = viewStore.assetInformation?.description { Text(rich: about) .lineLimit(isExpanded ? nil : 6) .typography(.paragraph1) .foregroundColor(.semantic.title) if !isExpanded { Button( action: { withAnimation { isExpanded.toggle() } }, label: { Text(Localization.Button.Title.readMore) .typography(.paragraph1) .foregroundColor(.semantic.primary) } ) } } if let url = viewStore.assetInformation?.website { Spacer() SmallMinimalButton(title: Localization.Link.Title.visitWebsite) { app.post( event: blockchain.ux.asset.bio.visit.website[].ref(to: context), context: [blockchain.ux.asset.bio.visit.website.url[]: url] ) } } } .padding(Spacing.padding3) } } } @ViewBuilder func navigationLeadingView() -> some View { if let url = viewStore.currency.assetModel.logoPngUrl { AsyncMedia( url: url, content: { media in media.cornerRadius(12) }, placeholder: { Color.semantic.muted .opacity(0.3) .overlay( ProgressView() .progressViewStyle(.circular) ) .clipShape(Circle()) } ) .resizingMode(.aspectFit) .frame(width: 24.pt, height: 24.pt) } } @ViewBuilder func dismiss() -> some View { IconButton(icon: .closev2.circle()) { viewStore.send(.dismiss) } .frame(width: 24.pt, height: 24.pt) } @ViewBuilder func actions() -> some View { VStack(spacing: 0) { PrimaryDivider() HStack(spacing: 8.pt) { ForEach(viewStore.actions, id: \.event) { action in SecondaryButton( title: action.title, leadingView: { action.icon }, action: { app.post(event: action.event[].ref(to: context), context: context) } ) .disabled(action.disabled) } } .padding(.horizontal, Spacing.padding2) .padding(.top) } } } // swiftlint:disable type_name struct CoinView_PreviewProvider: PreviewProvider { static var previews: some View { PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .bitcoin, kycStatus: .gold, accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], isFavorite: true, graph: .init( interval: .day, result: .success(.preview) ) ), reducer: coinViewReducer, environment: .preview ) ) .app(App.preview) } .previewDevice("iPhone SE (2nd generation)") .previewDisplayName("Gold - iPhone SE (2nd generation)") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .bitcoin, kycStatus: .gold, accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], isFavorite: true, graph: .init( interval: .day, result: .success(.preview) ) ), reducer: coinViewReducer, environment: .preview ) ) .app(App.preview) } .previewDevice("iPhone 13 Pro Max") .previewDisplayName("Gold - iPhone 13 Pro Max") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .ethereum, kycStatus: .silver, accounts: [ .preview.privateKey, .preview.trading, .preview.rewards ], isFavorite: false, graph: .init( interval: .day, result: .success(.preview) ) ), reducer: coinViewReducer, environment: .preview ) ) .app(App.preview) } .previewDisplayName("Silver") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .nonTradeable, kycStatus: .unverified, accounts: [ .preview.rewards ], isFavorite: false, graph: .init( interval: .day, result: .success(.preview) ) ), reducer: coinViewReducer, environment: .preview ) ) .app(App.preview) } .previewDisplayName("Not Tradable") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .bitcoin, kycStatus: .unverified, accounts: [ .preview.privateKey ], isFavorite: false, graph: .init( interval: .day, result: .success(.preview) ) ), reducer: coinViewReducer, environment: .preview ) ) .app(App.preview) } .previewDisplayName("Unverified") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .stellar, isFavorite: nil, graph: .init(isFetching: true) ), reducer: coinViewReducer, environment: .previewEmpty ) ) .app(App.preview) } .previewDisplayName("Loading") PrimaryNavigationView { CoinView( store: .init( initialState: .init( currency: .bitcoin, kycStatus: .unverified, error: .failedToLoad, isFavorite: false, graph: .init( interval: .day, result: .failure(.init(request: nil, type: .serverError(.badResponse))) ) ), reducer: coinViewReducer, environment: .previewEmpty ) ) .app(App.preview) } .previewDisplayName("Error") } }
lgpl-3.0
08c26ddccaa455efcedf09811aa24e9d
34.187354
114
0.410516
6.211244
false
false
false
false
shaps80/Peek
Pod/Classes/PeekOptions.swift
1
3869
/* Copyright © 23/04/2016 Shaps 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 /** Available activation modes - Auto: Peek will use a shake gesture when running in the Simulator, and the volume controls on a device - Shake: Peek will use a shake gesture on both the Simulator and a device */ @objc public enum PeekActivationMode: Int { /// Peek will use a shake gesture when running in the Simulator, and the volume controls on a device case auto = 0 /// Peek will use a shake gesture on both the Simulator and a device case shake } @objc public enum PeekTheme: Int { case dark = 0 case black case light } /// Defines various options to use when enabling Peek public final class PeekOptions: NSObject { /// Defines how peek looks (.black mode is optimised for OLED displays). Defaults to .dark @objc public var theme: PeekTheme = .dark /// Defines how Peek is activated/de-activated. Defaults to auto @objc public var activationMode: PeekActivationMode = .auto /// When this is true, views that are not subclassed but contain subviews, will be ignored. Defaults to false @objc public var ignoresContainerViews = false /// You can provide meta data that will be attached to every report. This is useful for passing additional info about the app, e.g. Environment, etc... @objc public var metadata: [String: String] = [:] // MARK: Obsoletions @available(*, deprecated, renamed: "ignoresContainerViews") @objc public var shouldIgnoreContainers: Bool { get { return ignoresContainerViews } set { ignoresContainerViews = newValue } } @available(*, deprecated) @objc public var includeScreenshot = true @available(*, deprecated, message: "Defaults to UIScreen.main.scale") @objc public var screenshotScale = UIScreen.main.scale @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var slackUserName = "Peek" @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var slackRecipient: String? @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var slackWebHookURL: URL? @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var emailRecipients: [String]? @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var emailSubject: String? @available(*, deprecated, message: "Peek now uses the built in UIActivityViewController") @objc public var slackImageUploader: ((URLSession, UIImage) -> URL?)? @available(*, deprecated, renamed: "metadata") @objc public var reportMetaData: [String: String]? }
mit
26231d0247cbee102bf7ec012acee03d
43.976744
155
0.73242
4.763547
false
false
false
false
gouyz/GYZBaking
baking/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
2
54274
// // IQUIView+IQKeyboardToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } private var kIQShouldHideToolbarPlaceholder = "kIQShouldHideToolbarPlaceholder" private var kIQToolbarPlaceholder = "kIQToolbarPlaceholder" private var kIQKeyboardToolbar = "kIQKeyboardToolbar" /** UIView category methods to add IQToolbar on UIKeyboard. */ public extension UIView { /** IQToolbar references for better customization control. */ public var keyboardToolbar: IQToolbar { get { var toolbar = inputAccessoryView as? IQToolbar if (toolbar == nil) { toolbar = objc_getAssociatedObject(self, &kIQKeyboardToolbar) as? IQToolbar } if let unwrappedToolbar = toolbar { return unwrappedToolbar } else { let newToolbar = IQToolbar() objc_setAssociatedObject(self, &kIQKeyboardToolbar, newToolbar, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return newToolbar } } } ///------------------------- /// MARK: Title ///------------------------- /** If `shouldHideToolbarPlaceholder` is YES, then title will not be added to the toolbar. Default to NO. */ public var shouldHideToolbarPlaceholder: Bool { get { let aValue: AnyObject? = objc_getAssociatedObject(self, &kIQShouldHideToolbarPlaceholder) as AnyObject? if let unwrapedValue = aValue as? Bool { return unwrapedValue } else { return false } } set(newValue) { objc_setAssociatedObject(self, &kIQShouldHideToolbarPlaceholder, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder; } } @available(*,deprecated, message: "This is renamed to `shouldHideToolbarPlaceholder` for more clear naming.") public var shouldHidePlaceholderText: Bool { get { return shouldHideToolbarPlaceholder } set(newValue) { shouldHideToolbarPlaceholder = newValue } } /** `toolbarPlaceholder` to override default `placeholder` text when drawing text on toolbar. */ public var toolbarPlaceholder: String? { get { let aValue = objc_getAssociatedObject(self, &kIQToolbarPlaceholder) as? String return aValue } set(newValue) { objc_setAssociatedObject(self, &kIQToolbarPlaceholder, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder; } } @available(*,deprecated, message: "This is renamed to `toolbarPlaceholder` for more clear naming.") public var placeholderText: String? { get { return toolbarPlaceholder } set(newValue) { toolbarPlaceholder = newValue } } /** `drawingToolbarPlaceholder` will be actual text used to draw on toolbar. This would either `placeholder` or `toolbarPlaceholder`. */ public var drawingToolbarPlaceholder: String? { if (self.shouldHideToolbarPlaceholder) { return nil } else if (self.toolbarPlaceholder?.isEmpty == false) { return self.toolbarPlaceholder } else if self.responds(to: #selector(getter: UITextField.placeholder)) { if let textField = self as? UITextField { return textField.placeholder } else if let textView = self as? IQTextView { return textView.placeholder } else { return nil } } else { return nil } } @available(*,deprecated, message: "This is renamed to `drawingToolbarPlaceholder` for more clear naming.") public var drawingPlaceholderText: String? { return drawingToolbarPlaceholder } ///--------------------- /// MARK: Private helper ///--------------------- fileprivate static func flexibleBarButtonItem () -> IQBarButtonItem { struct Static { static let nilButton = IQBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) } Static.nilButton.isSystemItem = true return Static.nilButton } ///------------ /// MARK: Done ///------------ /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addDoneOnKeyboardWithTarget(_ target : AnyObject?, action : Selector) { addDoneOnKeyboardWithTarget(target, action: action, titleText: nil) } /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addDoneOnKeyboardWithTarget (_ target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: target, action: action) doneButton.isSystemItem = true doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add Done button on keyboard. @param target Target object for selector. @param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addDoneOnKeyboardWithTarget (_ target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addDoneOnKeyboardWithTarget(target, action: action, titleText: title) } ///------------ /// MARK: Right ///------------ /** Helper function to add Right button on keyboard. @param image Image icon to use as right button. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightButtonOnKeyboardWithImage (_ image : UIImage, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton.title = nil doneButton.image = image doneButton.target = target doneButton.action = action } else { doneButton = IQBarButtonItem(image: image, style: UIBarButtonItemStyle.done, target: target, action: action) doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add Right button on keyboard. @param image Image icon to use as right button. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightButtonOnKeyboardWithImage (_ image : UIImage, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addRightButtonOnKeyboardWithImage(image, target: target, action: action, titleText: title) } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector) { addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil) } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton.title = text doneButton.image = nil doneButton.target = target doneButton.action = action } else { doneButton = IQBarButtonItem(title: text, style: UIBarButtonItemStyle.done, target: target, action: action) doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add Right button on keyboard. @param text Title for rightBarButtonItem, usually 'Done'. @param target Target object for selector. @param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title) } ///------------------ /// MARK: Cancel/Done ///------------------ /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector) { addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil) } /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] //Cancel button var cancelButton = toolbar.previousBarButton if cancelButton.isSystemItem == false { cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: target, action: cancelAction) cancelButton.isSystemItem = true cancelButton.invocation = toolbar.previousBarButton.invocation cancelButton.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel toolbar.previousBarButton = cancelButton } items.append(cancelButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: target, action: doneAction) doneButton.isSystemItem = true doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add Cancel and Done button on keyboard. @param target Target object for selector. @param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title) } ///----------------- /// MARK: Right/Left ///----------------- /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) { addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil) } /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] //Left button var cancelButton = toolbar.previousBarButton if cancelButton.isSystemItem == false { cancelButton.title = rightButtonTitle cancelButton.image = nil cancelButton.target = target cancelButton.action = rightButtonAction } else { cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItemStyle.plain, target: target, action: leftButtonAction) cancelButton.invocation = toolbar.previousBarButton.invocation cancelButton.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel toolbar.previousBarButton = cancelButton } items.append(cancelButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton.title = rightButtonTitle doneButton.image = nil doneButton.target = target doneButton.action = rightButtonAction } else { doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.done, target: target, action: rightButtonAction) doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add Left and Right button on keyboard. @param target Target object for selector. @param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title) } ///------------------------- /// MARK: Previous/Next/Done ///------------------------- /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) { addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil) } /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] // Get the top level "bundle" which may actually be the framework var bundle = Bundle(for: IQKeyboardManager.self) if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } var imageLeftArrow : UIImage! var imageRightArrow : UIImage! if #available(iOS 10, *) { imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil) } else { imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil) } //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) if #available(iOS 9, *) { imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection() imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection() } var prev = toolbar.previousBarButton if prev.isSystemItem == false { prev.title = nil prev.image = imageLeftArrow prev.target = target prev.action = previousAction } else { prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.plain, target: target, action: previousAction) prev.invocation = toolbar.previousBarButton.invocation prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel toolbar.previousBarButton = prev } var next = toolbar.nextBarButton if next.isSystemItem == false { next.title = nil next.image = imageRightArrow next.target = target next.action = nextAction } else { next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.plain, target: target, action: nextAction) next.invocation = toolbar.nextBarButton.invocation next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel toolbar.nextBarButton = next } //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) fixed.isSystemItem = true if #available(iOS 10, *) { fixed.width = 6 } else { fixed.width = 20 } items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Done button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: target, action: doneAction) doneButton.isSystemItem = true doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } /** Helper function to add ArrowNextPrevious and Done button on keyboard. @param target Target object for selector. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. */ public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title) } ///-------------------------- /// MARK: Previous/Next/Right ///-------------------------- /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] // Get the top level "bundle" which may actually be the framework var bundle = Bundle(for: IQKeyboardManager.self) if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } var imageLeftArrow : UIImage! var imageRightArrow : UIImage! if #available(iOS 10, *) { imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil) } else { imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil) } //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) if #available(iOS 9, *) { imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection() imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection() } var prev = toolbar.previousBarButton if prev.isSystemItem == false { prev.title = nil prev.image = imageLeftArrow prev.target = target prev.action = previousAction } else { prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.plain, target: target, action: previousAction) prev.invocation = toolbar.previousBarButton.invocation prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel toolbar.previousBarButton = prev } var next = toolbar.nextBarButton if next.isSystemItem == false { next.title = nil next.image = imageRightArrow next.target = target next.action = nextAction } else { next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.plain, target: target, action: nextAction) next.invocation = toolbar.nextBarButton.invocation next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel toolbar.nextBarButton = next } //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) fixed.isSystemItem = true if #available(iOS 10, *) { fixed.width = 6 } else { fixed.width = 20 } items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton.title = nil doneButton.image = rightButtonImage doneButton.target = target doneButton.action = rightButtonAction } else { doneButton = IQBarButtonItem(image: rightButtonImage, style: UIBarButtonItemStyle.done, target: target, action: rightButtonAction) doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } // /** // Helper function to add ArrowNextPrevious and Right button on keyboard. // // @param target Target object for selector. // @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. // @param previousAction Previous button action name. Usually 'previousAction:(id)item'. // @param nextAction Next button action name. Usually 'nextAction:(id)item'. // @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. // @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. // */ public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addPreviousNextRightOnKeyboardWithTarget(target, rightButtonImage: rightButtonImage, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title) } /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. */ public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector) { addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: nil) } /** Helper function to add ArrowNextPrevious and Right button on keyboard. @param target Target object for selector. @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. @param previousAction Previous button action name. Usually 'previousAction:(id)item'. @param nextAction Next button action name. Usually 'nextAction:(id)item'. @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param titleText text to show as title in IQToolbar'. */ public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) { //If can't set InputAccessoryView. Then return if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) { // Creating a toolBar for phoneNumber keyboard let toolbar = self.keyboardToolbar var items : [IQBarButtonItem] = [] // Get the top level "bundle" which may actually be the framework var bundle = Bundle(for: IQKeyboardManager.self) if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") { if let resourcesBundle = Bundle(path: resourcePath) { bundle = resourcesBundle } } var imageLeftArrow : UIImage! var imageRightArrow : UIImage! if #available(iOS 10, *) { imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil) } else { imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil) imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil) } //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) if #available(iOS 9, *) { imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection() imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection() } var prev = toolbar.previousBarButton if prev.isSystemItem == false { prev.title = nil prev.image = imageLeftArrow prev.target = target prev.action = previousAction } else { prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItemStyle.plain, target: target, action: previousAction) prev.invocation = toolbar.previousBarButton.invocation prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel toolbar.previousBarButton = prev } var next = toolbar.nextBarButton if next.isSystemItem == false { next.title = nil next.image = imageRightArrow next.target = target next.action = nextAction } else { next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItemStyle.plain, target: target, action: nextAction) next.invocation = toolbar.nextBarButton.invocation next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel toolbar.nextBarButton = next } //Previous button items.append(prev) //Fixed space let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) fixed.isSystemItem = true if #available(iOS 10, *) { fixed.width = 6 } else { fixed.width = 20 } items.append(fixed) //Next button items.append(next) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Title button toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText if #available(iOS 11, *) { } else { toolbar.titleBarButton.customView?.frame = CGRect.zero; } items.append(toolbar.titleBarButton) //Flexible space items.append(UIView.flexibleBarButtonItem()) //Right button var doneButton = toolbar.doneBarButton if doneButton.isSystemItem == false { doneButton.title = rightButtonTitle doneButton.image = nil doneButton.target = target doneButton.action = rightButtonAction } else { doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.done, target: target, action: rightButtonAction) doneButton.invocation = toolbar.doneBarButton.invocation doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel toolbar.doneBarButton = doneButton } items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar switch textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar switch textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black default: toolbar.barStyle = UIBarStyle.default } } } } // /** // Helper function to add ArrowNextPrevious and Right button on keyboard. // // @param target Target object for selector. // @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'. // @param previousAction Previous button action name. Usually 'previousAction:(id)item'. // @param nextAction Next button action name. Usually 'nextAction:(id)item'. // @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'. // @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'. // */ public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) { var title : String? if shouldShowPlaceholder == true { title = self.drawingToolbarPlaceholder } addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title) } }
mit
734ab71609ca3e7265b4a5184bc81784
40.179059
220
0.599421
6.104375
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamUI/Sheets/MailSheet.swift
1
3255
// // MailSheet.swift // ZamzamUI // // Created by Basem Emara on 2021-08-16. // Copyright © 2021 Zamzam Inc. All rights reserved. // #if os(iOS) && canImport(MessageUI) import MessageUI import SwiftUI private struct MailView: UIViewControllerRepresentable { let item: MailItem func makeCoordinator() -> Coordinator { Coordinator() } func makeUIViewController(context: Context) -> UIViewController { context.coordinator.makeViewController(with: item) } func updateUIViewController(_ uiViewController: UIViewController, context: Context) {} } private extension MailView { class Coordinator: NSObject, MFMailComposeViewControllerDelegate { /// A standard interface for managing, editing, and sending an email message. func makeViewController(with request: MailItem) -> UIViewController { MFMailComposeViewController().apply { $0.mailComposeDelegate = self $0.setToRecipients(request.emails) if let subject = request.subject { $0.setSubject(subject) } if let body = request.body { $0.setMessageBody(body, isHTML: request.isHTML) } if let attachment = request.attachment { $0.addAttachmentData( attachment.data, mimeType: attachment.mimeType, fileName: attachment.fileName ) } } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true) } } } public struct MailItem: Identifiable, Equatable { public struct Attachment: Equatable { let data: Data let mimeType: String let fileName: String } public let id = UUID() let emails: [String] let subject: String? let body: String? let isHTML: Bool let attachment: Attachment? public init( emails: String..., subject: String? = nil, body: String? = nil, isHTML: Bool = true, attachment: Attachment? = nil ) { self.emails = emails self.subject = subject self.body = body self.isHTML = isHTML self.attachment = attachment } } public extension View { /// Presents a compose mail sheet using the given options for sending a message. /// /// If the current device is not able to send email, determined via `MFMailComposeViewController.canSendMail()`, /// an alert will notify the user of the failure. @ViewBuilder func sheet(mail item: Binding<MailItem?>) -> some View { if MFMailComposeViewController.canSendMail() { sheet(item: item) { item in MailView(item: item) .ignoresSafeArea() } } else { alert(item: item) { _ in Alert( title: Text("Could Not Send Email"), message: Text("Your device could not send email.") ) } } } } #endif
mit
d3ebc5d2b41f7bded33a224127f49efe
28.315315
137
0.580209
5.198083
false
false
false
false
abertelrud/swift-package-manager
Sources/Commands/PackageTools/Describe.swift
2
2636
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ArgumentParser import CoreCommands import Foundation import PackageModel import TSCBasic extension SwiftPackageTool { struct Describe: SwiftCommand { static let configuration = CommandConfiguration( abstract: "Describe the current package") @OptionGroup(_hiddenFromHelp: true) var globalOptions: GlobalOptions @Option(help: "json | text") var type: DescribeMode = .text func run(_ swiftTool: SwiftTool) throws { let workspace = try swiftTool.getActiveWorkspace() guard let packagePath = try swiftTool.getWorkspaceRoot().packages.first else { throw StringError("unknown package") } let package = try tsc_await { workspace.loadRootPackage( at: packagePath, observabilityScope: swiftTool.observabilityScope, completion: $0 ) } try self.describe(package, in: type) } /// Emits a textual description of `package` to `stream`, in the format indicated by `mode`. func describe(_ package: Package, in mode: DescribeMode) throws { let desc = DescribedPackage(from: package) let data: Data switch mode { case .json: let encoder = JSONEncoder.makeWithDefaults() encoder.keyEncodingStrategy = .convertToSnakeCase data = try encoder.encode(desc) case .text: var encoder = PlainTextEncoder() encoder.formattingOptions = [.prettyPrinted] data = try encoder.encode(desc) } print(String(decoding: data, as: UTF8.self)) } enum DescribeMode: String, ExpressibleByArgument { /// JSON format (guaranteed to be parsable and stable across time). case json /// Human readable format (not guaranteed to be parsable). case text } } }
apache-2.0
d36a5ad63995f74893cfab485f569033
35.611111
100
0.549317
5.718004
false
false
false
false
tjw/swift
stdlib/public/core/DropWhile.swift
1
8928
//===--- DropWhile.swift - Lazy views for drop(while:) --------*- 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 whose elements consist of the elements that follow the initial /// consecutive elements of some base sequence that satisfy a given predicate. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyDropWhileSequence<Base: Sequence> { public typealias Element = Base.Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable // FIXME(sil-serialize-all) internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } extension LazyDropWhileSequence { /// An iterator over the elements traversed by a base iterator that follow the /// initial consecutive elements that satisfy a given predicate. /// /// This is the associated iterator for the `LazyDropWhileSequence`, /// `LazyDropWhileCollection`, and `LazyDropWhileBidirectionalCollection` /// types. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { public typealias Element = Base.Element @inlinable // FIXME(sil-serialize-all) internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _predicateHasFailed = false @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base.Iterator @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } } extension LazyDropWhileSequence.Iterator: IteratorProtocol { @inlinable // FIXME(sil-serialize-all) public mutating func next() -> Element? { // Once the predicate has failed for the first time, the base iterator // can be used for the rest of the elements. if _predicateHasFailed { return _base.next() } // Retrieve and discard elements from the base iterator until one fails // the predicate. while let nextElement = _base.next() { if !_predicate(nextElement) { _predicateHasFailed = true return nextElement } } return nil } } extension LazyDropWhileSequence: Sequence { public typealias SubSequence = AnySequence<Element> // >:( /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileSequence: LazySequenceProtocol { public typealias Elements = LazyDropWhileSequence } extension LazySequenceProtocol { /// Returns a lazy sequence that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // FIXME(sil-serialize-all) public func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileSequence<Self.Elements> { return LazyDropWhileSequence(_base: self.elements, predicate: predicate) } } /// A lazy wrapper that includes the elements of an underlying /// collection after any initial consecutive elements that satisfy a /// predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, or any methods /// that depend on `startIndex` depends on how many elements satisfy the /// predicate at the start of the collection, and may not offer the usual /// performance given by the `Collection` protocol. Be aware, therefore, /// that general operations on lazy collections may not have the /// documented complexity. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyDropWhileCollection<Base: Collection> { public typealias Element = Base.Element @inlinable // FIXME(sil-serialize-all) internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } extension LazyDropWhileCollection: Sequence { public typealias Iterator = LazyDropWhileSequence<Base>.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileCollection { public typealias SubSequence = Slice<LazyDropWhileCollection<Base>> /// A position in a `LazyDropWhileCollection` or /// `LazyDropWhileBidirectionalCollection` instance. @_fixed_layout // FIXME(sil-serialize-all) public struct Index { /// The position corresponding to `self` in the underlying collection. public let base: Base.Index @inlinable // FIXME(sil-serialize-all) internal init(_base: Base.Index) { self.base = _base } } } extension LazyDropWhileCollection.Index: Equatable, Comparable { @inlinable // FIXME(sil-serialize-all) public static func == ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base == rhs.base } @inlinable // FIXME(sil-serialize-all) public static func < ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base < rhs.base } } extension LazyDropWhileCollection.Index: Hashable where Base.Index: Hashable { @inlinable // FIXME(sil-serialize-all) public var hashValue: Int { return base.hashValue } @inlinable // FIXME(sil-serialize-all) public func _hash(into hasher: inout _Hasher) { hasher.combine(base) } } extension LazyDropWhileCollection: Collection { @inlinable // FIXME(sil-serialize-all) public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && _predicate(_base[index]) { _base.formIndex(after: &index) } return Index(_base: index) } @inlinable // FIXME(sil-serialize-all) public var endIndex: Index { return Index(_base: _base.endIndex) } @inlinable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { _precondition(i.base < _base.endIndex, "Can't advance past endIndex") return Index(_base: _base.index(after: i.base)) } @inlinable // FIXME(sil-serialize-all) public subscript(position: Index) -> Element { return _base[position.base] } } extension LazyDropWhileCollection: LazyCollectionProtocol { } extension LazyDropWhileCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { _precondition(i > startIndex, "Can't move before startIndex") return Index(_base: _base.index(before: i.base)) } } extension LazyCollectionProtocol { /// Returns a lazy collection that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the collection /// as its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // FIXME(sil-serialize-all) public func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileCollection<Self.Elements> { return LazyDropWhileCollection( _base: self.elements, predicate: predicate) } } @available(*, deprecated, renamed: "LazyDropWhileSequence.Iterator") public typealias LazyDropWhileIterator<T> = LazyDropWhileSequence<T>.Iterator where T: Sequence @available(*, deprecated, renamed: "LazyDropWhileCollection.Index") public typealias LazyDropWhileIndex<T> = LazyDropWhileCollection<T>.Index where T: Collection @available(*, deprecated, renamed: "LazyDropWhileCollection") public typealias LazyDropWhileBidirectionalCollection<T> = LazyDropWhileCollection<T> where T: BidirectionalCollection
apache-2.0
d5e491c29bf0ee638f9a94921568db1a
33.471042
118
0.705645
4.338192
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/Calendars/controller/CalendarsEventsViewController.swift
2
4643
// // CalendarsEventsViewController.swift // byuSuite // // Created by Erik Brady on 5/2/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit private let DEFAULT_MONTHS = 3 private let DATE_FORMAT = DateFormatter.defaultDateFormat("YYYY-MM-dd") class CalendarsEventsViewController: ByuSearchViewController, UITableViewDataSource { //MARK: Outlets @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var tableFooter: UIView! @IBOutlet private weak var tableFooterText: UILabel! //MARK: Properties var category: CalendarCategory? var events = [CalendarEvent]() var displayedEvents = [CalendarEvent]() var currentSearchText: String? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = category?.name self.loadEvents(startDate: Date()) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRow() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showEvent", let vc = segue.destination as? CalendarsEventDetailViewController, let sender = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: sender) { vc.event = displayedEvents[indexPath.row] } } //MARK: UITableViewDataSource/Delegate Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return displayedEvents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) let event = displayedEvents[indexPath.row] cell.textLabel?.text = event.title cell.detailTextLabel?.text = event.startTimeString return cell } //MARK: IBActions @IBAction func actionButtonTapped(_ sender: Any) { if let iCalFeed = category?.iCalFeed, let url = URL(string: iCalFeed) { self.displayActionSheet(from: sender, actions: [UIAlertAction(title: "Add Calendar to My Calendar", style: UIAlertActionStyle.default, handler: { (action) in UIApplication.open(url: url) })]) } } //MARK: ByuSearch Methods override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { currentSearchText = searchText filterEvents() } //MARK: Custom Methods private func loadEvents(startDate: Date, months: Int = DEFAULT_MONTHS) { if let categoryId = category?.categoryId, let currentEndDate = Calendar.current.date(byAdding: .month, value: months, to: startDate) { CalendarsClient.getCalendarEvents(categoryId: categoryId, startDate: DATE_FORMAT.string(from: startDate), endDate: DATE_FORMAT.string(from: currentEndDate)) { (events, error) in if let events = events { if (events.count) > 0 { //Sort just the events coming back. Because we know this small back are within a set date range it will not put self.events out of order since we sort by date. //Default to today's date just to prevent crashing but will likely never come back as nil self.events.append(contentsOf: events.sorted { return $0.startTime ?? Date() < $1.startTime ?? Date() }) self.filterEvents() self.tableView.reloadData() self.tableFooterText.text = "Getting More Results..." self.loadEvents(startDate: currentEndDate) } else { if self.events.count == 0 { self.tableFooterText.text = "No Events" } else { self.tableFooter.isHidden = true } } } else { super.displayAlert(error: error) } } } } private func filterEvents() { if let searchText = currentSearchText, !searchText.isEmpty { displayedEvents = events.filter { $0.title?.lowercased().range(of: searchText.lowercased()) != nil } } else { displayedEvents = events } tableView.reloadData() } }
apache-2.0
d093220bffcca1dfe1d4ce6b21e4d24e
35.84127
189
0.599741
5.169265
false
false
false
false
josepvaleriano/iOS-practices
PetCens/PetCens/MasterViewController.swift
1
9268
// // MasterViewController.swift // PetCens // // Created by Jan Zelaznog on 14/10/16. // Copyright © 2016 JanZelaznog. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { self.performSegueWithIdentifier("nuevo", sender: self) /*let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. newManagedObject.setValue(NSDate(), forKey: "fechanacimiento") // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() }*/ } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject self.configureCell(cell, withObject: object) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: UITableViewCell, withObject object: NSManagedObject) { cell.textLabel!.text = object.valueForKey("nombre")!.description } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Responsable", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "fechanacimiento", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, withObject: anObject as! NSManagedObject) case .Move: tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
mit
b08395e029a4afbd31296f14e0d70d69
45.335
360
0.690407
6.232011
false
false
false
false
tjw/swift
test/SILGen/objc_blocks_bridging.swift
1
18601
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_blocks_bridging -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module -enable-sil-ownership %s | %FileCheck %s --check-prefix=GUARANTEED // REQUIRES: objc_interop import Foundation @objc class Foo { // CHECK-LABEL: sil hidden [thunk] @$S20objc_blocks_bridging3FooC3foo_1xS3iXE_SitFTo : // CHECK: bb0([[ARG1:%.*]] : @unowned $@convention(block) @noescape (Int) -> Int, {{.*}}, [[SELF:%.*]] : @unowned $Foo): // CHECK: [[ARG1_COPY:%.*]] = copy_block [[ARG1]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @$SS2iIyByd_S2iIegyd_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG1_COPY]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @$S20objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (Int) -> Int, Int, @guaranteed Foo) -> Int // CHECK: apply [[NATIVE]]([[CONVERT]], {{.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '$S20objc_blocks_bridging3FooC3foo_1xS3iXE_SitFTo' dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int { return f(x) } // CHECK-LABEL: sil hidden [thunk] @$S20objc_blocks_bridging3FooC3bar_1xS3SXE_SStFTo : $@convention(objc_method) (@convention(block) @noescape (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString { // CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : @unowned $NSString, [[SELF:%.*]] : @unowned $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @$SSo8NSStringCABIyBya_S2SIeggo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @$S20objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (@guaranteed String) -> @owned String, @guaranteed String, @guaranteed Foo) -> @owned String // CHECK: apply [[NATIVE]]([[CONVERT]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '$S20objc_blocks_bridging3FooC3bar_1xS3SXE_SStFTo' dynamic func bar(_ f: (String) -> String, x: String) -> String { return f(x) } // GUARANTEED-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSo8NSStringCABIyBya_S2SIeggo_TR : $@convention(thin) (@guaranteed String, @guaranteed @convention(block) @noescape (NSString) -> @autoreleased NSString) -> @owned String { // GUARANTEED: bb0(%0 : @guaranteed $String, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape (NSString) -> @autoreleased NSString): // GUARANTEED: [[BRIDGE:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // GUARANTEED: [[NSSTR:%.*]] = apply [[BRIDGE]](%0) // GUARANTEED: apply [[BLOCK]]([[NSSTR]]) : $@convention(block) @noescape (NSString) -> @autoreleased NSString // GUARANTEED: } // end sil function '$SSo8NSStringCABIyBya_S2SIeggo_TR' // CHECK-LABEL: sil hidden [thunk] @$S20objc_blocks_bridging3FooC3bas_1xSSSgA2FXE_AFtFTo : $@convention(objc_method) (@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> { // CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @$SSo8NSStringCSgACIyBya_SSSgADIeggo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[BRIDGED]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @$S20objc_blocks_bridging3FooC3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@noescape @callee_guaranteed (@guaranteed Optional<String>) -> @owned Optional<String>, @guaranteed Optional<String>, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]]([[CONVERT]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] dynamic func bas(_ f: (String?) -> String?, x: String?) -> String? { return f(x) } // CHECK-LABEL: sil hidden [thunk] @$S20objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}FTo // CHECK: bb0([[F:%.*]] : @trivial $@convention(c) @noescape (Int) -> Int, [[X:%.*]] : @trivial $Int, [[SELF:%.*]] : @unowned $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @$S20objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: apply [[NATIVE]]([[F]], [[X]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] dynamic func cFunctionPointer(_ fp: @convention(c) (Int) -> Int, x: Int) -> Int { _ = fp(x) } // Blocks and C function pointers must not be reabstracted when placed in optionals. // CHECK-LABEL: sil hidden [thunk] @$S20objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}FTo // CHECK: bb0([[ARG0:%.*]] : @unowned $Optional<@convention(block) (NSString) -> @autoreleased NSString>, // CHECK: [[COPY:%.*]] = copy_block [[ARG0]] // CHECK: switch_enum [[COPY]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[BLOCK:%.*]] : @owned $@convention(block) (NSString) -> @autoreleased NSString): // TODO: redundant reabstractions here // CHECK: [[BLOCK_THUNK:%.*]] = function_ref @$SSo8NSStringCABIeyBya_S2SIeggo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [callee_guaranteed] [[BLOCK_THUNK]]([[BLOCK]]) // CHECK: enum $Optional<@callee_guaranteed (@guaranteed String) -> @owned String>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = function_ref @$S20objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Optional<@callee_guaranteed (@guaranteed String) -> @owned String>, @guaranteed String, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]] dynamic func optFunc(_ f: ((String) -> String)?, x: String) -> String? { return f?(x) } // CHECK-LABEL: sil hidden @$S20objc_blocks_bridging3FooC19optCFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: switch_enum %0 // // CHECK: bb2([[FP_BUF:%.*]] : @trivial $@convention(c) (NSString) -> @autoreleased NSString): dynamic func optCFunctionPointer(_ fp: (@convention(c) (String) -> String)?, x: String) -> String? { return fp?(x) } } // => SEMANTIC SIL TODO: This test needs to be filled out more for ownership // // CHECK-LABEL: sil hidden @$S20objc_blocks_bridging10callBlocks{{[_0-9a-zA-Z]*}}F func callBlocks(_ x: Foo, f: @escaping (Int) -> Int, g: @escaping (String) -> String, h: @escaping (String?) -> String? ) -> (Int, String, String?, String?) { // CHECK: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed String) -> @owned String, [[ARG3:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Optional<String>) -> @owned Optional<String>): // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE_COPY]] // CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]] // CHECK: store [[CONVERT]] to [trivial] [[F_BLOCK_CAPTURE]] // CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @$SS2iIgyd_S2iIyByd_TR // CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]] // CHECK: [[F_BLOCK:%.*]] = copy_block [[F_STACK_BLOCK]] // CHECK: [[FOO:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.foo!1.foreign // CHECK: apply [[FOO]]([[F_BLOCK]] // CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @$SS2SIggo_So8NSStringCABIyBya_TR // CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]] // CHECK: [[G_BLOCK:%.*]] = copy_block [[G_STACK_BLOCK]] // CHECK: [[BAR:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.bar!1.foreign // CHECK: apply [[BAR]]([[G_BLOCK]] // CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @$SSSSgAAIggo_So8NSStringCSgADIyBya_TR // CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]] // CHECK: [[H_BLOCK:%.*]] = copy_block [[H_STACK_BLOCK]] // CHECK: [[BAS:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.bas!1.foreign // CHECK: apply [[BAS]]([[H_BLOCK]] // CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: enum $Optional<@convention(block) (NSString) -> @autoreleased NSString>, #Optional.some!enumelt.1, [[G_BLOCK]] return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three")) } class Test: NSObject { func blockTakesBlock() -> ((Int) -> Int) -> Int {} } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SS2iIgyd_SiIegyd_S2iIyByd_SiIeyByd_TR // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] : // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[BLOCK_COPY]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]] // CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CONVERT]]) // CHECK: return [[RESULT]] func clearDraggingItemImageComponentsProvider(_ x: NSDraggingItem) { x.imageComponentsProvider = {} } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSayypGIego_So7NSArrayCSgIeyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @$SSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]] // CHECK: return [[OPTIONAL]] // CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}} // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSSIego_So8NSStringCSgIeyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: return [[OPTIONAL_BRIDGED]] func bridgeNonnullBlockResult() { nonnullStringBlockResult { return "test" } } // CHECK-LABEL: sil hidden @$S20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtF func bridgeNoescapeBlock(fn: () -> (), optFn: (() -> ())?) { // CHECK: [[CLOSURE_FN:%.*]] = function_ref @$S20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtFyyXEfU_ // CHECK: [[CONV_FN:%.*]] = convert_function [[CLOSURE_FN]] // CHECK: [[THICK_FN:%.*]] = thin_to_thick_function [[CONV_FN]] // CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @noescape @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]] // CHECK: store [[THICK_FN]] to [trivial] [[BLOCK_ADDR]] // CHECK: [[THUNK:%.*]] = function_ref @$SIg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}} // FIXME: We're passing the block as a no-escape -- so we don't have to copy it // CHECK: [[BLOCK:%.*]] = copy_block [[BLOCK_STACK]] // CHECK: [[SOME_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.some!enumelt.1, [[BLOCK]] // CHECK: dealloc_stack [[BLOCK_ALLOC]] // CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> () // CHECK: apply [[FN]]([[SOME_BLOCK]]) noescapeBlock { } // CHECK: destroy_value [[SOME_BLOCK]] // CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @noescape @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]] // CHECK: store %0 to [trivial] [[BLOCK_ADDR]] // CHECK: [[THUNK:%.*]] = function_ref @$SIg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}} // FIXME: We're passing the block as a no-escape -- so we don't have to copy it // CHECK: [[BLOCK:%.*]] = copy_block [[BLOCK_STACK]] // CHECK: [[SOME_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.some!enumelt.1, [[BLOCK]] // CHECK: dealloc_stack [[BLOCK_ALLOC]] // CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> () // CHECK: apply [[FN]]([[SOME_BLOCK]]) noescapeBlock(fn) // CHECK: destroy_value [[SOME_BLOCK]] // CHECK: [[NIL_BLOCK:%.*]] = enum $Optional<@convention(block) @noescape () -> ()>, #Optional.none!enumelt // CHECK: [[FN:%.*]] = function_ref @noescapeBlock : $@convention(c) (Optional<@convention(block) @noescape () -> ()>) -> () // CHECK: apply [[FN]]([[NIL_BLOCK]]) noescapeBlock(nil) // CHECK: [[CLOSURE_FN:%.*]] = function_ref @$S20objc_blocks_bridging19bridgeNoescapeBlock2fn5optFnyyyXE_yycSgtF // CHECK: [[CONV_FN:%.*]] = convert_function [[CLOSURE_FN]] // CHECK: [[THICK_FN:%.*]] = thin_to_thick_function [[CONV_FN]] // CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @noescape @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]] // CHECK: store [[THICK_FN]] to [trivial] [[BLOCK_ADDR]] // CHECK: [[THUNK:%.*]] = function_ref @$SIg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}} // FIXME: We're passing the block as a no-escape -- so we don't have to copy it // CHECK: [[BLOCK:%.*]] = copy_block [[BLOCK_STACK]] // CHECK: [[FN:%.*]] = function_ref @noescapeNonnullBlock : $@convention(c) (@convention(block) @noescape () -> ()) -> () // CHECK: apply [[FN]]([[BLOCK]]) noescapeNonnullBlock { } // CHECK: destroy_value [[BLOCK]] // CHECK: [[BLOCK_ALLOC:%.*]] = alloc_stack $@block_storage @noescape @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK_ALLOC]] // CHECK: store %0 to [trivial] [[BLOCK_ADDR]] // CHECK: [[THUNK:%.*]] = function_ref @$SIg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_STACK:%.*]] = init_block_storage_header [[BLOCK_ALLOC]] : {{.*}}, invoke [[THUNK]] : {{.*}} // FIXME: We're passing the block as a no-escape -- so we don't have to copy it // CHECK: [[BLOCK:%.*]] = copy_block [[BLOCK_STACK]] // CHECK: [[FN:%.*]] = function_ref @noescapeNonnullBlock : $@convention(c) (@convention(block) @noescape () -> ()) -> () // CHECK: apply [[FN]]([[BLOCK]]) noescapeNonnullBlock(fn) noescapeBlock(optFn) noescapeBlockAlias { } noescapeBlockAlias(fn) noescapeBlockAlias(nil) noescapeNonnullBlockAlias { } noescapeNonnullBlockAlias(fn) } public func bridgeNoescapeBlock( optFn: ((String?) -> ())?, optFn2: ((String?) -> ())?) { noescapeBlock3(optFn, optFn2, "Foobar") } @_silgen_name("_returnOptionalEscape") public func returnOptionalEscape() -> (() ->())? public func bridgeNoescapeBlock() { noescapeBlock(returnOptionalEscape()) } class ObjCClass : NSObject {} extension ObjCClass { func someDynamicMethod(closure: (() -> ()) -> ()) {} } struct GenericStruct<T> { let closure: (() -> ()) -> () func doStuff(o: ObjCClass) { o.someDynamicMethod(closure: closure) } } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SIg_Igy_IyB_IyBy_TR : $@convention(c) (@inout_aliasable @block_storage @noescape @callee_guaranteed (@noescape @callee_guaranteed () -> ()) -> (), @convention(block) @noescape () -> ()) -> () { // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SIyB_Ieg_TR : $@convention(thin) (@guaranteed @convention(block) @noescape () -> ()) -> () // rdar://35402696 func takeOptStringFunction(fn: (String) -> String?) {} func testGlobalBlock() { takeOptStringFunction(fn: GlobalBlock) } // CHECK-LABEL: sil hidden @$S20objc_blocks_bridging15testGlobalBlockyyF // CHECK: global_addr @GlobalBlock : $*@convention(block) (NSString) -> @autoreleased Optional<NSString> // CHECK: function_ref @$SSo8NSStringCABSgIeyBya_S2SIeggo_TR : $@convention(thin) (@guaranteed String, @guaranteed @convention(block) (NSString) -> @autoreleased Optional<NSString>) -> @owned String
apache-2.0
8d4a1253041b5876f4c006201261bcf6
63.141379
302
0.620612
3.503673
false
false
false
false
tjw/swift
test/IDE/complete_member_decls_from_parent_decl_context.swift
2
37888
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_INSTANCE_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_INSTANCE_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_STATIC_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_CLASS_STATIC_METHOD_1_NEGATIVE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=IN_CLASS_CONSTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLASS_DESTRUCTOR_1 | %FileCheck %s -check-prefix=IN_CLASS_DESTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_INSTANCE_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_INSTANCE_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_STATIC_METHOD_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_STATIC_METHOD_1 | %FileCheck %s -check-prefix=IN_STRUCT_STATIC_METHOD_1_NEGATIVE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_STRUCT_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=IN_STRUCT_CONSTRUCTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_A_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_A_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_B_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_B_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_2 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_3 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_4 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_C_5 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_C_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_D_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_D_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NESTED_NOMINAL_DECL_E_1 | %FileCheck %s -check-prefix=NESTED_NOMINAL_DECL_E_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SR627_SUBCLASS | %FileCheck %s -check-prefix=SR627_SUBCLASS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SR627_SUB_SUBCLASS | %FileCheck %s -check-prefix=SR627_SUB_SUBCLASS //===--- //===--- Test that we can code complete in methods, and correctly distinguish //===--- static and non-static contexts. //===--- class CodeCompletionInClassMethods1 { /// @{ Members. /// Warning: there are negative tests about code completion of instance /// members of this class. Read the tests below before adding, removing or /// modifying members. var instanceVar: Int func instanceFunc0() {} func instanceFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedStruct {} class NestedClass {} enum NestedEnum {} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int class var staticVar: Int class func staticFunc0() {} class func staticFunc1(_ a: Int) {} /// @} Members. /// @{ Tests. func instanceTest1() { #^IN_CLASS_INSTANCE_METHOD_1^# // IN_CLASS_INSTANCE_METHOD_1: Begin completions // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInClassMethods1.NestedStruct#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInClassMethods1.NestedClass#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInClassMethods1.NestedEnum#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_INSTANCE_METHOD_1: End completions } class func staticTest1() { #^IN_CLASS_STATIC_METHOD_1^# // Negative tests. // IN_CLASS_STATIC_METHOD_1_NEGATIVE-NOT: instanceVar // // Positive tests. // IN_CLASS_STATIC_METHOD_1: Begin completions // IN_CLASS_STATIC_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1.Type#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#self: CodeCompletionInClassMethods1#})[#() -> Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#self: CodeCompletionInClassMethods1#})[#(Int) -> Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInClassMethods1.NestedStruct#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInClassMethods1.NestedClass#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInClassMethods1.NestedEnum#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_STATIC_METHOD_1: End completions } init() { #^IN_CLASS_CONSTRUCTOR_1^# // IN_CLASS_CONSTRUCTOR_1: Begin completions // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInClassMethods1.NestedStruct#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInClassMethods1.NestedClass#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInClassMethods1.NestedEnum#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_CONSTRUCTOR_1: End completions } deinit { #^IN_CLASS_DESTRUCTOR_1^# // IN_CLASS_DESTRUCTOR_1: Begin completions // IN_CLASS_DESTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInClassMethods1#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInClassMethods1.NestedStruct#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInClassMethods1.NestedClass#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInClassMethods1.NestedEnum#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_CLASS_DESTRUCTOR_1: End completions } /// @} } struct CodeCompletionInStructMethods1 { /// @{ Members. /// Warning: there are negative tests about code completion of instance /// members of this struct. Read the tests below before adding, removing or /// modifying members. var instanceVar: Int mutating func instanceFunc0() {} mutating func instanceFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedStruct {} class NestedClass {} enum NestedEnum {} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int static var staticVar: Int static func staticFunc0() {} static func staticFunc1(_ a: Int) {} /// @} Members. func instanceTest1() { #^IN_STRUCT_INSTANCE_METHOD_1^# // IN_STRUCT_INSTANCE_METHOD_1: Begin completions // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInStructMethods1.NestedStruct#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInStructMethods1.NestedClass#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInStructMethods1.NestedEnum#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_INSTANCE_METHOD_1: End completions } static func staticTest1() { #^IN_STRUCT_STATIC_METHOD_1^# // Negative tests. // IN_STRUCT_STATIC_METHOD_1_NEGATIVE-NOT: instanceVar // // Positive tests. // IN_STRUCT_STATIC_METHOD_1: Begin completions // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1.Type#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#self: &CodeCompletionInStructMethods1#})[#() -> Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#self: &CodeCompletionInStructMethods1#})[#(Int) -> Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInStructMethods1.NestedStruct#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInStructMethods1.NestedClass#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInStructMethods1.NestedEnum#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1-DAG: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_STATIC_METHOD_1: End completions } init() { #^IN_STRUCT_CONSTRUCTOR_1^# // IN_STRUCT_CONSTRUCTOR_1: Begin completions // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[LocalVar]/Local: self[#CodeCompletionInStructMethods1#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#CodeCompletionInStructMethods1.NestedStruct#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Class]/CurrNominal: NestedClass[#CodeCompletionInStructMethods1.NestedClass#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#CodeCompletionInStructMethods1.NestedEnum#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}} // IN_STRUCT_CONSTRUCTOR_1: End completions } } //===--- //===--- Test that code completion works in non-toplevel nominal type decls. //===--- struct NestedOuter1 { mutating func testInstanceFunc() { struct NestedInnerA { mutating func aTestInstanceFunc() { #^NESTED_NOMINAL_DECL_A_1^# // NESTED_NOMINAL_DECL_A_1: Begin completions // NESTED_NOMINAL_DECL_A_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/CurrNominal: aTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceVar]/CurrNominal: aInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/CurrNominal: aInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/CurrNominal: NestedInnerAStruct[#NestedInnerA.NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Class]/CurrNominal: NestedInnerAClass[#NestedInnerA.NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Enum]/CurrNominal: NestedInnerAEnum[#NestedInnerA.NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_A_1-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceVar]/OutNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_1: End completions } static func aTestStaticFunc() { #^NESTED_NOMINAL_DECL_A_2^# // NESTED_NOMINAL_DECL_A_2: Begin completions // NESTED_NOMINAL_DECL_A_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerA.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/CurrNominal: aTestInstanceFunc({#self: &NestedInnerA#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticMethod]/CurrNominal: aTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/CurrNominal: aInstanceFunc({#self: &NestedInnerA#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticVar]/CurrNominal: aStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[StaticMethod]/CurrNominal: aStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/CurrNominal: NestedInnerAStruct[#NestedInnerA.NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Class]/CurrNominal: NestedInnerAClass[#NestedInnerA.NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Enum]/CurrNominal: NestedInnerAEnum[#NestedInnerA.NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_A_2-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceVar]/OutNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_2: End completions } typealias ATestTypealias = #^NESTED_NOMINAL_DECL_A_3^# // NESTED_NOMINAL_DECL_A_3: Begin completions // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/CurrNominal: NestedInnerAStruct[#NestedInnerA.NestedInnerAStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Class]/CurrNominal: NestedInnerAClass[#NestedInnerA.NestedInnerAClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Enum]/CurrNominal: NestedInnerAEnum[#NestedInnerA.NestedInnerAEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerATypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var aInstanceVar: Int mutating func aInstanceFunc() {} static var aStaticVar: Int = 42 static func aStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerAStruct {} class NestedInnerAClass {} enum NestedInnerAEnum {} typealias NestedInnerATypealias = Int } // end NestedInnerA #^NESTED_NOMINAL_DECL_A_4^# // NESTED_NOMINAL_DECL_A_4: Begin completions // NESTED_NOMINAL_DECL_A_4-DAG: Decl[Struct]/Local: NestedInnerA[#NestedInnerA#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[LocalVar]/Local: self[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceMethod]/CurrNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceVar]/CurrNominal: outerInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[InstanceMethod]/CurrNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[TypeAlias]/CurrNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_4: End completions NestedInnerA(aInstanceVar: 42)#^NESTED_NOMINAL_DECL_A_5^# // NESTED_NOMINAL_DECL_A_5: Begin completions, 4 items // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceMethod]/CurrNominal: .aTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceVar]/CurrNominal: .aInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[InstanceMethod]/CurrNominal: .aInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_A_5-NEXT: End completions } static func testStaticFunc() { struct NestedInnerB { mutating func bTestInstanceFunc() { #^NESTED_NOMINAL_DECL_B_1^# // NESTED_NOMINAL_DECL_B_1: Begin completions // NESTED_NOMINAL_DECL_B_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/CurrNominal: bTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceVar]/CurrNominal: bInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/CurrNominal: bInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/CurrNominal: NestedInnerBStruct[#NestedInnerB.NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Class]/CurrNominal: NestedInnerBClass[#NestedInnerB.NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Enum]/CurrNominal: NestedInnerBEnum[#NestedInnerB.NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_B_1-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticMethod]/OutNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticVar]/OutNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[StaticMethod]/OutNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_1: End completions } static func bTestStaticFunc() { #^NESTED_NOMINAL_DECL_B_2^# // NESTED_NOMINAL_DECL_B_2: Begin completions // NESTED_NOMINAL_DECL_B_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerB.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/CurrNominal: bTestInstanceFunc({#self: &NestedInnerB#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/CurrNominal: bTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/CurrNominal: bInstanceFunc({#self: &NestedInnerB#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticVar]/CurrNominal: bStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/CurrNominal: bStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/CurrNominal: NestedInnerBStruct[#NestedInnerB.NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Class]/CurrNominal: NestedInnerBClass[#NestedInnerB.NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Enum]/CurrNominal: NestedInnerBEnum[#NestedInnerB.NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // FIXME: the following decls are wrong. // NESTED_NOMINAL_DECL_B_2-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/OutNominal: testInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/OutNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[InstanceMethod]/OutNominal: outerInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticVar]/OutNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[StaticMethod]/OutNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_2: End completions } typealias BTestTypealias = #^NESTED_NOMINAL_DECL_B_3^# // NESTED_NOMINAL_DECL_B_3: Begin completions // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/CurrNominal: NestedInnerBStruct[#NestedInnerB.NestedInnerBStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Class]/CurrNominal: NestedInnerBClass[#NestedInnerB.NestedInnerBClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Enum]/CurrNominal: NestedInnerBEnum[#NestedInnerB.NestedInnerBEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerBTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[TypeAlias]/OutNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var bInstanceVar: Int mutating func bInstanceFunc() {} static var bStaticVar: Int = 17 static func bStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerBStruct {} class NestedInnerBClass {} enum NestedInnerBEnum {} typealias NestedInnerBTypealias = Int } // end NestedInnerB #^NESTED_NOMINAL_DECL_B_4^# // NESTED_NOMINAL_DECL_B_4: Begin completions // NESTED_NOMINAL_DECL_B_4-DAG: Decl[Struct]/Local: NestedInnerB[#NestedInnerB#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[LocalVar]/Local: self[#NestedOuter1.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[InstanceMethod]/CurrNominal: testInstanceFunc({#self: &NestedOuter1#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticMethod]/CurrNominal: testStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[InstanceMethod]/CurrNominal: outerInstanceFunc({#self: &NestedOuter1#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticVar]/CurrNominal: outerStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[StaticMethod]/CurrNominal: outerStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[TypeAlias]/CurrNominal: OuterTypealias[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_4: End completions NestedInnerB(bInstanceVar: 42)#^NESTED_NOMINAL_DECL_B_5^# // NESTED_NOMINAL_DECL_B_5: Begin completions, 4 items // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceMethod]/CurrNominal: .bTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceVar]/CurrNominal: .bInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[InstanceMethod]/CurrNominal: .bInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5-DAG: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_B_5: End completions } var outerInstanceVar: Int mutating func outerInstanceFunc() {} static var outerStaticVar: Int = 1 static func outerStaticFunc() {} typealias OuterTypealias = Int } func testOuterC() { struct NestedInnerC { mutating func cTestInstanceFunc() { #^NESTED_NOMINAL_DECL_C_1^# // NESTED_NOMINAL_DECL_C_1: Begin completions // NESTED_NOMINAL_DECL_C_1-DAG: Decl[LocalVar]/Local: self[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceMethod]/CurrNominal: cTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceVar]/CurrNominal: cInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[InstanceMethod]/CurrNominal: cInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/CurrNominal: NestedInnerCStruct[#NestedInnerC.NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Class]/CurrNominal: NestedInnerCClass[#NestedInnerC.NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Enum]/CurrNominal: NestedInnerCEnum[#NestedInnerC.NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_1: End completions } static func cTestStaticFunc() { #^NESTED_NOMINAL_DECL_C_2^# // NESTED_NOMINAL_DECL_C_2: Begin completions // NESTED_NOMINAL_DECL_C_2-DAG: Decl[LocalVar]/Local: self[#NestedInnerC.Type#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[InstanceMethod]/CurrNominal: cTestInstanceFunc({#self: &NestedInnerC#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticMethod]/CurrNominal: cTestStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[InstanceMethod]/CurrNominal: cInstanceFunc({#self: &NestedInnerC#})[#() -> Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticVar]/CurrNominal: cStaticVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[StaticMethod]/CurrNominal: cStaticFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/CurrNominal: NestedInnerCStruct[#NestedInnerC.NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Class]/CurrNominal: NestedInnerCClass[#NestedInnerC.NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Enum]/CurrNominal: NestedInnerCEnum[#NestedInnerC.NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2-DAG: Decl[Struct]/CurrModule: NestedOuter1[#NestedOuter1#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_2: End completions } typealias CTestTypealias = #^NESTED_NOMINAL_DECL_C_3^# // NESTED_NOMINAL_DECL_C_3: Begin completions // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Struct]/CurrNominal: NestedInnerCStruct[#NestedInnerC.NestedInnerCStruct#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Class]/CurrNominal: NestedInnerCClass[#NestedInnerC.NestedInnerCClass#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Enum]/CurrNominal: NestedInnerCEnum[#NestedInnerC.NestedInnerCEnum#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3-DAG: Decl[TypeAlias]/CurrNominal: NestedInnerCTypealias[#Int#]{{; name=.+$}} // FIXME: should this really come as Local? // NESTED_NOMINAL_DECL_C_3-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_3: End completions // Put these decls after code completion points to ensure that delayed // parsing works. var cInstanceVar: Int mutating func cInstanceFunc() {} static var cStaticVar: Int = 1 static func cStaticFunc() {} subscript(i: Int) -> Double { get { return Double(i) } set(v) { instanceVar = i } } struct NestedInnerCStruct {} class NestedInnerCClass {} enum NestedInnerCEnum {} typealias NestedInnerCTypealias = Int } // end NestedInnerC #^NESTED_NOMINAL_DECL_C_4^# // NESTED_NOMINAL_DECL_C_4: Begin completions // NESTED_NOMINAL_DECL_C_4-DAG: Decl[Struct]/Local: NestedInnerC[#NestedInnerC#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_4: End completions NestedInnerC(cInstanceVar: 42)#^NESTED_NOMINAL_DECL_C_5^# // NESTED_NOMINAL_DECL_C_5: Begin completions, 4 items // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceMethod]/CurrNominal: .cTestInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceVar]/CurrNominal: .cInstanceVar[#Int#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[InstanceMethod]/CurrNominal: .cInstanceFunc()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}} // NESTED_NOMINAL_DECL_C_5-NEXT: End completions } func testOuterD() { func dFunc1() {} func foo() { func dFunc2() {} struct Nested1 { struct Nested2 { func bar() { func dFunc4() {} #^NESTED_NOMINAL_DECL_D_1^# } func dFunc3() {} } func dFunc2() {} } } } // NESTED_NOMINAL_DECL_D_1: Begin completions // NESTED_NOMINAL_DECL_D_1-DAG: Decl[LocalVar]/Local: self[#Nested1.Nested2#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc4()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[InstanceMethod]/CurrNominal: dFunc3()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1-DAG: Decl[FreeFunction]/Local: dFunc1()[#Void#]{{; name=.+$}} // NESTED_NOMINAL_DECL_D_1: End completions func testOuterE() { var c1 = { func dFunc1() {} var c2 = { func dFunc2() {} struct Nested1 { struct Nested2 { func bar() { func dFunc4() {} var c3 = { func dFunc5() {} #^NESTED_NOMINAL_DECL_E_1^# } } func dFunc3() {} } func dFunc2() {} } } // end c2 } // end c1 } // NESTED_NOMINAL_DECL_E_1: Begin completions // NESTED_NOMINAL_DECL_E_1-DAG: Decl[LocalVar]/Local: self[#Nested1.Nested2#]{{; name=.+$}} // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc5()[#Void#]; name=dFunc5() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc4()[#Void#]; name=dFunc4() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[InstanceMethod]/OutNominal: dFunc3()[#Void#]; name=dFunc3() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[InstanceMethod]/OutNominal: dFunc2()[#Void#]; name=dFunc2() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc2()[#Void#]; name=dFunc2() // NESTED_NOMINAL_DECL_E_1-DAG: Decl[FreeFunction]/Local: dFunc1()[#Void#]; name=dFunc1() // NESTED_NOMINAL_DECL_E_1: End completions class SR627_BaseClass<T> { func myFunction(_ x: T) -> T? { return nil } } class SR627_Subclass: SR627_BaseClass<String> { #^SR627_SUBCLASS^# // SR627_SUBCLASS: Begin completions // SR627_SUBCLASS-DAG: Decl[InstanceMethod]/Super: override func myFunction(_ x: String) -> String? {|}; name=myFunction(_ x: String) -> String? // SR627_SUBCLASS: End completions } class SR627_SubSubclass: SR627_Subclass { #^SR627_SUB_SUBCLASS^# // SR627_SUB_SUBCLASS: Begin completions // SR627_SUB_SUBCLASS-DAG: Decl[InstanceMethod]/Super: override func myFunction(_ x: String) -> String? {|}; name=myFunction(_ x: String) -> String? // SR627_SUB_SUBCLASS: End completions }
apache-2.0
93d02e0081bd56b3de9354632830a1c1
61.213465
181
0.676388
3.773329
false
true
false
false
SwiftStudies/OysterKit
Sources/OysterKit/Parser/Grammar.swift
1
5394
// Copyright (c) 2016, RED When Excited // 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. // // 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 Foundation /// Depricated, use `Grammar` @available(*,deprecated,message: "Parser has been depricated the rules used at initialization can be directly used as a Grammar. e.g. let parser = Parser(grammar:rules) becomes let parser = rules") public typealias Parser = Grammar /// Depricated, use `Grammar` @available(*,deprecated,message: "Replace with Grammar and use the rules property of Grammar instead of a grammar property of Language") public typealias Language = Grammar /** A language stores a set of grammar rules that can be used to parse `String`s. Extensions provide additional methods (such as parsing) that operate on these rules. */ public protocol Grammar{ /// The rules in the `Language`'s grammar var rules : [Rule] {get} } /// Extensions to an array where the elements are `Rule`s extension Array : Grammar where Element == Rule { public var rules: [Rule] { return self } } public extension Grammar { /** Creates an iterable stream of tokens using the supplied source and this `Grammar` It is very easy to create and iterate through a stream, for example: let source = "12+3+10" for token in try calculationGrammar.stream(source){ // Do something cool... } Streams are the easiest way to use a `Grammar`, and consume less memory and are in general faster (they certainly will never be slower). However you cannot easily navigate and reason about the stream, and only top level rules and tokens will be created. - Parameter source: The source to parse - Returns: An iterable stream of tokens **/ public func tokenize(_ source:String)->TokenStream{ return TokenStream(source, using: self) } /** Creates a `HomogenousTree` using the supplied grammar. A `HomogenousTree` captures the result of parsing hierarchically making it easy to manipulate the resultant data-structure. It is also possible to get more information about any parsing errors. For example: let source = "12+3+10" do { // Build the HomogenousTree let ast = try calculationGrammar.parse(source) // Prints the parsing tree print(ast) } catch let error as ProcessingError { print(error.debugDescription) } - Parameter source: The source to parse with the `Grammar` - Returns: A `HomogenousTree` **/ public func parse(_ source:String) throws ->HomogenousTree{ return try AbstractSyntaxTreeConstructor(with: source).build(using: self) } /** Builds the supplied source into a Heterogeneous representation (any Swift `Decodable` type). This is the most powerful application of a `Grammar` and leverages Swift's `Decoable` protocol. It is strongly recommended that you [read a little about that first](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types). Essentially each token in the grammar will be mapped to a `CodingKey`. You should first parse into a `HomogenousTree` to make sure your types and the hierarchy generated from your grammar align. If you want to automatically generate the `Decodable` types you can do this using [STLR](https://github.com/SwiftStudies/OysterKit/blob/master/Documentation/STLR.md) and [`stlrc`](https://github.com/SwiftStudies/OysterKit/blob/master/Documentation/stlr-toolc.md) which will automatically synthesize your grammar and data-structures in Swift. - Parameter source: The source to compile - Parameter type: The `Decodable` type that should be created - Returns: The populated type **/ public func build<T : Decodable>(_ source:String,as type: T.Type) throws -> T{ return try ParsingDecoder().decode(T.self, using: parse(source)) } }
bsd-2-clause
a6979a5230c29fd8d186102396666f65
44.327731
197
0.702633
4.610256
false
false
false
false
rdhiggins/PythonMacros
PythonMacros/DailyProgress.swift
1
4455
// // DailyProgress.swift // PythonMacros // // Created by Rodger Higgins on 7/5/16. // Copyright © 2016 Rodger Higgins. All rights reserved. // import Foundation /// Class used to store the global progress model used for this tutorial. The /// daily progress is represented as three properties off of the singleton. /// /// This class also register 6 swift blocks into the CPython runtime. These /// python functions are used by python scripts to retrieve/set each of the /// three progress values. /// /// This class also supports a delegate for getting notification of /// any progress changes. class DailyProgress { /// Class property used to retrieve the singleton object static var sharedInstance: DailyProgress = DailyProgress() fileprivate var engine: PythonMacroEngine = PythonMacroEngine.sharedInstance fileprivate var functions: [PythonFunction] = [] /// Property containing the current value for the daily active calories var activeCalories: Double = 0.0 { didSet { delegate?.activeCalorieUpdate(activeCalories) } } /// Property containing the current value for the daily active minutes var activity: Double = 0.0 { didSet { delegate?.activityUpdate(activity) } } /// Property containing the current number of standup hours var standup: Double = 0.0 { didSet { delegate?.standupUpdate(standup) } } /// Property used to register delegate var delegate: DailyProgressDelegate? init() { setupPythonCallbacks() } /// A private method used to register the swift blocks with the /// PythonMacroEngine. fileprivate func setupPythonCallbacks() { functions.append( PythonFunction(name: "getActiveCalories", callArgs: [], returnType: .Double, block: { Void -> AnyObject? in return self.activeCalories as AnyObject! })) _ = engine.callable?.registerFunction(functions.last!) functions.append( PythonFunction(name: "setActiveCalories", callArgs: [.Double], returnType: .Void, block: { (args) -> AnyObject? in guard let newValue = args?[0] as? Double else { return nil } self.activeCalories = newValue return nil })) _ = engine.callable?.registerFunction(functions.last!) functions.append( PythonFunction(name: "getActivity", callArgs: [], returnType: .Double, block: { Void -> AnyObject? in return self.activity as AnyObject! })) _ = engine.callable?.registerFunction(functions.last!) functions.append( PythonFunction(name: "setActivity", callArgs: [.Double], returnType: .Void, block: { (args) -> AnyObject? in guard let newValue = args?[0] as? Double else { return nil } self.activity = newValue return nil })) _ = engine.callable?.registerFunction(functions.last!) functions.append( PythonFunction(name: "getStandup", callArgs: [], returnType: .Double, block: { Void -> AnyObject? in return self.standup as AnyObject! })) _ = engine.callable?.registerFunction(functions.last!) functions.append( PythonFunction(name: "setStandup", callArgs: [.Double], returnType: .Void, block: { (args) -> AnyObject? in guard let newValue = args?[0] as? Double else { return nil } self.standup = newValue return nil })) _ = engine.callable?.registerFunction(functions.last!) } } protocol DailyProgressDelegate { func activeCalorieUpdate(_ newValue: Double) func activityUpdate(_ newValue: Double) func standupUpdate(_ newValue: Double) }
mit
931b6ab68ffd8b202a88ec734c9ba928
26.493827
80
0.547598
5.283511
false
false
false
false
xedin/swift
test/SILGen/vtable_thunks.swift
1
13094
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s protocol AddrOnly {} func callMethodsOnD<U>(d: D, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } func callMethodsOnF<U>(d: F, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } @objc class B { // We only allow B! -> B overrides for @objc methods. // The IUO force-unwrap requires a thunk. @objc func iuo(x: B, y: B!, z: B) -> B? {} // f* don't require thunks, since the parameters and returns are object // references. func f(x: B, y: B) -> B? {} func f2(x: B, y: B) -> B? {} func f3(x: B, y: B) -> B {} func f4(x: B, y: B) -> B {} // Thunking monomorphic address-only params and returns func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {} func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} // Thunking polymorphic address-only params and returns func h<T>(x: T, y: T) -> T? {} func h2<T>(x: T, y: T) -> T? {} func h3<T>(x: T, y: T) -> T {} func h4<T>(x: T, y: T) -> T {} // Thunking value params and returns func i(x: Int, y: Int) -> Int? {} func i2(x: Int, y: Int) -> Int? {} func i3(x: Int, y: Int) -> Int {} func i4(x: Int, y: Int) -> Int {} // Note: i3, i4 are implicitly @objc } class D: B { override func iuo(x: B?, y: B, z: B) -> B {} override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // Inherits the thunked impls from D class E: D { } // Overrides w/ its own thunked impls class F: D { override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // This test is incorrect in semantic SIL today. But it will be fixed in // forthcoming commits. // // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks1DC3iuo{{[_0-9a-zA-Z]*}}FTV // CHECK: bb0([[X:%.*]] : @guaranteed $B, [[Y:%.*]] : @guaranteed $Optional<B>, [[Z:%.*]] : @guaranteed $B, [[W:%.*]] : @guaranteed $D): // CHECK: [[WRAP_X:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[X]] : $B // CHECK: [[Y_COPY:%.*]] = copy_value [[Y]] // CHECK: switch_enum [[Y_COPY]] : $Optional<B>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[NONE_BB]]: // CHECK: [[DIAGNOSE_UNREACHABLE_FUNC:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{.*}} // CHECK: apply [[DIAGNOSE_UNREACHABLE_FUNC]] // CHECK: unreachable // CHECK: [[SOME_BB]]([[UNWRAP_Y:%.*]] : @owned $B): // CHECK: [[BORROWED_UNWRAP_Y:%.*]] = begin_borrow [[UNWRAP_Y]] // CHECK: [[THUNK_FUNC:%.*]] = function_ref @$s13vtable_thunks1DC3iuo{{.*}} // CHECK: [[RES:%.*]] = apply [[THUNK_FUNC]]([[WRAP_X]], [[BORROWED_UNWRAP_Y]], [[Z]], [[W]]) // CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]] // CHECK: return [[WRAP_RES]] // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks1DC1g{{[_0-9a-zA-Z]*}}FTV // TODO: extra copies here // CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] : // CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]] // CHECK: inject_enum_addr [[WRAP_X_ADDR]] // CHECK: [[RES_ADDR:%.*]] = alloc_stack // CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3) // CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0 // CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]] // CHECK: inject_enum_addr %0 class ThrowVariance { func mightThrow() throws {} } class NoThrowVariance: ThrowVariance { override func mightThrow() {} } // rdar://problem/20657811 class X<T: B> { func foo(x: T) { } } class Y: X<D> { override func foo(x: D) { } } // rdar://problem/21154055 // Ensure reabstraction happens when necessary to get a value in or out of an // optional. class Foo { func foo(x: @escaping (Int) -> Int) -> ((Int) -> Int)? {} } class Bar: Foo { override func foo(x: ((Int) -> Int)?) -> (Int) -> Int {} } // rdar://problem/21364764 // Ensure we can override an optional with an IUO or vice-versa. struct S {} class Aap { func cat(b: B?) -> B? {} func dog(b: B!) -> B! {} func catFast(s: S?) -> S? {} func dogFast(s: S!) -> S! {} func flip() -> (() -> S?) {} func map() -> (S) -> () -> Aap? {} } class Noot : Aap { override func cat(b: B!) -> B! {} override func dog(b: B?) -> B? {} override func catFast(s: S!) -> S! {} override func dogFast(s: S?) -> S? {} override func flip() -> (() -> S) {} override func map() -> (S?) -> () -> Noot {} } // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}FTV : $@convention(method) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed Bar) -> @owned Optional<@callee_guaranteed (Int) -> Int> // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}F // CHECK: apply [[IMPL]] // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVIegd_ACSgIegd_TR // CHECK: [[INNER:%.*]] = apply %0() // CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, [[INNER]] : $S // CHECK: return [[OUTER]] : $Optional<S> // CHECK-LABEL: sil private [ossa] @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @$s13vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[OUTER:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s13vtable_thunks1SVSgAA4NootCIego_Iegyo_AcA3AapCSgIego_Iegyo_TR // CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %0 // CHECK: [[INNER:%.*]] = apply %1([[ARG]]) // CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_guaranteed () -> @owned Noot to $@callee_guaranteed () -> @owned Optional<Aap> // CHECK: return [[OUTER]] // CHECK-LABEL: sil_vtable D { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable E { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable F { // CHECK: #B.iuo!1: {{.*}} : @$s13vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : @$s13vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable NoThrowVariance { // CHECK: #ThrowVariance.mightThrow!1: {{.*}} : @$s13vtable_thunks{{[A-Z0-9a-z_]*}}F
apache-2.0
1140759dfe2cc4d8eedaac6e5309cc85
41.375405
220
0.520467
2.515658
false
false
false
false
mnespor/AzureNotificationHubClient
Pod/Classes/HubHelper.swift
1
2193
// // HubHelper.swift // Pods // // Created by Matthew Nespor on 4/9/16. // // import Foundation internal class HubHelper { internal static func url(url: NSURL, withScheme scheme: String) -> NSURL? { var urlString = url.absoluteString if !urlString.hasSuffix("/") { urlString = "\(urlString)/" } if let indexOfColon = urlString.rangeOfString(":")?.startIndex { urlString = "\(scheme)\(urlString.substringFromIndex(indexOfColon))" } else { urlString = "\(scheme)://\(urlString)" } return NSURL(string: urlString) } internal static func parseConnectionString(connectionString: String) -> [String: String] { let validFieldPrefixes = ["endpoint==", "sharedaccesskeyname=", "sharedaccesskey=", "sharedsecretissuer=", "sharedsecretvalue=", "stsendpoint="] var connectionDictionary: [String: String] = [:] let fields = connectionString.componentsSeparatedByString(";") var previousLeft = "" for i in 0..<fields.count { if (i+1) < fields.count { if validFieldPrefixes.indexOf({ prefix -> Bool in return fields[i].hasPrefix(prefix) }) == nil { previousLeft = "\(previousLeft)\(fields[i])" continue } } let currentField = "\(previousLeft)\(fields[i])" previousLeft = "" let keyValuePairs = currentField.componentsSeparatedByString("=") guard keyValuePairs.count >= 2 else { break } let keyName = keyValuePairs[0].lowercaseString var keyValue = keyValuePairs[1] if keyName == "endpoint" { keyValue = HubHelper.url(NSURL(string: keyValue)!, withScheme: "https")?.absoluteString ?? "" } connectionDictionary[keyName] = keyValue } return connectionDictionary } }
apache-2.0
b966d56ca48b47aae2d691e3ba6016c5
32.738462
94
0.5171
5.468828
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Workspace/XCWorkspace.swift
1
2110
import Foundation import PathKit /// Model that represents a Xcode workspace. public final class XCWorkspace: Writable, Equatable { /// Workspace data public var data: XCWorkspaceData // MARK: - Init /// Initializes the workspace with the path where the workspace is. /// The initializer will try to find an .xcworkspacedata inside the workspace. /// If the .xcworkspacedata cannot be found, the init will fail. /// /// - Parameter path: .xcworkspace path. /// - Throws: throws an error if the workspace cannot be initialized. public convenience init(path: Path) throws { if !path.exists { throw XCWorkspaceError.notFound(path: path) } let xcworkspaceDataPaths = path.glob("*.xcworkspacedata") if xcworkspaceDataPaths.isEmpty { self.init() } else { try self.init(data: XCWorkspaceData(path: xcworkspaceDataPaths.first!)) } } /// Initializes a default workspace with a single reference that points to self: public convenience init() { let data = XCWorkspaceData(children: [.file(.init(location: .self("")))]) self.init(data: data) } /// Initializes the workspace with the path string. /// /// - Parameter pathString: path string. /// - Throws: throws an error if the initialization fails. public convenience init(pathString: String) throws { try self.init(path: Path(pathString)) } /// Initializes the workspace with its properties. /// /// - Parameters: /// - data: workspace data. public init(data: XCWorkspaceData) { self.data = data } // MARK: - Writable public func write(path: Path, override: Bool = true) throws { let dataPath = path + "contents.xcworkspacedata" if override, dataPath.exists { try dataPath.delete() } try dataPath.mkpath() try data.write(path: dataPath) } // MARK: - Equatable public static func == (lhs: XCWorkspace, rhs: XCWorkspace) -> Bool { lhs.data == rhs.data } }
mit
a1032a62218b300e82b49bc02f149982
30.492537
84
0.627488
4.489362
false
false
false
false
swift-lang/swift-k
bgq-swift/simanalyze/part05/p5.swift
1
943
type file; app (file out, file log) simulation (int sim_steps, int sim_range, int sim_values) { bgsh "/home/ketan/SwiftApps/subjobs/simanalyze/app/simulate" "--timesteps" sim_steps "--range" sim_range "--nvalues" sim_values stdout=@out stderr=@log; } app (file out, file log) analyze (file s[]) { bgsh "/home/ketan/SwiftApps/subjobs/simanalyze/app/stats" filenames(s) stdout=@out stderr=@log; } int nsim = toInt(arg("nsim", "10")); int steps = toInt(arg("steps", "1")); int range = toInt(arg("range", "100")); int values = toInt(arg("values", "5")); file sims[]; foreach i in [0:nsim-1] { file simout <single_file_mapper; file=strcat("output/sim_",i,".out")>; file simlog <single_file_mapper; file=strcat("output/sim_",i,".log")>; (simout,simlog) = simulation(steps,range,values); sims[i] = simout; } file stats_out<"output/average.out">; file stats_log<"output/average.log">; (stats_out, stats_log) = analyze(sims);
apache-2.0
abc31dcaf89c21d9c34f923defd62030
31.517241
154
0.670201
2.848943
false
false
true
false
cpageler93/ConsulSwift
Sources/ConsulSwift/ConsulEvent.swift
1
1193
// // ConsulEvent.swift // ConsulSwift // // Created by Christoph Pageler on 19.06.17. // // import Foundation import Quack public extension Consul { public class Event: Quack.Model { public var id: String public var name: String public var payload: String? public var nodeFilter: String public var serviceFilter: String public var tagFilter: String public var version: Int public var lTime: Int public required init?(json: JSON) { guard let id = json["ID"].string, let name = json["Name"].string, let version = json["Version"].int, let lTime = json["LTime"].int else { return nil } self.id = id self.name = name self.payload = json["Payload"].string self.nodeFilter = json["NodeFilter"].string ?? "" self.serviceFilter = json["ServiceFilter"].string ?? "" self.tagFilter = json["TagFilter"].string ?? "" self.version = version self.lTime = lTime } } }
mit
b54f6c2567ee4b11728917a12b570855
24.382979
67
0.517184
4.606178
false
false
false
false
Sherlouk/monzo-vapor
Tests/MonzoTests/ClientTests.swift
1
1524
import XCTest @testable import Monzo class ClientTests: XCTestCase { func testInitialiser() { let client = MonzoClient(publicKey: "public", privateKey: "private", httpClient: MockResponder()) XCTAssertEqual(client.publicKey, "public") XCTAssertEqual(client.privateKey, "private") XCTAssertTrue(client.httpClient is MockResponder) XCTAssertNotNil(client.provider) } func testMonzoSetup() { let _ = MonzoClient(publicKey: "...", privateKey: "...", httpClient: MockResponder()) XCTAssertTrue(Date.incomingDateFormatters.contains(.rfc3339)) } func testMonzoPing() { let responder = MockResponder() let client = MonzoClient(publicKey: "public", privateKey: "private", httpClient: responder) XCTAssertTrue(client.ping()) responder.statusOverride = .tooManyRequests XCTAssertFalse(client.ping()) } func testMonzoPingRequest() { let responder = MockResponder() let client = MonzoClient(publicKey: "public", privateKey: "private", httpClient: responder) let request = try? client.provider.createRequest(.ping) XCTAssertEqual(request?.uri.description, "https://api.monzo.com:443/ping") } static var allTests = [ ("testInitialiser", testInitialiser), ("testMonzoSetup", testMonzoSetup), ("testMonzoPing", testMonzoPing), ("testMonzoPingRequest", testMonzoPingRequest), ] }
mit
51be4ea1b55ef6d90f9cbd0561a0cdda
33.636364
105
0.646325
4.822785
false
true
false
false
AlexHmelevski/AHFuture
Example/Tests/AHFutureTests.swift
1
7816
// // AHFutureTests.swift // AHFuture // // Created by Alex Hmelevski on 2017-05-03. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import AHFuture import ALEither enum TestError: Error { case empty } class AHFutureTests: XCTestCase { var exp: XCTestExpectation! override func setUp() { super.setUp() exp = expectation(description: "AHFutureTests") } func test_onSuccess_called() { var count = 0 AHFuture<Int, TestError>.init { (completion) in completion(.right(value: 1)) }.onSuccess { _ in count += 1 } .onSuccess { _ in count += 1 } .onFailure { _ in XCTFail() } .onSuccess { (_) in count += 1 self.exp.fulfill() }.execute() wait(for: [exp], timeout: 5) XCTAssertEqual(count, 3) } func test_onError_called() { var count = 0 AHFuture<Int, TestError> { (completion) in completion(.wrong(value: .empty)) }.onFailure { _ in count += 1 } .onFailure { _ in count += 1 } .onSuccess { _ in XCTFail() } .onFailure { (_) in count += 1 self.exp.fulfill() }.execute() wait(for: [exp], timeout: 5) XCTAssertEqual(count, 3) } func test_map_called_on_success() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 completion(.right(value: 1)) }.map(transform: String.init) .onSuccess { (str) in XCTAssertEqual(str, "1") }.map(transform: {_ in "secondMap"}) .onSuccess(callback: { (str) in XCTAssertEqual(str, "secondMap") self.exp.fulfill() }) .execute() wait(for: [exp], timeout: 5) XCTAssertEqual(scopeCount, 1) } func test_flatMap_called_on_sucess() { var f1ScopeCount = 0 var f2ScopeCount = 0 let f1 = AHFuture<Int, TestError> { (completion) in f1ScopeCount += 1 completion(.right(value: 1)) } let f2 = AHFuture<String, TestError> { (completion) in f2ScopeCount += 1 completion(.right(value: String(1))) self.exp.fulfill() } f1.flatMap { (Int) -> AHFuture<String, TestError> in return f2 }.execute() wait(for: [exp], timeout: 10) XCTAssertEqual(f1ScopeCount, 1) XCTAssertEqual(f2ScopeCount, 1) } func test_flatMap_with_retry_called_on_sucess() { var f1ScopeCount = 0 var f2ScopeCount = 0 let f1 = AHFuture<Int, TestError> { (completion) in f1ScopeCount += 1 completion(.right(value: 1)) } let f2 = AHFuture<String, TestError> { (completion) in f2ScopeCount += 1 if f2ScopeCount < 3 { completion(.wrong(value: TestError.empty)) } else { completion(.right(value: String(1))) self.exp.fulfill() } } f1.flatMap { (Int) -> AHFuture<String, TestError> in return f2 }.retry(attempt: 3) .execute() wait(for: [exp], timeout: 10) XCTAssertEqual(f1ScopeCount, 3) XCTAssertEqual(f2ScopeCount, 3) } func test_filter_continues() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 completion(.right(value: 1)) }.filter(predicate: { $0 == 1 }) .map(transform: String.init) .onSuccess { (str) in XCTAssertEqual(str, "1") self.exp.fulfill() }.execute() wait(for: [exp], timeout: 5) } func test_filter_doesnt_continue() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 completion(.right(value: 1)) }.filter(predicate: { $0 == 0 }) .map(transform: String.init) .onSuccess { (str) in XCTFail() }.execute() DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 2)) { self.exp.fulfill() } wait(for: [exp], timeout: 5) } func test_filter_map_to_error() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 completion(.right(value: 1)) }.filter(predicate: {$0 == 0}, error: .empty) .map(transform: String.init) .onSuccess { (str) in XCTFail() } .onFailure(callback: { (_) in self.exp.fulfill() }) .execute() wait(for: [exp], timeout: 5) } func test_filter_with_erro_map_returns_success() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 completion(.right(value: 1)) }.filter(predicate: {$0 == 1}, error: .empty) .map(transform: String.init) .onSuccess { (str) in self.exp.fulfill() } .onFailure(callback: { (_) in XCTFail() }) .execute() wait(for: [exp], timeout: 5) } func test_retry_success_after_attempts() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 if scopeCount > 5 { return completion(.right(value: 1)) } else { return completion(.wrong(value: .empty)) } }.retry(attempt: 5) .onSuccess { (str) in self.exp.fulfill() } .onFailure(callback: { (_) in XCTFail() }) .execute() wait(for: [exp], timeout: 5) XCTAssertEqual(scopeCount, 6) } func test_retry_fails_after_not_enough_attempts() { var scopeCount = 0 AHFuture<Int, TestError> { (completion) in scopeCount += 1 if scopeCount > 10 { return completion(.right(value: 1)) } else { return completion(.wrong(value: .empty)) } }.retry(attempt: 5) .onSuccess { (str) in XCTFail() } .onFailure(callback: { (_) in self.exp.fulfill() }) .execute() wait(for: [exp], timeout: 5) XCTAssertEqual(scopeCount, 6) } func test_recover_calls_on_success_for_successFalue() { AHFuture<Int, TestError> { (completion) in completion(.right(value: 1)) } .map(transform: String.init) .recover(transform: {_ in String("RECOVERED")}) .onSuccess { (str) in XCTAssertEqual(str, "1") self.exp.fulfill() }.execute() wait(for: [exp], timeout: 5) } func test_recover_calls_on_success_for_errorFalue() { AHFuture<Int, TestError> { (completion) in completion(.wrong(value: TestError.empty)) } .map(transform: String.init) .recover(transform: {_ in String("RECOVERED")}) .onSuccess { (str) in XCTAssertEqual(str, "RECOVERED") self.exp.fulfill() } .execute() wait(for: [exp], timeout: 5) } }
mit
2b2967a970683cdf79f81063decd0ec9
26.910714
85
0.484069
4.322456
false
true
false
false
canalesb93/MantleModal
MantleDemos/ManualDemo/Mantle/RCMantleViewController.swift
1
10633
// // RCMantleViewController.swift // Mantle // // Created by Ricardo Canales on 11/11/15. // Copyright © 2015 canalesb. All rights reserved. // import UIKit // Declare this protocol outside the class public protocol RCMantleViewDelegate { // This method allows a child to tell the parent view controller // to change to a different child view func dismissView(animated: Bool) } public class RCMantleViewController: UIViewController, RCMantleViewDelegate, UIScrollViewDelegate { public var scrollView: UIScrollView! private var contentView: UIView! // A strong reference to the height contraint of the contentView var contentViewConstraint: NSLayoutConstraint! // ==================== CONFIGURATION VARIABLES - START ==================== // draggable to the top/bottom public var bottomDismissible: Bool = false public var topDismissable: Bool = true private var mainView: Int = 1 // show modal from the top public var appearFromTop: Bool = false public var appearOffset: CGFloat = 0 // draggable to sides configuration variables public var draggableToSides: Bool = false private var draggableWidth: CGFloat = 0 private var draggableMultiplier: CGFloat = 1.0 private var glassScreens: Int = 1 // 1 + 1 // ===================== CONFIGURATION VARIABLES - END ===================== // A computed version of this reference var computedContentViewConstraint: NSLayoutConstraint { let constraint = NSLayoutConstraint(item: contentView, attribute: .height, relatedBy: .equal, toItem: scrollView, attribute: .height, multiplier: CGFloat(controllers.count + glassScreens + 1), constant: 0) return constraint } // The list of controllers currently present in the scrollView var controllers = [UIViewController]() // setup initialization public func setUpScrollView(){ self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext glassScreens = 1 if bottomDismissible && topDismissable { glassScreens = 2 // 2 + 1 mainView = 1 } else if topDismissable { mainView = 1 } else if bottomDismissible { mainView = 0 } else { glassScreens = 0 mainView = 0 } if draggableToSides { draggableWidth = view.frame.width draggableMultiplier = CGFloat(3.0) } createMantleViewController() initScrollView() } override public func viewDidLoad() { super.viewDidLoad() } // Creates the ScrollView and the ContentView (UIView), don't move private func createMantleViewController() { view.backgroundColor = UIColor.clear scrollView = UIScrollView() scrollView.backgroundColor = UIColor.clear view.addSubview(scrollView) let top = NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0) let bottom = NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0) let leading = NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0) let trailing = NSLayoutConstraint(item: scrollView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0) scrollView.translatesAutoresizingMaskIntoConstraints = false contentView = UIView() contentView.backgroundColor = UIColor.clear contentView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(contentView) let ctop = NSLayoutConstraint(item: contentView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0) let cbottom = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 0) let cleading = NSLayoutConstraint(item: contentView, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leading, multiplier: 1.0, constant: 0) let ctrailing = NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: scrollView, attribute: .trailing, multiplier: 1.0, constant: 0) let cwidth = NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .equal, toItem: scrollView, attribute: .width, multiplier: draggableMultiplier, constant: 0) NSLayoutConstraint.activate([top, bottom, leading, trailing, ctop, cbottom, cleading, ctrailing, cwidth]) } func initScrollView(){ scrollView.isHidden = true scrollView.isScrollEnabled = false scrollView.isPagingEnabled = true scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.delegate = self contentView.translatesAutoresizingMaskIntoConstraints = false contentViewConstraint = computedContentViewConstraint view.addConstraint(contentViewConstraint) } override public func viewDidAppear(_ animated: Bool) { accomodateScrollView() scrollView.isHidden = false moveToView(viewNum: mainView) } private func accomodateScrollView(){ var xPos: CGFloat = 0 var yPos: CGFloat = appearOffset if draggableToSides { xPos = self.view.frame.width } if appearFromTop { yPos = self.contentView.frame.height - self.view.frame.height - appearOffset } scrollView.setContentOffset(CGPoint(x: xPos, y: yPos), animated: false) } public func addToScrollViewNewController(controller: UIViewController) { controller.willMove(toParentViewController: self) contentView.addSubview(controller.view) controller.view.translatesAutoresizingMaskIntoConstraints = false let heightConstraint = NSLayoutConstraint(item: controller.view, attribute: .height, relatedBy: .equal, toItem: scrollView, attribute: .height, multiplier: 1.0, constant: 0) let leadingConstraint = NSLayoutConstraint(item: contentView, attribute: .leading, relatedBy: .equal, toItem: controller.view, attribute: .leading, multiplier: 1.0, constant: -draggableWidth) let trailingConstraint = NSLayoutConstraint(item: contentView, attribute: .trailing, relatedBy: .equal, toItem: controller.view, attribute: .trailing, multiplier: 1.0, constant: draggableWidth) // Setting all the constraints var bottomConstraint: NSLayoutConstraint! if controllers.isEmpty { // Since it's the first one, the trailing constraint is from the controller view to the contentView bottomConstraint = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: controller.view, attribute: .bottom, multiplier: 1.0, constant: 0) } else { bottomConstraint = NSLayoutConstraint(item: controllers.last!.view, attribute: .top, relatedBy: .equal, toItem: controller.view, attribute: .bottom, multiplier: 1.0, constant: 0) } if bottomDismissible { bottomConstraint.constant = controller.view.frame.height } // Setting the new width constraint of the contentView view.removeConstraint(contentViewConstraint) contentViewConstraint = computedContentViewConstraint // Adding all the constraints to the view hierarchy view.addConstraint(contentViewConstraint) contentView.addConstraints([bottomConstraint, trailingConstraint, leadingConstraint]) scrollView.addConstraints([heightConstraint]) self.addChildViewController(controller) controller.didMove(toParentViewController: self) // Finally adding the controller in the list of controllers controllers.append(controller) } public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { if(scrollView.contentOffset.y < view.frame.height-20){ scrollView.isScrollEnabled = false } else if scrollView.contentOffset.y > scrollView.frame.height - view.frame.height + 20 { scrollView.isScrollEnabled = false } } // close view or not public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let currentHorizontalPage = floor(scrollView.contentOffset.x / scrollView.bounds.size.width + 0.5); let currentPage = floor(scrollView.contentOffset.y / scrollView.bounds.size.height + 0.5); // let lastPage = floor(contentView.frame.height / scrollView.bounds.size.height - 1); if(draggableToSides && (currentHorizontalPage == 0 || currentHorizontalPage == 2)){ dismissView(animated: false) } if(Int(currentPage) != mainView){ dismissView(animated: false) } else { scrollView.isScrollEnabled = true } } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let currentPage = floor(scrollView.contentOffset.y / scrollView.bounds.size.height + 0.5); if currentPage != CGFloat(mainView) { dismissView(animated: false) } else { scrollView.isScrollEnabled = true } } private func moveToView(viewNum: Int) { // Determine the offset in the scroll view we need to move to scrollView.isScrollEnabled = false let yPos: CGFloat = (self.view.frame.height) * CGFloat(viewNum) self.scrollView.setContentOffset(CGPoint(x: self.scrollView.contentOffset.x , y: yPos), animated: true) } public func dismissView(animated: Bool){ if appearFromTop && animated { moveToView(viewNum: mainView + 1) //self.dismissViewControllerAnimated(false, completion: nil) } else { self.dismiss(animated: animated, completion: nil) } } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7ecab77b17b3c5b8d963c6b1b3dbf1a0
42.044534
213
0.665256
5.237438
false
false
false
false
TENDIGI/LocaleKit
Pod/DictionaryExtensions.swift
1
705
// // DictionaryExtensions.swift // Pods // // Created by Nick Lee on 1/26/16. // // import Foundation // Thanks: http://stackoverflow.com/questions/32929981/how-to-deep-merge-2-swift-dictionaries internal func deepMerge(_ d1: [String : AnyObject], _ d2: [String : AnyObject]) -> [String : AnyObject] { var result = [String : AnyObject]() for (k1, v1) in d1 { result[k1] = v1 } for (k2, v2) in d2 { if v2 is [String : AnyObject], let v1 = result[k2], v1 is [String : AnyObject] { result[k2] = deepMerge(v1 as! [String : AnyObject], v2 as! [String : AnyObject]) as AnyObject? } else { result[k2] = v2 } } return result }
mit
19ed42ac320d70913b8bc3db881c2fe1
27.2
106
0.587234
3.133333
false
false
false
false
OpenKitten/MongoKitten
Sources/_MongoKittenCrypto/Hash.swift
2
2143
public protocol Hash { static var littleEndian: Bool { get } static var chunkSize: Int { get } static var digestSize: Int { get } var processedBytes: UInt64 { get } var hashValue: [UInt8] { get } mutating func reset() mutating func update(from pointer: UnsafePointer<UInt8>) } extension Hash { public mutating func finish(from pointer: UnsafeBufferPointer<UInt8>) -> [UInt8] { // Hash size in _bits_ let hashSize = (UInt64(pointer.count) &+ processedBytes) &* 8 var needed = (pointer.count + 9) let remainder = needed % Self.chunkSize if remainder != 0 { needed = needed - remainder + Self.chunkSize } var data = [UInt8](repeating: 0, count: needed) data.withUnsafeMutableBufferPointer { buffer in buffer.baseAddress!.assign(from: pointer.baseAddress!, count: pointer.count) buffer[pointer.count] = 0x80 buffer.baseAddress!.advanced(by: needed &- 8).withMemoryRebound(to: UInt64.self, capacity: 1) { pointer in if Self.littleEndian { pointer.pointee = hashSize.littleEndian } else { pointer.pointee = hashSize.bigEndian } } var offset = 0 while offset < needed { self.update(from: buffer.baseAddress!.advanced(by: offset)) offset = offset &+ Self.chunkSize } } return self.hashValue } public mutating func hash(bytes data: [UInt8]) -> [UInt8] { defer { self.reset() } return data.withUnsafeBufferPointer { buffer in self.finish(from: buffer) } } public mutating func hash(_ data: UnsafePointer<UInt8>, count: Int) -> [UInt8] { defer { self.reset() } let buffer = UnsafeBufferPointer(start: data, count: count) return finish(from: buffer) } }
mit
19d26324b29005c137b232caa3e7f945
29.614286
118
0.531965
4.960648
false
false
false
false
cocoascientist/Playgrounds
Bindings.playground/Contents.swift
1
1059
// http://five.agency/solving-the-binding-problem-with-swift/ class Dynamic<T> { var value: T { didSet { // inform parties about change for bondBox in bonds { bondBox.bond?.listener(value) } } } var bonds: [BondBox<T>] = [] init(_ value: T) { self.value = value } } public class Bond<T> { public typealias Listener = T -> Void var listener: Listener init(_ listener: Listener) { self.listener = listener } func bind(dynamic: Dynamic<T>) { // bind to the dynamic dynamic.bonds.append(BondBox(self)) } } class BondBox<T> { weak var bond: Bond<T>? init(_ bond: Bond<T>) { self.bond = bond } } // var name: Dynamic<String>? = Dynamic("") let observer = { (name: String) -> Void in let n = name print("name is now \(n)") } let nameBond = Bond(observer) nameBond.bind(name!) name?.value = "Robert" name?.value = "Mary" name?.value = "Martha"
mit
1ac2f12780ed6e1812ed18b4bc146e9f
17.258621
61
0.532578
3.541806
false
false
false
false
hanjoes/Breakout
Breakout/Breakout/BreakoutSettingViewController.swift
1
4464
// // BreakoutSettingViewController.swift // Breakout // // Created by Hanzhou Shi on 5/30/16. // Copyright © 2016 USF. All rights reserved. // import UIKit struct SettingConstants { static let BallSpeedDefaultKey = "Breakout.BallSpeed" static let NumberOfBallsDefaultKey = "Breakout.NumberOfBalls" static let BouncinessDefaultKey = "Breakout.Bounciness" static let ResistenceDefaultKey = "Breakout.Resistence" static let BallSpeedDefaultValue = 0.02 static let NumberOfBallsDefaultValue = 1.0 static let BouncinessDefaultValue = 0.8 static let ResistenceDefaultValue = 0.0 } class BreakoutSettingViewController: UIViewController { // MARK: Actions/Outlets @IBOutlet weak var ballSpeedLabel: UILabel! @IBOutlet weak var numberOfBallsLabel: UILabel! @IBOutlet weak var bouncinessLabel: UILabel! @IBOutlet weak var resistenceLabel: UILabel! // the speed of the push applied to the balls @IBOutlet weak var ballSpeedStepper: UIStepper! @IBOutlet weak var numberOfBallsStepper: UIStepper! @IBOutlet weak var bouncinessStepper: UIStepper! @IBOutlet weak var resistenceStepper: UIStepper! @IBAction func changeBallSpeed(sender: UIStepper) { ballSpeed = sender.value } @IBAction func changeNumberOfBalls(sender: UIStepper) { numberOfBalls = sender.value } @IBAction func changeBounciness(sender: UIStepper) { bounciness = sender.value } @IBAction func changeResistence(sender: UIStepper) { resistence = sender.value } var ballSpeed: Double { set { ballSpeedLabel.text = "\(newValue)" setDefault(forKey: SettingConstants.BallSpeedDefaultKey, doubleVal: newValue) } get { return NSUserDefaults.standardUserDefaults().objectForKey(SettingConstants.BallSpeedDefaultKey) as! Double } } var numberOfBalls: Double { set { numberOfBallsLabel.text = "\(newValue)" setDefault(forKey: SettingConstants.NumberOfBallsDefaultKey, doubleVal: newValue) } get { return NSUserDefaults.standardUserDefaults().objectForKey(SettingConstants.NumberOfBallsDefaultKey) as! Double } } var bounciness: Double { set { bouncinessLabel.text = "\(newValue)" setDefault(forKey: SettingConstants.BouncinessDefaultKey, doubleVal: newValue) } get { return NSUserDefaults.standardUserDefaults().objectForKey(SettingConstants.BouncinessDefaultKey) as! Double } } var resistence: Double { set { resistenceLabel.text = "\(newValue)" setDefault(forKey: SettingConstants.ResistenceDefaultKey, doubleVal: newValue) } get { return NSUserDefaults.standardUserDefaults().objectForKey(SettingConstants.ResistenceDefaultKey) as! Double } } // MARK: Lifecycles override func viewDidLoad() { super.viewDidLoad() // setup stepper properties setupStepperProperties(ballSpeedStepper, minVal: 0.02, maxVal: 0.1, stepVal: 0.02) setupStepperProperties(numberOfBallsStepper, minVal: 1.0, maxVal: 4.0) setupStepperProperties(bouncinessStepper, minVal: 0.1, maxVal: 1.0, stepVal: 0.1) setupStepperProperties(resistenceStepper, minVal: 0.0, maxVal: 0.8, stepVal: 0.1) // initialize from NSUserDefaults initialize() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Methods private func setupStepperProperties(stepper: UIStepper, minVal: Double, maxVal: Double, stepVal: Double = 1.0) { stepper.minimumValue = minVal stepper.maximumValue = maxVal stepper.stepValue = stepVal } private func getDefaultDouble(forKey key: String) -> Double? { return NSUserDefaults.standardUserDefaults().objectForKey(key) as? Double } private func setDefault(forKey key: String, doubleVal: Double) { NSUserDefaults.standardUserDefaults().setObject(doubleVal, forKey: key) } private func initialize() { ballSpeed = getDefaultDouble(forKey: SettingConstants.BallSpeedDefaultKey) ?? SettingConstants.BallSpeedDefaultValue ballSpeedStepper.value = ballSpeed numberOfBalls = getDefaultDouble(forKey: SettingConstants.NumberOfBallsDefaultKey) ?? SettingConstants.NumberOfBallsDefaultValue numberOfBallsStepper.value = numberOfBalls bounciness = getDefaultDouble(forKey: SettingConstants.BouncinessDefaultKey) ?? SettingConstants.BouncinessDefaultValue bouncinessStepper.value = bounciness resistence = getDefaultDouble(forKey: SettingConstants.ResistenceDefaultKey) ?? SettingConstants.ResistenceDefaultValue resistenceStepper.value = resistence } }
mit
8fd4f5b50d12805f96f4904d1274d3d2
28.753333
130
0.766301
3.94258
false
false
false
false
valine/octotap
octo-tap/octo-tap/Constants/Constants.swift
1
2170
// Copyright Lukas Valine 2017 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit struct Constants { enum Server : String { case apiKey case address case streamUrl } enum Printer { enum JogDistance { case x case y case z } enum Extruder { case extrusionAmount case flowRate } } enum TabelCellResuseIDs : String { case toolCell case filesCell } enum App : String { case firstLaunch case setupSuccessful } struct Strings { static let invalidURL = "The URL you entered is invalid".capitalized static let badConnections = "The OctoPrint server is not responding".capitalized static let successful = "Connection successful".capitalized static let bedToolName = "Bed" static let toolName = "Tool" } struct Colors { static let octotapGreen = #colorLiteral(red: 0.0974875365, green: 0.9805322289, blue: 0.4432027052, alpha: 1) static let errorRed = #colorLiteral(red: 0.9805322289, green: 0.4494236022, blue: 0.4543004445, alpha: 1) static let happyRed = #colorLiteral(red: 1, green: 0, blue: 0.2552101016, alpha: 1) static let linkBlue = #colorLiteral(red: 0.120020397, green: 0.5770391822, blue: 0.9824696183, alpha: 1) static let ashGrey = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) static let almostBlack = #colorLiteral(red: 0.03166640236, green: 0.03166640236, blue: 0.03166640236, alpha: 1) } struct Dimensions { static let cellClosedHeight: CGFloat = 135 static let cellOpenHeight: CGFloat = 230 static let extrusionAmounts: Array<Float> = [2, 5, 10, 30] } }
apache-2.0
b8c29a4d7518ab9a5497ce9285157246
29.138889
114
0.706912
3.297872
false
false
false
false
siberianisaev/NeutronBarrel
NeutronBarrel/CalculationsController.swift
1
2286
// // CalculationsController.swift // NeutronBarrel // // Created by Andrey Isaev on 07.04.2021. // Copyright © 2021 Flerov Laboratory. All rights reserved. // import Cocoa class CalculationsController: NSWindowController { // MARK: Half Life @IBInspectable dynamic var sTimePeakCenter: String = "" { didSet { updateHalfLife() } } @IBInspectable dynamic var sTimePeakCenterError: String = "" { didSet { updateHalfLife() } } @IBOutlet weak var textFieldHalfLife: NSTextField! fileprivate func updateHalfLife() { let xc = max(Float(sTimePeakCenter) ?? 0, 0) let xcError = max(Float(sTimePeakCenterError) ?? 0, 0) let tau = pow(10, xc) let positiveError = pow(10, xc + xcError) - tau let negativeError = tau - pow(10, xc - xcError) textFieldHalfLife.stringValue = "\(tau)\n+\(positiveError)\n-\(negativeError)" } // MARK: Beam @IBInspectable dynamic var sBeamIonCharge: String = "" { didSet { updateIntegral() updateIntensity() } } @IBInspectable dynamic var sIntegral: String = "" { didSet { updateIntegral() } } @IBInspectable dynamic var sIntensity: String = "" { didSet { updateIntensity() } } @IBOutlet weak var textIntegral: NSTextField! fileprivate func updateIntegral() { // From microcoulombs to particles let particles = (pow(10, 13) * max(Float(sIntegral) ?? 0, 0))/(max(Float(sBeamIonCharge) ?? 1, 1) * 1.602176634) // 1E-6 / 1E-19 textIntegral.stringValue = "\(particles) particles" } @IBOutlet weak var textIntensity: NSTextField! fileprivate func updateIntensity() { // From microampere to particles per seconds let pps = (6.25*pow(10, 12) * max(Float(sIntensity) ?? 0, 0))/(max(Float(sBeamIonCharge) ?? 1, 1)) textIntensity.stringValue = "\(pps) particles/seconds" } override func windowDidLoad() { super.windowDidLoad() for tf in [textFieldHalfLife, textIntegral, textIntensity] { tf?.usesSingleLineMode = false } } }
mit
83e2ffda4518c2685829c9319ee23e85
26.865854
136
0.586871
4.094982
false
false
false
false
haawa799/WaniKani-iOS
WaniKani/Utils/NotificationManager.swift
1
2628
// // NotificationManager.swift // // // Created by Andriy K. on 8/12/15. // // import UIKit import Crashlytics class NotificationManager: NSObject { static let sharedInstance = NotificationManager() static let notificationsAllowedKey = "NotificationsAllowedKey" var notificationsEnabled = NSUserDefaults.standardUserDefaults().boolForKey(NotificationManager.notificationsAllowedKey) { didSet { if oldValue != notificationsEnabled { NSUserDefaults.standardUserDefaults().setBool(notificationsEnabled, forKey: NotificationManager.notificationsAllowedKey) NSUserDefaults.standardUserDefaults().synchronize() if notificationsEnabled == false { unscheduleNotification() } else { if let date = lastAttemptDate { scheduleNextReviewNotification(date) } } } } } private var lastAttemptDate: NSDate? func scheduleNextReviewNotification(date: NSDate) -> Bool { // Make sure notification is in future guard date.timeIntervalSinceNow > 0 else { return false } var newNotificationScheduled = false if notificationsEnabled { // Clean up past notifications if UIApplication.sharedApplication().scheduledLocalNotifications?.count > 0 { for notif in UIApplication.sharedApplication().scheduledLocalNotifications! { if notif.fireDate?.timeIntervalSinceNow < 0 { unscheduleNotification() break } } } // Schedule new notification if there is none yet if UIApplication.sharedApplication().scheduledLocalNotifications?.count == 0 { if date.compare(NSDate()) == .OrderedDescending { print("orderDescending") let notification = UILocalNotification() notification.fireDate = date notification.alertBody = "New reviews available!" notification.soundName = "notification.m4a" UIApplication.sharedApplication().scheduleLocalNotification(notification) newNotificationScheduled = true var backgroundCall = false if let isBackgroundFetch = (UIApplication.sharedApplication().delegate as? AppDelegate)?.isBackgroundFetching { backgroundCall = isBackgroundFetch } appDelegate.fabricManager.postNotificationScheduled(backgroundCall) } } } lastAttemptDate = date return newNotificationScheduled } func unscheduleNotification() { UIApplication.sharedApplication().cancelAllLocalNotifications() } }
gpl-3.0
9c9058415897d6803187917ba277ecd5
29.917647
128
0.673896
6.097448
false
false
false
false
phimage/MomXML
Sources/Model/MomFetchedProperty.swift
1
843
// // MomFetchedProperty.swift // MomXML // // Created by Eric Marchand on 03/01/2019. // Copyright © 2019 phimage. All rights reserved. // import Foundation public struct MomFetchedProperty { public var name: String public var isOptional: Bool = true public var syncable: Bool = true public var fetchRequest: MomFetchRequest public var userInfo = MomUserInfo() public init(name: String, fetchRequest: MomFetchRequest) { self.name = name self.fetchRequest = fetchRequest } } public struct MomFetchRequest { public var name: String public var entity: String public var predicateString: String public init(name: String, entity: String, predicateString: String) { self.name = name self.entity = entity self.predicateString = predicateString } }
mit
ea39fbe182e7abb1e7147887f3b3e299
21.756757
72
0.685273
4.252525
false
true
false
false
gregomni/swift
stdlib/public/core/VarArgs.swift
6
23443
//===----------------------------------------------------------------------===// // // 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 type whose instances can be encoded, and appropriately passed, as /// elements of a C `va_list`. /// /// You use this protocol to present a native Swift interface to a C "varargs" /// API. For example, a program can import a C API like the one defined here: /// /// ~~~c /// int c_api(int, va_list arguments) /// ~~~ /// /// To create a wrapper for the `c_api` function, write a function that takes /// `CVarArg` arguments, and then call the imported C function using the /// `withVaList(_:_:)` function: /// /// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int { /// return withVaList(arguments) { c_api(x, $0) } /// } /// /// Swift only imports C variadic functions that use a `va_list` for their /// arguments. C functions that use the `...` syntax for variadic arguments /// are not imported, and therefore can't be called using `CVarArg` arguments. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Note: Declaring conformance to the `CVarArg` protocol for types defined /// outside the standard library is not supported. public protocol CVarArg { // Note: the protocol is public, but its requirement is stdlib-private. // That's because there are APIs operating on CVarArg instances, but // defining conformances to CVarArg outside of the standard library is // not supported. /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. var _cVarArgEncoding: [Int] { get } } /// Floating point types need to be passed differently on x86_64 /// systems. CoreGraphics uses this to make CGFloat work properly. public // SPI(CoreGraphics) protocol _CVarArgPassedAsDouble: CVarArg {} /// Some types require alignment greater than Int on some architectures. public // SPI(CoreGraphics) protocol _CVarArgAligned: CVarArg { /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. var _cVarArgAlignment: Int { get } } #if !_runtime(_ObjC) /// Some pointers require an alternate object to be retained. The object /// that is returned will be used with _cVarArgEncoding and held until /// the closure is complete. This is required since autoreleased storage /// is not available on all platforms. public protocol _CVarArgObject: CVarArg { /// Returns the alternate object that should be encoded. var _cVarArgObject: CVarArg { get } } #endif #if arch(x86_64) @usableFromInline internal let _countGPRegisters = 6 // Note to future visitors concerning the following SSE register count. // // AMD64-ABI section 3.5.7 says -- as recently as v0.99.7, Nov 2014 -- to make // room in the va_list register-save area for 16 SSE registers (XMM0..15). This // may seem surprising, because the calling convention of that ABI only uses the // first 8 SSE registers for argument-passing; why save the other 8? // // According to a comment in X86_64ABIInfo::EmitVAArg, in clang's TargetInfo, // the AMD64-ABI spec is itself in error on this point ("NOTE: 304 is a typo"). // This comment (and calculation) in clang has been there since varargs support // was added in 2009, in rev be9eb093; so if you're about to change this value // from 8 to 16 based on reading the spec, probably the bug you're looking for // is elsewhere. @usableFromInline internal let _countFPRegisters = 8 @usableFromInline internal let _fpRegisterWords = 2 @usableFromInline internal let _registerSaveWords = _countGPRegisters + _countFPRegisters * _fpRegisterWords #elseif arch(s390x) @usableFromInline internal let _countGPRegisters = 16 @usableFromInline internal let _registerSaveWords = _countGPRegisters #elseif arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows)) // ARM Procedure Call Standard for aarch64. (IHI0055B) // The va_list type may refer to any parameter in a parameter list may be in one // of three memory locations depending on its type and position in the argument // list : // 1. GP register save area x0 - x7 // 2. 128-bit FP/SIMD register save area q0 - q7 // 3. Stack argument area @usableFromInline internal let _countGPRegisters = 8 @usableFromInline internal let _countFPRegisters = 8 @usableFromInline internal let _fpRegisterWords = 16 / MemoryLayout<Int>.size @usableFromInline internal let _registerSaveWords = _countGPRegisters + (_countFPRegisters * _fpRegisterWords) #endif #if arch(s390x) @usableFromInline internal typealias _VAUInt = CUnsignedLongLong @usableFromInline internal typealias _VAInt = Int64 #else @usableFromInline internal typealias _VAUInt = CUnsignedInt @usableFromInline internal typealias _VAInt = Int32 #endif /// Invokes the given closure with a C `va_list` argument derived from the /// given array of arguments. /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withVaList(_:_:)`. Do not store or return the pointer for /// later use. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Parameters: /// - args: An array of arguments to convert to a C `va_list` pointer. /// - body: A closure with a `CVaListPointer` parameter that references the /// arguments passed as `args`. If `body` has a return value, that value /// is also used as the return value for the `withVaList(_:)` function. /// The pointer argument is valid only for the duration of the function's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable // c-abi public func withVaList<R>(_ args: [CVarArg], _ body: (CVaListPointer) -> R) -> R { let builder = __VaListBuilder() for a in args { builder.append(a) } return _withVaList(builder, body) } /// Invoke `body` with a C `va_list` argument derived from `builder`. @inlinable // c-abi internal func _withVaList<R>( _ builder: __VaListBuilder, _ body: (CVaListPointer) -> R ) -> R { let result = body(builder.va_list()) _fixLifetime(builder) return result } #if _runtime(_ObjC) // Excluded due to use of dynamic casting and Builtin.autorelease, neither // of which correctly work without the ObjC Runtime right now. // See rdar://problem/18801510 /// Returns a `CVaListPointer` that is backed by autoreleased storage, built /// from the given array of arguments. /// /// You should prefer `withVaList(_:_:)` instead of this function. In some /// uses, such as in a `class` initializer, you may find that the language /// rules do not allow you to use `withVaList(_:_:)` as intended. /// /// If you need to pass an optional pointer as a `CVarArg` argument, use the /// `Int(bitPattern:)` initializer to interpret the optional pointer as an /// `Int` value, which has the same C variadic calling conventions as a pointer /// on all supported platforms. /// /// - Parameter args: An array of arguments to convert to a C `va_list` /// pointer. /// - Returns: A pointer that can be used with C functions that take a /// `va_list` argument. @inlinable // c-abi public func getVaList(_ args: [CVarArg]) -> CVaListPointer { let builder = __VaListBuilder() for a in args { builder.append(a) } // FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one. Builtin.retain(builder) Builtin.autorelease(builder) return builder.va_list() } #endif @inlinable // c-abi public func _encodeBitsAsWords<T>(_ x: T) -> [Int] { let result = [Int]( repeating: 0, count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size) _internalInvariant(!result.isEmpty) var tmp = x // FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy. _memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!), src: UnsafeMutablePointer(Builtin.addressof(&tmp)), size: UInt(MemoryLayout<T>.size)) return result } // CVarArg conformances for the integer types. Everything smaller // than an Int32 must be promoted to Int32 or CUnsignedInt before // encoding. // Signed types extension Int: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension Bool: CVarArg { public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self ? 1:0)) } } extension Int64: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } extension Int32: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } extension Int16: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } extension Int8: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAInt(self)) } } // Unsigned types extension UInt: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UInt64: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } extension UInt32: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension UInt16: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension UInt8: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(_VAUInt(self)) } } extension OpaquePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UnsafePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } extension UnsafeMutablePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } #if _runtime(_ObjC) extension AutoreleasingUnsafeMutablePointer: CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } } #endif extension Float: _CVarArgPassedAsDouble, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(Double(self)) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: Double(self)) } } extension Double: _CVarArgPassedAsDouble, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // c-abi public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // c-abi public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) extension Float80: CVarArg, _CVarArgAligned { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs. @inlinable // FIXME(sil-serialize-all) public var _cVarArgEncoding: [Int] { return _encodeBitsAsWords(self) } /// Returns the required alignment in bytes of /// the value returned by `_cVarArgEncoding`. @inlinable // FIXME(sil-serialize-all) public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures return MemoryLayout.alignment(ofValue: self) } } #endif #if (arch(x86_64) && !os(Windows)) || arch(s390x) || (arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))) /// An object that can manage the lifetime of storage backing a /// `CVaListPointer`. // NOTE: older runtimes called this _VaListBuilder. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. @_fixed_layout @usableFromInline // c-abi final internal class __VaListBuilder { #if arch(x86_64) || arch(s390x) @frozen // c-abi @usableFromInline internal struct Header { @usableFromInline // c-abi internal var gp_offset = CUnsignedInt(0) @usableFromInline // c-abi internal var fp_offset = CUnsignedInt(_countGPRegisters * MemoryLayout<Int>.stride) @usableFromInline // c-abi internal var overflow_arg_area: UnsafeMutablePointer<Int>? @usableFromInline // c-abi internal var reg_save_area: UnsafeMutablePointer<Int>? @inlinable // c-abi internal init() {} } #endif @usableFromInline // c-abi internal var gpRegistersUsed = 0 @usableFromInline // c-abi internal var fpRegistersUsed = 0 #if arch(x86_64) || arch(s390x) @usableFromInline // c-abi final // Property must be final since it is used by Builtin.addressof. internal var header = Header() #endif @usableFromInline // c-abi internal var storage: ContiguousArray<Int> #if !_runtime(_ObjC) @usableFromInline // c-abi internal var retainer = [CVarArg]() #endif @inlinable // c-abi internal init() { // prepare the register save area storage = ContiguousArray(repeating: 0, count: _registerSaveWords) } @inlinable // c-abi deinit {} @inlinable // c-abi internal func append(_ arg: CVarArg) { #if !_runtime(_ObjC) var arg = arg // We may need to retain an object that provides a pointer value. if let obj = arg as? _CVarArgObject { arg = obj._cVarArgObject retainer.append(arg) } #endif var encoded = arg._cVarArgEncoding #if arch(x86_64) || arch(arm64) let isDouble = arg is _CVarArgPassedAsDouble if isDouble && fpRegistersUsed < _countFPRegisters { #if arch(arm64) var startIndex = fpRegistersUsed * _fpRegisterWords #else var startIndex = _countGPRegisters + (fpRegistersUsed * _fpRegisterWords) #endif for w in encoded { storage[startIndex] = w startIndex += 1 } fpRegistersUsed += 1 } else if encoded.count == 1 && !isDouble && gpRegistersUsed < _countGPRegisters { #if arch(arm64) let startIndex = ( _fpRegisterWords * _countFPRegisters) + gpRegistersUsed #else let startIndex = gpRegistersUsed #endif storage[startIndex] = encoded[0] gpRegistersUsed += 1 } else { for w in encoded { storage.append(w) } } #elseif arch(s390x) if gpRegistersUsed < _countGPRegisters { for w in encoded { storage[gpRegistersUsed] = w gpRegistersUsed += 1 } } else { for w in encoded { storage.append(w) } } #endif } @inlinable // c-abi internal func va_list() -> CVaListPointer { #if arch(x86_64) || arch(s390x) header.reg_save_area = storage._baseAddress header.overflow_arg_area = storage._baseAddress + _registerSaveWords return CVaListPointer( _fromUnsafeMutablePointer: UnsafeMutableRawPointer( Builtin.addressof(&self.header))) #elseif arch(arm64) let vr_top = storage._baseAddress + (_fpRegisterWords * _countFPRegisters) let gr_top = vr_top + _countGPRegisters return CVaListPointer(__stack: gr_top, __gr_top: gr_top, __vr_top: vr_top, __gr_off: -64, __vr_off: -128) #endif } } #else /// An object that can manage the lifetime of storage backing a /// `CVaListPointer`. // NOTE: older runtimes called this _VaListBuilder. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. @_fixed_layout @usableFromInline // c-abi final internal class __VaListBuilder { @inlinable // c-abi internal init() {} @inlinable // c-abi internal func append(_ arg: CVarArg) { #if !_runtime(_ObjC) var arg = arg // We may need to retain an object that provides a pointer value. if let obj = arg as? _CVarArgObject { arg = obj._cVarArgObject retainer.append(arg) } #endif // Write alignment padding if necessary. // This is needed on architectures where the ABI alignment of some // supported vararg type is greater than the alignment of Int, such // as non-iOS ARM. Note that we can't use alignof because it // differs from ABI alignment on some architectures. #if (arch(arm) && !os(iOS)) || arch(arm64_32) || arch(wasm32) if let arg = arg as? _CVarArgAligned { let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size let misalignmentInWords = count % alignmentInWords if misalignmentInWords != 0 { let paddingInWords = alignmentInWords - misalignmentInWords appendWords([Int](repeating: -1, count: paddingInWords)) } } #endif // Write the argument's value itself. appendWords(arg._cVarArgEncoding) } // NB: This function *cannot* be @inlinable because it expects to project // and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`. // Marking it inlinable will cause it to resiliently use accessors to // project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed // property. @usableFromInline // c-abi internal func va_list() -> CVaListPointer { // Use Builtin.addressof to emphasize that we are deliberately escaping this // pointer and assuming it is safe to do so. let emptyAddr = UnsafeMutablePointer<Int>( Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists)) return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr) } // Manage storage that is accessed as Words // but possibly more aligned than that. // FIXME: this should be packaged into a better storage type @inlinable // c-abi internal func appendWords(_ words: [Int]) { let newCount = count + words.count if newCount > allocated { let oldAllocated = allocated let oldStorage = storage let oldCount = count allocated = max(newCount, allocated * 2) let newStorage = allocStorage(wordCount: allocated) storage = newStorage // count is updated below if let allocatedOldStorage = oldStorage { newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount) deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage) } } let allocatedStorage = storage! for word in words { allocatedStorage[count] = word count += 1 } } @inlinable // c-abi internal func rawSizeAndAlignment( _ wordCount: Int ) -> (Builtin.Word, Builtin.Word) { return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue, requiredAlignmentInBytes._builtinWordValue) } @inlinable // c-abi internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> { let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount) let rawStorage = Builtin.allocRaw(rawSize, rawAlignment) return UnsafeMutablePointer<Int>(rawStorage) } @usableFromInline // c-abi internal func deallocStorage( wordCount: Int, storage: UnsafeMutablePointer<Int> ) { let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount) Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment) } @inlinable // c-abi deinit { if let allocatedStorage = storage { deallocStorage(wordCount: allocated, storage: allocatedStorage) } } // FIXME: alignof differs from the ABI alignment on some architectures @usableFromInline // c-abi internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment @usableFromInline // c-abi internal var count = 0 @usableFromInline // c-abi internal var allocated = 0 @usableFromInline // c-abi internal var storage: UnsafeMutablePointer<Int>? #if !_runtime(_ObjC) @usableFromInline // c-abi internal var retainer = [CVarArg]() #endif internal static var alignedStorageForEmptyVaLists: Double = 0 } #endif
apache-2.0
d04164ea76c7c578d6e2712e5aa592f4
31.925562
135
0.691166
4.096278
false
false
false
false
jane/JanePhotoBrowser
JanePhotoBrowser/PhotoBrowser/ImageNumberView.swift
1
1789
// // ImageNumberView.swift // PhotoBrowser // // Created by Gordon Tucker on 8/2/19. // Copyright © 2019 Jane. All rights reserved. // import UIKit public class ImageNumberView: UIView { public var blurView: UIVisualEffectView! public var label = UILabel() public var font: UIFont = UIFont.systemFont(ofSize: 12) { didSet { self.label.font = self.font } } public var text: String { get { return self.label.text ?? "" } set { self.label.text = newValue } } public override init(frame: CGRect) { super.init(frame: frame) self.setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { self.layer.cornerRadius = 4 self.layer.masksToBounds = true self.backgroundColor = .clear // Add a blur view so we get a nice effect behind the number count let blurView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffect.Style.extraLight)) blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.blurView = blurView self.addSubview(blurView) { $0.edges.pinToSuperview() } blurView.contentView.addSubview(self.label) { $0.edges.pinToSuperview(insets: UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12), relation: .equal) } self.label.textColor = UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1) self.label.isAccessibilityElement = false self.label.font = self.font self.label.minimumScaleFactor = 0.5 self.label.adjustsFontSizeToFitWidth = true } }
mit
13e41c0c68b6f8643f4f2c79798b5ee3
27.83871
115
0.599553
4.360976
false
false
false
false
netyouli/WHC_AutoLayoutKit
WHC_AutoLayoutExample/Demo8/Other/WHC_ImageDisplayView.swift
1
11330
// // WHC_ImageDisplayView.swift // CRM // // Created by 吴海超 on 15/10/26. // Copyright © 2015年 吴海超. All rights reserved. // /********************************************************* * gitHub:https://github.com/netyouli/WHC_AutoLayoutKit * * 本人其他优秀开源库:https://github.com/netyouli * *********************************************************/ import UIKit @objc protocol WHC_GestureImageViewDelegate { @objc optional func WHCGestureImageViewExit(); } class WHC_GestureImageView: UIImageView { /// 退出手势 fileprivate var exitTapGesture: UITapGestureRecognizer!; /// 双击手势 fileprivate var tapGesture: UITapGestureRecognizer!; /// 是否已经放大 var isZoomBig = false; /// 协议 var delegate: WHC_GestureImageViewDelegate!; override init(frame: CGRect) { super.init(frame: frame); self.layoutUI(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } fileprivate func layoutUI() { self.isUserInteractionEnabled = true; self.exitTapGesture = UITapGestureRecognizer(target: self, action: #selector(WHC_GestureImageView.handleExitGesture(_:))); self.addGestureRecognizer(exitTapGesture); self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(WHC_GestureImageView.handleTapGesture(_:))); self.tapGesture.numberOfTapsRequired = 2; self.addGestureRecognizer(tapGesture); self.exitTapGesture.require(toFail: tapGesture); } @objc func handleExitGesture(_ sender: UITapGestureRecognizer) { let scrollView = self.superview as! UIScrollView; scrollView.setZoomScale(1, animated: false); self.delegate?.WHCGestureImageViewExit?(); } @objc func handleTapGesture(_ sender: UITapGestureRecognizer) { let scrollView = self.superview as! UIScrollView; if self.isZoomBig { scrollView.setZoomScale(1, animated: true); }else { scrollView.setZoomScale(2.5, animated: true); } self.isZoomBig = !self.isZoomBig; } } class WHC_ImageDisplayView: UIView , UIScrollViewDelegate , WHC_GestureImageViewDelegate{ fileprivate var images: [AnyObject]!; fileprivate var scrollView: UIScrollView!; fileprivate var index = 0; fileprivate var kZoomAniamtionTime = 0.3; fileprivate var currentIndex = 0; fileprivate var column = 0; fileprivate var currentImageView: WHC_GestureImageView!; fileprivate let kImageViewTag = 10; fileprivate var backView: UIView!; fileprivate var rect: CGRect!; fileprivate var kShowLabelHeight:CGFloat = 20; fileprivate var showLabel: UILabel!; class func show(_ images: [AnyObject] , index: Int , item: UIView , column: Int) -> WHC_ImageDisplayView { return WHC_ImageDisplayView(frame: UIScreen.main.bounds, images: images , index: index, rect: item.convert(item.bounds, to: (UIApplication.shared.delegate?.window)!), column: column); } init(frame: CGRect , images: [AnyObject] , index: Int , rect: CGRect , column: Int) { super.init(frame: frame); self.images = images; self.index = index; self.currentIndex = index; self.column = column; self.rect = rect; self.layoutUI(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } fileprivate func layoutUI() { self.backView = UIView(frame: UIScreen.main.bounds); self.backView.backgroundColor = UIColor.black; self.backView.alpha = 0; UIApplication.shared.delegate?.window??.addSubview(self.backView); self.backgroundColor = UIColor.clear; self.scrollView = UIScrollView(frame: self.bounds); self.scrollView.delegate = self; self.scrollView.showsHorizontalScrollIndicator = false; self.scrollView.showsVerticalScrollIndicator = false; self.addSubview(self.scrollView); if self.images.count > 0 { for (i , image) in self.images.enumerated() { let imageScrollView = UIScrollView(frame: CGRect(x: CGFloat(i) * self.width(), y: 0, width: self.width(), height: self.height())); let imageView = WHC_GestureImageView(frame: imageScrollView.bounds); imageView.delegate = self; if self.currentIndex == i { self.currentImageView = imageView; } imageView.tag = kImageViewTag; imageScrollView.addSubview(imageView); imageScrollView.delegate = self; imageScrollView.isMultipleTouchEnabled = true; imageScrollView.minimumZoomScale = 1.0; imageScrollView.maximumZoomScale = 2.5; imageScrollView.backgroundColor = UIColor.clear; imageScrollView.tag = i; self.scrollView.addSubview(imageScrollView); var imageObject: UIImage!; if image is UIImage { imageObject = image as! UIImage; }else if image is String { let imageName: String = image as! String; imageObject = UIImage(named: imageName); } if imageObject.size.width < imageScrollView.width() { imageView.setWidth(imageObject.size.width); } if imageObject.size.height < imageScrollView.height() { imageView.setHeight(imageObject.size.height); } imageView.setXy(CGPoint(x: (imageScrollView.width() - imageView.width()) / 2.0, y: (imageScrollView.height() - imageView.height()) / 2.0)); imageView.image = imageObject; } self.scrollView.isPagingEnabled = true; self.scrollView.contentSize = CGSize(width: CGFloat(self.images.count) * self.scrollView.width(), height: self.scrollView.height()); self.scrollView.setContentOffset(CGPoint(x: CGFloat(self.index) * self.width(), y: 0), animated: false); self.showLabel = UILabel(frame: CGRect(x: 0, y: self.height() - kShowLabelHeight, width: self.width(), height: kShowLabelHeight)); self.showLabel.text = "\(self.images.count) / \(self.index + 1)"; self.showLabel.textColor = UIColor.white; self.showLabel.textAlignment = .center; self.addSubview(self.showLabel); UIApplication.shared.delegate?.window??.addSubview(self); var rc = CGRect(x: 0, y: 0, width: self.currentImageView.width(), height: self.currentImageView.height()); rc.origin = CGPoint(x: (self.width() - currentImageView.width()) / 2.0, y: (self.height() - currentImageView.height()) / 2.0); self.currentImageView.frame = self.rect; UIView.animate(withDuration: kZoomAniamtionTime, delay: 0, options: .curveEaseIn, animations: { () -> Void in self.currentImageView.frame = rc; self.backView.alpha = 1.0; }, completion: nil); } } fileprivate func getExitRect() -> CGRect { var rc = CGRect(x: 0, y: 0, width: self.rect.width, height: self.rect.height); var startRect = CGRect(x: 0, y: 0, width: self.rect.width, height: self.rect.height); if self.index < self.column { startRect.origin.x = self.rect.minX - CGFloat(self.index) * self.rect.width; startRect.origin.y = self.rect.minY; }else { let row = ((self.index + 1) / self.column + ((self.index + 1) % self.column != 0 ? 1 : 0) - 1); let col = ((self.index + 1) % self.column == 0 ? self.column : (self.index + 1) % self.column) - 1; startRect.origin.x = self.rect.minX - CGFloat(col) * self.rect.width; startRect.origin.y = self.rect.minY - CGFloat(row) * self.rect.height; } if self.currentIndex < self.column { rc.origin.x = startRect.minX + CGFloat(self.currentIndex) * self.rect.width; rc.origin.y = startRect.minY; }else { let row = ((self.currentIndex + 1) / self.column + ((self.currentIndex + 1) % self.column != 0 ? 1 : 0) - 1); let col = ((self.currentIndex + 1) % self.column == 0 ? self.column : (self.currentIndex + 1) % self.column) - 1; rc.origin.x = startRect.minX + CGFloat(col) * self.rect.width; rc.origin.y = startRect.minY + CGFloat(row) * self.rect.height; } return rc; } //MARK: - WHC_GestureImageViewDelegate func WHCGestureImageViewExit() { let subView = self.scrollView.viewWithTag(self.currentIndex)!; self.currentImageView = subView.viewWithTag(kImageViewTag) as! WHC_GestureImageView; let rc = self.getExitRect(); UIView.animate(withDuration: kZoomAniamtionTime, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.backView.alpha = 0; self.currentImageView.frame = rc; }) { (finish) -> Void in self.backView.removeFromSuperview(); self.removeFromSuperview(); } } //MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if self.scrollView === scrollView { self.currentIndex = Int(floor((scrollView.contentOffset.x - scrollView.width() / 2.0) / scrollView.width())) + 1; if self.currentIndex < 0 { self.currentIndex = 0; }else if self.currentIndex > self.images.count { self.currentIndex = self.images.count - 1; } self.showLabel.text = "\(self.images.count) / \(self.currentIndex + 1)"; } } func scrollViewDidZoom(_ scrollView: UIScrollView) { if scrollView !== self.scrollView { let offsetX = (scrollView.width() > scrollView.contentSize.width) ? (scrollView.width() - scrollView.contentSize.width) / 2.0 : 0.0; let offsetY = (scrollView.height() > scrollView.contentSize.height) ? (scrollView.height() - scrollView.contentSize.height) / 2.0 : 0.0; self.currentImageView.center = CGPoint(x: scrollView.contentSize.width / 2.0 + offsetX, y: scrollView.contentSize.height / 2.0 + offsetY); } } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { if scale <= 1 { self.currentImageView.isZoomBig = false; }else { self.currentImageView.isZoomBig = true; } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { if scrollView !== self.scrollView { let subView = self.scrollView.viewWithTag(self.currentIndex)!; self.currentImageView = subView.viewWithTag(kImageViewTag) as! WHC_GestureImageView; return self.currentImageView; } return nil; } }
mit
2c5034ac388de80d4998ea12b3bf2bdc
43.168627
155
0.599396
4.494413
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Layers/GroupedBarsCompanionsLayer.swift
4
4212
// // GroupedBarsCompanionsLayer.swift // SwiftCharts // // Created by ischuetz on 07/10/16. // Copyright (c) 2016 ivanschuetz. All rights reserved. // import UIKit /** Allows to add views to chart which require grouped bars position. E.g. a label on top of each bar. It works by holding a reference to the grouped bars layer and requesting the position of the bars on updates We use a custom layer, since screen position of a grouped bar can't be derived directly from the chart point it represents. We need other factors like the passed spacing parameters, the width of the bars, etc. It seems convenient to implement an "observer" for current position of bars. NOTE: has to be passed to the chart after the grouped bars layer, in the layers array, in order to get its updated state. */ open class GroupedBarsCompanionsLayer<U: UIView>: ChartPointsLayer<ChartPoint> { public typealias CompanionViewGenerator = (_ barModel: ChartBarModel, _ barIndex: Int, _ viewIndex: Int, _ barView: UIView, _ layer: GroupedBarsCompanionsLayer<U>, _ chart: Chart) -> U? public typealias ViewUpdater = (_ barModel: ChartBarModel, _ barIndex: Int, _ viewIndex: Int, _ barView: UIView, _ layer: GroupedBarsCompanionsLayer<U>, _ chart: Chart, _ companionView: U) -> Void fileprivate let groupedBarsLayer: ChartGroupedStackedBarsLayer fileprivate let viewGenerator: CompanionViewGenerator fileprivate let viewUpdater: ViewUpdater fileprivate let delayInit: Bool fileprivate var companionViews: [U] = [] public init(xAxis: ChartAxis, yAxis: ChartAxis, viewGenerator: @escaping CompanionViewGenerator, viewUpdater: @escaping ViewUpdater, groupedBarsLayer: ChartGroupedStackedBarsLayer, displayDelay: Float = 0, delayInit: Bool = false) { self.groupedBarsLayer = groupedBarsLayer self.viewGenerator = viewGenerator self.delayInit = delayInit self.viewUpdater = viewUpdater super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: [], displayDelay: displayDelay) } override open func display(chart: Chart) { super.display(chart: chart) if !delayInit { initViews(chart, applyDelay: false) } } fileprivate func initViews(_ chart: Chart) { iterateBars {[weak self] (barModel, barIndex, viewIndex, barView) in guard let weakSelf = self else {return} if let companionView = weakSelf.viewGenerator(barModel, barIndex, viewIndex, barView, weakSelf, chart) { chart.addSubviewNoTransform(companionView) weakSelf.companionViews.append(companionView) } } } open func initViews(_ chart: Chart, applyDelay: Bool = true) { if applyDelay { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(Double(displayDelay) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {() -> Void in self.initViews(chart) } } else { initViews(chart) } } fileprivate func updatePositions() { guard let chart = chart else {return} iterateBars {[weak self] (barModel, barIndex, viewIndex, barView) in guard let weakSelf = self else {return} if viewIndex < weakSelf.companionViews.count { let companionView = weakSelf.companionViews[viewIndex] weakSelf.viewUpdater(barModel, barIndex, viewIndex, barView, weakSelf, chart, companionView) } } } fileprivate func iterateBars(_ f: (_ barModel: ChartBarModel, _ barIndex: Int, _ viewIndex: Int, _ barView: UIView) -> Void) { var viewIndex = 0 for (group, barViews) in groupedBarsLayer.groupViews { for (barIndex, barModel) in group.bars.enumerated() { f(barModel, barIndex, viewIndex, barViews[barIndex]) viewIndex += 1 } } } open override func handlePanFinish() { super.handlePanEnd() updatePositions() } open override func handleZoomFinish() { super.handleZoomEnd() updatePositions() } }
apache-2.0
7c04bf05b11f277c21650d996f972031
41.545455
287
0.659544
4.613363
false
false
false
false
PerfectExamples/staffDirectory
Sources/staffDirectory/utility/makeRequest.swift
2
2606
// // makeRequest.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-02-22. // // import Foundation import PerfectLib import PerfectCURL import cURL import SwiftString import PerfectHTTP extension Utility { /// The function that triggers the specific interaction with a remote server /// Parameters: /// - method: The HTTP Method enum, i.e. .get, .post /// - route: The route required /// - body: The JSON formatted sring to sent to the server /// Response: /// "data" - [String:Any] static func makeRequest( _ method: HTTPMethod, _ url: String, body: String = "", encoding: String = "JSON", bearerToken: String = "" ) -> ([String:Any]) { let curlObject = CURL(url: url) curlObject.setOption(CURLOPT_HTTPHEADER, s: "Accept: application/json") curlObject.setOption(CURLOPT_HTTPHEADER, s: "Cache-Control: no-cache") curlObject.setOption(CURLOPT_USERAGENT, s: "PerfectAPI2.0") if !bearerToken.isEmpty { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Authorization: Bearer \(bearerToken)") } switch method { case .post : let byteArray = [UInt8](body.utf8) curlObject.setOption(CURLOPT_POST, int: 1) curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count) curlObject.setOption(CURLOPT_COPYPOSTFIELDS, v: UnsafeMutablePointer(mutating: byteArray)) if encoding == "form" { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/x-www-form-urlencoded") } else { curlObject.setOption(CURLOPT_HTTPHEADER, s: "Content-Type: application/json") } default: //.get : curlObject.setOption(CURLOPT_HTTPGET, int: 1) } var header = [UInt8]() var bodyIn = [UInt8]() var code = 0 var data = [String: Any]() var raw = [String: Any]() var perf = curlObject.perform() defer { curlObject.close() } while perf.0 { if let h = perf.2 { header.append(contentsOf: h) } if let b = perf.3 { bodyIn.append(contentsOf: b) } perf = curlObject.perform() } if let h = perf.2 { header.append(contentsOf: h) } if let b = perf.3 { bodyIn.append(contentsOf: b) } let _ = perf.1 // assamble the body from a binary byte array to a string let content = String(bytes:bodyIn, encoding:String.Encoding.utf8) // parse the body data into a json convertible do { if (content?.characters.count)! > 0 { if (content?.startsWith("["))! { let arr = try content?.jsonDecode() as! [Any] data["response"] = arr } else { data = try content?.jsonDecode() as! [String : Any] } } return data } catch { return [:] } } }
apache-2.0
a7498a867f99e042a677875ff19a6341
23.35514
98
0.662318
3.087678
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch15/15.4.3使用Any和AnyObject类型.playground/section-1.swift
1
2208
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] import UIKit class Person { var name : String var age : Int func description() -> String { return "\(name) 年龄是: \(age)" } convenience init () { self.init(name: "Tony") self.age = 18 } convenience init (name : String) { self.init(name: name, age: 18) } init (name : String, age : Int) { self.name = name self.age = age } } class Student : Person { var school : String init (name : String, age : Int, school : String) { self.school = school super.init(name : name, age : age) } } class Worker : Person { var factory : String init (name : String, age : Int, factory : String) { self.factory = factory super.init(name : name, age : age) } } let p1 : Person = Student(name : "Tom", age : 20, school : "清华大学") let p2 : Person = Worker(name : "Tom", age : 18, factory : "钢厂") let p3 : Person = Person(name : "Tom", age : 28) let student1 = Student(name : "Tom", age : 18, school : "清华大学") let student2 = Student(name : "Ben", age : 28, school : "北京大学") let student3 = Student(name : "Tony", age : 38, school : "香港大学") let worker1 = Worker(name : "Tom", age : 18, factory : "钢厂") let worker2 = Worker(name : "Ben", age : 20, factory : "电厂") let people1: [Person] = [student1, student2, student3, worker1, worker2] let people2: [AnyObject] = [student1, student2, student3, worker1, worker2] let people3: [Any] = [student1, student2, student3, worker1, worker2] for item in people3 { if let student = item as? Student { println("Student school: \(student.school)") } else if let worker = item as? Worker { println("Worker factory: \(worker.factory)") } }
gpl-2.0
2f5b0648f7b17999b40c23f0fd87d3c2
26.540541
75
0.604514
3.06006
false
false
false
false
CatalystOfNostalgia/hoot
Hoot/Hoot/Comment.swift
1
630
// // Comment.swift // Hoot // // Created by Eric Luan on 4/3/16. // Copyright © 2016 Eric Luan. All rights reserved. // import Foundation // Represents a single comment on a product class Comment { var emotions: String var complexEmotions: String var comment: String var relevancy: Double var rating: Double init(emotions: String, comment: String, relevancy: Double, rating: Double, complexEmotions: String) { self.emotions = emotions self.comment = comment self.relevancy = relevancy self.rating = rating self.complexEmotions = complexEmotions } }
mit
ba0ef95f5209b956d64b5d8b5bd961fe
23.230769
105
0.664547
3.955975
false
false
false
false
loganSims/wsdot-ios-app
wsdot/VesselDetailsViewController.swift
1
3611
// // VesselDetailsViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import UIKit import SafariServices class VesselDetailsViewController: UIViewController{ let vesselBaseUrlString = "https://www.wsdot.com/ferries/vesselwatch/VesselDetail.aspx?vessel_id=" var vesselItem: VesselItem? = nil @IBOutlet weak var routeLabel: UILabel! @IBOutlet weak var departLabel: UILabel! @IBOutlet weak var arrLabel: UILabel! @IBOutlet weak var schedDepartLabel: UILabel! @IBOutlet weak var actualDepartLabel: UILabel! @IBOutlet weak var etaLabel: UILabel! @IBOutlet weak var headinglabel: UILabel! @IBOutlet weak var speedLabel: UILabel! @IBOutlet weak var updatedLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = vesselItem?.vesselName routeLabel.text = vesselItem?.route departLabel.text = vesselItem?.departingTerminal arrLabel.text = vesselItem?.arrivingTerminal if let departTime = vesselItem?.nextDeparture { schedDepartLabel.text = TimeUtils.getTimeOfDay(departTime) } else { schedDepartLabel.text = "--:--" } if let actualDepartTime = vesselItem?.leftDock { actualDepartLabel.text = TimeUtils.getTimeOfDay(actualDepartTime) } else { actualDepartLabel.text = "--:--" } if let eta = vesselItem?.eta { etaLabel.text = TimeUtils.getTimeOfDay(eta) } else { etaLabel.text = "--:--" } if let speed = vesselItem?.speed { speedLabel.text = String(speed) } else { speedLabel.text = "" } headinglabel.text = vesselItem?.headText if let updated = vesselItem?.updateTime { updatedLabel.text = TimeUtils.timeAgoSinceDate(date: updated, numericDates: true) } else { updatedLabel.text = "" } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "VesselDetails") } @IBAction func linkAction(_ sender: UIBarButtonItem) { let config = SFSafariViewController.Configuration() config.entersReaderIfAvailable = true let svc = SFSafariViewController(url: URL(string: vesselBaseUrlString + String((vesselItem?.vesselID)!))!, configuration: config) if #available(iOS 10.0, *) { svc.preferredControlTintColor = ThemeManager.currentTheme().secondaryColor svc.preferredBarTintColor = ThemeManager.currentTheme().mainColor } else { svc.view.tintColor = ThemeManager.currentTheme().mainColor } self.present(svc, animated: true, completion: nil) } }
gpl-3.0
da8d2091d85c789e9dbf08f007182204
34.058252
137
0.649405
4.665375
false
false
false
false
mozilla/focus
Blockzilla/FindInPageBar.swift
4
7141
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit protocol FindInPageBarDelegate: class { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) func findInPageDidPressClose(_ findInPage: FindInPageBar) } private struct FindInPageUX { static let ButtonColor = UIColor.white static let MatchCountColor = UIConstants.Photon.Grey10.withAlphaComponent(0.6) static let MatchCountFont = UIConstants.fonts.searchButton static let SearchTextColor = UIColor.white static let SearchTextFont = UIConstants.fonts.searchButton static let TopBorderColor = UIConstants.Photon.Grey80 } class FindInPageBar: UIView { weak var delegate: FindInPageBarDelegate? private let searchText = UITextField() private let matchCountView = UILabel() private let previousButton = UIButton() private let nextButton = UIButton() var currentResult = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } } } var totalResults = 0 { didSet { if totalResults > 500 { matchCountView.text = "\(currentResult)/500+" } else { matchCountView.text = "\(currentResult)/\(totalResults)" } previousButton.isEnabled = totalResults > 1 nextButton.isEnabled = previousButton.isEnabled } } var text: String? { get { return searchText.text } set { searchText.text = newValue didTextChange(searchText) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIConstants.Photon.Grey70 searchText.addTarget(self, action: #selector(didTextChange), for: .editingChanged) searchText.textColor = FindInPageUX.SearchTextColor searchText.font = FindInPageUX.SearchTextFont searchText.autocapitalizationType = .none searchText.autocorrectionType = .no searchText.inputAssistantItem.leadingBarButtonGroups = [] searchText.inputAssistantItem.trailingBarButtonGroups = [] searchText.enablesReturnKeyAutomatically = true searchText.returnKeyType = .search searchText.accessibilityIdentifier = "FindInPage.searchField" searchText.delegate = self addSubview(searchText) matchCountView.textColor = FindInPageUX.MatchCountColor matchCountView.font = FindInPageUX.MatchCountFont matchCountView.isHidden = true matchCountView.accessibilityIdentifier = "FindInPage.matchCount" addSubview(matchCountView) previousButton.setImage(UIImage(named: "find_previous"), for: []) previousButton.setTitleColor(FindInPageUX.ButtonColor, for: []) previousButton.accessibilityLabel = UIConstants.strings.findInPagePreviousLabel previousButton.addTarget(self, action: #selector(didFindPrevious), for: .touchUpInside) previousButton.accessibilityIdentifier = "FindInPage.find_previous" addSubview(previousButton) nextButton.setImage(UIImage(named: "find_next"), for: []) nextButton.setTitleColor(FindInPageUX.ButtonColor, for: []) nextButton.accessibilityLabel = UIConstants.strings.findInPageNextLabel nextButton.addTarget(self, action: #selector(didFindNext), for: .touchUpInside) nextButton.accessibilityIdentifier = "FindInPage.find_next" addSubview(nextButton) let closeButton = UIButton() closeButton.setImage(UIImage(named: "find_close"), for: []) closeButton.setTitleColor(FindInPageUX.ButtonColor, for: []) closeButton.accessibilityLabel = UIConstants.strings.findInPageDoneLabel closeButton.addTarget(self, action: #selector(didPressClose), for: .touchUpInside) closeButton.accessibilityIdentifier = "FindInPage.close" addSubview(closeButton) let topBorder = UIView() topBorder.backgroundColor = FindInPageUX.TopBorderColor addSubview(topBorder) searchText.snp.makeConstraints { make in make.leading.top.bottom.equalTo(self).inset(UIConstants.layout.findInPageSearchTextInsets) } searchText.setContentHuggingPriority(.defaultLow, for: .horizontal) searchText.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) matchCountView.snp.makeConstraints { make in make.leading.equalTo(searchText.snp.trailing) make.centerY.equalTo(self) } matchCountView.setContentHuggingPriority(.defaultHigh, for: .horizontal) matchCountView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) previousButton.snp.makeConstraints { make in make.leading.equalTo(matchCountView.snp.trailing).offset(UIConstants.layout.findInPagePreviousButtonOffset) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } nextButton.snp.makeConstraints { make in make.leading.equalTo(previousButton.snp.trailing) make.size.equalTo(self.snp.height) make.centerY.equalTo(self) } closeButton.snp.makeConstraints { make in make.leading.equalTo(nextButton.snp.trailing) make.size.equalTo(self.snp.height) make.trailing.centerY.equalTo(self) } topBorder.snp.makeConstraints { make in make.height.equalTo(1) make.left.right.top.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult override func becomeFirstResponder() -> Bool { searchText.becomeFirstResponder() return super.becomeFirstResponder() } @objc private func didFindPrevious(_ sender: UIButton) { delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "") } @objc private func didFindNext(_ sender: UIButton) { delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "") } @objc private func didTextChange(_ sender: UITextField) { matchCountView.isHidden = searchText.text?.trimmingCharacters(in: .whitespaces).isEmpty ?? true delegate?.findInPage(self, didTextChange: searchText.text ?? "") } @objc private func didPressClose(_ sender: UIButton) { delegate?.findInPageDidPressClose(self) } } extension FindInPageBar: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.endEditing(true) return true } }
mpl-2.0
eccdd46a529555847a811995b3ee564a
38.236264
119
0.683658
5.321162
false
false
false
false
Knoxantropicen/Focus-iOS
Focus/MainViewController.swift
1
9221
// // MainViewController.swift // Focus // // Created by TianKnox on 2017/4/15. // Copyright © 2017年 TianKnox. All rights reserved. // import UIKit class MainViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var typingArea: UITextView! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var checkButton: UIButton! @IBOutlet weak var plusButton: UIButton! @IBOutlet weak var swipeInstructionLabel: UILabel! public var pushNotification = PushNotification() private let defaults = UserDefaults.standard func setThemeIcon() { settingsButton.setImage(Style.settingsIcon, for: .normal) checkButton.setImage(Style.checkIcon, for: .normal) plusButton.setImage(Style.plusIcon, for: .normal) } func setThemeColor() { view.backgroundColor = Style.mainBackgroundColor typingArea.backgroundColor = Style.mainBackgroundColor typingArea.textColor = Style.mainTextColor mode.setTitleColor(Style.symbolColor, for: .normal) } func resetDefaults() { let defaults = UserDefaults.standard let dictionary = defaults.dictionaryRepresentation() dictionary.keys.forEach { key in defaults.removeObject(forKey: key) } defaults.synchronize() let widgetDefaults = UserDefaults(suiteName: "group.knox.Focuson.extension") let widgetDictionary = widgetDefaults?.dictionaryRepresentation() widgetDictionary?.keys.forEach { key in widgetDefaults?.removeObject(forKey: key) } widgetDefaults?.synchronize() } override func viewDidLoad() { super.viewDidLoad() typingArea.delegate = self // resetDefaults() if UserDefaults.standard.bool(forKey: "LightMode") { Style.themeLight() } else { Style.themeDark() } if UserDefaults.standard.bool(forKey: "EnglishLanguage") { Language.setEnglish() } else { Language.setChinese() } if !UserDefaults.standard.bool(forKey: "initialLaunch") { Style.themeLight() Language.setEnglish() var displayInstructionCount = 0 func displayInstruction() { UIView.animate(withDuration: 1.5, animations: { self.swipeInstructionLabel.alpha = 0.8 }, completion:{(finished : Bool) in if finished { UIView.animate(withDuration: 1.5, animations: { self.swipeInstructionLabel.alpha = 0.0 }, completion:{(finished : Bool) in displayInstructionCount += 1 if displayInstructionCount < 3 { displayInstruction() } }) } }) } displayInstruction() UserDefaults.standard.set(true, forKey: "initialLaunch") } setThemeIcon() setThemeColor() let tapGesture = UITapGestureRecognizer(target: self, action:#selector(MainViewController.hideKeyboard)) view.addGestureRecognizer(tapGesture) if let mainAffairString = UserDefaults.standard.string(forKey: "mainAffairString") { typingArea.text = mainAffairString if (mainAffairString == Language.mainModel) { typingArea.alpha = 0.3 } else { typingArea.alpha = 1 typingArea.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30) } } if MainViewController.isQuestion == UserDefaults.standard.bool(forKey: "mainModeRevBool") { MainViewController.isQuestion = !MainViewController.isQuestion changeMode(mode) } PushNotification.isNotificationEnabled = UserDefaults.standard.bool(forKey: "notificationEnabled") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if defaults.bool(forKey: "outerReplaced") { typingArea.text = defaults.string(forKey: "mainAffairString") if typingArea.text != Language.mainModel { typingArea.alpha = 1 typingArea.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30) } if MainViewController.isQuestion { mode.setTitle("?", for: .normal) } else { mode.setTitle("!", for: .normal) } defaults.set(false, forKey: "outerReplaced") } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) swipeInstructionLabel.alpha = 0.0 } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { textView.alpha = 1 textView.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30) if textView.text == Language.mainModel { textView.text = "" } if text.contains("\n") { hideKeyboard() return false } if textView.text.characters.count + (text.characters.count - range.length) >= 120 { return false } return true } func textViewDidChange(_ textView: UITextView) { defaults.set(textView.text, forKey: "mainAffairString") UserDefaults(suiteName: "group.knox.Focuson.extension")?.set(textView.text, forKey: "mainAffairString") } func hideKeyboard() { if typingArea.text == "" { typingArea.text = Language.mainModel typingArea.alpha = 0.3 typingArea.font = UIFont(name: "HelveticaNeue-UltraLightItalic", size: 30) } defaults.set(typingArea.text, forKey: "mainAffairString") UserDefaults(suiteName: "group.knox.Focuson.extension")?.set(typingArea.text, forKey: "mainAffairString") view.endEditing(true) } @IBOutlet weak var mode: UIButton! static var isQuestion = true @IBAction func changeMode(_ sender: UIButton) { if let mode = sender.currentTitle { if mode == "?" { sender.setTitle("!", for: .normal) MainViewController.isQuestion = false } else { sender.setTitle("?", for: .normal) MainViewController.isQuestion = true } defaults.set(!MainViewController.isQuestion, forKey: "mainModeRevBool") UserDefaults(suiteName: "group.knox.Focuson.extension")?.set(!MainViewController.isQuestion, forKey: "mainModeRevBool") } } @IBOutlet weak var createLabel: UILabel! @IBOutlet weak var finishLabel: UILabel! @IBAction func createAffair(_ sender: UIButton) { if typingArea.text == Language.mainModel { return } let createAffair = DoingTableViewController() createAffair.addAffair(newAffair: typingArea.text, newMode: mode.currentTitle!) typingArea.text = "" // defaults.set(typingArea.text, forKey: "mainAffairString") hideKeyboard() createLabel.text = Language.createAction createLabel.textColor = Style.mainTextColor UIView.animate(withDuration: 1.0, animations: { self.createLabel.alpha = 0.5 }, completion:{(finished : Bool) in if (finished) { UIView.animate(withDuration: 0.5, animations: { self.createLabel.alpha = 0.0 }) } }) } @IBAction func finishAffair(_ sender: UIButton) { if typingArea.text == Language.mainModel { return } let finishAffair = DoneTableViewController() finishAffair.addAffair(newAffair: typingArea.text, newMode: mode.currentTitle!) typingArea.text = "" hideKeyboard() finishLabel.text = Language.finishAction finishLabel.textColor = Style.mainTextColor UIView.animate(withDuration: 1.0, animations: { self.finishLabel.alpha = 0.5 }, completion:{(finished : Bool) in if (finished) { UIView.animate(withDuration: 0.5, animations: { self.finishLabel.alpha = 0.0 }) } }) } @IBAction func helpShowSettings(_ sender: UIButton) { showSettings(sender) } @IBAction func showSettings(_ sender: UIButton) { let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController self.addChildViewController(popOverVC) popOverVC.view.frame = self.view.frame self.view.addSubview(popOverVC.view) popOverVC.didMove(toParentViewController: self) } }
mit
e21ac9e46e87950537d4a8e894535dc9
34.867704
158
0.585485
5.017964
false
false
false
false
dsxNiubility/SXSwiftWeibo
103 - swiftWeibo/103 - swiftWeibo/Classes/UI/Main/SXMainTabBar.swift
1
2206
// // SXMainTabBar.swift // 103 - swiftWeibo // // Created by 董 尚先 on 15/3/5. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import UIKit class SXMainTabBar: UITabBar { var composedButtonClicked:(()->())? override func awakeFromNib() { self.addSubview(composeBtn!) self.backgroundColor = UIColor(patternImage: UIImage(named: "tabbar_background")!) } override func layoutSubviews() { super.layoutSubviews() /// 设置按钮位置 setButtonFrame() } func setButtonFrame(){ let buttonCount = 5 let w = self.bounds.width/CGFloat(buttonCount) let h = self.bounds.height var index = 0 for view in self.subviews { if view is UIControl && !(view is UIButton){ let r = CGRectMake(CGFloat(index) * w, 0, w, h) view.frame = r /// 如果是后两个 就往右边靠 index++ if index == 2 { index++ } // println(index) } } composeBtn!.frame = CGRectMake(0, 0, w, h) composeBtn!.center = CGPointMake(self.center.x, h * 0.5) } /// 创建撰写微博按钮 lazy var composeBtn: UIButton? = { let btn = UIButton() btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) // 添加按钮的监听方法 btn.addTarget(self, action: "clickCompose", forControlEvents: .TouchUpInside) return btn }() func clickCompose(){ print("发微博") if composedButtonClicked != nil{ composedButtonClicked!() } } }
mit
ff0bfe1bb724a5ef05c38a1ea257f682
26.947368
121
0.549906
4.637555
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/UI/PaymentMethod/PXPaymentMethodIconRenderer.swift
1
2146
import UIKit class PXPaymentMethodIconRenderer: NSObject { let RADIUS_DELTA_FROM_ICON_TO_BACKGROUND: CGFloat = 58 func render(component: PXPaymentMethodIconComponent) -> PXPaymentMethodIconView { let pmIconView = PXPaymentMethodIconView() pmIconView.translatesAutoresizingMaskIntoConstraints = false let background = UIView() background.translatesAutoresizingMaskIntoConstraints = false background.backgroundColor = ThemeManager.shared.iconBackgroundColor() pmIconView.paymentMethodIconBackground = background pmIconView.addSubview(pmIconView.paymentMethodIconBackground!) PXLayout.matchWidth(ofView: pmIconView.paymentMethodIconBackground!).isActive = true PXLayout.matchHeight(ofView: pmIconView.paymentMethodIconBackground!).isActive = true PXLayout.centerVertically(view: pmIconView.paymentMethodIconBackground!).isActive = true PXLayout.centerHorizontally(view: pmIconView.paymentMethodIconBackground!).isActive = true let pmIcon = UIImageView() pmIcon.translatesAutoresizingMaskIntoConstraints = false pmIcon.image = component.props.paymentMethodIcon pmIconView.paymentMethodIcon = pmIcon pmIconView.addSubview(pmIconView.paymentMethodIcon!) PXLayout.matchWidth(ofView: pmIconView.paymentMethodIcon!, toView: pmIconView.paymentMethodIconBackground, withPercentage: self.RADIUS_DELTA_FROM_ICON_TO_BACKGROUND).isActive = true PXLayout.matchHeight(ofView: pmIconView.paymentMethodIcon!, toView: pmIconView.paymentMethodIconBackground, withPercentage: self.RADIUS_DELTA_FROM_ICON_TO_BACKGROUND).isActive = true PXLayout.centerVertically(view: pmIconView.paymentMethodIcon!, to: pmIconView.paymentMethodIconBackground).isActive = true PXLayout.centerHorizontally(view: pmIconView.paymentMethodIcon!, to: pmIconView.paymentMethodIconBackground).isActive = true pmIconView.layer.masksToBounds = true return pmIconView } } class PXPaymentMethodIconView: PXBodyView { var paymentMethodIcon: UIImageView? var paymentMethodIconBackground: UIView? }
mit
917beb48933732a75932d42e153e53c7
55.473684
190
0.779124
5.285714
false
false
false
false
UberJason/DateTools
DateToolsSwift/DateTools/Date+Manipulations.swift
1
6167
// // Date+Manipulations.swift // DateToolsTests // // Created by Grayson Webster on 9/28/16. // Copyright © 2016 Matthew York. All rights reserved. // import Foundation /** * Extends the Date class by adding manipulation methods for transforming dates */ public extension Date { static let autoupdatingCurrentCalendar = Calendar.autoupdatingCurrent // MARK: - StartOf /** * Return a date set to the start of a given component. * * - parameter component: The date component (second, minute, hour, day, month, or year) * * - returns: A date retaining the value of the given component and all larger components, * with all smaller components set to their minimum */ func start(of component: Component) -> Date { var newDate = self; if component == .second { newDate.second(self.second) } else if component == .minute { newDate.second(0) } else if component == .hour { newDate.second(0) newDate.minute(0) } else if component == .day { newDate.second(0) newDate.minute(0) newDate.hour(0) } else if component == .month { newDate.second(0) newDate.minute(0) newDate.hour(0) newDate.day(1) } else if component == .year { newDate.second(0) newDate.minute(0) newDate.hour(0) newDate.day(1) newDate.month(1) } return newDate } /** * Return a date set to the end of a given component. * * - parameter component: The date component (second, minute, hour, day, month, or year) * * - returns: A date retaining the value of the given component and all larger components, * with all smaller components set to their maximum */ func end(of component: Component) -> Date { var newDate = self; if component == .second { newDate.second(newDate.second + 1) newDate = newDate - 0.001 } else if component == .minute { newDate.second(60) newDate = newDate - 0.001 } else if component == .hour { newDate.second(60) newDate = newDate - 0.001 newDate.minute(59) } else if component == .day { newDate.second(60) newDate = newDate - 0.001 newDate.minute(59) newDate.hour(23) } else if component == .month { newDate.second(60) newDate = newDate - 0.001 newDate.minute(59) newDate.hour(23) newDate.day(daysInMonth(date: newDate)) } else if component == .year { newDate.second(60) newDate = newDate - 0.001 newDate.minute(59) newDate.hour(23) newDate.month(12) newDate.day(31) } return newDate } func daysInMonth(date: Date) -> Int { let month = date.month if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 { // 31 day month return 31 } else if month == 2 && date.isInLeapYear { // February with leap year return 29 } else if month == 2 && !date.isInLeapYear { // February without leap year return 28 } else { // 30 day month return 30 } } // MARK: - Addition / Subtractions /** * # Add (TimeChunk to Date) * Increase a date by the value of a given `TimeChunk`. * * - parameter chunk: The amount to increase the date by (ex. 2.days, 4.years, etc.) * * - returns: A date with components increased by the values of the * corresponding `TimeChunk` variables */ func add(_ chunk: TimeChunk) -> Date { let calendar = Date.autoupdatingCurrentCalendar var components = DateComponents() components.year = chunk.years components.month = chunk.months components.day = chunk.days + (chunk.weeks*7) components.hour = chunk.hours components.minute = chunk.minutes components.second = chunk.seconds return calendar.date(byAdding: components, to: self)! } /** * # Subtract (TimeChunk from Date) * Decrease a date by the value of a given `TimeChunk`. * * - parameter chunk: The amount to decrease the date by (ex. 2.days, 4.years, etc.) * * - returns: A date with components decreased by the values of the * corresponding `TimeChunk` variables */ func subtract(_ chunk: TimeChunk) -> Date { let calendar = Date.autoupdatingCurrentCalendar var components = DateComponents() components.year = -chunk.years components.month = -chunk.months components.day = -(chunk.days + (chunk.weeks*7)) components.hour = -chunk.hours components.minute = -chunk.minutes components.second = -chunk.seconds return calendar.date(byAdding: components, to: self)! } // MARK: - Operator Overloads /** * Operator overload for adding a `TimeChunk` to a date. */ static func +(leftAddend: Date, rightAddend: TimeChunk) -> Date { return leftAddend.add(rightAddend) } /** * Operator overload for subtracting a `TimeChunk` from a date. */ static func -(minuend: Date, subtrahend: TimeChunk) -> Date { return minuend.subtract(subtrahend) } /** * Operator overload for adding a `TimeInterval` to a date. */ static func +(leftAddend: Date, rightAddend: Int) -> Date { return leftAddend.addingTimeInterval((TimeInterval(rightAddend))) } /** * Operator overload for subtracting a `TimeInterval` from a date. */ static func -(minuend: Date, subtrahend: Int) -> Date { return minuend.addingTimeInterval(-(TimeInterval(subtrahend))) } }
mit
e6f81bc1d170c3d41369148bb72d048b
30.783505
109
0.562926
4.379261
false
false
false
false
liu044100/SmileClock
SmileClock-Example/SmileClock-Example/ClockLayout.swift
1
1191
// // ClockLayout.swift // MustangClock // // Created by ryu-ushin on 12/14/15. // Copyright © 2015 rain. All rights reserved. // import UIKit class ClockLayout: UICollectionViewFlowLayout { let kItemWidth: CGFloat = 150.0 override init() { super.init() self.itemSize = CGSizeMake(kItemWidth, kItemWidth + 50.0); self.scrollDirection = .Vertical self.sectionInset = updateSectionInset() } required init?(coder aDecoder: NSCoder) { super.init() } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { self.sectionInset = updateSectionInset() return true } func updateSectionInset() -> UIEdgeInsets { guard (self.collectionView != nil) else { return UIEdgeInsetsMake(0, 0, 0, 0) } let screenWidth = self.collectionView!.bounds.size.width let i: Int = Int(screenWidth/kItemWidth) let count: CGFloat = CGFloat(i) let space: CGFloat = (screenWidth - count * kItemWidth) / (count+1) self.minimumInteritemSpacing = space - 1.0 return UIEdgeInsetsMake(0, space, 0, space) } }
mit
690322ffbef06ae7b6892d87cf3b81d5
27.333333
84
0.630252
4.456929
false
false
false
false
micolous/metrodroid
native/metrodroid/metrodroid/SubscriptionViewCell.swift
1
2852
// // SubscriptionViewCell.swift // // Copyright 2019 Google // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // import Foundation import UIKit import metrolib class SubscriptionViewCell : UICollectionViewCell { @IBOutlet weak var agencyLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var validityLabel: UILabel! @IBOutlet weak var tripsLabel: UILabel! @IBOutlet weak var extraInfoTable: UITableView! @IBOutlet weak var paxLabel: UILabel! @IBOutlet weak var paxImage: UIImageView! @IBOutlet weak var usedLabel: UILabel! @IBOutlet weak var daysLabel: UILabel! var extraInfoDataSource: ListViewDataSource? func setSubscription(_ formatted: Subscription.Formatted) { agencyLabel?.attributedText = formatted.shortAgencyLabel?.attributed nameLabel?.text = formatted.subscriptionName validityLabel?.attributedText = formatted.validity?.attributed tripsLabel.text = formatted.remainingTrips if let subInfo = formatted.info { extraInfoTable.isHidden = false print("subinfo.size = \(subInfo.count)") extraInfoDataSource = ListViewDataSource(items: subInfo) extraInfoTable.delegate = extraInfoDataSource extraInfoTable.dataSource = extraInfoDataSource extraInfoTable.reloadData() } else { print("no subinfo") extraInfoTable.isHidden = true extraInfoTable.delegate = nil extraInfoTable.dataSource = nil } Utils.renderPax(paxLabel: paxLabel, paxImage: paxImage, pax: Int(formatted.passengerCount)) let subState = formatted.subscriptionState if (subState == Subscription.SubscriptionState.unknown) { usedLabel?.text = nil } else { usedLabel?.text = Utils.localizeString(subState.descriptionRes) } if let remainingDays = formatted.remainingDayCount { daysLabel?.text = Utils.localizePlural(RKt.R.plurals.remaining_day_count, Int(truncating: remainingDays), remainingDays) } else { daysLabel?.text = nil } layer.cornerRadius = 8.0 } }
gpl-3.0
9207d85d88eb0d25e4c9dffa3f307d71
39.742857
99
0.679523
4.745424
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/WebViewEmbedded/WebViewControllerEmbedded.swift
1
3046
// // WebViewControllerEmbedded.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 11/24/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import UIKit import WebKit final class WebViewControllerEmbedded: UIViewController { var urlLoaded = false var url: URL? weak var webView: WKWebView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var navigationBar: UINavigationBar! lazy var activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge) activityIndicator.frame = CGRect(x: 0, y: 0, width: 80, height: 80) activityIndicator.layer.cornerRadius = 10 activityIndicator.backgroundColor = UIColor.black.withAlphaComponent(0.5) activityIndicator.center = view.center view.addSubview(activityIndicator) return activityIndicator }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !urlLoaded { if let url = url?.removingDuplicatedSlashes() { let request = URLRequest(url: url) let webView = WKWebView(frame: containerView.frame) webView.navigationDelegate = self webView.load(request) containerView.addSubview(webView) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "|-0-[view]-0-|", options: [], metrics: nil, views: ["view": webView] ) ) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": webView] ) ) webView.translatesAutoresizingMaskIntoConstraints = false containerView.translatesAutoresizingMaskIntoConstraints = false self.webView = webView self.urlLoaded = true self.activityIndicator.startAnimating() } } } @IBAction func donePressed(_ sender: Any) { self.dismiss(animated: true) } } extension WebViewControllerEmbedded: WKNavigationDelegate { func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { activityIndicator.stopAnimating() activityIndicator.removeFromSuperview() let token = AuthManager.isAuthenticated()?.token ?? "" //swiftlint:disable let authenticationJavaScriptMethod = "Meteor.loginWithToken('\(token)', function() { })" //swiftlint:enable webView.evaluateJavaScript(authenticationJavaScriptMethod) { (_, _) in // Do nothing } } }
mit
a8e6c7198061db74d8edc136e6da6791
32.097826
113
0.625944
5.712946
false
false
false
false
BelledonneCommunications/linphone-iphone
Classes/Swift/Voip/VoipDialog_BASE_973.swift
4
3708
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linphone-iphone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import UIKit class VoipDialog : UIView{ // Layout constants let center_corner_radius = 7.0 let title_margin_top = 20 let button_margin = 20.0 let button_width = 135.0 let button_height = 40.0 let button_radius = 3.0 let button_spacing = 15.0 let center_view_sides_margin = 13.0 let title = StyledLabel(VoipTheme.basic_popup_title) init(message:String, givenButtons:[ButtonAttributes]? = nil) { super.init(frame: .zero) backgroundColor = VoipTheme.voip_translucent_popup_background let centerView = UIView() centerView.backgroundColor = VoipTheme.dark_grey_color.withAlphaComponent(0.8) centerView.layer.cornerRadius = center_corner_radius centerView.clipsToBounds = true addSubview(centerView) title.numberOfLines = 0 centerView.addSubview(title) title.alignParentTop(withMargin:title_margin_top).matchParentSideBorders().done() title.text = message let buttonsView = UIStackView() buttonsView.axis = .horizontal buttonsView.spacing = button_spacing var buttons = givenButtons if (buttons == nil) { // assuming info popup, just putting an ok button let ok = ButtonAttributes(text:VoipTexts.ok, action: {}, isDestructive:false) buttons = [ok] } buttons?.forEach { let b = ButtonWithStateBackgrounds(backgroundStateColors: $0.isDestructive ? VoipTheme.primary_colors_background_gray : VoipTheme.primary_colors_background) b.setTitle($0.text, for: .normal) b.layer.cornerRadius = button_radius b.clipsToBounds = true buttonsView.addArrangedSubview(b) b.applyTitleStyle(VoipTheme.form_button_bold) let action = $0.action b.onClick { self.removeFromSuperview() action() } b.size(w: button_width,h: button_height).done() } centerView.addSubview(buttonsView) buttonsView.alignUnder(view:title,withMargin:button_margin).alignParentBottom(withMargin:button_margin).centerX().done() centerView.matchParentSideBorders(insetedByDx: center_view_sides_margin).center().done() } func show() { VoipDialog.rootVC()?.view.addSubview(self) matchParentDimmensions().done() } private static func rootVC() -> UIViewController? { return PhoneMainView.instance().mainViewController } required init?(coder: NSCoder) { super.init(coder: coder) } static var toastQueue: [String] = [] static func toast(message:String, timeout:CGFloat = 1.5) { if (toastQueue.count > 0) { toastQueue.append(message) return } let alert = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet) rootVC()?.present(alert, animated: true) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeout) { alert.dismiss(animated: true) if (toastQueue.count > 0) { let message = toastQueue.first toastQueue.remove(at: 0) self.toast(message: message!) } } } } struct ButtonAttributes { let text:String let action: (()->Void) let isDestructive: Bool }
gpl-3.0
2f3a92ef89e2baf71a5a31bcd941229b
28.428571
159
0.729234
3.568816
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/NSUserDefaults+WMFExtensions.swift
1
17387
let WMFAppBecomeActiveDateKey = "WMFAppBecomeActiveDateKey" let WMFAppResignActiveDateKey = "WMFAppResignActiveDateKey" let WMFOpenArticleURLKey = "WMFOpenArticleURLKey" let WMFAppSiteKey = "Domain" let WMFSearchURLKey = "WMFSearchURLKey" let WMFMigrateHistoryListKey = "WMFMigrateHistoryListKey" let WMFMigrateToSharedContainerKey = "WMFMigrateToSharedContainerKey" let WMFMigrateSavedPageListKey = "WMFMigrateSavedPageListKey" let WMFMigrateBlackListKey = "WMFMigrateBlackListKey" let WMFMigrateToFixArticleCacheKey = "WMFMigrateToFixArticleCacheKey3" let WMFDidMigrateToGroupKey = "WMFDidMigrateToGroup" let WMFDidMigrateToCoreDataFeedKey = "WMFDidMigrateToCoreDataFeedKey" let WMFMostRecentInTheNewsNotificationDateKey = "WMFMostRecentInTheNewsNotificationDate" let WMFInTheNewsMostRecentDateNotificationCountKey = "WMFInTheNewsMostRecentDateNotificationCount" let WMFDidShowNewsNotificatonInFeedKey = "WMFDidShowNewsNotificatonInFeedKey" let WMFInTheNewsNotificationsEnabled = "WMFInTheNewsNotificationsEnabled" let WMFFeedRefreshDateKey = "WMFFeedRefreshDateKey" let WMFLocationAuthorizedKey = "WMFLocationAuthorizedKey" let WMFPlacesDidPromptForLocationAuthorization = "WMFPlacesDidPromptForLocationAuthorization" let WMFExploreDidPromptForLocationAuthorization = "WMFExploreDidPromptForLocationAuthorization" let WMFPlacesHasAppeared = "WMFPlacesHasAppeared" let WMFAppThemeName = "WMFAppThemeName" let WMFIsImageDimmingEnabled = "WMFIsImageDimmingEnabled" let WMFIsAutomaticTableOpeningEnabled = "WMFIsAutomaticTableOpeningEnabled" let WMFDidShowThemeCardInFeed = "WMFDidShowThemeCardInFeed" let WMFDidShowReadingListCardInFeed = "WMFDidShowReadingListCardInFeed" let WMFDidShowEnableReadingListSyncPanelKey = "WMFDidShowEnableReadingListSyncPanelKey" let WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey = "WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey" let WMFDidShowLimitHitForUnsortedArticlesPanel = "WMFDidShowLimitHitForUnsortedArticlesPanel" let WMFDidShowSyncDisabledPanel = "WMFDidShowSyncDisabledPanel" let WMFDidShowSyncEnabledPanel = "WMFDidShowSyncEnabledPanel" let WMFDidSplitExistingReadingLists = "WMFDidSplitExistingReadingLists" let WMFDefaultTabTypeKey = "WMFDefaultTabTypeKey" //Legacy Keys let WMFOpenArticleTitleKey = "WMFOpenArticleTitleKey" let WMFSearchLanguageKey = "WMFSearchLanguageKey" @objc public enum WMFAppDefaultTabType: Int { case explore case settings } @objc public extension UserDefaults { @objc public class func wmf_userDefaults() -> UserDefaults { #if WMF_NO_APP_GROUP return UserDefaults.standard #else guard let defaults = UserDefaults(suiteName: WMFApplicationGroupIdentifier) else { assertionFailure("Defaults not found!") return UserDefaults.standard } return defaults #endif } @objc public class func wmf_migrateToWMFGroupUserDefaultsIfNecessary() { let newDefaults = self.wmf_userDefaults() let didMigrate = newDefaults.bool(forKey: WMFDidMigrateToGroupKey) if (!didMigrate) { let oldDefaults = UserDefaults.standard let oldDefaultsDictionary = oldDefaults.dictionaryRepresentation() for (key, value) in oldDefaultsDictionary { let lowercaseKey = key.lowercased() if lowercaseKey.hasPrefix("apple") || lowercaseKey.hasPrefix("ns") { continue } newDefaults.set(value, forKey: key) } newDefaults.set(true, forKey: WMFDidMigrateToGroupKey) newDefaults.synchronize() } } @objc public func wmf_dateForKey(_ key: String) -> Date? { return self.object(forKey: key) as? Date } @objc public func wmf_appBecomeActiveDate() -> Date? { return self.wmf_dateForKey(WMFAppBecomeActiveDateKey) } @objc public func wmf_setAppBecomeActiveDate(_ date: Date?) { if let date = date { self.set(date, forKey: WMFAppBecomeActiveDateKey) }else{ self.removeObject(forKey: WMFAppBecomeActiveDateKey) } self.synchronize() } @objc public func wmf_appResignActiveDate() -> Date? { return self.wmf_dateForKey(WMFAppResignActiveDateKey) } @objc public func wmf_setAppResignActiveDate(_ date: Date?) { if let date = date { self.set(date, forKey: WMFAppResignActiveDateKey) }else{ self.removeObject(forKey: WMFAppResignActiveDateKey) } self.synchronize() } @objc public func wmf_setFeedRefreshDate(_ date: Date) { self.set(date, forKey: WMFFeedRefreshDateKey) self.synchronize() } @objc public func wmf_feedRefreshDate() -> Date? { return self.wmf_dateForKey(WMFFeedRefreshDateKey) } @objc public func wmf_setLocationAuthorized(_ authorized: Bool) { self.set(authorized, forKey: WMFLocationAuthorizedKey) self.synchronize() } @objc public var wmf_appTheme: Theme { return Theme.withName(string(forKey: WMFAppThemeName)) ?? Theme.standard } @objc public func wmf_setAppTheme(_ theme: Theme) { set(theme.name, forKey: WMFAppThemeName) synchronize() } @objc public var wmf_isImageDimmingEnabled: Bool { get { return bool(forKey: WMFIsImageDimmingEnabled) } set { set(newValue, forKey: WMFIsImageDimmingEnabled) synchronize() } } @objc public var wmf_isAutomaticTableOpeningEnabled: Bool { get { return bool(forKey: WMFIsAutomaticTableOpeningEnabled) } set { set(newValue, forKey: WMFIsAutomaticTableOpeningEnabled) synchronize() } } @objc public var wmf_didShowThemeCardInFeed: Bool { get { return bool(forKey: WMFDidShowThemeCardInFeed) } set { set(newValue, forKey: WMFDidShowThemeCardInFeed) synchronize() } } @objc public var wmf_didShowReadingListCardInFeed: Bool { get { return bool(forKey: WMFDidShowReadingListCardInFeed) } set { set(newValue, forKey: WMFDidShowReadingListCardInFeed) synchronize() } } @objc public func wmf_locationAuthorized() -> Bool { return self.bool(forKey: WMFLocationAuthorizedKey) } @objc public func wmf_setPlacesHasAppeared(_ hasAppeared: Bool) { self.set(hasAppeared, forKey: WMFPlacesHasAppeared) self.synchronize() } @objc public func wmf_placesHasAppeared() -> Bool { return self.bool(forKey: WMFPlacesHasAppeared) } @objc public func wmf_setPlacesDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFPlacesDidPromptForLocationAuthorization) self.synchronize() } @objc public func wmf_placesDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc public func wmf_setExploreDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFExploreDidPromptForLocationAuthorization) self.synchronize() } @objc public func wmf_exploreDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFExploreDidPromptForLocationAuthorization) } @objc public func wmf_openArticleURL() -> URL? { if let url = self.url(forKey: WMFOpenArticleURLKey) { return url }else if let data = self.data(forKey: WMFOpenArticleTitleKey){ if let title = NSKeyedUnarchiver.unarchiveObject(with: data) as? MWKTitle { self.wmf_setOpenArticleURL(title.mobileURL) return title.mobileURL }else{ return nil } }else{ return nil } } @objc public func wmf_setOpenArticleURL(_ url: URL?) { guard let url = url else{ self.removeObject(forKey: WMFOpenArticleURLKey) self.removeObject(forKey: WMFOpenArticleTitleKey) self.synchronize() return } guard !url.wmf_isNonStandardURL else{ return; } self.set(url, forKey: WMFOpenArticleURLKey) self.synchronize() } @objc public func wmf_setShowSearchLanguageBar(_ enabled: Bool) { self.set(NSNumber(value: enabled as Bool), forKey: "ShowLanguageBar") self.synchronize() } @objc public func wmf_showSearchLanguageBar() -> Bool { if let enabled = self.object(forKey: "ShowLanguageBar") as? NSNumber { return enabled.boolValue }else{ return false } } @objc public func wmf_currentSearchLanguageDomain() -> URL? { if let url = self.url(forKey: WMFSearchURLKey) { return url }else if let language = self.object(forKey: WMFSearchLanguageKey) as? String { let url = NSURL.wmf_URL(withDefaultSiteAndlanguage: language) self.wmf_setCurrentSearchLanguageDomain(url) return url }else{ return nil } } @objc public func wmf_setCurrentSearchLanguageDomain(_ url: URL?) { guard let url = url else{ self.removeObject(forKey: WMFSearchURLKey) self.synchronize() return } guard !url.wmf_isNonStandardURL else{ return; } self.set(url, forKey: WMFSearchURLKey) self.synchronize() } @objc public func wmf_setDidShowWIconPopover(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowWIconPopover") self.synchronize() } @objc public func wmf_didShowWIconPopover() -> Bool { if let enabled = self.object(forKey: "ShowWIconPopover") as? NSNumber { return enabled.boolValue }else{ return false } } @objc public func wmf_setDidShowMoreLanguagesTooltip(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowMoreLanguagesTooltip") self.synchronize() } @objc public func wmf_didShowMoreLanguagesTooltip() -> Bool { if let enabled = self.object(forKey: "ShowMoreLanguagesTooltip") as? NSNumber { return enabled.boolValue }else{ return false } } @objc public func wmf_setTableOfContentsIsVisibleInline(_ visibleInline: Bool) { self.set(NSNumber(value: visibleInline as Bool), forKey: "TableOfContentsIsVisibleInline") self.synchronize() } @objc public func wmf_isTableOfContentsVisibleInline() -> Bool { if let enabled = self.object(forKey: "TableOfContentsIsVisibleInline") as? NSNumber { return enabled.boolValue }else{ return true } } @objc public func wmf_setDidFinishLegacySavedArticleImageMigration(_ didFinish: Bool) { self.set(didFinish, forKey: "DidFinishLegacySavedArticleImageMigration2") self.synchronize() } @objc public func wmf_didFinishLegacySavedArticleImageMigration() -> Bool { return self.bool(forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc public func wmf_setDidMigrateHistoryList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateHistoryListKey) self.synchronize() } @objc public func wmf_didMigrateHistoryList() -> Bool { return self.bool(forKey: WMFMigrateHistoryListKey) } @objc public func wmf_setDidMigrateSavedPageList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateSavedPageListKey) self.synchronize() } @objc public func wmf_didMigrateSavedPageList() -> Bool { return self.bool(forKey: WMFMigrateSavedPageListKey) } @objc public func wmf_setDidMigrateBlackList(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateBlackListKey) self.synchronize() } @objc public func wmf_didMigrateBlackList() -> Bool { return self.bool(forKey: WMFMigrateBlackListKey) } @objc public func wmf_setDidMigrateToFixArticleCache(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateToFixArticleCacheKey) self.synchronize() } @objc public func wmf_didMigrateToFixArticleCache() -> Bool { return self.bool(forKey: WMFMigrateToFixArticleCacheKey) } @objc public func wmf_setDidMigrateToSharedContainer(_ didFinish: Bool) { self.set(didFinish, forKey: WMFMigrateToSharedContainerKey) self.synchronize() } @objc public func wmf_didMigrateToSharedContainer() -> Bool { return self.bool(forKey: WMFMigrateToSharedContainerKey) } @objc public func wmf_setDidMigrateToNewFeed(_ didMigrate: Bool) { self.set(didMigrate, forKey: WMFDidMigrateToCoreDataFeedKey) self.synchronize() } @objc public func wmf_didMigrateToNewFeed() -> Bool { return self.bool(forKey: WMFDidMigrateToCoreDataFeedKey) } @objc public func wmf_mostRecentInTheNewsNotificationDate() -> Date? { return self.wmf_dateForKey(WMFMostRecentInTheNewsNotificationDateKey) } @objc public func wmf_setMostRecentInTheNewsNotificationDate(_ date: Date) { self.set(date, forKey: WMFMostRecentInTheNewsNotificationDateKey) self.synchronize() } @objc public func wmf_inTheNewsMostRecentDateNotificationCount() -> Int { return self.integer(forKey: WMFInTheNewsMostRecentDateNotificationCountKey) } @objc public func wmf_setInTheNewsMostRecentDateNotificationCount(_ count: Int) { self.set(count, forKey: WMFInTheNewsMostRecentDateNotificationCountKey) self.synchronize() } @objc public func wmf_inTheNewsNotificationsEnabled() -> Bool { return self.bool(forKey: WMFInTheNewsNotificationsEnabled) } @objc public func wmf_setInTheNewsNotificationsEnabled(_ enabled: Bool) { self.set(enabled, forKey: WMFInTheNewsNotificationsEnabled) self.synchronize() } @objc public func wmf_setDidShowNewsNotificationCardInFeed(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowNewsNotificatonInFeedKey) self.synchronize() } @objc public func wmf_didShowNewsNotificationCardInFeed() -> Bool { return self.bool(forKey: WMFDidShowNewsNotificatonInFeedKey) } @objc public func wmf_setDidShowEnableReadingListSyncPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowEnableReadingListSyncPanelKey) self.synchronize() } @objc public func wmf_didShowEnableReadingListSyncPanel() -> Bool { return self.bool(forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc public func wmf_setDidShowLoginToSyncSavedArticlesToReadingListPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) self.synchronize() } @objc public func wmf_didShowLoginToSyncSavedArticlesToReadingListPanel() -> Bool { return self.bool(forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc public func wmf_didShowLimitHitForUnsortedArticlesPanel() -> Bool { return self.bool(forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc public func wmf_setDidShowLimitHitForUnsortedArticlesPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) self.synchronize() } @objc public func wmf_didShowSyncDisabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncDisabledPanel) } @objc public func wmf_setDidShowSyncDisabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncDisabledPanel) } @objc public func wmf_didShowSyncEnabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncEnabledPanel) } @objc public func wmf_setDidShowSyncEnabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncEnabledPanel) } @objc public func wmf_didSplitExistingReadingLists() -> Bool { return self.bool(forKey: WMFDidSplitExistingReadingLists) } @objc public func wmf_setDidSplitExistingReadingLists(_ didSplit: Bool) { self.set(didSplit, forKey: WMFDidSplitExistingReadingLists) self.synchronize() } @objc public var defaultTabType: WMFAppDefaultTabType { get { guard let defaultTabType = WMFAppDefaultTabType(rawValue: integer(forKey: WMFDefaultTabTypeKey)) else { let explore = WMFAppDefaultTabType.explore set(explore.rawValue, forKey: WMFDefaultTabTypeKey) synchronize() return explore } return defaultTabType } set { set(newValue.rawValue, forKey: WMFDefaultTabTypeKey) synchronize() } } }
mit
02e12bde4f06d4053f863aee83248a6c
35.147609
119
0.677345
4.608269
false
false
false
false
s-aska/TwitterAPI
TwitterAPI/Client.swift
2
10024
// // Client.swift // Justaway // // Created by Shinichiro Aska on 8/17/15. // Copyright © 2015 Shinichiro Aska. All rights reserved. // import Foundation import OAuthSwift #if os(iOS) import Accounts import Social #endif /** Have the authentication information. It is possible to generate the request. */ public protocol Client { /** It will generate a NSURLRequest object with the authentication header. - parameter method: HTTPMethod - parameter url: API endpoint URL - parameter parameters: API Parameters - returns: NSURLRequest */ func makeRequest(_ method: Method, url: String, parameters: Dictionary<String, String>) -> URLRequest /** It be to storable the Client object How to Restore ```swift let client = ClientDeserializer.deserialize(client.serialize) ``` - returns: String */ var serialize: String { get } } /** Deserialize the Client Instance from String. */ public class ClientDeserializer { /** Create a Client Instance from serialized data. Like to restore it from the saved information Keychain. - parameter string: Getting by Client#serialize - returns: Client */ public class func deserialize(_ string: String) -> Client { #if os(iOS) switch string { case let string where string.hasPrefix(OAuthClient.serializeIdentifier): return OAuthClient(serializedString: string) case let string where string.hasPrefix(AccountClient.serializeIdentifier): return AccountClient(serializedString: string) default: fatalError("invalid serializedString:\(string)") } #else return OAuthClient(serializedString: string) #endif } } public extension Client { /** Create a StreamingRequest Instance. - parameter url: Streaming API endpoint URL. (e.g., https://userstream.twitter.com/1.1/user.json) - parameter parameters: Streaming API Request Parameters (See https://dev.twitter.com/streaming/overview) - returns: StreamingRequest */ public func streaming(_ url: String, parameters: Dictionary<String, String> = [:]) -> StreamingRequest { let method: Method = url == "https://stream.twitter.com/1.1/statuses/filter.json" ? .POST : .GET return StreamingRequest(makeRequest(method, url: url, parameters: parameters)) } /** Create a Request Instance to use to GET Method API. - parameter url: REST API endpoint URL. (e.g., https://api.twitter.com/1.1/statuses/home_timeline.json) - parameter parameters: REST API Request Parameters (See https://dev.twitter.com/rest/public) - returns: RESTRequest */ public func get(_ url: String, parameters: Dictionary<String, String> = [:]) -> Request { return request(.GET, url: url, parameters: parameters) } /** Create a Request Instance to use to POST Method API. - parameter url: REST API endpoint URL. (e.g., https://api.twitter.com/1.1/statuses/update.json) - parameter parameters: REST API Request Parameters (See https://dev.twitter.com/rest/public) - returns: RESTRequest */ public func post(_ url: String, parameters: Dictionary<String, String> = [:]) -> Request { return request(.POST, url: url, parameters: parameters) } /** Create a Request Instance to use to Media Upload API. Media uploads for images are limited to 5MB in file size. MIME-types supported by this endpoint: PNG, JPEG, BMP, WEBP, GIF, Animated GIF See: https://dev.twitter.com/rest/reference/post/media/upload - parameter data: The raw binary file content being uploaded. - returns: RESTRequest */ public func postMedia(_ data: Data) -> Request { let media = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) let url = "https://upload.twitter.com/1.1/media/upload.json" return post(url, parameters: ["media": media]) } /** Create a Request Instance. - parameter method: HTTP Method - parameter url: REST API endpoint URL. (e.g., https://api.twitter.com/1.1/statuses/update.json) - parameter parameters: REST API Request Parameters (See https://dev.twitter.com/rest/public) - returns: RESTRequest */ public func request(_ method: Method, url: String, parameters: Dictionary<String, String>) -> Request { return Request(self, request: makeRequest(method, url: url, parameters: parameters)) } } /** Client to have the authentication information of OAuth */ open class OAuthClient: Client { static var serializeIdentifier = "OAuth" /// Twitter Consumer Key (API Key) open let consumerKey: String /// Twitter Consumer Secret (API Secret) open let consumerSecret: String /// Twitter Credential (AccessToken) open let oAuthCredential: OAuthSwiftCredential open var debugDescription: String { return "[consumerKey: \(consumerKey), consumerSecret: \(consumerSecret), accessToken: \(oAuthCredential.oauthToken), accessTokenSecret: \(oAuthCredential.oauthTokenSecret)]" } /** Create a TwitterAPIClient Instance from OAuth Information. See: https://apps.twitter.com/ - parameter consumerKey: Consumer Key (API Key) - parameter consumerSecret: Consumer Secret (API Secret) - parameter accessToken: Access Token - parameter accessTokenSecret: Access Token Secret */ public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret let credential = OAuthSwiftCredential(consumerKey: consumerKey, consumerSecret: consumerSecret) credential.oauthToken = accessToken credential.oauthTokenSecret = accessTokenSecret self.oAuthCredential = credential } convenience init(serializedString string: String) { let parts = string.components(separatedBy: "\t") self.init(consumerKey: parts[1], consumerSecret: parts[2], accessToken: parts[3], accessTokenSecret: parts[4]) } /** It be to storable the Client object How to Restore ```swift let client = ClientDeserializer.deserialize(client.serialize) ``` - returns: String */ open var serialize: String { return [OAuthClient.serializeIdentifier, consumerKey, consumerSecret, oAuthCredential.oauthToken, oAuthCredential.oauthTokenSecret].joined(separator: "\t") } /** It will generate a NSURLRequest object with the authentication header. - parameter method: HTTPMethod - parameter url: API endpoint URL - parameter parameters: API Parameters - returns: NSURLRequest */ open func makeRequest(_ method: Method, url urlString: String, parameters: Dictionary<String, String>) -> URLRequest { let url = URL(string: urlString)! let authorization = oAuthCredential.authorizationHeader(method: method.oAuthSwiftValue, url: url, parameters: parameters) let headers = ["Authorization": authorization] let request: URLRequest do { request = try OAuthSwiftHTTPRequest.makeRequest(url: url, method: method.oAuthSwiftValue, headers: headers, parameters: parameters, dataEncoding: String.Encoding.utf8) as URLRequest } catch let error as NSError { fatalError("TwitterAPIOAuthClient#request invalid request error:\(error.description)") } catch { fatalError("TwitterAPIOAuthClient#request invalid request unknwon error") } return request } } #if os(iOS) /** Client to have the authentication information of ACAccount */ open class AccountClient: Client { static var serializeIdentifier = "Account" open let identifier: String /// ACAccount open var account: ACAccount { get { if let ac = accountCache { return ac } else { let ac = ACAccountStore().account(withIdentifier: identifier) accountCache = ac return ac! } } } fileprivate var accountCache: ACAccount? open var debugDescription: String { return "[identifier: \(identifier), cache: " + (accountCache != nil ? "exists" : "nil") + "]" } /** Create a Client Instance from ACAccount(Social.framework). - parameter account: ACAccount */ public init(account: ACAccount) { self.accountCache = account self.identifier = account.identifier! as String } init(serializedString string: String) { let parts = string.components(separatedBy: "\t") self.identifier = parts[1] } /** It be to storable the Client object How to Restore ```swift let client = ClientDeserializer.deserialize(client.serialize) ``` - returns: String */ open var serialize: String { return AccountClient.serializeIdentifier + "\t" + (account.identifier! as String) } /** It will generate a NSURLRequest object with the authentication header. - parameter method: HTTPMethod - parameter url: API endpoint URL - parameter parameters: API Parameters - returns: NSURLRequest */ open func makeRequest(_ method: Method, url urlString: String, parameters: Dictionary<String, String>) -> URLRequest { let url = URL(string: urlString)! let socialRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: method.slValue, url: url as URL!, parameters: parameters) socialRequest?.account = account return socialRequest!.preparedURLRequest() } } #endif
mit
88af63bd854557f7679f52604b460c4d
31.022364
181
0.655492
4.867897
false
false
false
false
micchyboy1023/Today
Today Watch App/Today Watch Extension/AddTodayInterfaceController.swift
1
2737
// // AddTodayInterfaceController.swift // Today // // Created by UetaMasamichi on 2016/01/21. // Copyright © 2016年 Masamichi Ueta. All rights reserved. // import WatchKit import WatchConnectivity import Foundation import TodayWatchKit protocol AddTodayInterfaceControllerDelegate: class { func todayDidAdd(_ score: Int) } final class AddTodayInterfaceController: WKInterfaceController { @IBOutlet var scorePicker: WKInterfacePicker! private var session: WCSession! private var score: Int = Today.maxMasterScore weak var delegate: ScoreInterfaceController? override func awake(withContext context: Any?) { super.awake(withContext: context) if WCSession.isSupported() { session = WCSession.default() session.delegate = self session.activate() } delegate = context as? ScoreInterfaceController let pickerItems: [WKPickerItem] = Today.masterScores.map { let pickerItem = WKPickerItem() pickerItem.title = "\($0)" return pickerItem } scorePicker.setItems(pickerItems) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func addToday() { if session.isReachable { let now = Date() session.sendMessage([watchConnectivityActionTypeKey: WatchConnectivityActionType.addToday.rawValue, WatchConnectivityContentType.addedScore.rawValue: score, WatchConnectivityContentType.addedDate.rawValue: now] , replyHandler: { content in var watchData = WatchData() watchData.score = self.score watchData.updatedAt = now //self.delegate?.todayDidAdd(self.score) self.dismiss() }, errorHandler: { error in self.dismiss() }) } else { self.dismiss() } } @IBAction func pickerItemDidChange(_ value: Int) { score = Today.masterScores[value] } } //MARK: - WCSessionDelegate extension AddTodayInterfaceController: WCSessionDelegate { func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } }
mit
104481d0cd71dec73b6210809391376c
29.377778
124
0.598391
5.468
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/QueryAggregation.swift
1
2605
/** * Copyright IBM Corporation 2018 * * 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 /** An aggregation produced by the Discovery service to analyze the input provided. */ public enum QueryAggregation: Decodable { // reference: https://console.bluemix.net/docs/services/discovery/query-reference.html#aggregations case term(Term) case filter(Filter) case nested(Nested) case histogram(Histogram) case timeslice(Timeslice) case topHits(TopHits) case uniqueCount(Calculation) case max(Calculation) case min(Calculation) case average(Calculation) case sum(Calculation) case generic(GenericQueryAggregation) private enum CodingKeys: String, CodingKey { case type = "type" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) guard let type = try container.decodeIfPresent(String.self, forKey: .type) else { // the specification does not identify `type` as a required field, // so we need a generic catch-all in case it is not present self = .generic(try GenericQueryAggregation(from: decoder)) return } switch type { case "term": self = .term(try Term(from: decoder)) case "filter": self = .filter(try Filter(from: decoder)) case "nested": self = .nested(try Nested(from: decoder)) case "histogram": self = .histogram(try Histogram(from: decoder)) case "timeslice": self = .timeslice(try Timeslice(from: decoder)) case "top_hits": self = .topHits(try TopHits(from: decoder)) case "unique_count": self = .uniqueCount(try Calculation(from: decoder)) case "max": self = .max(try Calculation(from: decoder)) case "min": self = .min(try Calculation(from: decoder)) case "average": self = .average(try Calculation(from: decoder)) case "sum": self = .sum(try Calculation(from: decoder)) default: self = .generic(try GenericQueryAggregation(from: decoder)) } } }
mit
a635e02d15ffc228826c6480e7b3cd33
39.076923
103
0.679463
4.249592
false
false
false
false
liuxuan30/SwiftCharts
SwiftCharts/Layers/ChartPointsLineTrackerLayer.swift
1
11558
// // ChartPointsTrackerLayer.swift // swift_charts // // Created by ischuetz on 16/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public struct ChartPointsLineTrackerLayerSettings { let thumbSize: CGFloat let thumbCornerRadius: CGFloat let thumbBorderWidth: CGFloat let thumbBGColor: UIColor let thumbBorderColor: UIColor let infoViewFont: UIFont let infoViewFontColor: UIColor let infoViewSize: CGSize let infoViewCornerRadius: CGFloat public init(thumbSize: CGFloat, thumbCornerRadius: CGFloat = 16, thumbBorderWidth: CGFloat = 4, thumbBorderColor: UIColor = UIColor.blackColor(), thumbBGColor: UIColor = UIColor.whiteColor(), infoViewFont: UIFont, infoViewFontColor: UIColor = UIColor.blackColor(), infoViewSize: CGSize, infoViewCornerRadius: CGFloat) { self.thumbSize = thumbSize self.thumbCornerRadius = thumbCornerRadius self.thumbBorderWidth = thumbBorderWidth self.thumbBGColor = thumbBGColor self.thumbBorderColor = thumbBorderColor self.infoViewFont = infoViewFont self.infoViewFontColor = infoViewFontColor self.infoViewSize = infoViewSize self.infoViewCornerRadius = infoViewCornerRadius } } public class ChartPointsLineTrackerLayer<T: ChartPoint>: ChartPointsLayer<T> { private let lineColor: UIColor private let animDuration: Float private let animDelay: Float private let settings: ChartPointsLineTrackerLayerSettings private lazy var currentPositionLineOverlay: UIView = { let currentPositionLineOverlay = UIView() currentPositionLineOverlay.backgroundColor = UIColor.grayColor() currentPositionLineOverlay.alpha = 0 return currentPositionLineOverlay }() private lazy var thumb: UIView = { let thumb = UIView() thumb.layer.cornerRadius = self.settings.thumbCornerRadius thumb.layer.borderWidth = self.settings.thumbBorderWidth thumb.layer.backgroundColor = UIColor.clearColor().CGColor thumb.layer.borderColor = self.settings.thumbBorderColor.CGColor thumb.alpha = 0 return thumb }() private var currentPositionInfoOverlay: UILabel? private var view: TrackerView? public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], lineColor: UIColor, animDuration: Float, animDelay: Float, settings: ChartPointsLineTrackerLayerSettings) { self.lineColor = lineColor self.animDuration = animDuration self.animDelay = animDelay self.settings = settings super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints) } private func linesIntersection(#line1P1: CGPoint, line1P2: CGPoint, line2P1: CGPoint, line2P2: CGPoint) -> CGPoint? { var resX: CGFloat = CGFloat(FLT_MIN) var resY: CGFloat = CGFloat(FLT_MIN) return self.findLineIntersection(p0X: line1P1.x, p0y: line1P1.y, p1x: line1P2.x, p1y: line1P2.y, p2x: line2P1.x, p2y: line2P1.y, p3x: line2P2.x, p3y: line2P2.y) } // src: http://stackoverflow.com/a/14795484/930450 (modified) private func findLineIntersection(#p0X: CGFloat , p0y: CGFloat, p1x: CGFloat, p1y: CGFloat, p2x: CGFloat, p2y: CGFloat, p3x: CGFloat, p3y: CGFloat) -> CGPoint? { var s02x: CGFloat, s02y: CGFloat, s10x: CGFloat, s10y: CGFloat, s32x: CGFloat, s32y: CGFloat, sNumer: CGFloat, tNumer: CGFloat, denom: CGFloat, t: CGFloat; s10x = p1x - p0X s10y = p1y - p0y s32x = p3x - p2x s32y = p3y - p2y denom = s10x * s32y - s32x * s10y if denom == 0 { return nil // Collinear } var denomPositive: Bool = denom > 0 s02x = p0X - p2x s02y = p0y - p2y sNumer = s10x * s02y - s10y * s02x if (sNumer < 0) == denomPositive { return nil // No collision } tNumer = s32x * s02y - s32y * s02x if (tNumer < 0) == denomPositive { return nil // No collision } if ((sNumer > denom) == denomPositive) || ((tNumer > denom) == denomPositive) { return nil // No collision } // Collision detected t = tNumer / denom let i_x = p0X + (t * s10x) let i_y = p0y + (t * s10y) return CGPoint(x: i_x, y: i_y) } private func createCurrentPositionInfoOverlay(#view: UIView) -> UILabel { var currentPosW: CGFloat = self.settings.infoViewSize.width var currentPosH: CGFloat = self.settings.infoViewSize.height var currentPosX: CGFloat = (view.frame.size.width - currentPosW) / CGFloat(2) var currentPosY: CGFloat = 100 let currentPositionInfoOverlay = UILabel(frame: CGRectMake(currentPosX, currentPosY, currentPosW, currentPosH)) currentPositionInfoOverlay.textColor = self.settings.infoViewFontColor currentPositionInfoOverlay.font = self.settings.infoViewFont currentPositionInfoOverlay.layer.cornerRadius = self.settings.infoViewCornerRadius currentPositionInfoOverlay.layer.borderWidth = 1 currentPositionInfoOverlay.textAlignment = NSTextAlignment.Center currentPositionInfoOverlay.layer.backgroundColor = UIColor.whiteColor().CGColor currentPositionInfoOverlay.layer.borderColor = UIColor.grayColor().CGColor currentPositionInfoOverlay.alpha = 0 return currentPositionInfoOverlay } private func currentPositionInfoOverlay(#view: UIView) -> UILabel { return self.currentPositionInfoOverlay ?? { let currentPositionInfoOverlay = self.createCurrentPositionInfoOverlay(view: view) self.currentPositionInfoOverlay = currentPositionInfoOverlay return currentPositionInfoOverlay }() } private func updateTrackerLineOnValidState(#updateFunc: (view: UIView) -> ()) { if !self.chartPointsModels.isEmpty { if let view = self.view { updateFunc(view: view) } } } private func updateTrackerLine(#touchPoint: CGPoint) { self.updateTrackerLineOnValidState{(view) in let touchlineP1 = CGPointMake(touchPoint.x, 0) let touchlineP2 = CGPointMake(touchPoint.x, view.frame.size.height) var intersections: [CGPoint] = [] for i in 0..<(self.chartPointsModels.count - 1) { let m1 = self.chartPointsModels[i] let m2 = self.chartPointsModels[i + 1] if let intersection = self.linesIntersection(line1P1: touchlineP1, line1P2: touchlineP2, line2P1: m1.screenLoc, line2P2: m2.screenLoc) { intersections.append(intersection) } } // Select point with smallest distance to touch point. // If there's only one intersection, returns intersection. If there's no intersection returns nil. var intersectionMaybe: CGPoint? = { var minDistancePoint: (distance: Float, point: CGPoint?) = (MAXFLOAT, nil) for intersection in intersections { let distance = hypotf(Float(intersection.x - touchPoint.x), Float(intersection.y - touchPoint.y)) if distance < minDistancePoint.0 { minDistancePoint = (distance, intersection) } } return minDistancePoint.point }() if let intersection = intersectionMaybe { if self.currentPositionInfoOverlay?.superview == nil { view.addSubview(self.currentPositionLineOverlay) view.addSubview(self.currentPositionInfoOverlay(view: view)) view.addSubview(self.thumb) } UIView.animateWithDuration(0.3, animations: { () -> Void in self.currentPositionLineOverlay.alpha = 1 self.currentPositionInfoOverlay(view: view).alpha = 1 self.thumb.alpha = 1 }, completion: { (Bool) -> Void in }) var w: CGFloat = self.settings.thumbSize var h: CGFloat = self.settings.thumbSize self.currentPositionLineOverlay.frame = CGRectMake(intersection.x, 0, 1, view.frame.size.height) self.thumb.frame = CGRectMake(intersection.x - w/2, intersection.y - h/2, w, h) func createTmpChartPoint(firstModel: ChartPointLayerModel<T>, secondModel: ChartPointLayerModel<T>) -> ChartPoint { let p1 = firstModel.chartPoint let p2 = secondModel.chartPoint // calculate x scalar let pxXDiff = secondModel.screenLoc.x - firstModel.screenLoc.x let scalarXDiff = p2.x.scalar - p1.x.scalar let factorX = scalarXDiff / pxXDiff let currentXPx = intersection.x - firstModel.screenLoc.x let currentXScalar = currentXPx * factorX + p1.x.scalar // calculate y scalar let pxYDiff = fabs(secondModel.screenLoc.y - firstModel.screenLoc.y); let scalarYDiff = p2.y.scalar - p1.y.scalar; let factorY = scalarYDiff / pxYDiff let currentYPx = fabs(intersection.y - firstModel.screenLoc.y) let currentYScalar = currentYPx * factorY + p1.y.scalar let x = firstModel.chartPoint.x.copy(currentXScalar) let y = secondModel.chartPoint.y.copy(currentYScalar) let chartPoint = T(x: x, y: y) return chartPoint } if self.chartPointsModels.count > 1 { let first = self.chartPointsModels[0] let second = self.chartPointsModels[1] self.currentPositionInfoOverlay(view: view).text = "Pos: \(createTmpChartPoint(first, second).text)" } } } } override func display(#chart: Chart) { let view = TrackerView(frame: chart.bounds, updateFunc: {[weak self] location in self?.updateTrackerLine(touchPoint: location) }) view.userInteractionEnabled = true chart.addSubview(view) self.view = view } } private class TrackerView: UIView { let updateFunc: ((CGPoint) -> ())? init(frame: CGRect, updateFunc: (CGPoint) -> ()) { self.updateFunc = updateFunc super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = event.allTouches()?.first! as! UITouch let location = touch.locationInView(self) self.updateFunc?(location) } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = event.allTouches()?.first! as! UITouch let location = touch.locationInView(self) self.updateFunc?(location) } }
apache-2.0
7c7a8b6643db5b4de62376c9901a0222
41.966543
323
0.615245
4.557571
false
false
false
false
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Home/Source/LBXScanWrapper.swift
1
23037
// // LBXScanWrapper.swift // swiftScan https://github.com/MxABC/swiftScan // // Created by lbxia on 15/12/10. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit import AVFoundation public struct LBXScanResult { //码内容 public var strScanned:String? = "" //扫描图像 public var imgScanned:UIImage? //码的类型 public var strBarCodeType:String? = "" //码在图像中的位置 public var arrayCorner:[AnyObject]? public init(str:String?,img:UIImage?,barCodeType:String?,corner:[AnyObject]?) { self.strScanned = str self.imgScanned = img self.strBarCodeType = barCodeType self.arrayCorner = corner } } open class LBXScanWrapper: NSObject,AVCaptureMetadataOutputObjectsDelegate { let device:AVCaptureDevice? = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo); var input:AVCaptureDeviceInput? var output:AVCaptureMetadataOutput let session = AVCaptureSession() var previewLayer:AVCaptureVideoPreviewLayer? var stillImageOutput:AVCaptureStillImageOutput? //存储返回结果 var arrayResult:[LBXScanResult] = []; //扫码结果返回block var successBlock:([LBXScanResult]) -> Void //是否需要拍照 var isNeedCaptureImage:Bool //当前扫码结果是否处理 var isNeedScanResult:Bool = true /** 初始化设备 - parameter videoPreView: 视频显示UIView - parameter objType: 识别码的类型,缺省值 QR二维码 - parameter isCaptureImg: 识别后是否采集当前照片 - parameter cropRect: 识别区域 - parameter success: 返回识别信息 - returns: */ init( videoPreView:UIView,objType:[String] = [AVMetadataObjectTypeQRCode],isCaptureImg:Bool,cropRect:CGRect=CGRect.zero,success:@escaping ( ([LBXScanResult]) -> Void) ) { do{ input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { print("AVCaptureDeviceInput(): \(error)") } successBlock = success // Output output = AVCaptureMetadataOutput() isNeedCaptureImage = isCaptureImg stillImageOutput = AVCaptureStillImageOutput(); super.init() if device == nil { return } if session.canAddInput(input) { session.addInput(input) } if session.canAddOutput(output) { session.addOutput(output) } if session.canAddOutput(stillImageOutput) { session.addOutput(stillImageOutput) } let outputSettings:Dictionary = [AVVideoCodecJPEG:AVVideoCodecKey] stillImageOutput?.outputSettings = outputSettings session.sessionPreset = AVCaptureSessionPresetHigh //参数设置 output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) output.metadataObjectTypes = objType // output.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code] if !cropRect.equalTo(CGRect.zero) { //启动相机后,直接修改该参数无效 output.rectOfInterest = cropRect } previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill var frame:CGRect = videoPreView.frame frame.origin = CGPoint.zero previewLayer?.frame = frame videoPreView.layer .insertSublayer(previewLayer!, at: 0) if ( device!.isFocusPointOfInterestSupported && device!.isFocusModeSupported(AVCaptureFocusMode.continuousAutoFocus) ) { do { try input?.device.lockForConfiguration() input?.device.focusMode = AVCaptureFocusMode.continuousAutoFocus input?.device.unlockForConfiguration() } catch let error as NSError { print("device.lockForConfiguration(): \(error)") } } } func start() { if !session.isRunning { isNeedScanResult = true if Platform.isSimulator { //模拟器 self.showInfo(info: "相机不可用") print("isSimulator") } else { //真机 session.startRunning() } } } func stop() { if session.isRunning { isNeedScanResult = false if Platform.isSimulator { //模拟器 self.showInfo(info: "相机不可用") print("isSimulator") } else { //真机 session.stopRunning() } } } open func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { if !isNeedScanResult { //上一帧处理中 return } isNeedScanResult = false arrayResult.removeAll() //识别扫码类型 for current:Any in metadataObjects { if (current as AnyObject).isKind(of: AVMetadataMachineReadableCodeObject.self) { let code = current as! AVMetadataMachineReadableCodeObject //码类型 let codeType = code.type print("code type:%@",codeType) //码内容 let codeContent = code.stringValue print("code string:%@",codeContent) //4个字典,分别 左上角-右上角-右下角-左下角的 坐标百分百,可以使用这个比例抠出码的图像 // let arrayRatio = code.corners arrayResult.append(LBXScanResult(str: codeContent, img: UIImage(), barCodeType: codeType,corner: code.corners as [AnyObject]?)) } } if arrayResult.count > 0 { if isNeedCaptureImage { captureImage() } else { stop() successBlock(arrayResult) } } else { isNeedScanResult = true } } //MARK: ----拍照 open func captureImage() { let stillImageConnection:AVCaptureConnection? = connectionWithMediaType(mediaType: AVMediaTypeVideo, connections: (stillImageOutput?.connections)! as [AnyObject]) stillImageOutput?.captureStillImageAsynchronously(from: stillImageConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in self.stop() if imageDataSampleBuffer != nil { let imageData: Data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) as Data let scanImg:UIImage? = UIImage(data: imageData) for idx in 0...self.arrayResult.count-1 { self.arrayResult[idx].imgScanned = scanImg } } self.successBlock(self.arrayResult) }) } open func connectionWithMediaType(mediaType:String,connections:[AnyObject]) -> AVCaptureConnection? { for connection:AnyObject in connections { let connectionTmp:AVCaptureConnection = connection as! AVCaptureConnection for port:Any in connectionTmp.inputPorts { if (port as AnyObject).isKind(of: AVCaptureInputPort.self) { let portTmp:AVCaptureInputPort = port as! AVCaptureInputPort if portTmp.mediaType == mediaType { return connectionTmp } } } } return nil } //MARK:切换识别区域 open func changeScanRect(cropRect:CGRect) { //待测试,不知道是否有效 stop() output.rectOfInterest = cropRect start() } //MARK: 切换识别码的类型 open func changeScanType(objType:[String]) { //待测试中途修改是否有效 output.metadataObjectTypes = objType } open func isGetFlash()->Bool { if (device != nil && device!.hasFlash && device!.hasTorch) { return true } return false } /** 打开或关闭闪关灯 - parameter torch: true:打开闪关灯 false:关闭闪光灯 */ open func setTorch(torch:Bool) { if isGetFlash() { do { try input?.device.lockForConfiguration() input?.device.torchMode = torch ? AVCaptureTorchMode.on : AVCaptureTorchMode.off input?.device.unlockForConfiguration() } catch let error as NSError { print("device.lockForConfiguration(): \(error)") } } } /** ------闪光灯打开或关闭 */ open func changeTorch() { if isGetFlash() { do { try input?.device.lockForConfiguration() var torch = false if input?.device.torchMode == AVCaptureTorchMode.on { torch = false } else if input?.device.torchMode == AVCaptureTorchMode.off { torch = true } input?.device.torchMode = torch ? AVCaptureTorchMode.on : AVCaptureTorchMode.off input?.device.unlockForConfiguration() } catch let error as NSError { print("device.lockForConfiguration(): \(error)") } } } //MARK: ------获取系统默认支持的码的类型 static func defaultMetaDataObjectTypes() ->[String] { var types = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode, ]; //if #available(iOS 8.0, *) types.append(AVMetadataObjectTypeInterleaved2of5Code) types.append(AVMetadataObjectTypeITF14Code) types.append(AVMetadataObjectTypeDataMatrixCode) types.append(AVMetadataObjectTypeInterleaved2of5Code) types.append(AVMetadataObjectTypeITF14Code) types.append(AVMetadataObjectTypeDataMatrixCode) return types; } static func isSysIos8Later()->Bool { // return Float(UIDevice.currentDevice().systemVersion) >= 8.0 ? true:false return floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_0 } /** 识别二维码码图像 - parameter image: 二维码图像 - returns: 返回识别结果 */ static open func recognizeQRImage(image:UIImage) ->[LBXScanResult] { var returnResult:[LBXScanResult]=[] if LBXScanWrapper.isSysIos8Later() { //if #available(iOS 8.0, *) let detector:CIDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])! let img = CIImage(cgImage: (image.cgImage)!) let features:[CIFeature]? = detector.features(in: img, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh]) if( features != nil && (features?.count)! > 0) { let feature = features![0] if feature.isKind(of: CIQRCodeFeature.self) { let featureTmp:CIQRCodeFeature = feature as! CIQRCodeFeature let scanResult = featureTmp.messageString let result = LBXScanResult(str: scanResult, img: image, barCodeType: AVMetadataObjectTypeQRCode,corner: nil) returnResult.append(result) } } } return returnResult } //MARK: -- - 生成二维码,背景色及二维码颜色设置 static open func createCode( codeType:String, codeString:String, size:CGSize,qrColor:UIColor,bkColor:UIColor )->UIImage? { //if #available(iOS 8.0, *) let stringData = codeString.data(using: String.Encoding.utf8) //系统自带能生成的码 // CIAztecCodeGenerator // CICode128BarcodeGenerator // CIPDF417BarcodeGenerator // CIQRCodeGenerator let qrFilter = CIFilter(name: codeType) qrFilter?.setValue(stringData, forKey: "inputMessage") qrFilter?.setValue("H", forKey: "inputCorrectionLevel") //上色 let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage":qrFilter!.outputImage!,"inputColor0":CIColor(cgColor: qrColor.cgColor),"inputColor1":CIColor(cgColor: bkColor.cgColor)]) let qrImage = colorFilter!.outputImage!; //绘制 let cgImage = CIContext().createCGImage(qrImage, from: qrImage.extent)! UIGraphicsBeginImageContext(size); let context = UIGraphicsGetCurrentContext()!; context.interpolationQuality = CGInterpolationQuality.none; context.scaleBy(x: 1.0, y: -1.0); context.draw(cgImage, in: context.boundingBoxOfClipPath) let codeImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return codeImage } static open func createCode128( codeString:String, size:CGSize,qrColor:UIColor,bkColor:UIColor )->UIImage? { let stringData = codeString.data(using: String.Encoding.utf8) //系统自带能生成的码 // CIAztecCodeGenerator 二维码 // CICode128BarcodeGenerator 条形码 // CIPDF417BarcodeGenerator // CIQRCodeGenerator 二维码 let qrFilter = CIFilter(name: "CICode128BarcodeGenerator") qrFilter?.setDefaults() qrFilter?.setValue(stringData, forKey: "inputMessage") let outputImage:CIImage? = qrFilter?.outputImage let context = CIContext() let cgImage = context.createCGImage(outputImage!, from: outputImage!.extent) let image = UIImage(cgImage: cgImage!, scale: 1.0, orientation: UIImageOrientation.up) // Resize without interpolating let scaleRate:CGFloat = 20.0 let resized = resizeImage(image: image, quality: CGInterpolationQuality.none, rate: scaleRate) return resized; } //MARK:根据扫描结果,获取图像中得二维码区域图像(如果相机拍摄角度故意很倾斜,获取的图像效果很差) static func getConcreteCodeImage(srcCodeImage:UIImage,codeResult:LBXScanResult)->UIImage? { let rect:CGRect = getConcreteCodeRectFromImage(srcCodeImage: srcCodeImage, codeResult: codeResult) if rect.isEmpty { return nil } let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect) if img != nil { let imgRotation = imageRotation(image: img!, orientation: UIImageOrientation.right) return imgRotation } return nil } //根据二维码的区域截取二维码区域图像 static open func getConcreteCodeImage(srcCodeImage:UIImage,rect:CGRect)->UIImage? { if rect.isEmpty { return nil } let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect) if img != nil { let imgRotation = imageRotation(image: img!, orientation: UIImageOrientation.right) return imgRotation } return nil } //获取二维码的图像区域 static open func getConcreteCodeRectFromImage(srcCodeImage:UIImage,codeResult:LBXScanResult)->CGRect { if (codeResult.arrayCorner == nil || (codeResult.arrayCorner?.count)! < 4 ) { return CGRect.zero } let corner:[[String:Float]] = codeResult.arrayCorner as! [[String:Float]] let dicTopLeft = corner[0] let dicTopRight = corner[1] let dicBottomRight = corner[2] let dicBottomLeft = corner[3] let xLeftTopRatio:Float = dicTopLeft["X"]! let yLeftTopRatio:Float = dicTopLeft["Y"]! let xRightTopRatio:Float = dicTopRight["X"]! let yRightTopRatio:Float = dicTopRight["Y"]! let xBottomRightRatio:Float = dicBottomRight["X"]! let yBottomRightRatio:Float = dicBottomRight["Y"]! let xLeftBottomRatio:Float = dicBottomLeft["X"]! let yLeftBottomRatio:Float = dicBottomLeft["Y"]! //由于截图只能矩形,所以截图不规则四边形的最大外围 let xMinLeft = CGFloat( min(xLeftTopRatio, xLeftBottomRatio) ) let xMaxRight = CGFloat( max(xRightTopRatio, xBottomRightRatio) ) let yMinTop = CGFloat( min(yLeftTopRatio, yRightTopRatio) ) let yMaxBottom = CGFloat ( max(yLeftBottomRatio, yBottomRightRatio) ) let imgW = srcCodeImage.size.width let imgH = srcCodeImage.size.height //宽高反过来计算 let rect = CGRect(x: xMinLeft * imgH, y: yMinTop*imgW, width: (xMaxRight-xMinLeft)*imgH, height: (yMaxBottom-yMinTop)*imgW) return rect } //MARK: ----图像处理 /** @brief 图像中间加logo图片 @param srcImg 原图像 @param LogoImage logo图像 @param logoSize logo图像尺寸 @return 加Logo的图像 */ static open func addImageLogo(srcImg:UIImage,logoImg:UIImage,logoSize:CGSize )->UIImage { UIGraphicsBeginImageContext(srcImg.size); srcImg.draw(in: CGRect(x: 0, y: 0, width: srcImg.size.width, height: srcImg.size.height)) let rect = CGRect(x: srcImg.size.width/2 - logoSize.width/2, y: srcImg.size.height/2-logoSize.height/2, width:logoSize.width, height: logoSize.height); logoImg.draw(in: rect) let resultingImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultingImage!; } //图像缩放 static func resizeImage(image:UIImage,quality:CGInterpolationQuality,rate:CGFloat)->UIImage? { var resized:UIImage?; let width = image.size.width * rate; let height = image.size.height * rate; UIGraphicsBeginImageContext(CGSize(width: width, height: height)); let context = UIGraphicsGetCurrentContext(); context!.interpolationQuality = quality; image.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) resized = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resized; } //图像裁剪 static func imageByCroppingWithStyle(srcImg:UIImage,rect:CGRect)->UIImage? { let imageRef = srcImg.cgImage let imagePartRef = imageRef!.cropping(to: rect) let cropImage = UIImage(cgImage: imagePartRef!) return cropImage } //图像旋转 static func imageRotation(image:UIImage,orientation:UIImageOrientation)->UIImage { var rotate:Double = 0.0; var rect:CGRect; var translateX:CGFloat = 0.0; var translateY:CGFloat = 0.0; var scaleX:CGFloat = 1.0; var scaleY:CGFloat = 1.0; switch (orientation) { case UIImageOrientation.left: rotate = M_PI_2; rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width); translateX = 0; translateY = -rect.size.width; scaleY = rect.size.width/rect.size.height; scaleX = rect.size.height/rect.size.width; break; case UIImageOrientation.right: rotate = 3 * M_PI_2; rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width); translateX = -rect.size.height; translateY = 0; scaleY = rect.size.width/rect.size.height; scaleX = rect.size.height/rect.size.width; break; case UIImageOrientation.down: rotate = M_PI; rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height); translateX = -rect.size.width; translateY = -rect.size.height; break; default: rotate = 0.0; rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height); translateX = 0; translateY = 0; break; } UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext()!; //做CTM变换 context.translateBy(x: 0.0, y: rect.size.height); context.scaleBy(x: 1.0, y: -1.0); context.rotate(by: CGFloat(rotate)); context.translateBy(x: translateX, y: translateY); context.scaleBy(x: scaleX, y: scaleY); //绘制图片 context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)) let newPic = UIGraphicsGetImageFromCurrentImageContext(); return newPic!; } deinit { print("LBXScanWrapper deinit") } }
mit
7390786a5335002da30ea0daeb35b727
30.366477
212
0.564985
4.999321
false
false
false
false
parkboo/ios-charts
Charts/Classes/Charts/BarLineChartViewBase.swift
1
66289
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, BarLineScatterCandleBubbleChartDataProvider, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// Sets the minimum offset (padding) around the chart, defaults to 10 public var minOffset = CGFloat(10.0) /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: UITapGestureRecognizer! internal var _doubleTapGestureRecognizer: UITapGestureRecognizer! #if !os(tvOS) internal var _pinchGestureRecognizer: UIPinchGestureRecognizer! #endif internal var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .Left) _rightAxis = ChartYAxis(position: .Right) _xAxis = ChartXAxis() _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) _highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")) _doubleTapGestureRecognizer.numberOfTapsRequired = 2 _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled _panGestureRecognizer.enabled = _dragEnabled #if !os(tvOS) _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")) _pinchGestureRecognizer.delegate = self self.addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let optionalContext = UIGraphicsGetCurrentContext() guard let context = optionalContext else { return } calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context) CGContextClipToRect(context, _viewPortHandler.contentRect) if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) // parkboo 151012 line chart의 dot가 앞에 그려지는 현상 방지! 밑에서 위로 옮겨옴 -> 160121 다시 원복 // renderer!.drawExtras(context: context) renderer?.drawData(context: context) if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHighlight) } // Removes clipping rectangle CGContextRestoreGState(context) renderer!.drawExtras(context: context) _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } var minLeft = _data.getYMin(.Left) var maxLeft = _data.getYMax(.Left) var minRight = _data.getYMin(.Right) var maxRight = _data.getYMax(.Right) let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)) let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)) // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0 if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0 } } if (rightRange == 0.0) { maxRight = maxRight + 1.0 if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0 } } let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop) let topSpaceRight = rightRange * Double(_rightAxis.spaceTop) let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom) let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom) _chartXMax = Double(_data.xVals.count - 1) _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) // Consider sticking one of the edges of the axis to zero (0.0) if _leftAxis.isStartAtZeroEnabled { if minLeft < 0.0 && maxLeft < 0.0 { // If the values are all negative, let's stay in the negative zone _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = 0.0 } else if minLeft >= 0.0 { // We have positive values only, stay in the positive zone _leftAxis.axisMinimum = 0.0 _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } } else { // Use the values as they are _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft) _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft) } if _rightAxis.isStartAtZeroEnabled { if minRight < 0.0 && maxRight < 0.0 { // If the values are all negative, let's stay in the negative zone _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = 0.0 } else if minRight >= 0.0 { // We have positive values only, stay in the positive zone _rightAxis.axisMinimum = 0.0 _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } } else { _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight) _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight) } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum) _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum) } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled) { let xlabelheight = xAxis.labelRotatedHeight + xAxis.yOffset // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelRotatedWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(e.xIndex) var yPos = CGFloat(e.value) if (self.isKindOfClass(BarChartView)) { let bd = _data as! BarChartData let space = bd.groupSpace let setCount = _data.dataSetCount let i = e.xIndex if self is HorizontalBarChartView { // calculate the x-position, depending on datasetcount let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 yPos = y if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { xPos = CGFloat(highlight.range!.to) } else { xPos = CGFloat(e.value) } } } else { let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 xPos = x if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { yPos = CGFloat(highlight.range!.to) } else { yPos = CGFloat(e.value) } } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY) getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context context: CGContext) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context) } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor) CGContextFillRect(context, _viewPortHandler.contentRect) } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth) CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextStrokeRect(context, _viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context) } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.Both private var _closestDataSetToTouch: ChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: UIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if !self.isHighLightPerTapEnabled { return } let h = getHighlightByTouchPoint(recognizer.locationInView(self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .Both } else { let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x) let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y) if (x > y) { _gestureScaleAxis = .X } else { _gestureScaleAxis = .Y } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == UIGestureRecognizerState.Changed) { let isZoomingOut = (recognizer.scale < 1) var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX var canZoomMoreY = isZoomingOut ? _viewPortHandler.canZoomOutMoreY : _viewPortHandler.canZoomInMoreY if (_isScaling) { canZoomMoreX = canZoomMoreX && _scaleXEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .X); canZoomMoreY = canZoomMoreY && _scaleYEnabled && (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y); if canZoomMoreX || canZoomMoreY { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = canZoomMoreX ? recognizer.scale : 1.0 let scaleY = canZoomMoreY ? recognizer.scale : 1.0 var matrix = CGAffineTransformMakeTranslation(location.x, location.y) matrix = CGAffineTransformScale(matrix, scaleX, scaleY) matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y) matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.scale = 1.0 } } } #endif @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0) { stopDeceleration() if _dataNotSet { // If we have no data, we have nothing to pan and no data to highlight return; } // If drag is enabled and we are in a position where there's something to drag: // * If we're zoomed in, then obviously we have something to drag. // * If we have a drag offset - we always have something to drag if self.isDragEnabled && (!self.hasNoDragOffset || !self.isFullyZoomedOut) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)) let translation = recognizer.translationInView(self) let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if (didUserDrag && !performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false } } _lastPanPoint = recognizer.translationInView(self) } else if self.isHighlightPerDragEnabled { // We will only handle highlights on UIGestureRecognizerState.Changed _isDragging = false } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { let originalTranslation = recognizer.translationInView(self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (isHighlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocityInView(self) _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true _outerScrollView = nil } } } private func performPanChange(var translation translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y) matrix = CGAffineTransformConcat(originalMatrix, matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } if (gestureRecognizer == _panGestureRecognizer) { if _dataNotSet || !_dragEnabled || (self.hasNoDragOffset && self.isFullyZoomedOut && !self.isHighlightPerDragEnabled) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)) { return false } } #endif } return true } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { #if !os(tvOS) if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true } #endif if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView)) { scrollView = scrollView?.superview } // If there is two scrollview together, we pick the superview of the inner scrollview. // In the case of UITableViewWrepperView, the superview will be UITableView if let superViewOfScrollView = scrollView?.superview where superViewOfScrollView.isKindOfClass(UIScrollView) { scrollView = superViewOfScrollView } var foundScrollView = scrollView as? UIScrollView if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: UIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.gestureRecognizers! { if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. public func zoomIn() { let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. public func zoomOut() { let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMaximum(maxXRange: CGFloat) { let xScale = _deltaX / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMinimum(minXRange: CGFloat) { let xScale = _deltaX / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = _deltaX / minXRange let minScale = _deltaX / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. /// This also refreshes the chart by calling setNeedsDisplay(). public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0) getTransformer(.Left).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }) } } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }) } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// This will move the center of the current viewport to the specified x-index and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled } } } /// **default**: true /// - returns: true if zooming via double-tap is enabled false if not. public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `UIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled } /// **default**: true /// - returns: true if drawing the grid background is enabled, false if not. public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled } /// **default**: false /// - returns: true if drawing the borders rectangle is enabled, false if not. public var isDrawBordersEnabled: Bool { return drawBordersEnabled } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { print("Can't select by touch. No data set.", terminator: "\n") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleBubbleChartDataSet! } return nil } /// - returns: the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis } else { return _rightAxis } } /// - returns: the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled simultaneously with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// **default**: false /// - returns: true if pinch-zoom is enabled, false if not public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer public var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer public var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer public var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } public override var chartYMax: Double { return max(leftAxis.axisMaximum, rightAxis.axisMaximum) } public override var chartYMin: Double { return min(leftAxis.axisMinimum, rightAxis.axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes public var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// **default**: false /// - returns: true if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; } /// Sets a minimum width to the specified y axis. public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } // MARK: - BarLineScatterCandleBubbleChartDataProvider /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } public func isInverted(axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(round(pt.x + 1.0)) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (_data != nil && Int(round(pt.x)) >= _data.xValCount) ? _data.xValCount - 1 : Int(round(pt.x)) } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { internal override init() { } internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, dataProvider: LineChartDataProvider) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if let data = dataProvider.data { if !dataProvider.getAxis(dataSet.axisDependency).isStartAtZeroEnabled { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = dataProvider.chartYMax } if (data.yMin < 0.0) { min = 0.0 } else { min = dataProvider.chartYMin } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } } return fillMin } internal func getCubicFillLinePosition(dataSet dataSet: CubicLineChartDataSet, dataProvider: CubicLineChartDataProvider) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if let data = dataProvider.data { if !dataProvider.getAxis(dataSet.axisDependency).isStartAtZeroEnabled { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = dataProvider.chartYMax } if (data.yMin < 0.0) { min = 0.0 } else { min = dataProvider.chartYMin } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } } return fillMin } }
apache-2.0
d2f57c27ec7e7f6474e444c48dd4fb77
35.336259
238
0.571081
5.655823
false
false
false
false
noppoMan/aws-sdk-swift
scripts/create-jazzy-yaml.swift
1
1439
#!/usr/bin/env swift sh //===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Files // JohnSundell/Files import Stencil // soto-project/Stencil class GenerateProcess { let environment: Environment let fsLoader: FileSystemLoader init() { self.fsLoader = FileSystemLoader(paths: ["./scripts/templates/create-jazzy-yaml"]) self.environment = Environment(loader: self.fsLoader) } func run() throws { let currentFolder = try Folder(path: ".") let sourceKittenFolder = try Folder(path: "./sourcekitten") var files = sourceKittenFolder.files.map { $0.nameExcludingExtension } files.removeAll { $0 == "SotoCore" } let context = [ "services": files, ] let package = try environment.renderTemplate(name: ".jazzy.yaml", context: context) let packageFile = try currentFolder.createFile(named: ".jazzy.yaml") try packageFile.write(package) } } try GenerateProcess().run()
apache-2.0
d68dc0f052d4f996a3ae6666b5bfd33e
31.704545
91
0.587908
4.525157
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift
21
2196
// // ControlTarget.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) || os(OSX) import Foundation #if !RX_NO_MODULE import RxSwift #endif #if os(iOS) || os(tvOS) import UIKit typealias Control = UIKit.UIControl typealias ControlEvents = UIKit.UIControlEvents #elseif os(OSX) import Cocoa typealias Control = Cocoa.NSControl #endif // This should be only used from `MainScheduler` class ControlTarget: RxTarget { typealias Callback = (Control) -> Void let selector: Selector = #selector(ControlTarget.eventHandler(_:)) weak var control: Control? #if os(iOS) || os(tvOS) let controlEvents: UIControlEvents #endif var callback: Callback? #if os(iOS) || os(tvOS) init(control: Control, controlEvents: UIControlEvents, callback: Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.controlEvents = controlEvents self.callback = callback super.init() control.addTarget(self, action: selector, forControlEvents: controlEvents) let method = self.methodForSelector(selector) if method == nil { rxFatalError("Can't find method") } } #elseif os(OSX) init(control: Control, callback: Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.callback = callback super.init() control.target = self control.action = selector let method = self.methodForSelector(selector) if method == nil { rxFatalError("Can't find method") } } #endif func eventHandler(sender: Control!) { if let callback = self.callback, control = self.control { callback(control) } } override func dispose() { super.dispose() #if os(iOS) || os(tvOS) self.control?.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents) #elseif os(OSX) self.control?.target = nil self.control?.action = nil #endif self.callback = nil } } #endif
mit
cd78f584b5fb424a2e75f86f369a4824
22.858696
101
0.642825
4.337945
false
false
false
false
kpham13/SkaterBrad
SkaterBrad/NewGameMenu.swift
1
5366
// // NewGrameNode.swift // SkaterBrad // // Copyright (c) 2014 Mother Functions. All rights reserved. // import UIKit import SpriteKit enum SoundButtonSwitch { case On case Off } class NewGameNode: SKNode { var titleLabel: SKLabelNode! var directionLabel: SKLabelNode! var playButton: SKSpriteNode! var soundOnButton: SKSpriteNode! var soundOffButton: SKSpriteNode! var gameCenterButton: SKSpriteNode! //xx init(scene: SKScene, playSound: Bool) { super.init() self.titleLabel = SKLabelNode(text: "Skater Brad") self.titleLabel.fontName = "SkaterDudes" self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.8) self.titleLabel.zPosition = 5 self.directionLabel = SKLabelNode(text: "Swipe up to jump") self.directionLabel.fontName = "SkaterDudes" self.directionLabel.zPosition = 5 // New Game Button self.playButton = SKSpriteNode(imageNamed: "playNow.png") self.playButton.name = "PlayNow" self.playButton.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMidY(scene.frame)) self.playButton.zPosition = 10 self.playButton.xScale = 0.6 self.playButton.yScale = 0.6 self.addChild(self.playButton) // Sound On Button self.soundOnButton = SKSpriteNode(imageNamed: "SoundOn") self.soundOnButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOnButton.frame.width / 2, y: CGRectGetMaxY(scene.frame) - self.soundOnButton.frame.height / 2) self.soundOnButton?.name = "SoundOn" self.soundOnButton.xScale = 0.40 self.soundOnButton.yScale = 0.40 self.soundOnButton.zPosition = 2.0 // Sound Off Button self.soundOffButton = SKSpriteNode(imageNamed: "SoundOff") self.soundOffButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOffButton.frame.width, y: CGRectGetMaxY(scene.frame) - self.soundOffButton.frame.height / 2) self.soundOffButton?.name = "SoundOff" self.soundOffButton.xScale = 0.40 self.soundOffButton.yScale = 0.40 self.soundOffButton.zPosition = 2.0 if playSound == true { self.addChild(self.soundOnButton) } else { self.addChild(self.soundOffButton) } // Game Center Button [KP] //15 self.gameCenterButton = SKSpriteNode(imageNamed: "GameCenter") self.gameCenterButton?.name = "GameCenterButton" self.gameCenterButton?.zPosition = 10 self.gameCenterButton.xScale = 0.8 self.gameCenterButton.yScale = 0.8 self.gameCenterButton?.anchorPoint = CGPointMake(0, 0) if scene.frame.size.height == 568 { self.titleLabel.fontSize = 40 self.directionLabel.fontSize = 18 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.13) self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.04), CGRectGetMaxY(scene.frame) * (-0.03)) } else if scene.frame.size.height == 667 { self.titleLabel.fontSize = 45 self.directionLabel.fontSize = 20 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11) self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.01), CGRectGetMaxY(scene.frame) * (-0.025)) } else if scene.frame.size.height == 736 { println(scene.frame.size.height) self.titleLabel.fontSize = 50 self.directionLabel.fontSize = 22 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11) self.gameCenterButton.xScale = 1.0 self.gameCenterButton.yScale = 1.0 self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * 0.02, CGRectGetMaxY(scene.frame) * (-0.015)) } else { self.titleLabel.fontSize = 40 self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.78) self.directionLabel.fontSize = 18 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.15) self.gameCenterButton.xScale = 0.7 self.gameCenterButton.yScale = 0.7 self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.03), CGRectGetMaxY(scene.frame) * (-0.03)) } self.addChild(self.titleLabel) self.addChild(self.directionLabel) self.addChild(self.gameCenterButton) } func turnSoundOnOff(switchButton : SoundButtonSwitch) { if switchButton == SoundButtonSwitch.On { println("SoundButtonSwitch.On") self.soundOffButton.removeFromParent() self.addChild(self.soundOnButton) } else { println("SoundButtonSwitch.Off") self.soundOnButton.removeFromParent() self.addChild(self.soundOffButton) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-2-clause
57357672db4bd47c4d79b8e9f75c13f2
42.282258
182
0.651137
4.25873
false
false
false
false
WeltN24/Carlos
Tests/CarlosTests/CompositionTests.swift
1
25622
import Foundation import Nimble import Quick import Carlos import Combine struct ComposedCacheSharedExamplesContext { static let CacheToTest = "composedCache" static let FirstComposedCache = "cache1" static let SecondComposedCache = "cache2" } final class CompositionSharedExamplesConfiguration: QuickConfiguration { override class func configure(_: Configuration) { sharedExamples("get without considering set calls") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling get") { let key = "test key" var cancellable: AnyCancellable? var cache1Subject: PassthroughSubject<Int, Error>! var cache2Subject: PassthroughSubject<Int, Error>! var successSentinel: Bool? var failureSentinel: Bool? var cancelSentinel: Bool! var successValue: Int? beforeEach { cancelSentinel = false successSentinel = nil successValue = nil failureSentinel = nil cache1Subject = PassthroughSubject() cache1.getSubject = cache1Subject cache1.setSubject = PassthroughSubject() cache2Subject = PassthroughSubject() cache2.getSubject = cache2Subject cache2.setSubject = PassthroughSubject() for cache in [cache1, cache2] { cache?.numberOfTimesCalledGet = 0 cache?.numberOfTimesCalledSet = 0 } cancellable = composedCache.get(key) .handleEvents(receiveCancel: { cancelSentinel = true }) .sink(receiveCompletion: { completion in if case .failure = completion { failureSentinel = true } }, receiveValue: { value in successSentinel = true successValue = value }) } afterEach { cancellable?.cancel() cancellable = nil } it("should not call any success closure") { expect(successSentinel).toEventually(beNil()) } it("should not call any failure closure") { expect(failureSentinel).toEventually(beNil()) } it("should not call any cancel closure") { expect(cancelSentinel).toEventually(beFalse()) } it("should call get on the first cache") { expect(cache1.numberOfTimesCalledGet).toEventually(equal(1)) } it("should not call get on the second cache") { expect(cache2.numberOfTimesCalledGet).toEventually(equal(0)) } context("when the first request succeeds") { let value = 1022 beforeEach { cache1Subject.send(value) } it("should call the success closure") { expect(successSentinel).toEventuallyNot(beNil()) } it("should pass the right value") { expect(successValue).toEventually(equal(value)) } it("should not call the failure closure") { expect(failureSentinel).toEventually(beNil()) } it("should not call the cancel closure") { expect(cancelSentinel).toEventually(beFalse()) } it("should not call get on the second cache") { expect(cache2.numberOfTimesCalledGet).toEventually(equal(0)) } } context("when the request is canceled") { beforeEach { cancellable?.cancel() } it("should not call the success closure") { expect(successSentinel).toEventually(beNil()) } it("should not call the failure closure") { expect(failureSentinel).toEventually(beNil()) } it("should call the cancel closure") { expect(cancelSentinel).toEventually(beTrue()) } } context("when the first request fails") { beforeEach { cache1Subject.send(completion: .failure(TestError.simpleError)) } it("should not call the success closure") { expect(successSentinel).toEventually(beNil()) } it("should not call the failure closure") { expect(failureSentinel).toEventually(beNil()) } it("should not call the cancel closure") { expect(cancelSentinel).toEventually(beFalse()) } it("should call get on the second cache") { expect(cache2.numberOfTimesCalledGet).toEventually(equal(1)) } it("should not do other get calls on the first cache") { expect(cache1.numberOfTimesCalledGet).toEventually(equal(1)) } context("when the second request succeeds") { let value = -122 beforeEach { cache2Subject.send(value) cache1.setSubject?.send(()) } it("should call the success closure") { expect(successSentinel).toEventuallyNot(beNil()) } it("should pass the right value") { expect(successValue).toEventually(equal(value)) } it("should not call the failure closure") { expect(failureSentinel).toEventually(beNil()) } it("should not call the cancel closure") { expect(cancelSentinel).toEventually(beFalse()) } } context("when the second request fails") { beforeEach { cache2Subject.send(completion: .failure(TestError.simpleError)) } it("should not call the success closure") { expect(successSentinel).toEventually(beNil()) } it("should call the failure closure") { expect(failureSentinel).toEventuallyNot(beNil()) } it("should not call the cancel closure") { expect(cancelSentinel).toEventually(beFalse()) } it("should not do other get calls on the first cache") { expect(cache1.numberOfTimesCalledGet).toEventually(equal(1)) } it("should not do other get calls on the second cache") { expect(cache2.numberOfTimesCalledGet).toEventually(equal(1)) } } } } } sharedExamples("get on caches") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling get") { let key = "test key" var cancellable: AnyCancellable? var cache1Subject: PassthroughSubject<Int, Error>! var cache2Subject: PassthroughSubject<Int, Error>! beforeEach { cache1Subject = PassthroughSubject() cache1.getSubject = cache1Subject cache2Subject = PassthroughSubject() cache2.getSubject = cache2Subject for cache in [cache1, cache2] { cache?.numberOfTimesCalledGet = 0 cache?.numberOfTimesCalledSet = 0 } cancellable = composedCache.get(key).sink(receiveCompletion: { _ in }, receiveValue: { _ in }) } afterEach { cancellable?.cancel() cancellable = nil } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } context("when the first request fails") { beforeEach { cache1Subject.send(completion: .failure(TestError.simpleError)) } context("when the second request succeeds") { let value = -122 beforeEach { cache2Subject.send(value) } it("should set the value on the first cache") { expect(cache1.numberOfTimesCalledSet).toEventually(equal(1)) } it("should set the value on the first cache with the right key") { expect(cache1.didSetKey).toEventually(equal(key)) } it("should set the right value on the first cache") { expect(cache1.didSetValue).toEventually(equal(value)) } it("should not set the same value again on the second cache") { expect(cache2.numberOfTimesCalledSet).toEventually(equal(0)) } } } } } sharedExamples("both caches are caches") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("first cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } itBehavesLike("second cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } context("when calling set") { let key = "this key" let value = 102 var succeeded: Bool! var failed: Error? var canceled: Bool! var cancellable: AnyCancellable? beforeEach { succeeded = false failed = nil canceled = false cancellable = composedCache.set(value, forKey: key) .handleEvents(receiveCancel: { canceled = true }) .sink(receiveCompletion: { completion in if case let .failure(error) = completion { failed = error } }, receiveValue: { _ in succeeded = true }) } afterEach { cancellable?.cancel() cancellable = nil } it("should call set on the first cache") { expect(cache1.numberOfTimesCalledSet).toEventually(equal(1)) } it("should pass the right key on the first cache") { expect(cache1.didSetKey).toEventually(equal(key)) } it("should pass the right value on the first cache") { expect(cache1.didSetValue).toEventually(equal(value)) } context("when the set closure succeeds") { beforeEach { cache1.setPublishers[key]?.send() } it("should call set on the second cache") { expect(cache2.numberOfTimesCalledSet).toEventually(equal(1)) } it("should pass the right key on the second cache") { expect(cache2.didSetKey).toEventually(equal(key)) } it("should pass the right value on the second cache") { expect(cache2.didSetValue).toEventually(equal(value)) } context("when the set closure succeeds") { beforeEach { cache2.setPublishers[key]?.send() } it("should succeed the future") { expect(succeeded).toEventually(beTrue()) } } context("when the set closure fails") { let error = TestError.anotherError beforeEach { cache2.setPublishers[key]?.send(completion: .failure(error)) } it("should fail the future") { expect(failed as? TestError).toEventually(equal(error)) } } } context("when the set clousure is canceled") { beforeEach { cancellable?.cancel() } it("should cancel the future") { expect(canceled).toEventually(beTrue()) } } context("when the set closure fails") { let error = TestError.anotherError beforeEach { cache1.setPublishers[key]?.send(completion: .failure(error)) } it("should fail the future") { expect(failed as? TestError).toEventually(equal(error)) } } } } sharedExamples("first cache is a cache") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling set") { let key = "this key" let value = 102 var failed: Error? var canceled: Bool! var cancellable: AnyCancellable? beforeEach { failed = nil canceled = false cancellable = composedCache.set(value, forKey: key) .handleEvents(receiveCancel: { canceled = true }) .sink(receiveCompletion: { completion in if case let .failure(error) = completion { failed = error } }, receiveValue: { _ in }) } afterEach { cancellable?.cancel() cancellable = nil } it("should call set on the first cache") { expect(cache1.numberOfTimesCalledSet).toEventually(equal(1)) } it("should pass the right key on the first cache") { expect(cache1.didSetKey).toEventually(equal(key)) } it("should pass the right value on the first cache") { expect(cache1.didSetValue).toEventually(equal(value)) } context("when the set clousure is canceled") { beforeEach { cancellable?.cancel() } it("should cancel the future") { expect(canceled).toEventually(beTrue()) } } context("when the set closure fails") { let error = TestError.anotherError beforeEach { cache1.setPublishers[key]?.send(completion: .failure(error)) } it("should fail the future") { expect(failed as? TestError).toEventually(equal(error)) } } } context("when calling clear") { beforeEach { composedCache.clear() } it("should call clear on the first cache") { expect(cache1.numberOfTimesCalledClear).toEventually(equal(1)) } } context("when calling onMemoryWarning") { beforeEach { composedCache.onMemoryWarning() } it("should call onMemoryWarning on the first cache") { expect(cache1.numberOfTimesCalledOnMemoryWarning).toEventually(equal(1)) } } } sharedExamples("second cache is a cache") { (sharedExampleContext: @escaping SharedExampleContext) in var cache2: CacheLevelFake<String, Int>! var cache1: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } context("when calling set") { let key = "this key" let value = 102 var succeeded: Bool! var failed: Error? var canceled: Bool! var cancellable: AnyCancellable? beforeEach { succeeded = false failed = nil canceled = false cancellable = composedCache.set(value, forKey: key) .handleEvents(receiveCancel: { canceled = true }) .sink(receiveCompletion: { completion in if case let .failure(error) = completion { failed = error } }, receiveValue: { _ in succeeded = true }) } afterEach { cancellable?.cancel() cancellable = nil } it("should call set on the second cache") { expect(cache2.numberOfTimesCalledSet).toEventually(equal(1)) } it("should pass the right key on the second cache") { expect(cache2.didSetKey).toEventually(equal(key)) } it("should pass the right value on the second cache") { expect(cache2.didSetValue).toEventually(equal(value)) } context("when the set closure succeeds") { beforeEach { cache1.setPublishers[key]?.send() cache2.setPublishers[key]?.send() } it("should succeed the future") { expect(succeeded).toEventually(beTrue()) } } context("when the set clousure is canceled") { beforeEach { cancellable?.cancel() } it("should cancel the future") { expect(canceled).toEventually(beTrue()) } } context("when the set closure fails") { let error = TestError.anotherError beforeEach { cache1.setPublishers[key]?.send(completion: .failure(error)) cache2.setPublishers[key]?.send(completion: .failure(error)) } it("should fail the future") { expect(failed as? TestError).toEventually(equal(error)) } } } context("when calling clear") { beforeEach { composedCache.clear() } it("should call clear on the second cache") { expect(cache2.numberOfTimesCalledClear).toEventually(equal(1)) } } context("when calling onMemoryWarning") { beforeEach { composedCache.onMemoryWarning() } it("should call onMemoryWarning on the second cache") { expect(cache2.numberOfTimesCalledOnMemoryWarning).toEventually(equal(1)) } } } sharedExamples("a composition of two fetch closures") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } } sharedExamples("a composition of a fetch closure and a cache") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get without considering set calls") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } itBehavesLike("second cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } } sharedExamples("a composition of a cache and a fetch closure") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get on caches") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } itBehavesLike("first cache is a cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } } sharedExamples("a composed cache") { (sharedExampleContext: @escaping SharedExampleContext) in var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! beforeEach { cache1 = sharedExampleContext()[ComposedCacheSharedExamplesContext.FirstComposedCache] as? CacheLevelFake<String, Int> cache2 = sharedExampleContext()[ComposedCacheSharedExamplesContext.SecondComposedCache] as? CacheLevelFake<String, Int> composedCache = sharedExampleContext()[ComposedCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int> } itBehavesLike("get on caches") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } itBehavesLike("both caches are caches") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } } } } final class CacheLevelCompositionTests: QuickSpec { override func spec() { var cache1: CacheLevelFake<String, Int>! var cache2: CacheLevelFake<String, Int>! var composedCache: BasicCache<String, Int>! describe("Cache composition using two cache levels with the instance function") { beforeEach { cache1 = CacheLevelFake<String, Int>() cache2 = CacheLevelFake<String, Int>() composedCache = cache1.compose(cache2) } itBehavesLike("a composed cache") { [ ComposedCacheSharedExamplesContext.FirstComposedCache: cache1 as Any, ComposedCacheSharedExamplesContext.SecondComposedCache: cache2 as Any, ComposedCacheSharedExamplesContext.CacheToTest: composedCache as Any ] } } } }
mit
e53f6a0bd5e788d3b7c5eac27196aa4b
32.981432
127
0.620951
5.309159
false
false
false
false