repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
breadwallet/breadwallet-ios
breadwallet/src/Views/TransactionCells/TxAddressCell.swift
1
1699
// // TxAddressCell.swift // breadwallet // // Created by Ehsan Rezaie on 2017-12-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class TxAddressCell: TxDetailRowCell { // MARK: Views private let addressButton = UIButton(type: .system) // MARK: - Init override func addSubviews() { super.addSubviews() container.addSubview(addressButton) } override func addConstraints() { super.addConstraints() addressButton.constrain([ addressButton.leadingAnchor.constraint(greaterThanOrEqualTo: titleLabel.trailingAnchor, constant: C.padding[1]), addressButton.constraint(.trailing, toView: container), addressButton.constraint(.top, toView: container), addressButton.constraint(.bottom, toView: container) ]) } override func setupStyle() { super.setupStyle() addressButton.titleLabel?.font = .customBody(size: 14.0) addressButton.titleLabel?.adjustsFontSizeToFitWidth = true addressButton.titleLabel?.minimumScaleFactor = 0.7 addressButton.titleLabel?.lineBreakMode = .byTruncatingMiddle addressButton.titleLabel?.textAlignment = .right addressButton.tintColor = .darkGray addressButton.tap = strongify(self) { myself in myself.addressButton.tempDisable() Store.trigger(name: .lightWeightAlert(S.Receive.copied)) UIPasteboard.general.string = myself.addressButton.titleLabel?.text } } func set(address: String) { addressButton.setTitle(address, for: .normal) } }
mit
a845eca7b592ea41d2660d20fe518edb
29.872727
124
0.649588
4.783099
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/InternalSchemeHandler/SessionRestoreHandler.swift
2
2378
// 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 WebKit import GCDWebServers import Shared private let apostropheEncoded = "%27" extension WKWebView { // Use JS to redirect the page without adding a history entry func replaceLocation(with url: URL) { let safeUrl = url.absoluteString.replacingOccurrences(of: "'", with: apostropheEncoded) evaluateJavascriptInDefaultContentWorld("location.replace('\(safeUrl)')") } } func generateResponseThatRedirects(toUrl url: URL) -> (URLResponse, Data) { var urlString: String if InternalURL.isValid(url: url), let authUrl = InternalURL.authorize(url: url) { urlString = authUrl.absoluteString } else { urlString = url.absoluteString } urlString = urlString.replacingOccurrences(of: "'", with: apostropheEncoded) let startTags = "<!DOCTYPE html><html><head><script>" let endTags = "</script></head></html>" let html = startTags + "location.replace('\(urlString)');" + endTags let data = html.data(using: .utf8)! let response = InternalSchemeHandler.response(forUrl: url) return (response, data) } /// Handles requests to /about/sessionrestore to restore session history. class SessionRestoreHandler: InternalSchemeResponse { static let path = "sessionrestore" func response(forRequest request: URLRequest) -> (URLResponse, Data)? { guard let _url = request.url, let url = InternalURL(_url) else { return nil } // Handle the 'url='query param if let urlParam = url.extractedUrlParam { return generateResponseThatRedirects(toUrl: urlParam) } // From here on, handle 'history=' query param let response = InternalSchemeHandler.response(forUrl: url.url) guard let sessionRestorePath = Bundle.main.path(forResource: "SessionRestore", ofType: "html"), let html = try? String(contentsOfFile: sessionRestorePath).replacingOccurrences( of: "%INSERT_UUID_VALUE%", with: InternalURL.uuid), let data = html.data(using: .utf8) else { assert(false) return nil } return (response, data) } }
mpl-2.0
abcfd2a61ea49c2df18d0c2ac104190c
35.584615
103
0.669891
4.355311
false
false
false
false
JRG-Developer/ObservableType
ObservableType/Library/OptionalConvertible.swift
1
5526
// // OptionalConvertible.swift // OptionalEquatable // // Created by Joshua Greene on 8/21/16. // Copyright © 2016 Joshua Greene. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /// `OptionalConvertible` allows `Optional` types to be used as a Generic type constraint. /// /// **See**: https://stackoverflow.com/questions/33436199/add-constraints-to-generic-parameters-in-extension public protocol OptionalConvertible { /// The wrapped value type. associatedtype WrappedValueType /// The underlying optional value var optionalValue: WrappedValueType? { get mutating set } /// Whether or not the underlying value is `nil` /// /// - Returns: `true` if the underlying value is `nil` or `false` otherwise func isNilValue() -> Bool /// Creates an instance that stores the given value. init(_ some: WrappedValueType) } extension Optional: OptionalConvertible { /// An alias `Wrapped` associated value public typealias WrappedValueType = Wrapped /// Returns `self` public var optionalValue: WrappedValueType? { get { return self } set { self = newValue } } /// Use this method to check if the `optionalValue` is `nil` or not. /// /// This works around an issue where Swift doesn't understand the type of `optionalValue` if used in a generic function, making it difficult to check if its `nil` or not. /// /// - Returns: `true` if the `optionaValue` is `nil` or false otherwise public func isNilValue() -> Bool { return self == nil } } // MARK: - Optional Updatable extension OptionalConvertible where WrappedValueType: Updatable { /// Use this method to update the current model with a new version. /// /// - Parameter newVersion: The new model version /// - Returns: `true` if the model was updated or `false` otherwise @discardableResult mutating func update(with _newVersion: Self) -> Bool { guard let value = optionalValue, let newVersion = _newVersion.optionalValue else { if isNilValue() && _newVersion.isNilValue() { return false } self = _newVersion return true } return value.update(with: newVersion) } } // MARK: - Optional ObservableCollection Updatable extension OptionalConvertible where WrappedValueType: ObservableCollection, WrappedValueType.Element: Updatable { /// Use this method to update this collection with a new version. /// /// This method iterates through each element within the new version. If there's a matching element by `identifier` found within this collection, it will be updated and added to a new collection. If a match isn't found, it's simply added to the new collection. /// /// Finally, this collection will be set to the new collection. /// /// - Parameter newVersion: The new version of the collection /// - Returns: `true` if the collection was updated or `false` otherwise @discardableResult mutating public func update(with _newVersion: Self) -> Bool { guard let value = optionalValue, let newVersion = _newVersion.optionalValue else { if isNilValue() && _newVersion.isNilValue() { return false } optionalValue = _newVersion.optionalValue return true } guard newVersion.count > 0 else { guard value.count > 0 else { return false } self = Self([]) return true } var updated = newVersion.count != value.count var newCollection: Self.WrappedValueType = [] newVersion.forEach { newElement in guard let index = value.index(where: { $0.identifier == newElement.identifier}) else { newCollection.add(newElement) updated = true return } let element = value[index] updated = updated || element.update(with: newElement) newCollection.add(element) } guard updated else { return false } self = Self(newCollection) return updated } /// Use this method to find and update a matching element by `identifier`. /// /// - Parameter newVersion: The new version /// - Returns: `true` if an element was found and updated or `false` otherwise @discardableResult public func updateMatchingElement(_ newVersion: WrappedValueType.Element) -> Bool { guard let value = optionalValue.optionalValue, let index = value.index(where: { $0.identifier == newVersion.identifier}) else { return false } return value[index].update(with: newVersion) } }
mit
752c2b5e87157b334ccb687c062ca59f
38.184397
262
0.697557
4.585062
false
false
false
false
BellAppLab/Keyboard
Sources/Keyboard/UIViewController+Frame+Keyboard.swift
1
4013
import ObjectiveC import UIKit //MARK: - ORIGINAL FRAMES //MARK: - Assotiation Keys private extension AssociationKeys { static var originalFrames = "com.bellapplab.originalFrames.key" } //MARK: - UIViewController + Original Frames @nonobjc internal extension UIViewController { func makeOriginalFrames() { guard hasKeyboardViews else { return } if let keyboardViews = keyboardViews { var frames: [Int: CGRect] = [:] (0..<keyboardViews.count).forEach { i in let view = keyboardViews[i] view.tag = i frames[i] = view.frame } originalFrames = frames } else { originalFrames = nil } } private(set) var originalFrames: [Int: CGRect]? { get { guard handlesKeyboard, let nsDictionary = objc_getAssociatedObject(self, &AssociationKeys.originalFrames) as? NSDictionary else { return nil } var result = [Int: CGRect]() nsDictionary.forEach { if let key = $0.key as? Int, let frame = ($0.value as? NSValue)?.cgRectValue { result[key] = frame } } return result } set { let nsDictionary: NSDictionary? let dictionary = newValue?.mapValues { NSValue(cgRect: $0) } if handlesKeyboard, dictionary != nil { nsDictionary = NSDictionary(dictionary: dictionary!) } else { nsDictionary = nil } objc_setAssociatedObject(self, &AssociationKeys.originalFrames, nsDictionary, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } //MARK: - KEYBOARD VIEWS //MARK: - Assotiation Keys private extension AssociationKeys { static var keyboardViews = "com.bellapplab.keyboardViews.key" } //MARK: - UIViewController + Keyboard Views @nonobjc internal extension UIViewController { var hasKeyboardViews: Bool { return handlesKeyboard && keyboardViews?.isEmpty ?? true == false } func setKeyboardViewsToOriginal() { guard hasKeyboardViews else { return } keyboardViews?.forEach { let originalFrame = originalFrames![$0.tag]! $0.frame = originalFrame } view.setNeedsDisplay() } func setKeyboardFrames(intersection: CGRect) { guard hasKeyboardViews, intersection != .zero else { return } keyboardViews?.forEach { let originalFrame = originalFrames![$0.tag]! $0.frame = CGRect(x: originalFrame.origin.x, y: originalFrame.origin.y - intersection.height, width: originalFrame.width, height: originalFrame.height) } } } @objc public extension UIViewController { /// The collection of views that should have their frames updated when the keyboard changes. /// - note: This should only be used if you are not using autolayout. @IBOutlet var keyboardViews: [UIView]? { get { if let nsArray = objc_getAssociatedObject(self, &AssociationKeys.keyboardViews) as? NSArray { #if swift(>=4.0) return nsArray.compactMap { $0 as? UIView } #else return nsArray.flatMap { $0 as? UIView } #endif } return nil } set { Keyboard.yo() objc_setAssociatedObject(self, &AssociationKeys.keyboardViews, newValue != nil ? NSArray(array: newValue!) : nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) makeOriginalFrames() } } }
mit
f799f684389358a02a858124a7a82586
31.104
115
0.548218
5.151476
false
false
false
false
gnachman/iTerm2
sources/SSHIdentity.swift
2
3166
// // SSHIdentity.swift // iTerm2SharedARC // // Created by George Nachman on 5/12/22. // import Foundation public class SSHIdentity: NSObject, Codable { private struct State: Equatable, Codable, CustomDebugStringConvertible { var debugDescription: String { let hostport = hostname + ":\(port)" if let username = username { return username + "@" + hostport } return hostport } var compactDescription: String { let hostport: String if port == 22 { hostport = hostname } else { hostport = hostname + " port \(port)" } if let username = username, username != NSUserName() { return username + "@" + hostport } return hostport } let hostname: String let username: String? let port: Int var commandLine: String { let parts = [username.map { "-l \($0)" }, port == 22 ? nil : "-p \(port)", "\(hostname)"].compactMap { $0 } return parts.joined(separator: " ") } } private let state: State @objc public var commandLine: String { return state.commandLine } @objc public var json: Data { return try! JSONEncoder().encode(state) } @objc public var compactDescription: String { return state.compactDescription } public override var debugDescription: String { return state.debugDescription } public override var description: String { return state.debugDescription } @objc public var hostname: String { return state.hostname } public var stringIdentifier: String { return state.compactDescription } public init?(stringIdentifier: String) { guard let at = stringIdentifier.range(of: "@"), let colon = stringIdentifier.range(of: ":") else { return nil } guard at.lowerBound < colon.lowerBound else { return nil } let username = stringIdentifier[..<at.lowerBound] guard let port = Int(stringIdentifier[colon.upperBound...]) else { return nil } state = State(hostname: String(stringIdentifier[at.upperBound..<colon.lowerBound]), username: username.isEmpty ? nil : String(username), port: port) } @objc public init?(_ json: Data?) { guard let data = json else { return nil } if let state = try? JSONDecoder().decode(State.self, from: data) { self.state = state } else { return nil } } @objc public init(_ hostname: String, username: String?, port: Int) { state = State(hostname: hostname, username: username, port: port) } public override func isEqual(to object: Any?) -> Bool { guard let other = object as? SSHIdentity else { return false } return other.state == state } }
gpl-2.0
2df5b6b644f72d555362ae1cd7b229dc
26.77193
91
0.542325
4.946875
false
false
false
false
gouyz/GYZBaking
baking/Classes/Mine/View/GYZMineConmentHeaderView.swift
1
3698
// // GYZMineConmentHeaderView.swift // baking // 我的评价header // Created by gouyz on 2017/4/2. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZMineConmentHeaderView: UITableViewHeaderFooterView { /// 填充数据 var dataModel : GYZMineConmentModel?{ didSet{ if let model = dataModel { //设置数据 logoImgView.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "icon_logo_default"), options: nil, progressBlock: nil, completionHandler: nil) nameLab.text = model.member_info?.company_name timeLab.text = model.add_time?.dateFromTimeInterval()?.dateToStringWithFormat(format: "yyyy/MM/dd HH:mm:ss") } } } override init(reuseIdentifier: String?){ super.init(reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ bgView.backgroundColor = kWhiteColor contentView.addSubview(bgView) bgView.addSubview(nameLab) bgView.addSubview(timeLab) bgView.addSubview(lineView) bgView.addSubview(rightIconView) bgView.addSubview(logoImgView) bgView.snp.makeConstraints { (make) in make.edges.equalTo(0) } logoImgView.snp.makeConstraints { (make) in make.centerY.equalTo(bgView) make.left.equalTo(bgView).offset(kMargin) make.size.equalTo(CGSize.init(width: 30, height: 30)) } nameLab.snp.makeConstraints { (make) in make.left.equalTo(logoImgView.snp.right).offset(kMargin) make.top.equalTo(logoImgView) make.right.equalTo(rightIconView.snp.left).offset(-5) make.height.equalTo(18) } timeLab.snp.makeConstraints { (make) in make.left.right.equalTo(nameLab) make.top.equalTo(nameLab.snp.bottom) make.height.equalTo(12) } rightIconView.snp.makeConstraints { (make) in make.centerY.equalTo(bgView) make.right.equalTo(bgView).offset(-5) make.size.equalTo(CGSize.init(width: 20, height: 20)) } lineView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(bgView) make.height.equalTo(klineWidth) } } fileprivate lazy var bgView : UIView = UIView() /// 商家图片 lazy var logoImgView : UIImageView = { let view = UIImageView() view.borderColor = kGrayLineColor view.borderWidth = klineWidth view.cornerRadius = kCornerRadius view.contentMode = .scaleAspectFill view.image = UIImage.init(named: "icon_logo_default") return view }() /// 店铺名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k14Font lab.textColor = kBlackFontColor lab.text = "杨小姐的烘焙店" return lab }() /// 评论日期 lazy var timeLab : UILabel = { let lab = UILabel() lab.font = k12Font lab.textColor = kGaryFontColor lab.text = "2017/03/08" return lab }() /// 右侧箭头图标 fileprivate lazy var rightIconView: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray")) fileprivate lazy var lineView : UIView = { let line = UIView() line.backgroundColor = kGrayLineColor return line }() }
mit
9b17b6b520c97c691c086286ad91bf34
30.763158
180
0.591273
4.394417
false
false
false
false
madcato/OSFramework
Sources/OSFramework/Serializator.swift
1
6048
// // Serializator.swift // TestPersistWebObject // // Created by Daniel Vela on 04/07/16. // Copyright © 2016 Daniel Vela. All rights reserved. // import Foundation // class SerializableWebQuery: NSObject, NSCoding { // var url: String // // init(url: String) { // self.url = url // } // // required init?(coder aDecoder: NSCoder) { // self.url = aDecoder.decodeObject(forKey: "url") as! String // } // // func encode(with aCoder: NSCoder) { // aCoder.encode(self.url, forKey: "url") // } // // func start(onOk: (), onError: ()) { // // } // } //class SerializableWebQueries { // // var fileName = "WebQueriesData" // // var data: [SerializableWebQuery] = [] // // var running = false // // func append(url: String, parameters: [NSObject:AnyObject]) { // self.data.append(SerializableWebQuery(url: url)) // // startContinue() // } // // func appBecomeActive() { // let restoredObjects = Serializator().restoreObject(fileName: fileName) // if let restoredObjects = restoredObjects { // self.data = restoredObjects as! [SerializableWebQuery] // } // startContinue() // } // // func appBecomeInactive() { // Serializator().saveObject(object: self.data, fileName: fileName) // } // // func startContinue() { // if running == false { // running = true // }else { // return // } // // sendAQuery() // // } // // static let initialSecondsToWaitOnError: Double = 5.0 // var secondsToWaitOnError = { // initialSecondsToWaitOnError // }() // // func sendAQuery() { // DispatchQueue.global(qos: .background).async { // if self.data.count > 0 { // let webQuery = self.data.removeFirst() // // webQuery.start(onOk: { // // Nothing. The query was ok // // Continue with next one // self.sendAQuery() // self.secondsToWaitOnError = SerializableWebQueries.initialSecondsToWaitOnError // }(), onError: { // // On error the query must be restored on the queue // DispatchQueue.global(qos: .background).async { // self.data.append(webQuery) // // and wait some seconds // Thread.sleep(forTimeInterval: self.secondsToWaitOnError) // self.secondsToWaitOnError *= 2 // self.sendAQuery() // } // }()) // } else { // self.running = false // } // } // } //} // 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. // Serializator().saveObject(self.data, fileName: "testData") // } // // 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. // // let restoredObjects = Serializator().restoreObject("testData") // if let restoredObjects = restoredObjects { // self.data = restoredObjects as! [SerializableWebQuery] // } // } /** Object serializator class */ public class Serializator { public init() { } /** Delete the serializator file for a class in the documents directory - Parameter fileName: Name of the file without directory part */ public func deleteSerial(fileName: String) { let formFilePath = self.formFilePath(className: fileName) do { try FileManager.default.removeItem(atPath: formFilePath) } catch let error as NSError { print("Error deleting file", fileName, error) } } /** Recreates an object from a serializaded object - Parameter fileName: Name of the file without directory part */ public func restoreObject(fileName: String) -> Any? { let formFilePath = self.formFilePath(className: fileName) let object = NSKeyedUnarchiver.unarchiveObject(withFile: formFilePath) return object as Any? } /** Saves an object. - Parameter object: This object must implement **NSCoding** class - Parameter fileName: Name of the file without directory part */ public func saveObject(object: Any, fileName: String) { let formFilePath = self.formFilePath(className: fileName) NSKeyedArchiver.archiveRootObject(object, toFile: formFilePath) } /** Constructs a complete path using the className as file name, document directory as base path and *.serial* as extension. - Parameter className: Name of the class to be used as file name */ private func formFilePath(className: String) -> String { let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let documentsDirectory = paths[0] let formFileName = "\(className).serial" let formFilePath = "\(documentsDirectory)/\(formFileName)" return formFilePath } }
mit
9148b392e2c1b7154e579b39a9877e23
32.782123
106
0.580618
4.536384
false
false
false
false
Brightify/Reactant
Source/Core/Properties+Core.swift
2
1251
// // Properties+Core.swift // Reactant // // Created by Tadeáš Kříž on 12/06/16. // Copyright © 2016 Brightify. All rights reserved. // import UIKit extension Properties { public static let layoutMargins = Property<UIEdgeInsets>(defaultValue: .zero) public static let closeButtonTitle = Property<String>(defaultValue: "Close") public static let defaultBackButton = Property<UIBarButtonItem?>() } extension Properties.Style { public static let controllerRoot = style(for: ControllerRootViewContainer.self) /// NOTE: Applied after `controllerRoot` style public static let dialogControllerRoot = style(for: ControllerRootViewContainer.self) { root in root.backgroundColor = UIColor.black.fadedOut(by: 20%) } public static let dialog = style(for: UIView.self) public static let dialogContentContainer = style(for: UIView.self) public static let scroll = style(for: UIScrollView.self) public static let button = style(for: UIButton.self) public static let control = style(for: UIControl.self) public static let container = style(for: ContainerView.self) public static let view = style(for: UIView.self) public static let textField = style(for: TextField.self) }
mit
e6654c416134987ef7ddca4c45aefca1
34.571429
99
0.729317
4.307958
false
false
false
false
uasys/swift
test/IRGen/big_types_corner_cases.swift
1
8694
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // UNSUPPORTED: resilient_stdlib public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( protected)?}} i32 @main(i32, i8**) #0 { // CHECK: call void @llvm.lifetime.start // CHECK: call void @llvm.memcpy // CHECK: call void @llvm.lifetime.end // CHECK: ret i32 0 let bigStructGlobalArray : [BigStruct] = [ BigStruct() ] // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIxcx_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @_T0SqWy // CHECK: call void @_T0SqWe // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10f3_uses_f2yyF() // CHECK: call swiftcc void @_T022big_types_corner_cases9BigStructVACycfC(%T22big_types_corner_cases9BigStructV* noalias nocapture sret // CHECK: call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18f4_tuple_use_of_f2yyF() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6StructyAA0eH0V0aH0_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) #0 { // CHECK: getelementptr inbounds %T22big_types_corner_cases8BigClassC, %T22big_types_corner_cases8BigClassC* // CHECK: call void @_T0SqWy // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10enumCalleeyAA9LargeEnumOF(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}})) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: _T0s5printySayypGd_SS9separatorSS10terminatortF // CHECK-64: ret void // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_(%T22big_types_corner_cases9BigStructV* noalias nocapture sret, %T22big_types_corner_cases8SuperSubC*) #0 { // CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK-64: [[ALLOC4:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK-64: call swiftcc void @_T022big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF(%T22big_types_corner_cases9BigStructV* noalias nocapture sret [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}}) // CHECK: ret void class SuperBase { func boom() -> BigStruct { return BigStruct() } } class SuperSub : SuperBase { override func boom() -> BigStruct { return BigStruct() } func f() { let _ = { nil ?? super.boom() } } } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}})) #0 { // CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data // CHECK: call swiftcc void %7(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.refcounted* swiftself [[LOAD]]) // CHECK: ret void public struct MUseStruct { var x = BigStruct() public var superclassMirror: BigStruct? { return callInternalLet() } internal let callInternalLet: () -> BigStruct? } // CHECK-LABEL-64: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18stringAndSubstringSS_s0G0VtyF(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK-LABEL-32: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18stringAndSubstringSS_s0G0VtyF(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK: alloca %Ts9SubstringV // CHECK: alloca %Ts9SubstringV // CHECK: ret void public func stringAndSubstring() -> (String, Substring) { let s = "Hello, World" let a = Substring(s).dropFirst() return (s, a) } func bigStructGet() -> BigStruct { return BigStruct() } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases11testGetFuncyyF() #0 { // CHECK: ret void public func testGetFunc() { let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet }
apache-2.0
4e8b307051af3e861175bcc21c9d2807
41
363
0.707384
3.33871
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/MomentModule/Model/CWMomentReply.swift
2
817
// // CWMomentReply.swift // CWWeChat // // Created by wei chen on 2017/3/30. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit enum CWMomentReplyType: Int { case unkown case comment case praise } class CWMomentReply: NSObject { // 对应的id var momentId: String! var replyId: String! var username: String! var userId: String! var receiveUserId: String? var receiveUserName: String? var replyDate: Date = Date() var replyType: CWMomentReplyType = .unkown // 初始化方法 init(replyId: String, momentId: String, username: String, userId: String) { self.replyId = replyId self.momentId = momentId self.username = username self.userId = userId } }
mit
3a0b45317e966d5a40479483069a8267
18
51
0.611529
3.99
false
false
false
false
DaSens/StartupDisk
Pods/ProgressKit/InDeterminate/IndeterminateAnimation.swift
2
1648
// // InDeterminateAnimation.swift // ProgressKit // // Created by Kauntey Suryawanshi on 09/07/15. // Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved. // import Cocoa protocol AnimationStatusDelegate { func startAnimation() func stopAnimation() } open class IndeterminateAnimation: BaseView, AnimationStatusDelegate { /// View is hidden when *animate* property is false @IBInspectable open var displayAfterAnimationEnds: Bool = false /** Control point for all Indeterminate animation True invokes `startAnimation()` on subclass of IndeterminateAnimation False invokes `stopAnimation()` on subclass of IndeterminateAnimation */ open var animate: Bool = false { didSet { guard animate != oldValue else { return } if animate { self.isHidden = false startAnimation() } else { if !displayAfterAnimationEnds { self.isHidden = true } stopAnimation() } } } /** Every function that extends Indeterminate animation must define startAnimation(). `animate` property of Indeterminate animation will indynamically invoke the subclass method */ func startAnimation() { fatalError("This is an abstract function") } /** Every function that extends Indeterminate animation must define **stopAnimation()**. *animate* property of Indeterminate animation will dynamically invoke the subclass method */ func stopAnimation() { fatalError("This is an abstract function") } }
apache-2.0
4d79c210d9796d76d319be8418d8a537
27.912281
95
0.648058
5.333333
false
false
false
false
harryzjm/SwipeMenu
Source/MenuIndicator.swift
1
4392
// // MenuIndicator.swift // Sample // // Created by Magic on 9/5/2016. // Copyright © 2016 Magic. All rights reserved. // import Foundation import UIKit private let kMenuIndicatorZPosition: CGFloat = 998 class MenuIndicator : UIView { fileprivate var imageView = UIImageView() var size = CGSize(width: 44, height: 40) static var ShapeColor = kDefautColor fileprivate var edgeWidth: CGFloat { return rint( size.width * 0.382 ) } override func draw(_ frame: CGRect) { let path = UIBezierPath(roundedRect: frame, cornerRadius: 15) path.close() MenuIndicator.ShapeColor.setFill() path.fill() } init() { super.init(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height)) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize() { backgroundColor = .clear layer.zPosition = kMenuIndicatorZPosition imageView.contentMode = .scaleAspectFit addSubview(imageView) let wh = min(size.width, size.height) * 0.618 imageView.translatesAutoresizingMaskIntoConstraints = false imageView.widthAnchor.constraint(equalToConstant: wh).isActive = true imageView.heightAnchor.constraint(equalToConstant: wh).isActive = true imageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true imageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true } fileprivate var indicatorLeft: NSLayoutConstraint? { willSet{ indicatorLeft?.isActive = false; newValue?.isActive = true } } fileprivate var indicatorRight: NSLayoutConstraint? { willSet{ indicatorRight?.isActive = false; newValue?.isActive = true } } fileprivate var indicatorTop: NSLayoutConstraint? { willSet{ indicatorTop?.isActive = false; newValue?.isActive = true } } override func didMoveToSuperview() { super.didMoveToSuperview() guard let superV = superview else { return } translatesAutoresizingMaskIntoConstraints = false indicatorTop = topAnchor.constraint(equalTo: superV.topAnchor) widthAnchor.constraint(equalToConstant: size.width).isActive = true heightAnchor.constraint(equalToConstant: size.height).isActive = true indicatorLeft = leftAnchor.constraint(equalTo: superV.leftAnchor, constant: -edgeWidth) indicatorLeft?.isActive = false indicatorRight = rightAnchor.constraint(equalTo: superV.rightAnchor, constant: edgeWidth) } } enum IndicatorChange { case origin case y(CGFloat) case edge case show(CGFloat) } extension MenuIndicator { func updateImage(_ image:UIImage) { imageView.image = image } func update(_ change: IndicatorChange, side: SwipeMenuSide) { switch change { case .origin: m_animate(middle:size.width, final: edgeWidth, side: side) case .y(let y): indicatorTop?.constant = y case .edge: m_animate(middle:edgeWidth, final: 0.0, side: side) case .show(let width): m_animate(0, middle:-width, final: size.width - width, side: side) } } private func m_animate(_ initial: CGFloat? = nil, middle: CGFloat, final: CGFloat, side: SwipeMenuSide) { guard let superV = superview else { return } (side == .left ? indicatorRight:indicatorLeft)?.isActive = false guard let constraint = side == .left ? indicatorLeft:indicatorRight else { return } constraint.isActive = true if let initialValue = initial { constraint.constant = initialValue superV.layoutIfNeeded() } let middleVlaue = middle * CGFloat( side.rawValue ) let finalValue = final * CGFloat( side.rawValue ) constraint.constant = middleVlaue UIView.animate(withDuration: 0.2, delay:0, options: [.curveEaseIn], animations: { () -> Void in superV.layoutIfNeeded() }) { (finished) -> Void in constraint.constant = finalValue UIView.animate(withDuration: 0.3, delay:0, options: [.curveEaseOut], animations: { () -> Void in superV.layoutIfNeeded() }, completion: nil) } } }
mit
5bc4f67d3e85f3598bba15d01c3533c4
35.591667
130
0.647233
4.706324
false
false
false
false
geekaurora/ReactiveListViewKit
ReactiveListViewKit/ReactiveListViewKit/CZFeedListViewModel.swift
1
2664
// // CZFeedListViewModel.swift // ReactiveListViewKit // // Created by Cheng Zhang on 1/3/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import UIKit /** ViewModel/State class for `CZFeedListFacadeView` */ public class CZFeedListViewModel: NSObject, NSCopying { private(set) var sectionModels: [CZSectionModel] /// Initializer for multiple section ListView public required init(sectionModels: [CZSectionModel]?) { self.sectionModels = sectionModels ?? [] } /// Convenience initializer for single section ListView public init(feedModels: [CZFeedModel]? = nil) { self.sectionModels = [] super.init() if let feedModels = feedModels { reset(withFeedModels: feedModels) } } /// Method for multiple section ListView @objc(resetWithSectionModels:) public func reset(withSectionModels sectionModels: [CZSectionModel]) { self.sectionModels = sectionModels } /// Convenient method for single section ListView @objc(resetWithFeedModels:) public func reset(withFeedModels feedModels: [CZFeedModel]) { let sectionModels = [CZSectionModel(feedModels: feedModels)] reset(withSectionModels: sectionModels) } // MARK: - UICollectionView DataSource public func numberOfSections() -> Int{ return sectionModels.count } public func numberOfItems(inSection section: Int) -> Int { let sectionModel = sectionModels[section] return sectionModel.isHorizontal ? 1 : sectionModel.feedModels.count } // SectionHeader/SectionFooter public func supplementaryModel(inSection section: Int, kind: String) -> CZFeedModel? { return (kind == UICollectionView.elementKindSectionHeader) ? sectionModels[section].headerModel : sectionModels[section].footerModel } public func feedModel(at indexPath: IndexPath) -> CZFeedModel? { guard indexPath.section < sectionModels.count && indexPath.row < sectionModels[indexPath.section].feedModels.count else { assertionFailure("Couldn't find matched cell/feedModel at \(indexPath)") return nil } let feedModel = sectionModels[indexPath.section].feedModels[indexPath.row] return feedModel } // MARK: - NSCopying public func copy(with zone: NSZone? = nil) -> Any { guard let sectionModelsCopy = sectionModels.copy() as? [CZSectionModel] else { fatalError("Failed to copy the instance.") } let viewModel = type(of: self).init(sectionModels: sectionModelsCopy) return viewModel } }
mit
3ea3dbf2520e1c750e4d955a50a8d982
31.876543
140
0.675554
4.850638
false
false
false
false
rafaelhbarros/swift-reddit
swift-reddit/RedditViewer.swift
1
5197
// // RedditViewer.swift // swift-reddit // // Created by rafael on 6/3/14. // Copyright (c) 2014 rafael. All rights reserved. // import UIKit //class TemplateCell: UITableViewCell { // @IBOutlet var labelText : UILabel // // init(style: UITableViewCellStyle, reuseIdentifier: String!) { // super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) // } //} class RedditViewer: UIViewController, UITableViewDelegate, UITableViewDataSource, NSURLConnectionDelegate, NSURLConnectionDataDelegate { var tableView: UITableView! var redditThreadsData: NSArray = NSArray() var data: NSMutableData! var imageCache: NSMutableDictionary = NSMutableDictionary() init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height), style: UITableViewStyle.Plain) self.tableView.delegate = self self.tableView.dataSource = self self.view.addSubview(self.tableView) self.refreshRedditData() } override func didReceiveMemoryWarning() { imageCache.removeAllObjects() super.didReceiveMemoryWarning() } func refreshRedditData(){ var url: NSURL = NSURL(string: "http://reddit.com/r/swift.json") var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate:self, startImmediately: false) connection.start() } func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { self.data = NSMutableData() } func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { self.data.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary if(jsonResult["data"].count > 0){ var data: NSDictionary = jsonResult["data"] as NSDictionary if(data["children"].count > 0){ self.redditThreadsData = data["children"] as NSArray self.tableView.reloadData() } } } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ return self.redditThreadsData.count } func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? { let reuseIdentifier = "redditThread" var cell: UITableViewCell? = tableView?.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell if !cell { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) } var thread: NSDictionary = self.redditThreadsData[indexPath!.row] as NSDictionary var data: NSDictionary = thread["data"] as NSDictionary var title: String = data["title"] as String var comments: Int = data["num_comments"] as Int var subtitle: String = "Comments: \(comments)" cell!.image = UIImage(named: title) cell!.detailTextLabel.text = subtitle cell!.text = title dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { var url: NSString = data["thumbnail"] as NSString println(url) if(url == "self" || url == "default"){ return } var image: UIImage? = self.imageCache.valueForKey(url) as? UIImage if( !image? ){ var imgURL: NSURL = NSURL(string: url) var request: NSURLRequest = NSURLRequest(URL: imgURL) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error:NSError!) -> Void in if !error? { image = UIImage(data: data) self.imageCache.setValue(image, forKey: url) cell!.image = image } else{ println("Error: \(error.localizedDescription) \(url)") } }) } else { cell!.image = image } }) return cell } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { var thread: NSDictionary = self.redditThreadsData[indexPath.row] as NSDictionary var data: NSDictionary = thread["data"] as NSDictionary var title: String = data["title"] as String println("Selected: \(title)") } }
mit
153348e9307fb750806afa0180ca2150
39.286822
160
0.629786
5.260121
false
false
false
false
uasys/swift
test/SILGen/objc_currying.swift
1
14894
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -enable-sil-ownership -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo func curry_pod(_ x: CurryTest) -> (Int) -> Int { return x.pod } // CHECK-LABEL: sil hidden @_T013objc_currying9curry_podS2icSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_1:_T0So9CurryTestC3podS2iFTcTO]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: [[COPIED_ARG1:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[COPIED_ARG1]]) // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying9curry_podS2icSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_FOO_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_2:_T0So9CurryTestC3podS2iFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_FOO_1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_FOO_2]] : $@convention(method) (Int, @guaranteed CurryTest) -> Int // CHECK: bb0([[ARG1:%.*]] : @trivial $Int, [[ARG2:%.*]] : @guaranteed $CurryTest): // CHECK: [[COPIED_ARG2:%.*]] = copy_value [[ARG2]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[COPIED_ARG2]] : $CurryTest, #CurryTest.pod!1.foreign // CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[ARG1]], [[COPIED_ARG2]]) // CHECK: destroy_value [[COPIED_ARG2]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK_FOO_2]]' func curry_bridged(_ x: CurryTest) -> (String!) -> String! { return x.bridged } // CHECK-LABEL: sil hidden @_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_1:_T0So9CurryTestC7bridgedSQySSGADFTcTO]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[ARG1_COPY]]) // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_BAR_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ARG1:%.*]] : @owned $CurryTest): // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_2:_T0So9CurryTestC7bridgedSQySSGADFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]]([[ARG1]]) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_BAR_1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_BAR_2]] : $@convention(method) (@owned Optional<String>, @guaranteed CurryTest) -> @owned Optional<String> // CHECK: bb0([[OPT_STRING:%.*]] : @owned $Optional<String>, [[SELF:%.*]] : @guaranteed $CurryTest): // CHECK: switch_enum [[OPT_STRING]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], // // CHECK: [[SOME_BB]]([[STRING:%.*]] : @owned $String): // CHECK: [[BRIDGING_FUNC:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[NSSTRING:%.*]] = apply [[BRIDGING_FUNC]]([[BORROWED_STRING]]) // CHECK: [[OPT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTRING]] : $NSString // CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]] // CHECK: destroy_value [[STRING]] // CHECK: br bb3([[OPT_NSSTRING]] : $Optional<NSString>) // CHECK: bb2: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt // CHECK: br bb3([[OPT_NONE]] : $Optional<NSString>) // CHECK: bb3([[OPT_NSSTRING:%.*]] : @owned $Optional<NSString>): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF_COPY]] : $CurryTest, #CurryTest.bridged!1.foreign // CHECK: [[RESULT_OPT_NSSTRING:%.*]] = apply [[METHOD]]([[OPT_NSSTRING]], [[SELF_COPY]]) : $@convention(objc_method) (Optional<NSString>, CurryTest) -> @autoreleased Optional<NSString> // CHECK: switch_enum [[RESULT_OPT_NSSTRING]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], // CHECK: [[SOME_BB]]([[RESULT_NSSTRING:%.*]] : @owned $NSString): // CHECK: [[BRIDGE_FUNC:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[REWRAP_RESULT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTRING]] // CHECK: [[RESULT_STRING:%.*]] = apply [[BRIDGE_FUNC]]([[REWRAP_RESULT_NSSTRING]] // CHECK: [[WRAPPED_RESULT_STRING:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT_STRING]] // CHECK: br bb6([[WRAPPED_RESULT_STRING]] : $Optional<String>) // CHECK: bb5: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb6([[OPT_NONE]] : $Optional<String>) // CHECK: bb6([[FINAL_RESULT:%.*]] : @owned $Optional<String>): // CHECK: destroy_value [[SELF_COPY]] // CHECK: destroy_value [[OPT_NSSTRING]] // CHECK: return [[FINAL_RESULT]] : $Optional<String> // CHECK: } // end sil function '[[THUNK_BAR_2]]' func curry_returnsInnerPointer(_ x: CurryTest) -> () -> UnsafeMutableRawPointer! { return x.returnsInnerPointer } // CHECK-LABEL: sil hidden @_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> { // CHECK: bb0([[SELF:%.*]] : @owned $CurryTest): // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTcTO]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[BORROWED_SELF]] // CHECK: [[FN:%.*]] = apply [[THUNK]]([[SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: destroy_value [[SELF]] // CHECK: return [[FN]] // CHECK: } // end sil function '_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF' // CHECK: sil shared [serializable] [thunk] @[[THUNK_RETURNSINNERPOINTER]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> // CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER_2:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTO]] // CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK: return [[FN]] // CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK_RETURNSINNERPOINTER_2]] : $@convention(method) (@guaranteed CurryTest) -> Optional<UnsafeMutableRawPointer> // CHECK: bb0([[ARG1:%.*]] : @guaranteed $CurryTest): // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[ARG1_COPY]] : $CurryTest, #CurryTest.returnsInnerPointer!1.foreign // CHECK: [[RES:%.*]] = apply [[METHOD]]([[ARG1_COPY]]) : $@convention(objc_method) (CurryTest) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer> // CHECK: autorelease_value // CHECK: return [[RES]] // CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER_2]]' // CHECK-LABEL: sil hidden @_T013objc_currying19curry_pod_AnyObjectS2icyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (Int) -> Int // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.pod!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying19curry_pod_AnyObjectS2icyXlF' func curry_pod_AnyObject(_ x: AnyObject) -> (Int) -> Int { return x.pod! } // normalOwnership requires a thunk to bring the method to Swift conventions // CHECK-LABEL: sil hidden @_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.normalOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Optional<CurryTest>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<CurryTest>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: [[THUNK:%.*]] = function_ref @_T0So9CurryTestCSgACIxyo_A2CIxxo_TR // CHECK: partial_apply [[THUNK]]([[PA]]) // CHECK: } // end sil function '_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF' func curry_normalOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! { return x.normalOwnership! } // weirdOwnership is NS_RETURNS_RETAINED and NS_CONSUMES_SELF so already // follows Swift conventions // CHECK-LABEL: sil hidden @_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[SELF:%.*]] : $@opened({{.*}}) AnyObject, #CurryTest.weirdOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: bb1([[METHOD:%.*]] : @trivial $@convention(objc_method) (@owned Optional<CurryTest>, @owned @opened({{.*}}) AnyObject) -> @owned Optional<CurryTest>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcyXlF' func curry_weirdOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! { return x.weirdOwnership! } // bridged requires a thunk to handle bridging conversions // CHECK-LABEL: sil hidden @_T013objc_currying23curry_bridged_AnyObjectSQySSGACcyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String> // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.bridged!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (Optional<NSString>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<NSString>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgACIxyo_SSSgADIxxo_TR // CHECK: partial_apply [[THUNK]]([[PA]]) // CHECK: } // end sil function '_T013objc_currying23curry_bridged_AnyObjectSQySSGACcyXlF' func curry_bridged_AnyObject(_ x: AnyObject) -> (String!) -> String! { return x.bridged! } // check that we substitute Self = AnyObject correctly for Self-returning // methods // CHECK-LABEL: sil hidden @_T013objc_currying27curry_returnsSelf_AnyObjectSQyyXlGycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> @owned Optional<AnyObject> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsSelf!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased Optional<AnyObject>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying27curry_returnsSelf_AnyObjectSQyyXlGycyXlF' func curry_returnsSelf_AnyObject(_ x: AnyObject) -> () -> AnyObject! { return x.returnsSelf! } // CHECK-LABEL: sil hidden @_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycyXlF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> { // CHECK: bb0([[ANY:%.*]] : @owned $AnyObject): // CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]] // CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]] // CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]] // CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsInnerPointer!1.foreign, [[HAS_METHOD:bb[0-9]+]] // CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer>): // CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]] // CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]]) // CHECK: } // end sil function '_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycyXlF' func curry_returnsInnerPointer_AnyObject(_ x: AnyObject) -> () -> UnsafeMutableRawPointer! { return x.returnsInnerPointer! }
apache-2.0
50cf1b4d2d3ad601857f36148d5546c9
65.789238
228
0.650195
3.44609
false
true
false
false
silt-lang/silt
Sources/InnerCore/IRGenPayload.swift
1
13096
import LLVM import Seismography import OuterCore import Mantle /// A payload value represented as an explosion of integers and pointers that /// together represent the bit pattern of the payload. final class Payload { enum Schema { case dynamic case bits(UInt64) case schema(Explosion.Schema) func forEachType(_ IGM: IRGenModule, _ fn: (IRType) -> Void) { switch self { case .dynamic: break case let .schema(explosion): for element in explosion.elements { let type = element.scalarType assert(IGM.dataLayout.sizeOfTypeInBits(type) == IGM.dataLayout.allocationSize(of: type), "enum payload schema elements should use full alloc size") fn(type) } case .bits(var bitSize): let pointerSize = IGM.getPointerSize().valueInBits() while bitSize >= pointerSize { fn(IGM.dataLayout.intPointerType()) bitSize -= pointerSize } if bitSize > 0 { fn(IntType(width: Int(bitSize), in: IGM.module.context)) } } } var isStatic: Bool { switch self { case .dynamic: return false default: return true } } } var payloadValues = [Either<IRValue, IRType>]() private var storageTypeCache: IRType? init() { } private init(raw payloadValues: [Either<IRValue, IRType>]) { self.payloadValues = payloadValues } /// Generate a "zero" enum payload. static func zero(_ IGM: IRGenModule, _ schema: Payload.Schema) -> Payload { // We don't need to create any values yet they can be filled in when // real values are inserted. var result = [Either<IRValue, IRType>]() schema.forEachType(IGM) { type in result.append(.right(type)) } return Payload(raw: result) } static func fromExplosion( _ IGM: IRGenModule, _ source: Explosion, _ schema: Payload.Schema ) -> Payload { var result = [Either<IRValue, IRType>]() schema.forEachType(IGM) { _ in result.append(.left(source.claimSingle())) } return Payload(raw: result) } /// Generate an enum payload containing the given bit pattern. static func fromBitPattern( _ IGM: IRGenModule, _ bitPattern: APInt, _ schema: Payload.Schema ) -> Payload { var result = [Either<IRValue, IRType>]() var bitPattern = bitPattern schema.forEachType(IGM) { type in let bitSize = IGM.dataLayout.sizeOfTypeInBits(type) // Take some bits off of the bottom of the pattern. var val: IRConstant = bitPattern.zeroExtendOrTruncate(to: bitSize) if val.type.asLLVM() != type.asLLVM() { val = val.bitCast(to: type) } result.append(.left(val)) // Shift the remaining bits down. bitPattern.logicallyShiftRight(by: UInt64(bitSize)) } return Payload(raw: result) } func packIntoEnumPayload( _ IGF: IRGenFunction, _ outerPayload: Payload, _ offset: Size ) { var bitOffset = offset let layout = IGF.IGM.dataLayout for value in self.payloadValues { let v = self.forcePayloadValue(value) outerPayload.insertValue(IGF, v, bitOffset) bitOffset += Size(layout.sizeOfTypeInBits(v.type)) } } static func unpackFromPayload( _ IGF: IRGenFunction, _ outerPayload: Payload, _ offset: Size, _ schema: Payload.Schema ) -> Payload { var bitOffset = offset var result = [Either<IRValue, IRType>]() let DL = IGF.IGM.dataLayout schema.forEachType(IGF.IGM) { type in let v = outerPayload.extractValue(IGF, type, bitOffset) result.append(.left(v)) bitOffset += Size(DL.sizeOfTypeInBits(type)) } return Payload(raw: result) } } extension Payload { static func load( _ IGF: IRGenFunction, _ address: Address, _ schema: Payload.Schema ) -> Payload { let result = Payload.zero(IGF.IGM, schema) guard !result.payloadValues.isEmpty else { return result } let storageTy = result.llvmType(in: IGF.IGM.module.context) let ptrTy = PointerType(pointee: storageTy) let address = IGF.B.createPointerBitCast(of: address, to: ptrTy) if result.payloadValues.count == 1 { let val = IGF.B.createLoad(address, alignment: address.alignment) result.payloadValues[0] = .left(val) } else { var offset = Size.zero var loadedPayloads = [Either<IRValue, IRType>]() loadedPayloads.reserveCapacity(result.payloadValues.count) for i in result.payloadValues.indices { let member = IGF.B.createStructGEP(address, i, offset, "") let loadedValue = IGF.B.createLoad(member, alignment: member.alignment) loadedPayloads.append(.left(loadedValue)) offset += Size(IGF.IGM.dataLayout.allocationSize(of: loadedValue.type)) } result.swapPayloadValues(for: loadedPayloads) } return result } func store(_ IGF: IRGenFunction, _ address: Address) { guard !self.payloadValues.isEmpty else { return } let storageTy = self.llvmType(in: IGF.IGM.module.context) let ptrTy = PointerType(pointee: storageTy) let address = IGF.B.createPointerBitCast(of: address, to: ptrTy) if self.payloadValues.count == 1 { IGF.B.buildStore(forcePayloadValue(self.payloadValues[0]), to: address.address) return } else { var offset = Size.zero for (i, value) in self.payloadValues.enumerated() { let member = IGF.B.createStructGEP(address, i, offset, "") let valueToStore = forcePayloadValue(value) IGF.B.buildStore(valueToStore, to: member.address) offset += Size(IGF.IGM.dataLayout.allocationSize(of: valueToStore.type)) } } } func swapPayloadValues(for other: [Either<IRValue, IRType>]) { self.payloadValues = other } func explode(_ IGM: IRGenModule, _ out: Explosion) { for value in self.payloadValues { out.append(forcePayloadValue(value)) } } func llvmType(in context: LLVM.Context) -> IRType { if let ty = self.storageTypeCache { return ty } if self.payloadValues.count == 1 { self.storageTypeCache = self.getPayloadType(self.payloadValues[0]) return self.storageTypeCache! } var elementTypes = [IRType]() for value in self.payloadValues { elementTypes.append(self.getPayloadType(value)) } let type = StructType(elementTypes: elementTypes, isPacked: false, in: context) self.storageTypeCache = type return type } func insertValue( _ IGF: IRGenFunction, _ value: IRValue, _ payloadOffset: Size, _ numBitsUsedInValue: Int? = nil ) { self.withValueInPayload( IGF, value.type, numBitsUsedInValue, payloadOffset ) { payloadValue, payloadWidth, payloadValueOff, valueBitWidth, valueOff in let payloadType = getPayloadType(payloadValue) // See if the value matches the payload type exactly. In this case we // don't need to do any work to use the value. if payloadValueOff == 0 && valueOff == 0 { if value.type.asLLVM() == payloadType.asLLVM() { payloadValue = .left(value) return } // If only the width matches exactly, we can still do a bitcast. if payloadWidth == valueBitWidth { let bitcast = IGF.B.createBitOrPointerCast(value, to: payloadType) payloadValue = .left(bitcast) return } } // Select out the chunk of the value to merge with the existing payload. var subvalue = value let valueIntTy = IntType(width: valueBitWidth, in: IGF.IGM.module.context) let payloadIntTy = IntType(width: payloadWidth, in: IGF.IGM.module.context) let payloadTy = getPayloadType(payloadValue) subvalue = IGF.B.createBitOrPointerCast(subvalue, to: valueIntTy) if valueOff > 0 { subvalue = IGF.B.buildShr(subvalue, valueIntTy.constant(valueOff), isArithmetic: false) } subvalue = IGF.B.buildZExt(subvalue, type: payloadIntTy) if payloadValueOff > 0 { subvalue = IGF.B.buildShl(subvalue, payloadIntTy.constant(payloadValueOff)) } switch payloadValue { case .right(_): // If there hasn't yet been a value stored here, we can use the adjusted // value directly. payloadValue = .left(IGF.B.createBitOrPointerCast(subvalue, to: payloadTy)) case let .left(val): // Otherwise, bitwise-or it in, brazenly assuming there are zeroes // underneath. // TODO: This creates a bunch of bitcasting noise for non-integer // payload fields. var lastValue = val lastValue = IGF.B.createBitOrPointerCast(lastValue, to: payloadIntTy) lastValue = IGF.B.buildOr(lastValue, subvalue) payloadValue = .left(IGF.B.createBitOrPointerCast(lastValue, to: payloadTy)) } } } func extractValue( _ IGF: IRGenFunction, _ type: IRType, _ offset: Size ) -> IRValue { var result = type.undef() self.withValueInPayload( IGF, type, nil, offset ) { payloadValue, payloadWidth, payloadValueOffset, valueWidth, valueOff in let payloadType = getPayloadType(payloadValue) // If the desired type matches the payload slot exactly, we don't need // to do anything. if payloadValueOffset == 0 && valueOff == 0 { if type.asLLVM() == payloadType.asLLVM() { result = forcePayloadValue(payloadValue) return } // If only the width matches exactly, do a bitcast. if payloadWidth == valueWidth { result = IGF.B.createBitOrPointerCast(forcePayloadValue(payloadValue), to: type) return } } // Integrate the chunk of payload into the result value. var value = forcePayloadValue(payloadValue) let valueIntTy = IntType(width: valueWidth, in: IGF.IGM.module.context) let payloadIntTy = IntType(width: payloadWidth, in: IGF.IGM.module.context) value = IGF.B.createBitOrPointerCast(value, to: payloadIntTy) if payloadValueOffset > 0 { value = IGF.B.buildShr(value, valueIntTy.constant(payloadValueOffset)) } if valueWidth > payloadWidth { value = IGF.B.buildZExt(value, type: valueIntTy) } if valueOff > 0 { value = IGF.B.buildShl(value, valueIntTy.constant(valueOff)) } if valueWidth < payloadWidth { value = IGF.B.buildTrunc(value, type: valueIntTy) } if !result.isUndef { result = value } else { result = IGF.B.buildOr(result, value) } } return IGF.B.createBitOrPointerCast(result, to: type) } private func withValueInPayload( _ IGF: IRGenFunction, _ valueType: IRType, _ numBitsUsedInValue: Int?, _ payloadOffset: Size, _ f: (inout Either<IRValue, IRType>, Int, Int, Int, Int) -> Void ) { let DataLayout = IGF.IGM.dataLayout let valueTypeBitWidth = DataLayout.sizeOfTypeInBits(valueType) let valueBitWidth = numBitsUsedInValue ?? valueTypeBitWidth // Find the elements we need to touch. // TODO: Linear search through the payload elements is lame. var payloadType: IRType var payloadBitWidth: Int = 0 var valueOffset = 0 var payloadValueOffset = Int(payloadOffset.rawValue) for idx in self.payloadValues.indices { payloadType = getPayloadType(self.payloadValues[idx]) payloadBitWidth = DataLayout.sizeOfTypeInBits(payloadType) // Does this element overlap the area we need to touch? if payloadValueOffset < payloadBitWidth { // See how much of the value we can fit here. var valueChunkWidth = payloadBitWidth - payloadValueOffset valueChunkWidth = min(valueChunkWidth, valueBitWidth - valueOffset) var val = self.payloadValues[idx] f(&val, payloadBitWidth, payloadValueOffset, valueTypeBitWidth, valueOffset) self.payloadValues[idx] = val valueOffset += valueChunkWidth // If we used the entire value, we're done. guard valueOffset < valueBitWidth else { return } } payloadValueOffset = max(payloadValueOffset - payloadBitWidth, 0) } } private func forcePayloadValue(_ value: Either<IRValue, IRType>) -> IRValue { switch value { case let .left(val): return val case let .right(ty): return ty.constPointerNull() } } private func getPayloadType(_ value: Either<IRValue, IRType>) -> IRType { switch value { case let .left(val): return val.type case let .right(ty): return ty } } }
mit
fc0fa3b0ec32860eb505b6bf94b5ed4a
32.15443
80
0.627138
4.109194
false
false
false
false
ericrwolfe/TouchMajorRadiusTest
TouchMajorRadiusTest/ViewController.swift
1
2426
// // ViewController.swift // TouchMajorRadiusTest // // Created by Eric Wolfe on 6/20/14. // Copyright (c) 2014 Eric Wolfe. All rights reserved. // import UIKit import QuartzCore class ViewController: UIViewController { var currentTouches: Dictionary<UITouch, UIView> = [:] override func viewDidLoad() { super.viewDidLoad() view.multipleTouchEnabled = true } } extension ViewController { override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { super.touchesBegan(touches, withEvent: event) for touch in touches.allObjects as UITouch[] { createTouchView(touch) } } override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { super.touchesMoved(touches, withEvent: event) for touch in touches.allObjects as UITouch[] { updateTouchView(touch) } } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { super.touchesEnded(touches, withEvent: event) for touch in touches.allObjects as UITouch[] { removeTouchView(touch) } } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) for touch in touches.allObjects as UITouch[] { removeTouchView(touch) } } } extension ViewController { func createTouchView(touch: UITouch) { var touchView = UIView() touchView.backgroundColor = UIColor.redColor() touchView.layer.borderColor = UIColor.blackColor().CGColor touchView.userInteractionEnabled = false view.addSubview(touchView) currentTouches[touch] = touchView updateTouchView(touch) } func updateTouchView(touch: UITouch) { if let touchView = currentTouches[touch] { touchView.center = touch.locationInView(view) touchView.bounds = CGRect(x: 0, y: 0, width: touch.majorRadius * 2, height: touch.majorRadius * 2) touchView.layer.cornerRadius = touch.majorRadius touchView.layer.borderWidth = touch.majorRadiusTolerance } } func removeTouchView(touch: UITouch) { var touchView = currentTouches[touch] touchView?.removeFromSuperview() } }
mit
d2a4e8388850ba2cbcd4577b95836942
27.541176
110
0.630256
4.99177
false
false
false
false
appsquickly/Typhoon-Swift-Example
PocketForecast/UserInterface/Controllers/WeatherReport/WeatherReportViewController.swift
1
4748
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import UIKit public class WeatherReportViewController: UIViewController { public var weatherReportView : WeatherReportView { get { return self.view as! WeatherReportView } set { self.view = newValue } } public private(set) var weatherClient : WeatherClient public private(set) var weatherReportDao : WeatherReportDao public private(set) var cityDao : CityDao public private(set) var assembly : ApplicationAssembly private var cityName : String? private var weatherReport : WeatherReport? //------------------------------------------------------------------------------------------- // MARK: - Initialization & Destruction //------------------------------------------------------------------------------------------- public dynamic init(view: WeatherReportView, weatherClient : WeatherClient, weatherReportDao : WeatherReportDao, cityDao : CityDao, assembly : ApplicationAssembly) { self.weatherClient = weatherClient self.weatherReportDao = weatherReportDao self.cityDao = cityDao self.assembly = assembly super.init(nibName: nil, bundle: nil) self.weatherReportView = view } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //------------------------------------------------------------------------------------------- // MARK: - Overridden Methods //------------------------------------------------------------------------------------------- public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController!.isNavigationBarHidden = true if let cityName = self.cityDao.loadSelectedCity() { self.cityName = cityName if let weatherReport = self.weatherReportDao.getReportForCityName(cityName: cityName) { self.weatherReport = weatherReport self.weatherReportView.weatherReport = self.weatherReport } else { self.refreshData() } } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.cityName != nil { let cityListButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.bookmarks, target: self, action: #selector(WeatherReportViewController.presentMenu)) cityListButton.tintColor = .white let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: #selector(WeatherReportViewController.refreshData)) refreshButton.tintColor = .white self.weatherReportView.toolbar.items = [ cityListButton, space, refreshButton ] } } public override func viewWillDisappear(_ animated: Bool) { self.navigationController!.isNavigationBarHidden = false super.viewWillDisappear(animated) } //------------------------------------------------------------------------------------------- // MARK: - Private Methods //------------------------------------------------------------------------------------------- private dynamic func refreshData() { ICLoader.present() self.weatherClient.loadWeatherReportFor(city: self.cityName!, onSuccess: { weatherReport in self.weatherReportView.weatherReport = weatherReport ICLoader.dismiss() }, onError: { message in ICLoader.dismiss() print ("Error" + message) }) } private dynamic func presentMenu() { let rootViewController = self.assembly.rootViewController() as! RootViewController rootViewController.toggleSideViewController() } }
apache-2.0
7999133b23b320534ad8dd5b3179be9a
34.17037
176
0.519166
6.576177
false
false
false
false
Tsiems/mobile-sensing-apps
HeartBeet/HeartBeet/ViewController.swift
1
17435
// // ViewController.swift // ImageLab // // Created by Eric Larson // Copyright © 2016 Eric Larson. All rights reserved. // import UIKit import AVFoundation import QuartzCore extension String { func image(withWidth w: CGFloat) -> UIImage { let size = CGSize(width: w+10, height: w+10) UIGraphicsBeginImageContextWithOptions(size, false, 0); // UIColor.white.set() let rect = CGRect(origin: CGPoint.zero, size: size) // UIRectFill(CGRect(origin: CGPoint.zero, size: size)) (self as NSString).draw(in: rect, withAttributes: [NSFontAttributeName: UIFont.systemFont(ofSize: w)]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } } class ViewController: UIViewController { //MARK: Class Properties var filters : [CIFilter]! = nil var eyeFilters : [CIFilter]! = nil var mouthFilters : [CIFilter]! = nil var videoManager:VideoAnalgesic! = nil let pinchFilterIndex = 2 var detector:CIDetector! = nil let bridge = OpenCVBridge() // let bridge = OpenCVBridgeSub() //MARK: Outlets in view @IBOutlet weak var flashSlider: UISlider! @IBOutlet weak var stageLabel: UILabel! @IBOutlet weak var cameraButton: UIButton! @IBOutlet weak var flashButton: UIButton! //MARK: ViewController Hierarchy override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = nil self.setupFilters() self.setupEyeFilters() self.setupMouthFilters() self.videoManager = VideoAnalgesic.sharedInstance self.videoManager.setCameraPosition(AVCaptureDevicePosition.front) self.videoManager.setPreset("AVCaptureSessionPresetMedium") // create dictionary for face detection // HINT: you need to manipulate these proerties for better face detection efficiency let optsDetector = [CIDetectorAccuracy:CIDetectorAccuracyLow,CIDetectorTracking:true] as [String : Any] // setup a face detector in swift self.detector = CIDetector(ofType: CIDetectorTypeFace, context: self.videoManager.getCIContext(), // perform on the GPU is possible options: (optsDetector as [String : AnyObject])) self.videoManager.setProcessingBlock(self.processImage) if !videoManager.isRunning{ videoManager.start() } NotificationCenter.default.addObserver(self, selector: #selector(ViewController.toggleButton(notification:)), name: NSNotification.Name(rawValue: "toggleOn"), object: nil) } func toggleButton(notification: NSNotification) { let userInfo:Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String,AnyObject> let toggleOn = userInfo["toggleOn"]! as! String if toggleOn == "On" { DispatchQueue.main.async{ self.flashButton.isEnabled = false self.cameraButton.isEnabled = false } } else { DispatchQueue.main.async{ self.flashButton.isEnabled = true self.cameraButton.isEnabled = true } } } //MARK: Process image output func processImage(_ inputImage:CIImage) -> CIImage{ // detect faces let f = getFaces(inputImage) // if no faces, just return original image if f.count == 0 { return inputImage } var retImage = inputImage // if you just want to process on separate queue use this code // this is a NON BLOCKING CALL, but any changes to the image in OpenCV cannot be displayed real time // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in // self.bridge.setImage(retImage, withBounds: retImage.extent, andContext: self.videoManager.getCIContext()) // self.bridge.processImage() // } // use this code if you are using OpenCV and want to overwrite the displayed image via OpenCv // this is a BLOCKING CALL // self.bridge.setTransforms(self.videoManager.transform) // self.bridge.setImage(retImage, withBounds: retImage.extent, andContext: self.videoManager.getCIContext()) // self.bridge.processImage() // retImage = self.bridge.getImage() //HINT: you can also send in the bounds of the face to ONLY process the face in OpenCV // or any bounds to only process a certain bounding region in OpenCV switch self.bridge.processType { case 2: retImage = applyFiltersToFaces(retImage, features: f) break case 1: for face in f { //determine which emoji to display based on facial expression (eyes closed/smile) var emoji = "😐" if face.hasSmile && face.leftEyeClosed && face.rightEyeClosed { emoji = "😆" } else if face.leftEyeClosed && face.rightEyeClosed { emoji = "😣" } else if face.hasSmile { emoji = "😁" } //create the emoji image and rotate it to form correctly var emojiImage = CIImage(image: emoji.image(withWidth: face.bounds.size.width/2))! let rotateFilt = CIFilter(name: "CIStraightenFilter", withInputParameters: ["inputImage":emojiImage,"inputAngle":1.57])! emojiImage = rotateFilt.outputImage! //make a composite filter to overlay the emoji over the original image let compositeFilt = CIFilter(name:"CISourceAtopCompositing")! let faceLocTransform = CGAffineTransform(translationX: face.bounds.origin.x-20, y: face.bounds.origin.y-5); compositeFilt.setValue(emojiImage.applying(faceLocTransform),forKey: "inputImage") compositeFilt.setValue(retImage, forKey: "inputBackgroundImage") //set the image the composite retImage = compositeFilt.outputImage! } break default: self.bridge.setTransforms(self.videoManager.transform) for face in f { self.bridge.setImage(retImage, withBounds: face.bounds, andContext: self.videoManager.getCIContext()) self.bridge.setFeatures(face) self.bridge.processImage() retImage = self.bridge.getImageComposite() // get back opencv processed part of the image (overlayed on original) } break } return retImage } //MARK: Setup filtering func setupFilters(){ filters = [] let filterPinch = CIFilter(name:"CIBumpDistortion")! filterPinch.setValue(-0.5, forKey: "inputScale") filterPinch.setValue(75, forKey: "inputRadius") filters.append(filterPinch) // let filterPosterize = CIFilter(name:"CIColorPosterize")! // filters.append(filterPosterize) } //MARK: Setup Eye filtering func setupEyeFilters(){ eyeFilters = [] let filterTwirl = CIFilter(name:"CITwirlDistortion")! filterTwirl.setValue(30, forKey: "inputRadius") filterTwirl.setValue(2.0, forKey: "inputAngle") eyeFilters.append(filterTwirl) } func setupMouthFilters(){ mouthFilters = [] let filterPinch = CIFilter(name:"CIBumpDistortion")! filterPinch.setValue(0.5, forKey: "inputScale") filterPinch.setValue(60, forKey: "inputRadius") mouthFilters.append(filterPinch) } //MARK: Apply filters and apply feature detectors func applyFiltersToFaces(_ inputImage:CIImage,features:[CIFaceFeature])->CIImage{ var retImage = inputImage var filterCenter = CGPoint() // let ciImageSize = retImage.extent.size // var transform = CGAffineTransform(scaleX: 1, y: -1) // transform = transform.translatedBy(x: 0, y: -ciImageSize.height) for f in features { if f.hasSmile { let filt = CIFilter(name:"CIBloom")! filt.setValue(0.7, forKey: "inputIntensity") filt.setValue(retImage, forKey: kCIInputImageKey) retImage = filt.outputImage! } // Apply the transform to convert the coordinates // var faceViewBounds = f.bounds.applying(transform) // // let faceView = UIView(frame:faceViewBounds) // // faceView.backgroundColor = UIColor.blue // self.view.addSubview(faceView) // // let context = CIContext() // let cgImg = context.createCGImage(retImage, from: retImage.extent) // Calculate the actual position and size of the rectangle in the image view // let viewSize = self.view.bounds.size // let scale = min(viewSize.width / ciImageSize.width, // viewSize.height / ciImageSize.height) // let offsetX = (viewSize.width - ciImageSize.width * scale) / 2 // let offsetY = (viewSize.height - ciImageSize.height * scale) / 2 // // faceViewBounds = faceViewBounds.applying(CGAffineTransform(scaleX: scale, y: scale)) // faceViewBounds.origin.x += offsetX // faceViewBounds.origin.y += offsetY // // let faceBox = UIView(frame: faceViewBounds) // // faceBox.layer.borderWidth = 3 // faceBox.layer.borderColor = UIColor.red.cgColor // faceBox.backgroundColor = UIColor.clear // self.view.addSubview(faceBox) // // retImage. //set where to apply filter filterCenter.x = f.bounds.midX filterCenter.y = f.bounds.midY //do for each filter (assumes all filters have property, "inputCenter") for filt in filters{ let inputKeys = filt.inputKeys filt.setValue(retImage, forKey: kCIInputImageKey) if inputKeys.contains("inputCenter") { filt.setValue(CIVector(cgPoint: filterCenter), forKey: "inputCenter") } // could also manipualte the radius of the filter based on face size! retImage = filt.outputImage! } //apply eye filters to left eye if f.hasLeftEyePosition { //circle left eye if it's closed if f.hasSmile { // do nothing } else if f.leftEyeClosed { let filterLens = CIFilter(name:"CITorusLensDistortion")! filterLens.setValue(f.bounds.width/8, forKey: "inputRadius") filterLens.setValue(0.5, forKey: "inputRefraction") filterLens.setValue(f.bounds.width/16, forKey: "inputWidth") filterLens.setValue(CIVector(cgPoint: f.leftEyePosition), forKey: "inputCenter") filterLens.setValue(retImage, forKey: kCIInputImageKey) retImage = filterLens.outputImage! } else { for filt in eyeFilters { let inputKeys = filt.inputKeys filt.setValue(retImage, forKey: kCIInputImageKey) if inputKeys.contains("inputCenter") { filt.setValue(CIVector(cgPoint: f.leftEyePosition), forKey: "inputCenter") } // could also manipualte the radius of the filter based on face size! if inputKeys.contains("inputRadius") { if f.hasRightEyePosition { filt.setValue(f.bounds.width/8, forKey: "inputRadius") } } retImage = filt.outputImage! } } } //apply eye filters to right eye if f.hasRightEyePosition { if f.hasSmile { // do nothing } //circle right eye if it's closed else if f.rightEyeClosed { let filterLens = CIFilter(name:"CITorusLensDistortion")! filterLens.setValue(f.bounds.width/8, forKey: "inputRadius") filterLens.setValue(0.5, forKey: "inputRefraction") filterLens.setValue(f.bounds.width/16, forKey: "inputWidth") filterLens.setValue(CIVector(cgPoint: f.rightEyePosition), forKey: "inputCenter") filterLens.setValue(retImage, forKey: kCIInputImageKey) retImage = filterLens.outputImage! } else { for filt in eyeFilters { let inputKeys = filt.inputKeys filt.setValue(retImage, forKey: kCIInputImageKey) if inputKeys.contains("inputCenter") { filt.setValue(CIVector(cgPoint: f.rightEyePosition), forKey: "inputCenter") } // could also manipualte the radius of the filter based on face size! if inputKeys.contains("inputRadius") { if f.hasLeftEyePosition { filt.setValue(f.bounds.width/8, forKey: "inputRadius") } } retImage = filt.outputImage! } } } //apply mouth filters if f.hasMouthPosition { for filt in mouthFilters { let inputKeys = filt.inputKeys filt.setValue(retImage, forKey: kCIInputImageKey) if inputKeys.contains("inputCenter") { filt.setValue(CIVector(cgPoint: f.mouthPosition), forKey: "inputCenter") } // could also manipualte the radius of the filter based on face size! if inputKeys.contains("inputRadius") { if f.hasLeftEyePosition { filt.setValue(f.bounds.width/4, forKey: "inputRadius") } } retImage = filt.outputImage! } } } return retImage } func getFaces(_ img:CIImage) -> [CIFaceFeature]{ // this ungodly mess makes sure the image is the correct orientation //let optsFace = [CIDetectorImageOrientation:self.videoManager.getImageOrientationFromUIOrientation(UIApplication.sharedApplication().statusBarOrientation)] let optsFace = [CIDetectorImageOrientation:self.videoManager.ciOrientation, CIDetectorSmile:true,CIDetectorEyeBlink:true] as [String : Any] // get Face Features return self.detector.features(in: img, options: optsFace) as! [CIFaceFeature] } @IBAction func swipeRecognized(_ sender: UISwipeGestureRecognizer) { switch sender.direction { case UISwipeGestureRecognizerDirection.left: self.bridge.processType += 1 case UISwipeGestureRecognizerDirection.right: self.bridge.processType -= 1 default: break } stageLabel.text = "Stage: \(self.bridge.processType)" } //MARK: Convenience Methods for UI Flash and Camera Toggle @IBAction func flash(_ sender: AnyObject) { if(self.videoManager.toggleFlash()){ self.flashSlider.value = 1.0 } else{ self.flashSlider.value = 0.0 } } @IBAction func switchCamera(_ sender: AnyObject) { self.videoManager.toggleCameraPosition() } @IBAction func setFlashLevel(_ sender: UISlider) { if(sender.value>0.0){ self.videoManager.turnOnFlashwithLevel(sender.value) } else if(sender.value==0.0){ self.videoManager.turnOffFlash() } } }
mit
488e38d76227fb02acda4e89e123c11c
37.975391
179
0.54391
5.188207
false
false
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/ingredient(食材)/main(主要模块)/view/IngreRecommendView.swift
1
12654
// // IngreRecommendView.swift // TestKitchen // // Created by ZL on 16/10/25. // Copyright © 2016年 zl. All rights reserved. // import UIKit //定义食材首页Widget列表的类型 public enum IngreWidgetType: Int{ case GuessYouLike = 1 //猜你喜欢 case RedPacket = 2 //红包入口 case TodayNew = 5 //今日新品 case Scene = 3 //早餐日记等 case SceneList = 9 //全部场景 case Talent = 4 //推荐达人 case Post = 8 //精选作品 case Topic = 7 //专题 } class IngreRecommendView: UIView { //闭包 var jumpClosure:IngreJumpClosure? //数据 var model:IngreRecommend?{ didSet { //set 方法调用之后会调用这里的方法 tbView?.reloadData() } } //表格 private var tbView:UITableView? //重新实现初始化方法 override init(frame: CGRect) { super.init(frame: frame) //创建表格视图 tbView = UITableView(frame: CGRectZero,style: .Plain) tbView?.delegate=self tbView?.dataSource = self addSubview(tbView!) //约束 tbView?.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView代理 extension IngreRecommendView:UITableViewDelegate,UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { //banner 广告部分显示一个分组 var section = 1 if model?.data?.widgetList?.count > 0{ section += (model?.data?.widgetList?.count)! } return section } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //banner广告的section显示一行 var row = 0 if section == 0 { //广告 row = 1 }else { //获取list对象 let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == IngreWidgetType.GuessYouLike.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.RedPacket.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.TodayNew.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.SceneList.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Post.rawValue{ //猜你喜欢 //红包入口 //今日新品 //早餐日记等 //全部场景 //精选作品 -- 精选作品 row = 1 }else if (listModel?.widget_type?.integerValue)! == IngreWidgetType.Talent.rawValue { //推荐达人 row = (listModel?.widget_data?.count)! / 4 }else if (listModel?.widget_type?.integerValue)! == IngreWidgetType.Topic.rawValue { //专题 row = (listModel?.widget_data?.count)! / 3 } } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat = 0 if indexPath.section == 0{ //banner广告高度为140 height = 140 }else { let listModel = model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue == IngreWidgetType.GuessYouLike.rawValue { //猜你喜欢 height = 70 }else if listModel?.widget_type?.integerValue == IngreWidgetType.RedPacket.rawValue { //红包入口 height = 75 }else if listModel?.widget_type?.integerValue == IngreWidgetType.TodayNew.rawValue { //今日新品 height = 280 }else if listModel?.widget_type?.integerValue == IngreWidgetType.Scene.rawValue { //早餐日记等 height = 200 }else if listModel?.widget_type?.integerValue == IngreWidgetType.SceneList.rawValue { //全部场景 height = 70 }else if listModel?.widget_type?.integerValue == IngreWidgetType.Talent.rawValue { //推荐达人 height = 80 }else if listModel?.widget_type?.integerValue == IngreWidgetType.Post.rawValue { //精选作品 -- Post height = 180 }else if listModel?.widget_type?.integerValue == IngreWidgetType.Topic.rawValue { //专题 -- Topic height = 120 } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { //banner广告 let cell = IngreBannerCell.createBannerCellFor(tableView, atIndexPath: indexPath, bannerArray: model?.data!.banner) //点击事件的响应代码 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else { let listModel = model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue == IngreWidgetType.GuessYouLike.rawValue { //猜你喜欢 let cell = IngreLikeCell.createLikeCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.RedPacket.rawValue { //猜你喜欢 let cell = IngreRedPacketCell.createRedPacketCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.TodayNew.rawValue { //今日新品 let cell = IngreTodayCell.createTodayCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.Scene.rawValue { //早餐日记等 let cell = IngreSceneCell.createSceneCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.SceneList.rawValue { //全部场景 let cell = IngreSceneListCell.createSceneListCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.Talent.rawValue { //推荐达人 //获取子数组 //indexPath.row==0 0 1 2 3 //indexPath.row==1 4 5 6 7 //indexPath.row==2 8 9 10 11 let range = NSMakeRange(indexPath.row*4, 4) let array = NSArray(array: (listModel?.widget_data)!).subarrayWithRange(range) as! Array<IngreRecommendWidgetData> let cell = IngreTalnetCell.createTalentCellFor(tableView, atIndexPath: indexPath, cellArray: array) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.Post.rawValue { //精选作品 let cell = TablePostCell.createPostCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell }else if listModel?.widget_type?.integerValue == IngreWidgetType.Topic.rawValue { //转子数组 let range = NSMakeRange(indexPath.row*3, 3) let cellArray = NSArray(array: (listModel?.widget_data)!).subarrayWithRange(range) as! Array<IngreRecommendWidgetData> //专题 let cell = IngreTopicCell.createTopicCellFor(tableView, atIndexPath: indexPath, cellArray: cellArray) //点击事件 cell.jumpClosure = jumpClosure //取消cell点击的效果 cell.selectionStyle = .None return cell } } return UITableViewCell() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section > 0 { let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == IngreWidgetType.GuessYouLike.rawValue { //猜你喜欢的分组 let likeHeaderView = IngreLikeHeaderView(frame: CGRectMake(0,0,(tbView?.bounds.size.width)!,44)) return likeHeaderView }else if listModel?.widget_type?.integerValue == IngreWidgetType.TodayNew.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Talent.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Post.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Topic.rawValue{ //今日新品 -- TodayNew //早餐日记等 -- Scene //推荐达人 -- Talent //精选作品 -- Post //专题 -- Topic let headerView = IngreHeaderView(frame: CGRectMake(0,0,(tbView?.bounds.size.width)!,54)) // headerView.configText((listModel?.title)!) headerView.jumpClosure = jumpClosure headerView.listModel = listModel return headerView } } return nil } //设置header的高度 func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { var height:CGFloat = 0 if section > 0 { let listModel = model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue == IngreWidgetType.GuessYouLike.rawValue { //猜你喜欢 height=44 }else if listModel?.widget_type?.integerValue == IngreWidgetType.TodayNew.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Talent.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Post.rawValue || listModel?.widget_type?.integerValue == IngreWidgetType.Topic.rawValue{ //今日新品 -- TodayNew //早餐日记等 -- Scene //推荐达人 -- Talent //精选作品 -- Post //专题 -- Topic height=54 } } return height } //去掉UITableView的粘滞性 func scrollViewDidScroll(scrollView: UIScrollView) { let h : CGFloat = 54 if scrollView.contentOffset.y >= h { scrollView.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0) }else if scrollView.contentOffset.y > 0 { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0) } } }
mit
d27027f1b1add25e8a53a543dfd087f1
39.438776
473
0.568845
5.140078
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/KeyPair.swift
1
4694
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Represents a basic bean to store keyName pair values @author Ferran Vila Conesa @since v2.0 @version 1.0 */ public class KeyPair : APIBean { /** Key of the element */ var keyName : String? /** Value of the element */ var keyValue : String? /** Default Constructor @since v2.0 */ public override init() { super.init() } /** Constructor using fields @param keyName Key of the element @param keyValue Value of the element @since v2.0 */ public init(keyName: String, keyValue: String) { super.init() self.keyName = keyName self.keyValue = keyValue } /** Returns the keyName of the element @return Key of the element @since v2.0 */ public func getKeyName() -> String? { return self.keyName } /** Sets the keyName of the element @param keyName Key of the element @since v2.0 */ public func setKeyName(keyName: String) { self.keyName = keyName } /** Returns the keyValue of the element @return Value of the element @since v2.0 */ public func getKeyValue() -> String? { return self.keyValue } /** Sets the keyValue of the element @param keyValue Value of the element @since v2.0 */ public func setKeyValue(keyValue: String) { self.keyValue = keyValue } /** JSON Serialization and deserialization support. */ public struct Serializer { public static func fromJSON(json : String) -> KeyPair { let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary return fromDictionary(dict!) } static func fromDictionary(dict : NSDictionary) -> KeyPair { let resultObject : KeyPair = KeyPair() if let value : AnyObject = dict.objectForKey("keyName") { if "\(value)" as NSString != "<null>" { resultObject.keyName = (value as! String) } } if let value : AnyObject = dict.objectForKey("keyValue") { if "\(value)" as NSString != "<null>" { resultObject.keyValue = (value as! String) } } return resultObject } public static func toJSON(object: KeyPair) -> String { let jsonString : NSMutableString = NSMutableString() // Start Object to JSON jsonString.appendString("{ ") // Fields. object.keyName != nil ? jsonString.appendString("\"keyName\": \"\(JSONUtil.escapeString(object.keyName!))\", ") : jsonString.appendString("\"keyName\": null, ") object.keyValue != nil ? jsonString.appendString("\"keyValue\": \"\(JSONUtil.escapeString(object.keyValue!))\"") : jsonString.appendString("\"keyValue\": null") // End Object to JSON jsonString.appendString(" }") return jsonString as String } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
2a47d613d2ee73a97e26a9ca34988e19
27.609756
172
0.566496
5.012821
false
false
false
false
MakeAWishFoundation/SwiftyMocky
Sources/Shared/Stubbing.swift
1
5735
import Foundation /// [Internal] Generic Mock library errors /// /// - notStubed: Calling method on mock, for which return value was not yet stubbed. DO NOT USE it as stub throw value! public enum MockError: Error { case notStubed } /// [Internal] Possible Given products. Method can either return or throw an error (in general) /// /// - `return`: Return value /// - `throw`: Thrown error value public enum StubProduct { case `return`(Any) case `throw`(Error) /// [Internal] If self is returns, and nested value can be casted to T, returns value. Can fail (fatalError) /// /// - Returns: Value if self is return /// - Throws: Error if self is throw public func casted<T>() throws -> T { switch self { case let .throw(error): throw error case let .return(value): return (value as? T).orFail("Casting to \(T.self) failed") } } } /// [Internal] Allows to reduce Mock.generated.swif size, by moving part of implementation here. open class StubbedMethod: WithStubbingPolicy { /// [Internal] Returns whether there are still products to be used as stub return values public var isValid: Bool { return index < products.count } /// [Internal] Stubbing policy. By default uses parent mock policy public var policy: StubbingPolicy = .default /// [Internal] Array of stub return values private var products: [StubProduct] /// [Internal] Index of next retutn value. Can be out of bounds. private var index: Int = 0 /// [Internal] Creates new method init with given products. /// /// - Parameter products: All stub return values public init(_ products: [StubProduct]) { self.products = products self.index = 0 } /// [Internal] Get next product, with respect to self.policy and inherited policy /// /// - Parameter policy: Inherited policy /// - Returns: StubProduct from products array public func getProduct(policy: StubbingPolicy) -> StubProduct { defer { index = self.policy.real(policy).updated(index, with: products.count) } return products[index] } /// [Internal] New instance of stubber class, used to populate products array /// /// - Parameter type: Returned value type /// - Returns: Stubber instance public func stub<T>(for type: T.Type) -> Stubber<T> { return Stubber(self, returning: T.self) } /// [Internal] New instance of stubber class, used to populate products array /// /// - Parameter type: Returned value type /// - Returns: Stubber instance public func stubThrows<T>(for type: T.Type) -> StubberThrows<T> { return StubberThrows(self, returning: T.self) } /// Appends new product to products array /// /// - Parameter product: New stub return value (or error thrown) to append fileprivate func append(_ product: StubProduct) { products.append(product) } } /// Used to populate stubbed method with sequence of events. Call it's methods, to record subsequent stub return values. public struct Stubber<ReturnedValue> { /// [Internal] stubbed method private var method: StubbedMethod /// Stubbing policy. If wrap - it will iterate over recorded values. If drop - it will remove value when stub returns. If default - it will use mock settings public var policy: StubbingPolicy { get { return method.policy } set { method.policy = newValue } } /// [Internal] New instance of stubber class, used to populate products array /// /// - Parameters: /// - method: Stubbed method /// - returning: Return public init(_ method: StubbedMethod, returning: ReturnedValue.Type) { self.method = method } /// Record return value /// /// - Parameter value: return value public func `return`(_ value: ReturnedValue) { method.append(.return(value)) } /// Record subsequent return values, in given order (comma separated) /// /// - Parameter values: return values public func `return`(_ values: ReturnedValue...) { values.forEach(self.return) } } /// Used to populate stubbed method with sequence of events. Call it's methods, to record subsequent stub return/throw values. public struct StubberThrows<ReturnedValue> { /// [Internal] stubbed method private var method: StubbedMethod /// Stubbing policy. If wrap - it will iterate over recorded values. If drop - it will remove value when stub returns. If default - it will use mock settings public var policy: StubbingPolicy { get { return method.policy } set { method.policy = newValue } } /// [Internal] New instance of stubber class, used to populate products array /// /// - Parameters: /// - method: Stubbed method /// - returning: Return public init(_ method: StubbedMethod, returning: ReturnedValue.Type) { self.method = method } /// Record return value /// /// - Parameter value: return value public func `return`(_ value: ReturnedValue) { method.append(.return(value)) } /// Record subsequent return values, in given order (comma separated) /// /// - Parameter values: return values public func `return`(_ values: ReturnedValue...) { values.forEach(self.return) } /// Record thrown error /// /// - Parameter error: Error to throw public func `throw`(_ error: Error) { method.append(.throw(error)) } /// Record subsequent thrown errors, in given order (comma separated) /// /// - Parameter errors: Errors to throw public func `throw`(_ errors: Error...) { errors.forEach(self.throw) } }
mit
6f15f95cea7d2c24caed621375d70146
34.401235
161
0.651264
4.401381
false
false
false
false
natecook1000/swift
stdlib/public/SDK/CloudKit/NestedNames.swift
3
1380
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import CloudKit // Clang module // Work arounds for 39295365, 39261783 @nonobjc @available(macOS 10.10, iOS 8.0, watchOS 3.0, *) public extension CKContainer { @available(swift 4.2) public enum Application { public typealias Permissions = CKContainer_Application_Permissions public typealias PermissionStatus = CKContainer_Application_PermissionStatus public typealias PermissionBlock = CKContainer_Application_PermissionBlock } } @nonobjc @available(macOS 10.10, iOS 8.0, watchOS 3.0, *) extension CKOperation { @available(swift 4.2) public typealias ID = String } #if os(watchOS) @available(watchOS 3.0, *) public enum CKSubscription {} #endif // os(watchOS) @available(macOS 10.10, iOS 8.0, watchOS 3.0, *) extension CKSubscription { @available(swift 4.2) public typealias ID = String }
apache-2.0
f6f4a186ca6e1fcb8208acfd3da0b197
29
84
0.641304
4.339623
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Jalousie/Animation/QJalousieViewControllerAnimation.swift
1
4273
// // Quickly // public final class QJalousieViewControllerAnimation : IQJalousieViewControllerFixedAnimation { public var detailFullscreenSize: CGFloat public var detailShowedSize: CGFloat public var acceleration: CGFloat public init( detailFullscreenSize: CGFloat = UIScreen.main.bounds.height, detailShowedSize: CGFloat = UIScreen.main.bounds.height * 0.5, acceleration: CGFloat = 1200 ) { self.detailFullscreenSize = detailFullscreenSize self.detailShowedSize = detailShowedSize self.acceleration = acceleration } public func layout( contentView: UIView, state: QJalousieViewControllerState, contentViewController: IQJalousieViewController?, detailViewController: IQJalousieViewController? ) { if let vc = contentViewController { vc.view.frame = self._contentFrame(contentView: contentView, state: state) } if let vc = detailViewController { vc.view.frame = self._detailFrame(contentView: contentView, state: state) contentView.bringSubviewToFront(vc.view) } } public func animate( contentView: UIView, currentState: QJalousieViewControllerState, targetState: QJalousieViewControllerState, contentViewController: IQJalousieViewController?, detailViewController: IQJalousieViewController?, animated: Bool, complete: @escaping () -> Void ) { if currentState == .closed { detailViewController?.willPresent(animated: animated) } if targetState == .closed { detailViewController?.willDismiss(animated: animated) } if animated == true { let contentCurrentFrame = self._contentFrame(contentView: contentView, state: currentState) let contentTargetFrame = self._contentFrame(contentView: contentView, state: targetState) let detailCurrentFrame = self._detailFrame(contentView: contentView, state: currentState) let detailTargetFrame = self._detailFrame(contentView: contentView, state: targetState) let duration = TimeInterval(abs(detailCurrentFrame.centerPoint.distance(to: detailTargetFrame.centerPoint)) / self.acceleration) contentViewController?.view.frame = contentCurrentFrame detailViewController?.view.frame = detailCurrentFrame UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: { contentViewController?.view.frame = contentTargetFrame detailViewController?.view.frame = detailTargetFrame }, completion: { (completed) in if currentState == .closed { detailViewController?.didPresent(animated: animated) } if targetState == .closed { detailViewController?.didDismiss(animated: animated) } complete() }) } else { contentViewController?.view.frame = self._contentFrame(contentView: contentView, state: targetState) detailViewController?.view.frame = self._detailFrame(contentView: contentView, state: targetState) if currentState == .closed { detailViewController?.didPresent(animated: animated) } if targetState == .closed { detailViewController?.didDismiss(animated: animated) } complete() } } } // MARK: Private private extension QJalousieViewControllerAnimation { func _contentFrame(contentView: UIView, state: QJalousieViewControllerState) -> CGRect { return contentView.bounds } func _detailFrame(contentView: UIView, state: QJalousieViewControllerState) -> CGRect { let bounds = contentView.bounds switch state { case .fullscreen: return CGRect(x: bounds.origin.x, y: bounds.maxY - self.detailFullscreenSize, width: bounds.width, height: self.detailFullscreenSize) case .showed: return CGRect(x: bounds.origin.x, y: bounds.maxY - self.detailShowedSize, width: bounds.width, height: self.detailShowedSize) case .closed: return CGRect(x: bounds.origin.x, y: bounds.maxY, width: bounds.width, height: self.detailShowedSize) } } }
mit
543e2eaff154b7669ece330937528387
45.956044
159
0.681956
5.015258
false
false
false
false
superk589/DereGuide
DereGuide/Live/Controller/BeatmapViewController.swift
2
13103
// // BeatmapViewController.swift // DereGuide // // Created by zzk on 16/7/25. // Copyright © 2016 zzk. All rights reserved. // import UIKit import SnapKit class BeatmapViewController: UIViewController { override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } var scene: CGSSLiveScene! private func updateUI() { if let beatmap = checkBeatmapData(scene) { titleLabel.text = "\(scene.live.name)\n\(scene.stars)☆ \(scene.difficulty.description) bpm: \(scene.live.bpm) notes: \(beatmap.numberOfNotes)" pause() beatmapView.setup(beatmap: beatmap, bpm: scene.live.bpm, type: scene.live.type, setting: setting) if setting.isMirrorFlippedByDefault { flip() } beatmapView.setNeedsDisplay() } } let beatmapView = BeatmapView() let descLabel = UILabel() let titleLabel = UILabel() private typealias Setting = BeatmapAdvanceOptionsViewController.Setting private var setting = Setting.load() ?? Setting() lazy var optionController: BeatmapAdvanceOptionsViewController = { let vc = BeatmapAdvanceOptionsViewController(style: .grouped) vc.setting = self.setting vc.delegate = self return vc }() override func viewDidLoad() { super.viewDidLoad() prepareToolbar() print("Beatmap loaded, liveId: \(scene.live.id) musicId: \(scene.live.musicDataId)") beatmapView.settingDelegate = self self.view.addSubview(beatmapView) beatmapView.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.edges.equalTo(view.safeAreaLayoutGuide) } else { make.edges.equalToSuperview() } } if #available(iOS 11.0, *) { view.layoutIfNeeded() } beatmapView.contentMode = .redraw beatmapView.delegate = self // 自定义title描述歌曲信息 titleLabel.frame = CGRect(x: 0, y: 0, width: 0, height: 44) titleLabel.numberOfLines = 2 titleLabel.font = .systemFont(ofSize: 12) titleLabel.textAlignment = .center titleLabel.adjustsFontSizeToFitWidth = true titleLabel.baselineAdjustment = .alignCenters navigationItem.titleView = titleLabel navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("难度", comment: "谱面页面导航按钮"), style: .plain, target: self, action: #selector(selectDifficulty)) navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "765-arrow-left-toolbar"), style: .plain, target: self, action: #selector(backAction)) view.backgroundColor = .white updateUI() NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let progress = beatmapView.getProgress(for: CGPoint(x: 0, y: beatmapView.playOffsetY - beatmapView.contentOffset.y)) let shouldResume = beatmapView.isAutoScrolling if shouldResume { pause() } coordinator.animate(alongsideTransition: { (context) in self.beatmapView.setProgress(progress, for: CGPoint(x: 0, y: self.beatmapView.playOffsetY - self.beatmapView.contentOffset.y)) self.beatmapView.setNeedsDisplay() }, completion: { finished in if shouldResume && !self.beatmapView.isAutoScrolling { self.play() } }) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if #available(iOS 11.0, *) { beatmapView.contentOffset = CGPoint(x: 0, y: beatmapView.contentSize.height - beatmapView.frame.size.height + beatmapView.adjustedContentInset.bottom) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if beatmapView.isAutoScrolling { pause() } } @objc private func backAction() { navigationController?.popViewController(animated: true) } @objc private func selectDifficulty() { let alert = UIAlertController(title: NSLocalizedString("选择难度", comment: "底部弹出框标题"), message: nil, preferredStyle: .actionSheet) alert.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem for detail in scene.live.details { alert.addAction(UIAlertAction(title: detail.difficulty.description, style: .default, handler: { (a) in self.scene.difficulty = detail.difficulty self.updateUI() })) } alert.addAction(UIAlertAction(title: NSLocalizedString("取消", comment: "底部弹出框按钮"), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func showBeatmapNotFoundAlert() { let alert = UIAlertController.init(title: NSLocalizedString("数据缺失", comment: "弹出框标题"), message: NSLocalizedString("未找到对应谱面,建议等待当前更新完成,或尝试下拉歌曲列表手动更新数据。如果更新后仍未找到,可能是官方还未更新此谱面。", comment: "弹出框正文"), preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: NSLocalizedString("确定", comment: "弹出框按钮"), style: .default, handler: nil)) self.navigationController?.present(alert, animated: true, completion: nil) } func checkBeatmapData(_ scene: CGSSLiveScene) -> CGSSBeatmap? { if let beatmap = scene.beatmap { if let info = checkShiftingInfo() { beatmap.addShiftingOffset(info: info, rawBpm: scene.live.bpm) } else { beatmap.addStartOffset(rawBpm: scene.live.bpm) } return beatmap } else { showBeatmapNotFoundAlert() return nil } } func checkShiftingInfo() -> CGSSBeatmapShiftingInfo? { if let path = Bundle.main.path(forResource: "BpmShift", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) { for (k, v) in dict { let keys = (k as! String).components(separatedBy: ",") for key in keys { if Int(key) == scene.live.id { return CGSSBeatmapShiftingInfo(info: v as! NSDictionary) } } } } return nil } lazy private var playItem = UIBarButtonItem(image: #imageLiteral(resourceName: "1241-play-toolbar"), style: .plain, target: self, action: #selector(self.play)) lazy private var pauseItem = UIBarButtonItem(image: #imageLiteral(resourceName: "1242-pause-toolbar"), style: .plain, target: self, action: #selector(self.pause)) lazy private var flipItem = UIBarButtonItem(image: #imageLiteral(resourceName: "1110-rotate-toolbar"), style: .plain, target: self, action: #selector(self.flip)) private func prepareToolbar() { let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixedSpaceItem.width = 20 let shareItem = UIBarButtonItem(image: #imageLiteral(resourceName: "702-share-toolbar"), style: .plain, target: self, action: #selector(share)) let advanceItem = UIBarButtonItem(title: NSLocalizedString("选项", comment: ""), style: .plain, target: self, action: #selector(showAdvanceOptions)) let fixedSpaceItem2 = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixedSpaceItem2.width = 20 toolbarItems = [shareItem, fixedSpaceItem, flipItem, fixedSpaceItem2, playItem, spaceItem, advanceItem] } func setup(with scene: CGSSLiveScene) { self.scene = scene } func getImageTitle() -> String { return "\(scene.live.name) \(scene.stars)☆ \(scene.difficulty.description) bpm:\(scene.live.bpm) notes:\(scene.beatmap?.numberOfNotes ?? 0) length:\(Int(scene.beatmap?.totalSeconds ?? 0))s \(beatmapView.mirrorFlip ? "mirror flipped" : "") powered by \(Config.appName)" } func enterImageView() { beatmapView.exportImageAsync(title: getImageTitle()) { (image) in let data = image!.pngData() try? data?.write(to: URL.init(fileURLWithPath: "/Users/zzk/Desktop/aaa.png")) } } @objc private func share(item: UIBarButtonItem) { // enterImageView() CGSSLoadingHUDManager.default.show() beatmapView.exportImageAsync(title: getImageTitle()) { (image) in CGSSLoadingHUDManager.default.hide() if image == nil { return } let urlArray = [image!] let activityVC = UIActivityViewController.init(activityItems: urlArray, applicationActivities: nil) activityVC.popoverPresentationController?.barButtonItem = item // activityVC.popoverPresentationController?.sourceRect = CGRect(x: item.width / 2, y: 0, width: 0, height: 0) // 需要屏蔽的模块 let cludeActivitys:[UIActivity.ActivityType] = [] // 排除活动类型 activityVC.excludedActivityTypes = cludeActivitys // 呈现分享界面 self.present(activityVC, animated: true, completion: { }) } } @objc private func showAdvanceOptions() { let nav = BaseNavigationController(rootViewController: optionController) optionController.setting = setting nav.modalPresentationStyle = .formSheet present(nav, animated: true, completion: nil) } @objc private func flip() { beatmapView.mirrorFlip = !beatmapView.mirrorFlip if beatmapView.mirrorFlip { flipItem.image = #imageLiteral(resourceName: "1110-rotate-toolbar-selected") } else { flipItem.image = #imageLiteral(resourceName: "1110-rotate-toolbar") } } @objc private func play() { if let index = toolbarItems?.firstIndex(of: playItem) { toolbarItems?[index] = pauseItem } startAutoScrolling() } @objc private func pause() { if let index = toolbarItems?.firstIndex(of: pauseItem) { toolbarItems?[index] = playItem } endAutoScrolling() } private lazy var displayLink = CADisplayLink(target: self.beatmapView, selector: #selector(BeatmapView.frameUpdated(displayLink:))) func startAutoScrolling() { displayLink.add(to: .current, forMode: RunLoop.Mode.default) beatmapView.startAutoScrolling() navigationController?.interactivePopGestureRecognizer?.isEnabled = false } func endAutoScrolling() { // if click too quickly, the main runloop may receive two or more pause action, removing display link from runloop twice will crash. if beatmapView.isAutoScrolling { displayLink.remove(from: .current, forMode: RunLoop.Mode.default) beatmapView.endAutoScrolling() navigationController?.interactivePopGestureRecognizer?.isEnabled = true } } @objc private func enterBackground() { if beatmapView.isAutoScrolling { pause() } } deinit { displayLink.invalidate() NotificationCenter.default.removeObserver(self) } } extension BeatmapViewController: BeatmapViewSettingDelegate { func beatmapView(_ beatmapView: BeatmapView, didChange setting: BeatmapAdvanceOptionsViewController.Setting) { self.setting = setting self.setting.save() } } extension BeatmapViewController: BeatmapAdvanceOptionsViewControllerDelegate { func didDone(_ beatmapAdvanceOptionsViewController: BeatmapAdvanceOptionsViewController) { self.setting = beatmapAdvanceOptionsViewController.setting view.setNeedsLayout() updateUI() } } extension BeatmapViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { beatmapView.setNeedsDisplay() guard let drawer = beatmapView.drawer else { return } if beatmapView.isAutoScrolling && beatmapView.playOffsetY + drawer.inset.bottom < drawer.getPointY(beatmapView.beatmap.lastNote?.offsetSecond ?? 0) { pause() } } }
mit
eb2fc2b497a662a08910a01bfcc6136d
39.56962
276
0.641498
4.781798
false
false
false
false
longitachi/ZLPhotoBrowser
Sources/General/ZLPhotoModel.swift
1
4430
// // ZLPhotoModel.swift // ZLPhotoBrowser // // Created by long on 2020/8/11. // // Copyright (c) 2020 Long Zhang <495181165@qq.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Photos public extension ZLPhotoModel { enum MediaType: Int { case unknown = 0 case image case gif case livePhoto case video } } public class ZLPhotoModel: NSObject { public let ident: String public let asset: PHAsset public var type: ZLPhotoModel.MediaType = .unknown public var duration: String = "" public var isSelected: Bool = false private var pri_editImage: UIImage? public var editImage: UIImage? { set { pri_editImage = newValue } get { if let _ = editImageModel { return pri_editImage } else { return nil } } } public var second: Second { guard type == .video else { return 0 } return Int(round(asset.duration)) } public var whRatio: CGFloat { return CGFloat(asset.pixelWidth) / CGFloat(asset.pixelHeight) } public var previewSize: CGSize { let scale: CGFloat = UIScreen.main.scale if whRatio > 1 { let h = min(UIScreen.main.bounds.height, ZLMaxImageWidth) * scale let w = h * whRatio return CGSize(width: w, height: h) } else { let w = min(UIScreen.main.bounds.width, ZLMaxImageWidth) * scale let h = w / whRatio return CGSize(width: w, height: h) } } // Content of the last edit. public var editImageModel: ZLEditImageModel? public init(asset: PHAsset) { ident = asset.localIdentifier self.asset = asset super.init() type = transformAssetType(for: asset) if type == .video { duration = transformDuration(for: asset) } } public func transformAssetType(for asset: PHAsset) -> ZLPhotoModel.MediaType { switch asset.mediaType { case .video: return .video case .image: if (asset.value(forKey: "filename") as? String)?.hasSuffix("GIF") == true { return .gif } if #available(iOS 9.1, *) { if asset.mediaSubtypes.contains(.photoLive) { return .livePhoto } } return .image default: return .unknown } } public func transformDuration(for asset: PHAsset) -> String { let dur = Int(round(asset.duration)) switch dur { case 0..<60: return String(format: "00:%02d", dur) case 60..<3600: let m = dur / 60 let s = dur % 60 return String(format: "%02d:%02d", m, s) case 3600...: let h = dur / 3600 let m = (dur % 3600) / 60 let s = dur % 60 return String(format: "%02d:%02d:%02d", h, m, s) default: return "" } } } public extension ZLPhotoModel { static func ==(lhs: ZLPhotoModel, rhs: ZLPhotoModel) -> Bool { return lhs.ident == rhs.ident } }
mit
451982ecdf02ea9b431107ede75c18db
27.766234
87
0.573815
4.452261
false
false
false
false
peferron/algo
EPI/Binary Trees/Compute the right sibling tree/swift/main.swift
1
1061
public class Node { public let left: Node? public let right: Node? public var rightSibling: Node? public init(left: Node? = nil, right: Node? = nil) { self.left = left self.right = right } func inorder(_ depth: Int = 0, _ process: (Node, Int) -> Void) { left?.inorder(depth + 1, process) process(self, depth) right?.inorder(depth + 1, process) } public func initRightSiblings() { var lastNodeAtDepth = [Int: Node]() inorder { node, depth in lastNodeAtDepth[depth]?.rightSibling = node lastNodeAtDepth[depth] = node } } public func initRightSiblingsOfPerfectTree() { var leftMost = self while let nextLeftMost = leftMost.left { var node: Node? = leftMost while let n = node { n.left!.rightSibling = n.right n.right!.rightSibling = n.rightSibling?.left node = n.rightSibling } leftMost = nextLeftMost } } }
mit
dd87a59da7c2485daa42dffb43b7bc02
27.675676
68
0.547597
4.144531
false
false
false
false
pacmacro/pm-iOS
PM pacMacro2/MapViewController.swift
1
5684
import Mapbox class MapViewController: UIViewController, MGLMapViewDelegate{ static let REFRESHRATE = TimeInterval(10) static let REFRESHPERIOD = TimeInterval(60)/REFRESHRATE var mapView: MGLMapView! var timer: Timer = Timer() var times = 0 var annotationList: [MGLPointAnnotation] = [] //list of annotations to display on the map let gameInstance = Game() var currentPlayers: [Player] = [] var currentDots: [Dot] = [] //Information override func viewDidLoad() { super.viewDidLoad() // initialize the map view mapView = MGLMapView(frame: view.bounds, styleURL: URL(string: "mapbox://styles/ctrlshiftgo/cihfgoup600o2jnkx6dhzb3eh")) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // set the map's center coordinate mapView.setCenter(CLLocationCoordinate2D(latitude: 49.280915, longitude: -123.122352), zoomLevel: 15, animated: false) view.addSubview(mapView) mapView.delegate = self // TODO Drawing overlay // TODO drawBoundingRect() //TODO Initialize Annotation List //Call Timer Object timer = Timer.scheduledTimer(timeInterval: MapViewController.REFRESHPERIOD, target: self, selector: #selector(MapViewController.mapLoop), userInfo: nil, repeats: true ) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { timer.invalidate() print("TImer should have been invalidated\n") } func drawBoundingRect(){ //Setup center location let vanLat = 49.280915 let vanLon = -123.122352 //Setting up coordinates var coords: [CLLocationCoordinate2D] = [ CLLocationCoordinate2DMake(vanLat, vanLon), CLLocationCoordinate2DMake(vanLat, vanLon + 0.002), CLLocationCoordinate2DMake(vanLat - 0.002, vanLon + 0.002), CLLocationCoordinate2DMake(vanLat - 0.002, vanLon) ] //Building Overlay let tmpOverlay = MGLPolygon(coordinates: &coords, count: UInt(coords.count)) //Adding the overlay to the map mapView.addAnnotation(tmpOverlay) } func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat{ return 0.5 } func mapView(_ mapView: MGLMapView, fillColorForPolygonAnnotation annotation: MGLPolygon) -> UIColor { return UIColor.white } /// Main game loop which runs until user exits the map view. /// Utilizes a timer which requires the @objc function to expose it to the Objective-C API /// [Source and further explanation](https://stackoverflow.com/a/48386977) @objc func mapLoop(){ // Update from server let update = gameInstance.updateServer() //Initializing and setup currentDots = gameInstance.getVisibleDots() currentPlayers = gameInstance.getVisiblePlayers() //Update Player locations on map for player in currentPlayers{ drawPlayer(player, annotationList: &annotationList) } for dot in currentDots { drawDot(dot, annotationList: &annotationList) } redrawAnnotations(annotationList) //Counter for times this has looped print("I have waited \(times) cycles") times += 1 } /** * Will check to see if the player has already been drawn * Removes the existing player based on the id * Redraws them at the new location */ func drawPlayer(_ playerInput: Player, annotationList: inout [MGLPointAnnotation]){ // Setting up annotation object let playerIcon = MGLPointAnnotation() playerIcon.coordinate = playerInput.coordinates playerIcon.title = playerInput.playerType.rawValue + "-" + playerInput.playerName // playerIcon.subtitle = playerInput.playerType //Check for player already existing on the screen var annotationExists: Bool = false for annotation in annotationList { if annotation.title == playerInput.playerType.rawValue + "-" + playerInput.playerName { annotationExists = true annotation.coordinate = playerInput.coordinates } } if(!annotationExists){ mapView.addAnnotation(playerIcon) annotationList.append(playerIcon) } } func drawDot(_ dotInput: Dot, annotationList: inout [MGLPointAnnotation]){ } // Removes all existing annotations and replaces them to update coordinates func redrawAnnotations(_ annotationList: [MGLPointAnnotation]){ mapView.removeAnnotations(annotationList) mapView.addAnnotations(annotationList) } /// Delegate function to set images for annotations. Will set the image based on the title of the annotation. func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage?{ var imageName = ""; // Unwrap the annotation subtitle if let iconType : String = annotation.subtitle! { imageName = iconType; } var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: imageName) let playerName : String = annotation.title!! if annotationImage == nil { let image = UIImage(named: imageName) annotationImage = MGLAnnotationImage(image: image!, reuseIdentifier: imageName + playerName) } return annotationImage } }
mit
c00e465dfe80018088c5ee5367cb4967
38.748252
176
0.643561
5.034544
false
false
false
false
jinSasaki/Vulcan
Sources/Vulcan/Vulcan.swift
1
5047
// // Vulcan.swift // Vulcan // // Created by Jin Sasaki on 2017/04/23. // Copyright © 2017年 Sasakky. All rights reserved. // import UIKit final public class Vulcan { public static var defaultImageDownloader: ImageDownloader = ImageDownloader.default public private(set) var priority: Int = Int.min public var imageDownloader: ImageDownloader { get { return _imageDownloader ?? Vulcan.defaultImageDownloader } set { _imageDownloader = newValue } } public static var cacheMemoryCapacity: Int? { get { return defaultImageDownloader.cache?.memoryCapacity } set { guard let newValue = newValue else { return } defaultImageDownloader.cache?.memoryCapacity = newValue } } public static var diskCapacity: Int? { get { return defaultImageDownloader.cache?.diskCapacity } set { guard let newValue = newValue else { return } defaultImageDownloader.cache?.diskCapacity = newValue } } public static var diskPath: String? { get { return defaultImageDownloader.cache?.diskPath } set { guard let newValue = newValue else { return } defaultImageDownloader.cache?.diskPath = newValue } } internal weak var imageView: UIImageView? private var _imageDownloader: ImageDownloader? private var downloadTaskId: String? private var dummyView: UIImageView? public static func setDefault(imageDownloader: ImageDownloader) { self.defaultImageDownloader = imageDownloader } public func setImage(url: URL, placeholderImage: UIImage? = nil, composer: ImageComposable? = nil, options: ImageDecodeOptions? = nil, completion: ImageDownloadHandler? = nil) { let downloader = imageDownloader cancelLoading() imageView?.image = placeholderImage let id = downloader.download(url: url, composer: composer, options: options) { (url, result) in switch result { case .success(let image): DispatchQueue.main.async { self.showImage(image: image) } default: break } completion?(url, result) } self.downloadTaskId = id } public enum PriorityURL { case url(URL, priority: Int) case request(URLRequest, priority: Int) public var priority: Int { switch self { case .url(_, let priority): return priority case .request(_, let priority): return priority } } public var url: URL { switch self { case .url(let url, _): return url case .request(let request, _): return request.url! } } } /// Download images with priority public func setImage(urls: [PriorityURL], placeholderImage: UIImage? = nil, composer: ImageComposable? = nil, options: ImageDecodeOptions? = nil) { let downloader = imageDownloader cancelLoading() imageView?.image = placeholderImage let ids = urls.sorted(by: { $0.priority < $1.priority }) .map({ (priorityURL) -> String in return downloader.download(url: priorityURL.url, composer: composer, options: options) { (url, result) in switch result { case .success(let image): DispatchQueue.main.async { if self.priority <= priorityURL.priority { self.priority = priorityURL.priority self.showImage(image: image) } } default: break } } }) self.downloadTaskId = ids.joined(separator: ",") } public func cancelLoading() { let downloader = imageDownloader guard let splited = downloadTaskId?.components(separatedBy: ",") else { return } splited.forEach({ downloader.cancel(id: $0) }) self.priority = Int.min } private func showImage(image newImage: UIImage) { guard let baseImageView = self.imageView else { return } let imageView = dummyView ?? UIImageView() imageView.frame = baseImageView.bounds imageView.alpha = 1 imageView.image = baseImageView.image imageView.contentMode = baseImageView.contentMode baseImageView.addSubview(imageView) baseImageView.image = newImage dummyView = imageView UIView.animate(withDuration: 0.3, animations: { self.dummyView?.alpha = 0 }) { (finished) in self.dummyView?.removeFromSuperview() self.dummyView = nil } } }
mit
1a53c2de932e846e689c853eba720c68
32.184211
181
0.565821
5.248699
false
false
false
false
AcaiBowl/Closurable
Closurable/Closurable.swift
1
2911
// // Closurable.swift // Closurable // // Created by Toru Asai on 2017/09/07. // Copyright © 2017年 AcaiBowl. All rights reserved. // import UIKit public protocol Closurable: class {} extension NSObject: Closurable {} extension Closurable where Self: NSObject { public func subscribe<Value>(_ keyPath: KeyPath<Self, Value>, closure: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void) -> Releasable { let observation = observe(keyPath, options: [.new, .initial], changeHandler: closure) return NoOptionalReleasable(with: observation) } } extension Closurable where Self: UIControl { public func on(_ events: UIControlEvents, closure: @escaping (Any) -> Void) -> Releasable { let container = Container(closure: closure) addTarget(container, action: container.selector, for: events) return NoOptionalReleasable(with: container) } } extension Closurable where Self: UIButton { public func onTap(_ closure: @escaping (Any) -> Void) -> Releasable { let container = Container(closure: closure) addTarget(container, action: container.selector, for: .touchUpInside) return NoOptionalReleasable(with: container) } } extension Closurable where Self: UIBarButtonItem { public init(title: String, style: UIBarButtonItemStyle) { self.init() self.title = title self.style = style } public init(image: UIImage?, style: UIBarButtonItemStyle) { self.init() self.image = image self.style = style } public func onTap(_ closure: @escaping (Any) -> Void) -> Releasable { let container = Container(closure: closure) self.target = container self.action = container.selector return NoOptionalReleasable(with: container) } } extension Closurable where Self: UIGestureRecognizer { public func on(_ closure: @escaping (Any) -> Void) -> Releasable { let container = Container(closure: closure) addTarget(container, action: container.selector) return NoOptionalReleasable(with: container) } } extension Closurable where Self: NotificationCenter { public func on(_ name: NSNotification.Name?, object: Any? = nil, closure: @escaping (Any) -> Void) -> Releasable { let container = Container(closure: closure) addObserver(container, selector: container.selector, name: name, object: object) return ActionReleasable(with: container, action: { [weak self] in self?.removeObserver(container) }) } } private final class Container { var closure: (Any) -> Void var selector: Selector { return #selector(selector(_:)) } init(closure: @escaping (Any) -> Void) { self.closure = closure } @objc func selector(_ sender: Any) { closure(sender) } }
mit
c93ba1f1f6719492dc5ff955a33da410
31.311111
118
0.652682
4.320951
false
false
false
false
nguyenkhiem/Swift3Validation
SwiftValidator/Core/Validator.swift
1
5893
// // Validator.swift // // Created by Jeff Potter on 11/10/14. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation import UIKit /** Class that makes `Validator` objects. Should be added as a parameter to ViewController that will display validation fields. */ open class Validator { /// Dictionary to hold all fields (and accompanying rules) that will undergo validation. open var validations = [UITextField:ValidationRule]() /// Dictionary to hold fields (and accompanying errors) that were unsuccessfully validated. open var errors = [UITextField:ValidationError]() /// Variable that holds success closure to display positive status of field. fileprivate var successStyleTransform:((_ validationRule:ValidationRule)->Void)? /// Variable that holds error closure to display negative status of field. fileprivate var errorStyleTransform:((_ validationError:ValidationError)->Void)? /// - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. public init(){} // MARK: Private functions /** This method is used to validate all fields registered to Validator. If validation is unsuccessful, field gets added to errors dictionary. - returns: No return value. */ fileprivate func validateAllFields() { errors = [:] for (textField, rule) in validations { if let error = rule.validateField() { errors[textField] = error // let the user transform the field if they want if let transform = self.errorStyleTransform { transform(error) } } else { // No error // let the user transform the field if they want if let transform = self.successStyleTransform { transform(rule) } } } } // MARK: Public functions /** This method is used to validate a single field registered to Validator. If validation is unsuccessful, field gets added to errors dictionary. - parameter textField: Holds validator field data. - returns: No return value. */ open func validateField(_ textField: UITextField, callback: (_ error:ValidationError?) -> Void){ if let fieldRule = validations[textField] { if let error = fieldRule.validateField() { errors[textField] = error if let transform = self.errorStyleTransform { transform(error) } callback(error) } else { if let transform = self.successStyleTransform { transform(fieldRule) } callback(nil) } } else { callback(nil) } } // MARK: Using Keys /** This method is used to style fields that have undergone validation checks. Success callback should be used to show common success styling and error callback should be used to show common error styling. - parameter success: A closure which is called with validationRule, an object that holds validation data - parameter error: A closure which is called with validationError, an object that holds validation error data - returns: No return value */ open func styleTransformers(success:((_ validationRule:ValidationRule)->Void)?, error:((_ validationError:ValidationError)->Void)?) { self.successStyleTransform = success self.errorStyleTransform = error } /** This method is used to add a field to validator. - parameter textField: field that is to be validated. - parameter Rule: An array which holds different rules to validate against textField. - returns: No return value */ open func registerField(_ textField:UITextField, rules:[Rule]) { validations[textField] = ValidationRule(textField: textField, rules: rules, errorLabel: nil) } /** This method is used to add a field to validator. - parameter textfield: field that is to be validated. - parameter errorLabel: A UILabel that holds error label data - parameter rules: A Rule array that holds different rules that apply to said textField. - returns: No return value */ open func registerField(_ textField:UITextField, errorLabel:UILabel, rules:[Rule]) { validations[textField] = ValidationRule(textField: textField, rules:rules, errorLabel:errorLabel) } /** This method is for removing a field validator. - parameter textField: field used to locate and remove textField from validator. - returns: No return value */ open func unregisterField(_ textField:UITextField) { validations.removeValue(forKey: textField) errors.removeValue(forKey: textField) } /** This method checks to see if all fields in validator are valid. - returns: No return value. */ open func validate(_ delegate:ValidationDelegate) { self.validateAllFields() if errors.isEmpty { delegate.validationSuccessful() } else { delegate.validationFailed(errors) } } /** This method validates all fields in validator and sets any errors to errors parameter of callback. - parameter callback: A closure which is called with errors, a dictionary of type UITextField:ValidationError. - returns: No return value. */ open func validate(_ callback:(_ errors:[UITextField:ValidationError])->Void) -> Void { self.validateAllFields() callback(errors) } }
mit
525a807ca98e96a5360dbe5bcef58fc3
35.376543
205
0.632106
5.32821
false
false
false
false
Eitot/vienna-rss
Vienna/Sources/Main window/ArticleConverter.swift
1
2296
// // ArticleConverter.swift // Vienna // // Copyright 2020 Tassilo Karge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation @objc extension ArticleConverter { func setup() { // Update the article content style when the active display style has // changed. NotificationCenter.default.addObserver(self, selector: #selector(self.initForCurrentStyle), name: NSNotification.Name("MA_Notify_StyleChange"), object: nil) self.initForCurrentStyle() } func initForCurrentStyle() { self.initForStyle(Preferences.standard.displayStyle) } func initForStyle(_ name: String) { guard let pathString = ArticleStyleLoader.stylesMap[name] as? String else { self.styleChangeFailed(name) return } let path = URL(fileURLWithPath: pathString) self.initForStyle(at: path) } func initForStyle(at path: URL) { preconditionFailure("must be overridden by subclasses") } func styleChangeFailed(_ name: String) { // If the template is invalid, revert to the default style // which should ALWAYS be valid. assert(name != "Default", "Default style is corrupted!") // Warn the user. let title = NSLocalizedString("The style %@ appears to be missing or corrupted", comment: "") .replacingOccurrences(of: "%@", with: name) let body = NSLocalizedString("The Default style will be used instead.", comment: "") runOKAlertPanelPlain(title, body) // We need to reset the preferences without firing off a notification since we want the // style change to happen immediately. Preferences.standard.setDisplayStyle("Default", withNotification: false) } }
apache-2.0
814cd1d69bb190eef8ddcd8808db4da5
33.787879
164
0.679007
4.501961
false
false
false
false
yukiasai/Shoyu
Classes/Row.swift
1
4119
// // Row.swift // Shoyu // // Created by asai.yuki on 2015/12/12. // Copyright © 2015年 yukiasai. All rights reserved. // import UIKit open class Row<T: UITableViewCell>: RowType { public typealias RowInformation = (row: Row<T>, tableView: UITableView, indexPath: IndexPath) public typealias RowMoveInformation = (row: Row<T>, tableView: UITableView, sourceIndexPath: IndexPath, destinationIndexPath: IndexPath) public init() { } public init(closure: ((Row<T>) -> Void)) { closure(self) } open var configureCell: ((T, RowInformation) -> Void)? open var heightFor: ((RowInformation) -> CGFloat?)? open var estimatedHeightFor: ((RowInformation) -> CGFloat?)? open var canRemove: ((RowInformation) -> Bool)? open var canMove: ((RowInformation) -> Bool)? open var canMoveTo: ((RowMoveInformation) -> Bool)? open var didSelect: ((RowInformation) -> Void)? open var didDeselect: ((RowInformation) -> Void)? open var willDisplayCell: ((T, RowInformation) -> Void)? open var didEndDisplayCell: ((T, RowInformation) -> Void)? open var willRemove: ((RowInformation) -> UITableViewRowAnimation?)? open var didRemove: ((RowInformation) -> Void)? fileprivate var _reuseIdentifier: String? open var reuseIdentifier: String { set { _reuseIdentifier = newValue } get { if let identifier = _reuseIdentifier { return identifier } let identifier = T() as ReuseIdentifierType return identifier.identifier } } open var height: CGFloat? open var estimatedHeight: CGFloat? } extension Row: RowDelegateType { func configureCell(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath) { guard let genericCell = cell as? T else { fatalError() } configureCell?(genericCell, (self, tableView, indexPath)) } func heightFor(_ tableView: UITableView, indexPath: IndexPath) -> CGFloat? { return heightFor?((self, tableView, indexPath)) ?? height } func estimatedHeightFor(_ tableView: UITableView, indexPath: IndexPath) -> CGFloat? { return estimatedHeightFor?((self, tableView, indexPath)) ?? estimatedHeight } func canEdit(_ tableView: UITableView, indexPath: IndexPath) -> Bool { return canRemove(tableView, indexPath: indexPath) || canMove(tableView, indexPath: indexPath) } func canRemove(_ tableView: UITableView, indexPath: IndexPath) -> Bool { return canRemove?((self, tableView, indexPath)) ?? false } func canMove(_ tableView: UITableView, indexPath: IndexPath) -> Bool { return canMove?((self, tableView, indexPath)) ?? false } func canMoveTo(_ tableView: UITableView, sourceIndexPath: IndexPath, destinationIndexPath: IndexPath) -> Bool { return canMoveTo?((self, tableView, sourceIndexPath, destinationIndexPath)) ?? false } func didSelect(_ tableView: UITableView, indexPath: IndexPath) { didSelect?((self, tableView, indexPath)) } func didDeselect(_ tableView: UITableView, indexPath: IndexPath) { didDeselect?((self, tableView, indexPath)) } func willDisplayCell(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath) { guard let genericCell = cell as? T else { fatalError() } willDisplayCell?(genericCell, (self, tableView, indexPath)) } func didEndDisplayCell(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath) { guard let genericCell = cell as? T else { return } didEndDisplayCell?(genericCell, (self, tableView, indexPath)) } func willRemove(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewRowAnimation { return willRemove?((self, tableView, indexPath)) ?? .fade } func didRemove(_ tableView: UITableView, indexPath: IndexPath) { didRemove?((self, tableView, indexPath)) } }
mit
f1aa09b22c79659cf489a63cf4ae4602
35.424779
140
0.646744
4.959036
false
false
false
false
victorpimentel/MarvelAPI
MarvelAPI.playground/Sources/Models/Image.swift
1
752
import Foundation /// Common object for images coming from the Marvel API /// Shows how to fully conform to Decodable public struct Image: Decodable { /// Server sends the remote URL splits in two: the path and the extension enum ImageKeys: String, CodingKey { case path = "path" case fileExtension = "extension" } /// The remote URL for this image public let url: URL public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ImageKeys.self) let path = try container.decode(String.self, forKey: .path) let fileExtension = try container.decode(String.self, forKey: .fileExtension) guard let url = URL(string: "\(path).\(fileExtension)") else { throw MarvelError.decoding } self.url = url } }
apache-2.0
67624ee8ba617ae80028a15d28c15a34
29.08
93
0.727394
3.85641
false
false
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFramework/base/model/HMResult.swift
1
3213
// // HMResult.swift // HMRequestFramework // // Created by Hai Pham on 8/10/17. // Copyright © 2017 Holmusk. All rights reserved. // import SwiftFP import SwiftUtilities /// Use this class to represent the result of some operation that is applied /// to multiple items (e.g. in an Array), for which the result of each application /// could be relevant to downstream flow. public struct HMResult<Val> { public static func just(_ obj: Val) -> HMResult<Val> { return HMResult<Val>.builder().with(object: obj).build() } public static func just(_ error: Error) -> HMResult<Val> { return HMResult<Val>.builder().with(error: error).build() } /// Convert a Try to a HMResult. /// /// - Parameter tryInstance: A Try instance. /// - Returns: A HMResult instance. public static func from(_ tryInstance: Try<Val>) -> HMResult<Val> { do { let result = try tryInstance.getOrThrow() return HMResult.just(result) } catch let e { return HMResult.just(e) } } /// Unwrap a Try that contains a HMResult. /// /// - Parameter wrapped: A Try instance. /// - Returns: A HMResult instance. public static func unwrap(_ wrapped: Try<HMResult<Val>>) -> HMResult<Val> { do { let result = try wrapped.getOrThrow() return result } catch let e { return HMResult.just(e) } } fileprivate var object: Val? fileprivate var error: Error? fileprivate init() {} public func appliedObject() -> Val? { return object } public func operationError() -> Error? { return error } } public extension HMResult { public func isSuccess() -> Bool { return error == nil } public func isFailure() -> Bool { return !isSuccess() } } extension HMResult: HMBuildableType { public static func builder() -> Builder { return Builder() } public final class Builder { fileprivate var result: HMResult fileprivate init() { result = HMResult() } /// Set the object to which the operation was applied. /// /// - Parameter object: A Val instance. /// - Returns: The current Builder instance. @discardableResult public func with(object: Val?) -> Self { result.object = object return self } /// Set the operation Error. /// /// - Parameter error: An Error instance. /// - Returns: The current Builder instance. @discardableResult public func with(error: Error?) -> Self { result.error = error return self } } } extension HMResult.Builder: HMBuilderType { public typealias Buildable = HMResult<Val> public func with(buildable: Buildable?) -> Self { if let buildable = buildable { return self .with(object: buildable.object) .with(error: buildable.error) } else { return self } } public func build() -> Buildable { return result } } extension HMResult: TryConvertibleType { public func asTry() -> Try<Val> { if let error = self.operationError() { return Try.failure(error) } else if let object = self.appliedObject() { return Try.success(object) } else { return Try.failure(Exception("Invalid result \(self)")) } } }
apache-2.0
63ae0a6872e64324f4bcd17c5d2285f0
22.445255
82
0.636052
4.025063
false
false
false
false
loudnate/LoopKit
LoopKitUI/Views/DatePickerTableViewCell.swift
1
3246
// // DatePickerTableViewCell.swift // CarbKit // // Created by Nathan Racklyeft on 1/15/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit public protocol DatePickerTableViewCellDelegate: class { func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) } open class DatePickerTableViewCell: UITableViewCell { open var date: Date { get { return datePicker.date } set { datePicker.setDate(newValue, animated: true) updateDateLabel() } } open var duration: TimeInterval { get { return datePicker.countDownDuration } set { datePicker.countDownDuration = newValue updateDateLabel() } } open var maximumDuration = TimeInterval(hours: 8) { didSet { if duration > maximumDuration { duration = maximumDuration } } } @IBOutlet open weak var datePicker: UIDatePicker! @IBOutlet open weak var datePickerHeightConstraint: NSLayoutConstraint! private var datePickerExpandedHeight: CGFloat = 0 open var isDatePickerHidden: Bool { get { return datePicker.isHidden || !datePicker.isEnabled } set { if datePicker.isEnabled { datePicker.isHidden = newValue datePickerHeightConstraint.constant = newValue ? 0 : datePickerExpandedHeight if !newValue, case .countDownTimer = datePicker.datePickerMode { // Workaround for target-action change notifications not firing if initial value is set while view is hidden DispatchQueue.main.async { self.datePicker.date = self.datePicker.date self.datePicker.countDownDuration = self.datePicker.countDownDuration } } } } } open override func awakeFromNib() { super.awakeFromNib() datePickerExpandedHeight = datePickerHeightConstraint.constant setSelected(true, animated: false) updateDateLabel() } open override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { isDatePickerHidden = !isDatePickerHidden } } open func updateDateLabel() { } @IBAction open func dateChanged(_ sender: UIDatePicker) { if case .countDownTimer = sender.datePickerMode, duration > maximumDuration { duration = maximumDuration } else { updateDateLabel() } } } /// UITableViewController extensions to aid working with DatePickerTableViewCell extension DatePickerTableViewCellDelegate where Self: UITableViewController { public func hideDatePickerCells(excluding indexPath: IndexPath? = nil) { guard isViewLoaded else { return } for case let cell as DatePickerTableViewCell in tableView.visibleCells where tableView.indexPath(for: cell) != indexPath && cell.isDatePickerHidden == false { cell.isDatePickerHidden = true } } }
mit
492236cf22b65ebd16c4a5895f8b7922
27.973214
166
0.623729
5.702988
false
false
false
false
nixzhu/MonkeyKing
Sources/MonkeyKing/MonkeyKing+Program.swift
1
1587
import Foundation extension MonkeyKing { public enum Program { public enum WeChatSubType { case miniApp(username: String, path: String?, type: MiniAppType) } case weChat(WeChatSubType) } public class func launch(_ program: Program, completionHandler: @escaping LaunchCompletionHandler) { guard program.platform.isAppInstalled else { completionHandler(.failure(.noApp)) return } guard let account = shared.accountSet[program.platform] else { completionHandler(.failure(.noAccount)) return } shared.launchCompletionHandler = completionHandler switch program { case .weChat(let type): switch type { case .miniApp(let username, let path, let type): var components = URLComponents(string: "weixin://app/\(account.appID)/jumpWxa/") components?.queryItems = [ URLQueryItem(name: "userName", value: username), URLQueryItem(name: "path", value: path), URLQueryItem(name: "miniProgramType", value: String(type.rawValue)), ] guard let url = components?.url else { completionHandler(.failure(.sdk(.urlEncodeFailed))) return } shared.openURL(url) { flag in if flag { return } completionHandler(.failure(.sdk(.invalidURLScheme))) } } } } }
mit
1e69183edb5dc12cf4c35e70ded157d2
31.387755
104
0.546944
5.510417
false
false
false
false
AlexLittlejohn/ALPlacesViewController
ALPlacesViewController/ALStickyHeaderFlowLayout.swift
1
1620
// // ALStickyHeaderFlowLayout.swift // ALPlacesViewController // // Created by Alex Littlejohn on 2015/07/13. // Copyright (c) 2015 zero. All rights reserved. // import UIKit internal class ALStickyHeaderFlowLayout: UICollectionViewFlowLayout { override var scrollDirection: UICollectionViewScrollDirection { get { return UICollectionViewScrollDirection.Vertical } set(newValue) { super.scrollDirection = newValue } } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let insets = collectionView!.contentInset let offset = collectionView!.contentOffset let minY = -insets.top let attributes = super.layoutAttributesForElementsInRect(rect)! if offset.y < minY { let headerSize = headerReferenceSize let deltaY = fabs(offset.y - minY) for item in attributes { if let attribute = item as? UICollectionViewLayoutAttributes, elementKind = attribute.representedElementKind { if elementKind == UICollectionElementKindSectionHeader { attribute.frame.size.height = fmax(minY, headerSize.height + deltaY) attribute.frame.origin.y = attribute.frame.origin.y - deltaY break } } } } return attributes } }
mit
119267962ac320a1ec80b4c7e7d70086
30.764706
126
0.601852
6.022305
false
false
false
false
practicalswift/Pythonic.swift
src/swift-style-checker.swift
1
2518
#!/usr/bin/env swift -I . // Usage: swift-style-checker.swift [FILE...] // // This is work in progress. Feel free to add additional checks! :-) import Pythonic if len(sys.argv) <= 1 { print("Usage: swift-style-checker.swift [FILE...]") sys.exit(0) } func countLeadingSpaces(s: String) -> Int { for (i, ch) in s.characters.enumerate() { if ch != " " { return i } } return 0 } func checkFile(fileName: String) -> Bool { var passed = true for (lineNumber, originalLine) in open(fileName).enumerate() { let numberOfLeadingSpaces = countLeadingSpaces(originalLine) let lineWithoutLeadingSpaces = originalLine[numberOfLeadingSpaces..<len(originalLine)] if re.search("\t", originalLine) { print("ERROR – Line #\(lineNumber + 1) of \(fileName) contains an raw/unquoted tab (\\t):") print(originalLine.replace("\t", "\\t")) passed = false } else if numberOfLeadingSpaces % 4 != 0 { print("ERROR – Line #\(lineNumber + 1) of \(fileName) has indentation of \(numberOfLeadingSpaces) spaces which is not a multiple of four (4):") print(originalLine) passed = false } else if lineWithoutLeadingSpaces != lineWithoutLeadingSpaces.lstrip() { print("ERROR – Line #\(lineNumber + 1) of \(fileName) contains leading whitespace:") print(originalLine) passed = false } else if lineWithoutLeadingSpaces != lineWithoutLeadingSpaces.rstrip() { print("ERROR – Line #\(lineNumber + 1) of \(fileName) contains trailing whitespace:") print(originalLine) passed = false } else if re.search(";$", originalLine) { print("ERROR – Line #\(lineNumber + 1) of \(fileName) ends with a redundant \";\":") print(originalLine) passed = false } else if re.search("^[^\"]+[\\[(][a-z0-9]+,[a-z0-9]", originalLine) || re.search("^[^\"]*\"[^\"]*\"[^\"]*[\\[(][a-z0-9]+,[a-z0-9]", originalLine) { print("ERROR – Line #\(lineNumber + 1) of \(fileName) has variables listed without being separated by space (\"foo,bar\" instead of \"foo, bar\"):") print(originalLine) passed = false } } return passed } var hasErrors = false let fileNames = sys.argv[1..<len(sys.argv)] for fileName in fileNames { if !checkFile(fileName) { hasErrors = true } } if hasErrors { sys.exit(-1) }
mit
ec7acc8cb7db54abcf6c64725e25ad4e
36.402985
160
0.588188
3.934066
false
false
false
false
tsolomko/SWCompression
Sources/7-Zip/7zCoder+Equatable.swift
1
716
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension SevenZipCoder: Equatable { static func == (lhs: SevenZipCoder, rhs: SevenZipCoder) -> Bool { let propertiesEqual: Bool if lhs.properties == nil && rhs.properties == nil { propertiesEqual = true } else if lhs.properties != nil && rhs.properties != nil { propertiesEqual = lhs.properties! == rhs.properties! } else { propertiesEqual = false } return lhs.id == rhs.id && lhs.numInStreams == rhs.numInStreams && lhs.numOutStreams == rhs.numOutStreams && propertiesEqual } }
mit
46e9526920d3fe4a744ce4204e62a607
30.130435
74
0.622905
4.447205
false
false
false
false
pccole/GitHubJobs-iOS
GitHubJobs/ViewRepresentable/AttributedText.swift
1
805
// // AttributedText.swift // GitHubJobs // // Created by Phil Cole on 4/25/20. // Copyright © 2020 Cole LLC. All rights reserved. // import Foundation import SwiftUI import UIKit struct AttributedText: UIViewRepresentable { let string: String var textView: UITextView { let view = UITextView() view.translatesAutoresizingMaskIntoConstraints = false view.isScrollEnabled = false view.isEditable = false return view } func makeUIView(context: Context) -> UITextView { return textView } func updateUIView(_ uiView: UITextView, context: Context) { string.htmlAttributedString { (attrString) in uiView.attributedText = attrString uiView.layoutIfNeeded() } } }
mit
70fa658d7fa10a7343db976d91920c43
20.72973
63
0.635572
5.088608
false
false
false
false
qlongming/shppingCat
shoppingCart-master/shoppingCart/Classes/Library/SnapKit/LayoutConstraint.swift
14
2176
// // SnapKit // // Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif /** Used to add extra information to the actual `NSLayoutConstraint`'s that will UIKit/AppKit will utilize */ public class LayoutConstraint: NSLayoutConstraint { internal var snp_constraint: Constraint? = nil public var snp_location: SourceLocation? { return snp_constraint?.location } } internal func ==(left: LayoutConstraint, right: LayoutConstraint) -> Bool { if left.firstItem !== right.firstItem { return false } if left.secondItem !== right.secondItem { return false } if left.firstAttribute != right.firstAttribute { return false } if left.secondAttribute != right.secondAttribute { return false } if left.relation != right.relation { return false } if left.priority != right.priority { return false } if left.multiplier != right.multiplier { return false } return true }
apache-2.0
f1e78b8d72cc6b4375b7df22a50a2f26
31.969697
106
0.700827
4.459016
false
false
false
false
pascalbros/PAPermissions
PAPermissions/Classes/Checks/PAPhotoLibraryPermissionsCheck.swift
1
1139
// // PAPhotoLibraryPermissionsCheck.swift // Pods // // Created by Joseph Blau on 9/24/16. // // import UIKit import Photos public class PAPhotoLibraryPermissionsCheck: PAPermissionsCheck { public override func checkStatus() { let currentStatus = self.status self.updatePermissions(status: PHPhotoLibrary.authorizationStatus()) if self.status != currentStatus { self.updateStatus() } } public override func defaultAction() { PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) in self.updatePermissions(status: status) self.updateStatus() }) } private func updatePermissions(status: PHAuthorizationStatus) { let oldStatus = self.status switch status { case .authorized: self.status = .enabled case .denied: self.status = .denied case .notDetermined, .limited: self.status = .disabled case .restricted: self.status = .unavailable @unknown default: self.status = .unavailable } if oldStatus == .denied && self.status == .denied { self.openSettings() } } }
mit
795703ee750b57a23dfd1b9c7e5b74cd
23.234043
74
0.661106
4.298113
false
false
false
false
fluttercommunity/plus_plugins
packages/device_info_plus/device_info_plus/macos/Classes/DeviceInfoPlusMacosPlugin.swift
1
1658
import Cocoa import FlutterMacOS public class DeviceInfoPlusMacosPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "dev.fluttercommunity.plus/device_info", binaryMessenger: registrar.messenger) let instance = DeviceInfoPlusMacosPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getDeviceInfo": handleDeviceInfo(result: result) default: result(FlutterMethodNotImplemented) } } private func handleDeviceInfo(result: @escaping FlutterResult)-> Void{ let computerName = Host.current().localizedName ?? Sysctl.hostName let hostName = Sysctl.osType let arch = Sysctl.machine let model = Sysctl.model let kernelVersion = Sysctl.version let osRelease = ProcessInfo.processInfo.operatingSystemVersionString let activeCPUs = Sysctl.activeCPUs let memorySize = Sysctl.memSize let cpuFrequency = Sysctl.cpuFreq let guid = SystemUUID.getSystemUUID() result([ "computerName": computerName, "hostName": hostName, "arch": arch, "model": model, "kernelVersion": kernelVersion, "osRelease": osRelease, "activeCPUs": activeCPUs, "memorySize": memorySize, "cpuFrequency": cpuFrequency, "systemGUID": guid ] as [String: Any?]) } }
bsd-3-clause
8f42455c973c3777af8e2eafab313fed
35.844444
127
0.646562
4.847953
false
false
false
false
programmerC/JNews
JNews/ViewController.swift
1
19801
// // ViewController.swift // JNews // // Created by ChenKaijie on 16/7/9. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit import Alamofire let WIDTH = UIScreen.mainScreen().bounds.size.width let HEIGHT = UIScreen.mainScreen().bounds.size.height let Base_URL = "http://139.129.133.227:8080/" class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIViewControllerPreviewingDelegate, MenuViewDelegate, MainBottomTableViewCellDelegate, ViewModelDelegate { @IBOutlet weak var mainTV: UITableView! @IBOutlet weak var menuButton: UIButton! let bottomCellHeight: CGFloat = 280 var topCellHeight: CGFloat = 0 var markFirstCellHeight: CGFloat = 0 //记录第一条新闻的高度 var lastOffset: CGFloat = 0 var type: TimeType = TimeType.Day var newsArray = Array<NewsModel>() let viewModel = ViewModel() var touchIndexPath: NSIndexPath? //MARK: - Life Circle override func viewDidLoad() { super.viewDidLoad() viewModel.delegate = self // Register Nib mainTV.registerNib(UINib.init(nibName: "MainTopTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Top") mainTV.registerNib(UINib.init(nibName: "MainTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Another") mainTV.registerNib(UINib.init(nibName: "MainBottomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "Bottom") // Cell Height topCellHeight = HEIGHT - 10 // 默认是true,UIScrollView及其子类,会在顶部和底部预留空白 self.automaticallyAdjustsScrollViewInsets = false // 读取数据 let newsManager = NewsHelpers.shareManager // 先从本地取数据 let submitString = String.getSubmitTimeString() var dayOrNight: NSInteger = 0 if validateTimeIsDay() { dayOrNight = 0 newsArray = newsManager.findNews(submitString, dayOrNight: dayOrNight) } else{ dayOrNight = 1 newsArray = newsManager.findNews(submitString, dayOrNight: dayOrNight) } if newsArray.count == 0 { loadingView.show() // 服务器已遗弃 // viewModel.loadTodayNews(submitString, dayOrNight: dayOrNight) let localDataPath = NSBundle.mainBundle().pathForResource("LocalData", ofType: ".plist") let dataArray = NSArray.init(contentsOfFile: localDataPath!) guard dataArray != nil && dataArray?.count > 0 else { return } let _ = dataArray!.map({ (dictionary) -> NewsModel in let model = NewsModel() model.newsType = Int(dictionary.objectForKey("newsType") as! String) model.newsTitle = dictionary.objectForKey("title") as? String model.commNum = Int(dictionary.objectForKey("commentNum") as! String) model.newsContent = dictionary.objectForKey("content") as? String model.isRead = Int(dictionary.objectForKey("isRead") as! String) model.newsDate = "2016.08.08" model.dayOrNight = 0 model.newsID = "" model.newsPicture = "" // 存储到数据库 newsManager.addNews(model) // 添加到 newsArray newsArray.append(model) return model }) loadingView.dismiss() mainTV.reloadData() } // 后台开启任务,从数据库清除6天前的新闻 // self.performSelectorInBackground(.deleteNewsAction, withObject: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Register 3DTouch guard #available(iOS 9.0, *) else { print("iOS version must be greater than 9.0"); return } guard self.traitCollection.forceTouchCapability == .Available else { print("This device does not support 3DTouch"); return } self.registerForPreviewingWithDelegate(self, sourceView: self.view) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let newsVC = segue.destinationViewController as! NewsViewController newsVC.modelArray = newsArray newsVC.currentRow = sender as? NSIndexPath // AnimationClosure newsVC.selectedClosure = {(selectedArray) in self.closureExecute(selectedArray) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - ViewModelDelegate func loadTodayNewsCallBack(dataArray: Array<NewsModel>) { guard dataArray.count > 0 else { // 今天没有数据,获取本地最新一天的数据 let newsManager = NewsHelpers.shareManager newsArray = newsManager.findLastestNews() if newsArray.count == 0 { // 本地没有数据,获取服务器某一天的数据(那天肯定有新闻,除非服务器崩了) viewModel.loadSomeDayNews("2016.08.03", dayOrNight: 0) } else { loadingView.dismiss() mainTV.reloadData() } return } newsArray.removeAll() newsArray = dataArray loadingView.dismiss() mainTV.reloadData() } func loadSomeDayNewsCallBack(dataArray: Array<NewsModel>) { guard dataArray.count > 0 else { loadingView.dismiss() return } newsArray.removeAll() newsArray = dataArray loadingView.dismiss() mainTV.reloadData() } //MARK: - UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if newsArray.count == 0 { return 0 } return newsArray.count + 1; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return topCellHeight } else if indexPath.row == self.newsArray.count { return bottomCellHeight } else { let context = newsArray[indexPath.row].newsTitle! as String let height = context.getHeight(context, margin: 65, fontSize: 17) return (height < 21) ? 110 : 110 - 21 + height; } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { // Top Cell let cell = tableView.dequeueReusableCellWithIdentifier("Top", forIndexPath: indexPath) as! MainTopTableViewCell; cell.model = newsArray[indexPath.row] return cell; } else if indexPath.row == newsArray.count { // Bottom Cell let cell = tableView.dequeueReusableCellWithIdentifier("Bottom", forIndexPath: indexPath) as! MainBottomTableViewCell; cell.delegate = self cell.modelArray = newsArray return cell; } else { let cell = tableView.dequeueReusableCellWithIdentifier("Another", forIndexPath: indexPath) as! MainTableViewCell; cell.indexPath = indexPath cell.model = newsArray[indexPath.row] return cell; } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard indexPath.row != newsArray.count else { // 点击最后一个Cell 没有效果 return } self.performSegueWithIdentifier("news", sender: indexPath) // 选中之后消除痕迹 guard indexPath.row != 0 else { return } self.performSelector(.deselectAction, withObject: indexPath, afterDelay: 0.3) } //MARK: - 3DTouch Peek And Pop func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // source Rect guard #available(iOS 9.0, *) else { print("iOS version must be greater than 9.0") return nil } previewingContext.sourceRect = CGRectMake(20, 20, WIDTH - 40, HEIGHT - 40) // current indexPath var tempLocation: CGPoint = location tempLocation.y = tempLocation.y + lastOffset touchIndexPath = mainTV.indexPathForRowAtPoint(tempLocation)! as NSIndexPath guard touchIndexPath!.row != newsArray.count else { return nil } let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let newsVC = storyBoard.instantiateViewControllerWithIdentifier("news") as! NewsViewController newsVC.modelArray = newsArray newsVC.currentRow = touchIndexPath return newsVC } func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) { // Pop let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let newsVC = storyBoard.instantiateViewControllerWithIdentifier("news") as! NewsViewController newsVC.modelArray = newsArray newsVC.currentRow = touchIndexPath // AnimationClosure newsVC.selectedClosure = {(selectedArray) in self.closureExecute(selectedArray) } self.navigationController?.pushViewController(newsVC, animated: true) } //MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { let offset_y = scrollView.contentOffset.y; // contentOffset.y < 0 guard let cell = mainTV.cellForRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: 0)) as? MainTopTableViewCell else { // MainTopTableViewCell 已经不在visiableCells数组 let distance = topCellHeight - markFirstCellHeight if offset_y > distance { if lastOffset > offset_y { menuButton.hidden = false } else{ menuButton.hidden = true } } else { menuButton.hidden = false } lastOffset = offset_y return } if offset_y < 0 { // BackgroundImage var imageRect = cell.backgroundImage.frame imageRect.origin.y = offset_y imageRect.size.height = topCellHeight - offset_y cell.backgroundImage.frame = imageRect // Date And Time var dateRect = cell.currentDate.frame var timeRect = cell.currentTime.frame dateRect.origin.y = offset_y + 12 timeRect.origin.y = offset_y + 49 cell.currentDate.frame = dateRect cell.currentTime.frame = timeRect } else { // 恢复到原始状态 cell.backgroundImage.frame = CGRectMake(0, 0, WIDTH, topCellHeight) cell.currentDate.frame = CGRectMake(16, 12, 110, 29) cell.currentTime.frame = CGRectMake(16, 49, 110, 21) // Mark Height markFirstCellHeight = cell.heightConstraint.constant } // 是否隐藏菜单按钮 let distance = topCellHeight - markFirstCellHeight if offset_y > distance { if lastOffset > offset_y { menuButton.hidden = false } else{ menuButton.hidden = true } } else { menuButton.hidden = false } lastOffset = offset_y } //MARK: - MenuViewDelegate func menuViewCallBack() { guard let data: NSData = UserDefault.objectForKey("SelectedItem") as? NSData else { return } // 获取选择新闻日期 let calendar = NSCalendar.init(calendarIdentifier: NSCalendarIdentifierGregorian) let components = calendar?.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate()) let dateFormate = NSDateFormatter() dateFormate.dateFormat = "yyyy.MM.dd" var dayOrNight: NSInteger = 0 let indexPath = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSIndexPath if type == TimeType.Day { // 白天 switch indexPath.section { case 0: components?.day = components!.day - 5 dayOrNight = 1 case 1: components?.day = components!.day - 4 if indexPath.row == 0 { dayOrNight = 0 } else { dayOrNight = 1 } case 2: components?.day = components!.day - 3 if indexPath.row == 0 { dayOrNight = 0 } else { dayOrNight = 1 } case 3: components?.day = components!.day - 2 if indexPath.row == 0 { dayOrNight = 0 } else { dayOrNight = 1 } case 4: components?.day = components!.day - 1 if indexPath.row == 0 { dayOrNight = 0 } else { dayOrNight = 1 } case 5: dayOrNight = 0 default: print("Error"); } } else { // 黑夜 switch indexPath.section { case 0: components?.day = components!.day - 4 case 1: components?.day = components!.day - 3 case 2: components?.day = components!.day - 2 case 3: components?.day = components!.day - 1 case 4: print("Nothing to do") default: print("Error"); } if indexPath.row == 0 { dayOrNight = 0 } else { dayOrNight = 1 } } let submitString = dateFormate.stringFromDate(calendar!.dateFromComponents(components!)!) // 读取CoreData数据 let newsManager = NewsHelpers.shareManager let tempArray = newsManager.findNews(submitString, dayOrNight: dayOrNight) if tempArray.count == 0 { // 本地没有数据,从网络获取 loadingView = LoadingView.init() loadingView.show() viewModel.loadSomeDayNews(submitString, dayOrNight: dayOrNight) } else { newsArray.removeAll() newsArray = tempArray mainTV.reloadData() } } //MARK: - MainBottomTableViewCellDelegate func listButtonCallBack() { if !validateTimeIsDay() { type = TimeType.Night } else { type = TimeType.Day } let springView = SpringView.init(timeType: type) springView.show() } //MARK: - UIButton Response @IBAction func menuButtonAction(sender: UIButton) { if !self.validateTimeIsDay() { type = TimeType.Night } else { type = TimeType.Day } // If SelectedItem Exist guard let data: NSData = UserDefault.objectForKey("SelectedItem") as? NSData else { let menuView = MenuView.init(timeType: type) menuView.delegate = self menuView.show({ () in menuView.countDownView?.animationExecute() }) return } let indexPath = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSIndexPath let menuView = MenuView.init(timeType: type, selectedItem: indexPath) menuView.delegate = self menuView.show({ () in menuView.countDownView?.animationExecute() }) } //MARK: - Custom Method func deselect(indexPath: NSIndexPath) { mainTV.deselectRowAtIndexPath(indexPath, animated: true) } // 判断当前时间是白天还是黑夜 func validateTimeIsDay() -> Bool { let currentDateString = String.getCurrentTimeString() if currentDateString.compare(String.getStartTimeString()) == NSComparisonResult.OrderedDescending && currentDateString.compare(String.getEndTimeString()) == NSComparisonResult.OrderedAscending { return true } else { return false } } func deleteNewsData() { // 获取六天前的日期 Delete News Six Days Ago let deleteTimeString = String.getXDaysAgoTimeString(6) let newsManager = NewsHelpers.shareManager newsManager.deleteNews(deleteTimeString) } func closureExecute(selectedArray: Array<Int>) { let _ = selectedArray.map({[unowned self] (row) -> Int in // 筛选在visiableCells的cell if row == 0 { guard let cell = self.mainTV.cellForRowAtIndexPath(NSIndexPath.init(forRow: row, inSection: 0)) as? MainTopTableViewCell else { return row } // 执行动画,如果已读则不执行 let model = self.newsArray[row] as NewsModel guard model.isRead!.intValue == 0 else { cell.number.textColor = UIColor.whiteColor() cell.numberView.backgroundColor = cell.color return row } cell.animationStart() } else { guard let cell = self.mainTV.cellForRowAtIndexPath(NSIndexPath.init(forRow: row, inSection: 0)) as? MainTableViewCell else { return row } let model = self.newsArray[row] as NewsModel guard model.isRead!.intValue == 0 else { return row } cell.animationStart() } // 设置新闻已读 let model = self.newsArray[row] as NewsModel model.isRead = NSNumber.init(short: 1) // 更新到数据库 let newsManager = NewsHelpers.shareManager newsManager.updateNews(model.newsID!) // 如果BottomViewCell存在的话执行动画 guard let bottomCell = self.mainTV.cellForRowAtIndexPath(NSIndexPath.init(forRow: self.newsArray.count, inSection: 0)) as? MainBottomTableViewCell else { return row } bottomCell.animationStart(row) return row }) } //MARK: - Lazy Getter lazy var loadingView: LoadingView = { let ldView = LoadingView.init() return ldView }() } //MARK: - Selector Extension private extension Selector { static let deselectAction = #selector(ViewController.deselect(_:)) static let deleteNewsAction = #selector(ViewController.deleteNewsData) }
gpl-3.0
1713dc4a05778719117e0c2812499909
35.198874
202
0.568311
5.161584
false
false
false
false
mgcm/CloudVisionKit
Pod/Classes/GCVRequest.swift
1
1814
// // GCVRequest.swift // CloudVisionKit // // Copyright (c) 2016 Milton Moura <miltonmoura@gmail.com> // // The MIT License (MIT) // // 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 SwiftyJSON public struct GCVRequest { public var requests: [GCVSingleRequest] public init(requests: [GCVSingleRequest]) { self.requests = requests } public func json() throws -> [String: AnyObject]? { var allRequests = [JSON]() var imageCount = 0 for r in requests { try allRequests += [r.json()] imageCount += 1 } guard imageCount <= 16 else { throw GCVApiError.imagesPerRequestExceeded } return ["requests": JSON(allRequests).rawValue as AnyObject] } }
mit
7d2307b51d87a5fbd8df2f029d78ae48
34.568627
82
0.694598
4.268235
false
false
false
false
krzyzanowskim/Natalie
Sources/natalie/OS.swift
1
6263
// // OS.swift // Natalie // // Created by Marcin Krzyzanowski on 07/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import Foundation enum OS: String, CustomStringConvertible { case iOS = "iOS" case OSX = "OSX" case tvOS = "tvOS" static let allValues = [iOS, OSX, tvOS] enum Runtime: String { case iOSCocoaTouch = "iOS.CocoaTouch" case MacOSXCocoa = "MacOSX.Cocoa" case AppleTV = "AppleTV" init(os: OS) { switch os { case iOS: self = .iOSCocoaTouch case OSX: self = .MacOSXCocoa case tvOS: self = .AppleTV } } } enum Framework: String { case UIKit = "UIKit" case Cocoa = "Cocoa" init(os: OS) { switch os { case iOS, .tvOS: self = .UIKit case OSX: self = .Cocoa } } } init(targetRuntime: String) { switch targetRuntime { case Runtime.iOSCocoaTouch.rawValue: self = .iOS case Runtime.MacOSXCocoa.rawValue: self = .OSX case Runtime.AppleTV.rawValue: self = .tvOS case "iOS.CocoaTouch.iPad": self = .iOS default: fatalError("Unsupported \(targetRuntime)") } } var description: String { return self.rawValue } var framework: String { return Framework(os: self).rawValue } var targetRuntime: String { return Runtime(os: self).rawValue } var storyboardType: String { switch self { case .iOS, .tvOS: return "UIStoryboard" case .OSX: return "NSStoryboard" } } var storyboardIdentifierType: String { switch self { case .iOS, .tvOS: return "String" case .OSX: return "NSStoryboard.Name" } } var storyboardSceneIdentifierType: String { switch self { case .iOS, .tvOS: return "String" case .OSX: return "NSStoryboard.SceneIdentifier" } } var storyboardSegueType: String { switch self { case .iOS, .tvOS: return "UIStoryboardSegue" case .OSX: return "NSStoryboardSegue" } } var storyboardSegueIdentifierType: String { switch self { case .iOS, .tvOS: return "String" case .OSX: return "NSStoryboardSegue.Identifier" } } var storyboardControllerTypes: [String] { switch self { case .iOS, .tvOS: return ["UIViewController"] case .OSX: return ["NSViewController", "NSWindowController"] } } var storyboardControllerReturnType: String { switch self { case .iOS, .tvOS: return "UIViewController" case .OSX: return "AnyObject" // NSViewController or NSWindowController } } var storyboardControllerSignatureType: String { switch self { case .iOS, .tvOS: return "ViewController" case .OSX: return "Controller" // NSViewController or NSWindowController } } var storyboardInstantiationInfo: [(String /* Signature type */, String /* Return type */)] { switch self { case .iOS, .tvOS: return [("ViewController", "UIViewController")] case .OSX: return [("Controller", "NSWindowController"), ("Controller", "NSViewController")] } } var viewType: String { switch self { case .iOS, .tvOS: return "UIView" case .OSX: return "NSView" } } var colorType: String { switch self { case .iOS, .tvOS: return "UIColor" case .OSX: return "NSColor" } } var colorNameType: String { switch self { case .iOS, .tvOS: return "String" case .OSX: return "NSColor.Name" } } var colorOS: String { switch self { case .iOS: return "iOS 11.0" case .tvOS: return "tvOS 11.0" case .OSX: return "OSX 10.13" } } var resuableViews: [String]? { switch self { case .iOS, .tvOS: return ["UICollectionReusableView", "UITableViewCell"] case .OSX: return nil } } func controllerType(for name: String) -> String? { switch self { case .iOS, .tvOS: switch name { case "viewController": return "UIViewController" case "navigationController": return "UINavigationController" case "tableViewController": return "UITableViewController" case "tabBarController": return "UITabBarController" case "splitViewController": return "UISplitViewController" case "pageViewController": return "UIPageViewController" case "collectionViewController": return "UICollectionViewController" case "exit", "viewControllerPlaceholder": return nil default: assertionFailure("Unknown controller element: \(name)") return nil } case .OSX: switch name { case "viewController": return "NSViewController" case "windowController": return "NSWindowController" case "pagecontroller": return "NSPageController" case "tabViewController": return "NSTabViewController" case "splitViewController": return "NSSplitViewController" case "exit", "viewControllerPlaceholder": return nil default: assertionFailure("Unknown controller element: \(name)") return nil } } } }
mit
35239e40d81d34bac55e8cdc10b77f04
24.148594
96
0.510699
5.244556
false
false
false
false
viczy/SwiftForward
Pods/Cartography/Cartography/Context.swift
1
2010
// // Context.swift // Cartography // // Created by Robert Böhnke on 06/10/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public class Context { internal var constraints: [Constraint] = [] internal func addConstraint(from: Property, to: Property? = nil, coefficients: Coefficients = Coefficients(), relation: NSLayoutRelation = .Equal) -> NSLayoutConstraint { from.view.car_setTranslatesAutoresizingMaskIntoConstraints(false) var toAttribute: NSLayoutAttribute! = NSLayoutAttribute.NotAnAttribute if to == nil { toAttribute = NSLayoutAttribute.NotAnAttribute } else { toAttribute = to!.attribute } let superview = closestCommonAncestor(from.view, to?.view) let layoutConstraint = NSLayoutConstraint(item: from.view, attribute: from.attribute, relatedBy: relation, toItem: to?.view, attribute: toAttribute, multiplier: CGFloat(coefficients.multiplier), constant: CGFloat(coefficients.constant)) constraints += [ Constraint(view: superview!, layoutConstraint: layoutConstraint) ] return layoutConstraint } internal func addConstraint(from: Compound, coefficients: [Coefficients]? = nil, to: Compound? = nil, relation: NSLayoutRelation = NSLayoutRelation.Equal) -> [NSLayoutConstraint] { var results: [NSLayoutConstraint] = [] for i in 0..<from.properties.count { let n: Coefficients = coefficients?[i] ?? Coefficients() results.append(addConstraint(from.properties[i], coefficients: n, to: to?.properties[i], relation: relation)) } return results } }
apache-2.0
aad7a5dc1c0cd7ac3fcfb063853f9f9b
35.509091
184
0.585657
5.562327
false
false
false
false
voloshynslavik/MVx-Patterns-In-Swift
MVX Patterns In Swift/Utils/Data Loader/DataLoader.swift
1
1249
// // DataLoader.swift // // Copyright © 2016 Voloshyn Slavik. All rights reserved. // import Foundation final class DataLoader { static let shared = DataLoader() private lazy var downloadQueue: OperationQueue = { var queue = OperationQueue() queue.name = "Download queue" queue.maxConcurrentOperationCount = 1 return queue }() private init() { } func downloadData(with url: String, callback: @escaping ((_ data: Data?) -> Void)) { guard !isFileInDownloadQueue(url: url) else { return } let operation = DownloadDataOperation(url: url, callback: callback) operation.name = url downloadQueue.addOperation(operation) } private func isFileInDownloadQueue(url: String) -> Bool{ for operation in downloadQueue.operations { if operation.name == url && !operation.isCancelled && !operation.isFinished { return true } } return false } func stopDownload(with url: String) { for operation in downloadQueue.operations { if operation.name == url { operation.cancel() } } } }
mit
bc912f2102029dfd7e9fe6c3179c1f15
25
89
0.579327
4.932806
false
false
false
false
XCEssentials/UniFlow
Sources/3_Storage/Storage.swift
1
7052
/* MIT License Copyright (c) 2016 Maxim Khatskevich (maxim@khatskevi.ch) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //--- public struct Storage { private var data: [String: SomeStateBase] = [:] public private(set) var history: History = [] public private(set) var lastHistoryResetId: String = UUID().uuidString //--- public init() {} } // MARK: - Nested types public extension Storage { enum ReadDataError: Error { case featureNotFound( SomeFeature.Type ) case stateTypeMismatch( feature: SomeFeature.Type, expected: SomeStateBase.Type, actual: SomeStateBase ) } } // MARK: - GET data public extension Storage { var allStates: [SomeStateBase] { .init(data.values) } var allFeatures: [SomeFeature.Type] { allStates .map { type(of: $0).feature } } func fetchState(forFeature featureType: SomeFeature.Type) throws -> SomeStateBase { if let result = data[featureType.name] { return result } else { throw ReadDataError.featureNotFound(featureType) } } func fetchState<S: SomeState>(ofType _: S.Type = S.self) throws -> S { let someState = try fetchState(forFeature: S.Feature.self) //--- if let result = someState as? S { return result } else { throw ReadDataError.stateTypeMismatch( feature: S.Feature.self, expected: S.self, actual: someState ) } } } // MARK: - SET data public extension Storage { @discardableResult mutating func store<S: SomeState>( _ state: S, expectedMutation: ExpectedMutation = .auto ) throws -> MutationAttemptOutcome { let proposedOutcome: MutationAttemptOutcome //--- switch (data[type(of: state).feature.name], state) { case (.none, let newState): proposedOutcome = .initialization(newState: newState) //--- try SemanticError.validateProposedOutcome( expected: expectedMutation, proposed: proposedOutcome ) //--- data[S.Feature.name] = newState //--- case (.some(let oldState), let newState): if type(of: oldState) == type(of: newState) { proposedOutcome = .actualization(oldState: oldState, newState: newState) } else { proposedOutcome = .transition(oldState: oldState, newState: newState) } //--- try SemanticError.validateProposedOutcome( expected: expectedMutation, proposed: proposedOutcome ) //--- data[S.Feature.name] = newState } //--- logHistoryEvent( outcome: proposedOutcome ) //--- return proposedOutcome } } // MARK: - REMOVE data public extension Storage { @discardableResult mutating func removeState( forFeature feature: SomeFeature.Type, fromStateType: SomeStateBase.Type? = nil, strict: Bool = true ) throws -> MutationAttemptOutcome { let implicitlyExpectedMutation: ExpectedMutation = .deinitialization( fromStateType: fromStateType, strict: strict ) let proposedOutcome: MutationAttemptOutcome //--- switch data[feature.name] { case .some(let oldState): proposedOutcome = .deinitialization(oldState: oldState) //--- try SemanticError.validateProposedOutcome( expected: implicitlyExpectedMutation, proposed: proposedOutcome ) //--- data.removeValue(forKey: feature.name) case .none: proposedOutcome = .nothingToRemove(feature: feature) //--- try SemanticError.validateProposedOutcome( expected: implicitlyExpectedMutation, proposed: proposedOutcome ) } //--- logHistoryEvent( outcome: proposedOutcome ) //--- return proposedOutcome } @discardableResult mutating func removeAll() throws -> [MutationAttemptOutcome] { try allFeatures .map { try removeState(forFeature: $0, fromStateType: nil, strict: false) } } } // MARK: - History management //internal extension Storage { mutating func logHistoryEvent( outcome: MutationAttemptOutcome ) { history.append( .init(operation: outcome) ) } /// Clear the history and return it's copy as result. mutating func resetHistory() -> History { let result = history history.removeAll() lastHistoryResetId = UUID().uuidString //--- return result } }
mit
bdac0244ed3e748c1d87a616e4ab9f5e
23.150685
92
0.515598
5.619124
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/URLSession/http/HTTPMessage.swift
1
12155
// Foundation/URLSession/HTTPMessage.swift - HTTP Message parsing // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// Helpers for parsing HTTP responses. /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif import CoreFoundation internal extension _HTTPURLProtocol._ResponseHeaderLines { /// Create an `NSHTTPRULResponse` from the lines. /// /// This will parse the header lines. /// - Returns: `nil` if an error occurred while parsing the header lines. func createHTTPURLResponse(for URL: URL) -> HTTPURLResponse? { guard let message = createHTTPMessage() else { return nil } return HTTPURLResponse(message: message, URL: URL) } /// Parse the lines into a `_HTTPURLProtocol.HTTPMessage`. func createHTTPMessage() -> _HTTPURLProtocol._HTTPMessage? { guard let (head, tail) = lines.decompose else { return nil } guard let startline = _HTTPURLProtocol._HTTPMessage._StartLine(line: head) else { return nil } guard let headers = createHeaders(from: tail) else { return nil } return _HTTPURLProtocol._HTTPMessage(startLine: startline, headers: headers) } } extension HTTPURLResponse { fileprivate convenience init?(message: _HTTPURLProtocol._HTTPMessage, URL: URL) { /// This needs to be a request, i.e. it needs to have a status line. guard case .statusLine(let statusLine) = message.startLine else { return nil } let fields = message.headersAsDictionary self.init(url: URL, statusCode: statusLine.status, httpVersion: statusLine.version.rawValue, headerFields: fields) } } extension _HTTPURLProtocol { /// HTTP Message /// /// A message consist of a *start-line* optionally followed by one or multiple /// message-header lines, and optionally a message body. /// /// This represents everything except for the message body. /// /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-4 struct _HTTPMessage { let startLine: _HTTPURLProtocol._HTTPMessage._StartLine let headers: [_HTTPURLProtocol._HTTPMessage._Header] } } extension _HTTPURLProtocol._HTTPMessage { var headersAsDictionary: [String: String] { var result: [String: String] = [:] headers.forEach { if result[$0.name] == nil { result[$0.name] = $0.value } else { result[$0.name]! += (", " + $0.value) } } return result } } extension _HTTPURLProtocol._HTTPMessage { /// A single HTTP message header field /// /// Most HTTP messages have multiple header fields. struct _Header { let name: String let value: String } /// The first line of a HTTP message /// /// This can either be the *request line* (RFC 2616 Section 5.1) or the /// *status line* (RFC 2616 Section 6.1) enum _StartLine { /// RFC 2616 Section 5.1 *Request Line* /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-5.1 case requestLine(method: String, uri: URL, version: _HTTPURLProtocol._HTTPMessage._Version) /// RFC 2616 Section 6.1 *Status Line* /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-6.1 case statusLine(version: _HTTPURLProtocol._HTTPMessage._Version, status: Int, reason: String) } /// A HTTP version, e.g. "HTTP/1.1" struct _Version: RawRepresentable { let rawValue: String } } extension _HTTPURLProtocol._HTTPMessage._Version { init?(versionString: String) { rawValue = versionString } } private extension _HTTPURLProtocol._HTTPMessage._StartLine { init?(line: String) { guard let r = line.splitRequestLine() else { return nil } if let version = _HTTPURLProtocol._HTTPMessage._Version(versionString: r.0) { // Status line: guard let status = Int(r.1), 100 <= status && status <= 999 else { return nil } self = .statusLine(version: version, status: status, reason: r.2) } else if let version = _HTTPURLProtocol._HTTPMessage._Version(versionString: r.2), let URI = URL(string: r.1) { // The request method must be a token (i.e. without separators): let separatorIdx = r.0.unicodeScalars.firstIndex(where: { !$0.isValidMessageToken } ) guard separatorIdx == nil else { return nil } self = .requestLine(method: r.0, uri: URI, version: version) } else { return nil } } } private extension String { /// Split a request line into its 3 parts: *Method*, *Request-URI*, and *HTTP-Version*. /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-5.1 func splitRequestLine() -> (String, String, String)? { let scalars = self.unicodeScalars[...] guard let firstSpace = scalars.rangeOfSpace else { return nil } let remainingRange = firstSpace.upperBound..<scalars.endIndex let remainder = scalars[remainingRange] guard let secondSpace = remainder.rangeOfSpace else { return nil } let methodRange = scalars.startIndex..<firstSpace.lowerBound let uriRange = remainder.startIndex..<secondSpace.lowerBound let versionRange = secondSpace.upperBound..<remainder.endIndex //TODO: is this necessary? If yes, this guard needs an alternate implementation //guard 0 < methodRange.count && 0 < uriRange.count && 0 < versionRange.count else { return nil } let m = String(scalars[methodRange]) let u = String(remainder[uriRange]) let v = String(remainder[versionRange]) return (m, u, v) } } /// Parses an array of lines into an array of /// `URLSessionTask.HTTPMessage.Header`. /// /// This respects the header folding as described by /// https://tools.ietf.org/html/rfc2616#section-2.2 : /// /// - SeeAlso: `_HTTPURLProtocol.HTTPMessage.Header.createOne(from:)` private func createHeaders(from lines: ArraySlice<String>) -> [_HTTPURLProtocol._HTTPMessage._Header]? { var headerLines = Array(lines) var headers: [_HTTPURLProtocol._HTTPMessage._Header] = [] while !headerLines.isEmpty { guard let (header, remaining) = _HTTPURLProtocol._HTTPMessage._Header.createOne(from: headerLines) else { return nil } headers.append(header) headerLines = remaining } return headers } private extension _HTTPURLProtocol._HTTPMessage._Header { /// Parse a single HTTP message header field /// /// Each header field consists /// of a name followed by a colon (":") and the field value. Field names /// are case-insensitive. The field value MAY be preceded by any amount /// of LWS, though a single SP is preferred. Header fields can be /// extended over multiple lines by preceding each extra line with at /// least one SP or HT. Applications ought to follow "common form", where /// one is known or indicated, when generating HTTP constructs, since /// there might exist some implementations that fail to accept anything /// beyond the common forms. /// /// Consumes lines from the given array of lines to produce a single HTTP /// message header and returns the resulting header plus the remainder. /// /// If an error occurs, it returns `nil`. /// /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-4.2 static func createOne(from lines: [String]) -> (_HTTPURLProtocol._HTTPMessage._Header, [String])? { // HTTP/1.1 header field values can be folded onto multiple lines if the // continuation line begins with a space or horizontal tab. All linear // white space, including folding, has the same semantics as SP. A // recipient MAY replace any linear white space with a single SP before // interpreting the field value or forwarding the message downstream. guard let (head, tail) = lines.decompose else { return nil } let headView = head.unicodeScalars[...] guard let nameRange = headView.rangeOfTokenPrefix else { return nil } guard headView.index(after: nameRange.upperBound) <= headView.endIndex && headView[nameRange.upperBound] == _Delimiters.Colon else { return nil } let name = String(headView[nameRange]) var value: String? let line = headView[headView.index(after: nameRange.upperBound)..<headView.endIndex] if !line.isEmpty { if line.hasSPHTPrefix && line.count == 1 { // to handle empty headers i.e header without value value = "" } else { guard let v = line.trimSPHTPrefix else { return nil } value = String(v) } } do { var t = tail while t.first?.unicodeScalars[...].hasSPHTPrefix ?? false { guard let (h2, t2) = t.decompose else { return nil } t = t2 guard let v = h2.unicodeScalars[...].trimSPHTPrefix else { return nil } let valuePart = String(v) value = value.map { $0 + " " + valuePart } ?? valuePart } return (_HTTPURLProtocol._HTTPMessage._Header(name: name, value: value ?? ""), Array(t)) } } } private extension Collection { /// Splits the collection into its first element and the remainder. var decompose: (Iterator.Element, Self.SubSequence)? { guard let head = self.first else { return nil } let tail = self[self.index(after: startIndex)..<endIndex] return (head, tail) } } private extension String.UnicodeScalarView.SubSequence { /// The range of *Token* characters as specified by RFC 2616. var rangeOfTokenPrefix: Range<Index>? { var end = startIndex while self[end].isValidMessageToken { end = self.index(after: end) } guard end != startIndex else { return nil } return startIndex..<end } /// The range of space (U+0020) characters. var rangeOfSpace: Range<Index>? { guard !isEmpty else { return startIndex..<startIndex } guard let idx = firstIndex(of: _Delimiters.Space!) else { return nil } return idx..<self.index(after: idx) } // Has a space (SP) or horizontal tab (HT) prefix var hasSPHTPrefix: Bool { guard !isEmpty else { return false } return self[startIndex] == _Delimiters.Space || self[startIndex] == _Delimiters.HorizontalTab } /// Unicode scalars after removing the leading spaces (SP) and horizontal tabs (HT). /// Returns `nil` if the unicode scalars do not start with a SP or HT. var trimSPHTPrefix: SubSequence? { guard !isEmpty else { return nil } var idx = startIndex while idx < endIndex { if self[idx] == _Delimiters.Space || self[idx] == _Delimiters.HorizontalTab { idx = self.index(after: idx) } else { guard startIndex < idx else { return nil } return self[idx..<endIndex] } } return nil } } private extension UnicodeScalar { /// Is this a valid **token** as defined by RFC 2616 ? /// /// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-2 var isValidMessageToken: Bool { guard UnicodeScalar(32) <= self && self <= UnicodeScalar(126) else { return false } return !_Delimiters.Separators.characterIsMember(UInt16(self.value)) } }
apache-2.0
f7e8392a504fab8e9b216879a994fa59
42.256228
153
0.631098
4.495192
false
false
false
false
InfyOmLabs/SwiftExtension
Pod/Classes/UIButtonExtension.swift
1
5033
// // UIButtonExtension.swift // SwiftExtension // // Created by Dhvl Golakiya on 04/04/16. // Copyright © 2016 Dhvl Golakiya. All rights reserved. // import Foundation import UIKit extension UIButton { // Apply corner radius public func applyCornerRadius(mask : Bool) { self.layer.masksToBounds = mask self.layer.cornerRadius = self.frame.size.width/2 } // Set background color for state public func setBackgroundColor(color: UIColor, forState: UIControl.State) { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor) UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) let colorImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setBackgroundImage(colorImage, for: forState) } // Set title text for all state public func textForAllState(titleText : String) { self.setTitle(titleText, for: .normal) self.setTitle(titleText, for: .selected) self.setTitle(titleText, for: .highlighted) self.setTitle(titleText, for: .disabled) } // Set title text for only normal state public func textForNormal(titleText : String) { self.setTitle(titleText, for: .normal) } // Set title text for only selected state public func textForSelected(titleText : String) { self.setTitle(titleText, for: .selected) } // Set title text for only highlight state public func textForHighlighted(titleText : String) { self.setTitle(titleText, for: .highlighted) } // Set image for all state public func imageForAllState(image : UIImage) { self.setImage(image, for: .normal) self.setImage(image, for: .selected) self.setImage(image, for: .highlighted) self.setImage(image, for: .disabled) } // Set image for only normal state public func imageForNormal(image : UIImage) { self.setImage(image, for: .normal) } // Set image for only selected state public func imageForSelected(image : UIImage) { self.setImage(image, for: .selected) } // Set image for only highlighted state public func imageForHighlighted(image : UIImage) { self.setImage(image, for: .highlighted) } // Set title color for all state public func colorOfTitleLabelForAllState(color : UIColor) { self.setTitleColor(color, for: .normal) self.setTitleColor(color, for: .selected) self.setTitleColor(color, for: .highlighted) self.setTitleColor(color, for: .disabled) } // Set title color for normal state public func colorOfTitleLabelForNormal(color : UIColor) { self.setTitleColor(color, for: .normal) } // Set title color for selected state public func colorOfTitleLabelForSelected(color : UIColor) { self.setTitleColor(color, for: .selected) } // Set title color for highkighted state public func colorForHighlighted(color : UIColor) { self.setTitleColor(color, for: .highlighted) } // Set image behind the text in button public func setImageBehindTextWithCenterAlignment(imageWidth : CGFloat, buttonWidth : CGFloat, space : CGFloat) { let titleLabelWidth = self.titleLabel?.text?.stringWidth(font: self.titleLabel!.font) let buttonMiddlePoint = buttonWidth/2 let fullLenght = titleLabelWidth! + space + imageWidth let imageInset = buttonMiddlePoint + fullLenght/2 - imageWidth + space let buttonInset = buttonMiddlePoint - fullLenght/2 - imageWidth self.imageEdgeInsets = UIEdgeInsets(top: 0, left: imageInset, bottom: 0, right: 0) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonInset, bottom: 0, right: 0) } // Set image behind text in left alignment public func setImageBehindTextWithLeftAlignment(imageWidth : CGFloat, buttonWidth : CGFloat) { let titleLabelWidth = self.titleLabel?.text?.stringWidth(font: self.titleLabel!.font) let fullLenght = titleLabelWidth! + 5 + imageWidth let imageInset = fullLenght - imageWidth + 5 let buttonInset = CGFloat(-10.0) self.imageEdgeInsets = UIEdgeInsets(top: 0, left: imageInset, bottom: 0, right: 0) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonInset, bottom: 0, right: 0) } // Set image behind text in right alignment public func setImageOnRightAndTitleOnLeft(imageWidth : CGFloat, buttonWidth : CGFloat) { let imageInset = CGFloat(buttonWidth - imageWidth - 10) let buttonInset = CGFloat(-10.0) self.imageEdgeInsets = UIEdgeInsets(top: 0, left: imageInset, bottom: 0, right: 0) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonInset, bottom: 0, right: 0) } }
mit
50b2c15db1c5cb2efbdd2353a497f2d7
36.552239
117
0.661367
4.484848
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/PlaceSearchSuggestionController.swift
1
7803
import UIKit import WMF protocol PlaceSearchSuggestionControllerDelegate: NSObjectProtocol { func placeSearchSuggestionController(_ controller: PlaceSearchSuggestionController, didSelectSearch search: PlaceSearch) func placeSearchSuggestionControllerClearButtonPressed(_ controller: PlaceSearchSuggestionController) func placeSearchSuggestionController(_ controller: PlaceSearchSuggestionController, didDeleteSearch search: PlaceSearch) } class PlaceSearchSuggestionController: NSObject, UITableViewDataSource, UITableViewDelegate, Themeable { fileprivate var theme = Theme.standard func apply(theme: Theme) { self.theme = theme tableView.backgroundColor = theme.colors.baseBackground tableView.tableFooterView?.backgroundColor = theme.colors.paperBackground tableView.reloadData() } static let cellReuseIdentifier = "org.wikimedia.places" static let headerReuseIdentifier = "org.wikimedia.places.header" static let suggestionSection = 0 static let recentSection = 1 static let currentStringSection = 2 static let completionSection = 3 var wikipediaLanguage: String? = "en" var siteURL: URL? = nil { didSet { wikipediaLanguage = siteURL?.wmf_language } } var tableView: UITableView = UITableView() { didSet { tableView.register(PlacesSearchSuggestionTableViewCell.wmf_classNib(), forCellReuseIdentifier: PlaceSearchSuggestionController.cellReuseIdentifier) tableView.register(WMFTableHeaderFooterLabelView.wmf_classNib(), forHeaderFooterViewReuseIdentifier: PlaceSearchSuggestionController.headerReuseIdentifier) tableView.dataSource = self tableView.delegate = self tableView.reloadData() let footerView = UIView() tableView.tableFooterView = footerView } } var searches: [[PlaceSearch]] = [[],[],[],[]]{ didSet { tableView.reloadData() } } weak var delegate: PlaceSearchSuggestionControllerDelegate? func numberOfSections(in tableView: UITableView) -> Int { return searches.count } var shouldUseFirstSuggestionAsDefault: Bool { return searches[PlaceSearchSuggestionController.suggestionSection].count == 0 && searches[PlaceSearchSuggestionController.completionSection].count > 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch (section, shouldUseFirstSuggestionAsDefault) { case (PlaceSearchSuggestionController.suggestionSection, true): return 1 case (PlaceSearchSuggestionController.completionSection, true): return searches[PlaceSearchSuggestionController.completionSection].count - 1 default: return searches[section].count } } func searchForIndexPath(_ indexPath: IndexPath) -> PlaceSearch { let search: PlaceSearch switch (indexPath.section, shouldUseFirstSuggestionAsDefault) { case (PlaceSearchSuggestionController.suggestionSection, true): search = searches[PlaceSearchSuggestionController.completionSection][0] case (PlaceSearchSuggestionController.completionSection, true): search = searches[PlaceSearchSuggestionController.completionSection][indexPath.row+1] default: search = searches[indexPath.section][indexPath.row] } return search } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PlaceSearchSuggestionController.cellReuseIdentifier, for: indexPath) guard let searchSuggestionCell = cell as? PlacesSearchSuggestionTableViewCell else { return cell } let search = searchForIndexPath(indexPath) switch search.type { case .nearby: searchSuggestionCell.iconImageView.image = #imageLiteral(resourceName: "places-suggestion-location") default: searchSuggestionCell.iconImageView.image = search.searchResult != nil ? #imageLiteral(resourceName: "nearby-mini") : #imageLiteral(resourceName: "places-suggestion-text") } searchSuggestionCell.titleLabel.text = search.localizedDescription searchSuggestionCell.detailLabel.text = search.searchResult?.wikidataDescription?.wmf_stringByCapitalizingFirstCharacter(usingWikipediaLanguage: wikipediaLanguage) searchSuggestionCell.apply(theme: theme) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let search = searchForIndexPath(indexPath) delegate?.placeSearchSuggestionController(self, didSelectSearch: search) tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard searches[section].count > 0, section < 2, let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: PlaceSearchSuggestionController.headerReuseIdentifier) as? WMFTableHeaderFooterLabelView else { return nil } header.prepareForReuse() if let ht = header as Themeable? { ht.apply(theme: theme) } header.isLabelVerticallyCentered = true switch section { // case PlaceSearchSuggestionController.suggestionSection: // header.text = WMFLocalizedString("places-search-suggested-searches-header", value:"Suggested searches", comment:"Suggested searches - header for the list of suggested searches") case PlaceSearchSuggestionController.recentSection: header.isClearButtonHidden = false header.addClearButtonTarget(self, selector: #selector(clearButtonPressed)) header.text = WMFLocalizedString("places-search-recently-searched-header", value:"Recently searched", comment:"Recently searched - header for the list of recently searched items") header.clearButton.accessibilityLabel = WMFLocalizedString("places-accessibility-clear-saved-searches", value:"Clear saved searches", comment:"Accessibility hint for clearing saved searches") default: return nil } return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let header = self.tableView(tableView, viewForHeaderInSection: section) as? WMFTableHeaderFooterLabelView else { return 0 } let calculatedHeight = header.height(withExpectedWidth: tableView.bounds.size.width) return calculatedHeight + 23 } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { switch indexPath.section { case PlaceSearchSuggestionController.recentSection: return true default: return false } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { switch indexPath.section { case PlaceSearchSuggestionController.recentSection: return [UITableViewRowAction(style: .destructive, title: "Delete", handler: { (action, indexPath) in let search = self.searchForIndexPath(indexPath) self.delegate?.placeSearchSuggestionController(self, didDeleteSearch: search) })] default: return nil } } @objc func clearButtonPressed() { delegate?.placeSearchSuggestionControllerClearButtonPressed(self) } }
mit
d3172e93d4c4f6fa3548e3ce644af70f
44.9
222
0.701781
5.62987
false
false
false
false
frootloops/swift
test/Sema/enum_equatable_hashable.swift
1
7702
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %t/main.swift %S/Inputs/enum_equatable_hashable_other.swift -verify-ignore-unknown enum Foo { case A, B } if Foo.A == .B { } var aHash: Int = Foo.A.hashValue enum Generic<T> { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } if Generic<Foo>.A == .B { } var gaHash: Int = Generic<Foo>.A.hashValue func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B var hashValue: Int { return 0 } } func ==(x: CustomHashable, y: CustomHashable) -> Bool { // expected-note 4 {{non-matching type}} return true } if CustomHashable.A == .B { } var custHash: Int = CustomHashable.A.hashValue // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-note{{previously declared here}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { // expected-note 4 {{non-matching type}} return "" } if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue var i: Int = InvalidCustomHashable.A.hashValue // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue func getFromOtherFile() -> AlsoFromOtherFile { return .A } if .A == getFromOtherFile() {} func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } if .A == overloadFromOtherFile() {} // Complex enums are not implicitly Equatable or Hashable. enum Complex { case A(Int) case B } if Complex.A(1) == .B { } // expected-error{{binary operator '==' cannot be applied to operands of type 'Complex' and '_'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } if GenericHashable<String>.A("a") == .B { } var genericHashableHash: Int = GenericHashable<String>.A("a").hashValue // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error {{does not conform}} case A(T) case B } if GenericNotHashable<String>.A("a") == .B { } var genericNotHashableHash: Int = GenericNotHashable<String>.A("a").hashValue // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hashValue'}} // An enum with no cases should not derive conformance. enum NoCases: Hashable {} // expected-error 2 {{does not conform}} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{use of undeclared type 'Unknown'}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { // expected-note 3 {{non-matching type}} return true } // No explicit conformance; it could be derived, but we don't support extensions // yet. extension Complex : Hashable {} // expected-error 2 {{cannot be automatically synthesized in an extension}} // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { // expected-note 3 {{non-matching type}} return true } var hashValue: Int { return 0 } } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
c59c4aeca48bb39e28557ee419baffaf
30.436735
168
0.723838
3.862588
false
false
false
false
mark2b/l10n
Classes/l10n.swift
1
1311
// // l10n.swift // // Created by Mark Berner on 19/01/2017. // Copyright © 2017 Mark Berner. All rights reserved. // import Foundation extension String { public func l10n(_ resource: l10NResources.RawValue = l10NResources.default, locale:Locale? = nil, args:CVarArg...) -> String { var bundle = Bundle.main if let locale = locale { let language = locale.languageCode if let path = Bundle.main.path(forResource: language, ofType: "lproj"), let localizedBundle = Bundle(path: path) { bundle = localizedBundle } } var format:String if resource == l10NResources.default { format = bundle.localizedString(forKey: self, value: self, table: nil) } else { format = bundle.localizedString(forKey: self, value: self, table: resource) } if args.count == 0 { return format } else { return NSString(format: format, arguments:getVaList(args)) as String } } } public struct l10NResources : RawRepresentable { public typealias RawValue = String public static let `default` = "default" public init?(rawValue: l10NResources.RawValue) { return nil } public var rawValue: String }
mit
2701f18ff4397eedede84a502968a93e
26.291667
131
0.603817
4.309211
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Utility/NotificationsManager.swift
2
14308
// // NotificationsManager.swift // Neocom // // Created by Artem Shimanski on 5/12/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import Foundation import UserNotifications import EVEAPI import Combine import Alamofire import CoreData import Expressible class NotificationsManager { struct SkillQueueNotificationOptions: OptionSet { var rawValue: Int static let inactive = SkillQueueNotificationOptions(rawValue: 1 << 0) static let oneHour = SkillQueueNotificationOptions(rawValue: 1 << 1) static let fourHours = SkillQueueNotificationOptions(rawValue: 1 << 2) static let oneDay = SkillQueueNotificationOptions(rawValue: 1 << 3) static let skillTrainingComplete = SkillQueueNotificationOptions(rawValue: 1 << 4) static let `default`: SkillQueueNotificationOptions = [.inactive, .oneHour, .fourHours, .oneDay, .skillTrainingComplete] } let managedObjectContext: NSManagedObjectContext @UserDefault(key: .notificationSettigs) private var _skillQueueNotificationOptions: Int = SkillQueueNotificationOptions.default.rawValue @UserDefault(key: .notificationsEnabled) private var notificationsEnabled = true var skillQueueNotificationOptions: SkillQueueNotificationOptions { get { SkillQueueNotificationOptions(rawValue: _skillQueueNotificationOptions) } set { _skillQueueNotificationOptions = newValue.rawValue } } private var observers: [NSObjectProtocol]? private var subscriptions = Set<AnyCancellable>() init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext let observer1 = NotificationCenter.default.addObserver(forName: .NSManagedObjectContextDidSave, object: nil, queue: nil) { [weak self] (note) in self?.managedObjectContextDidSave(note) } #if targetEnvironment(macCatalyst) let observer2 = NotificationCenter.default.addObserver(forName: Notification.Name("NSApplicationDidBecomeActiveNotification"), object: nil, queue: .main) { [weak self] (note) in self?.updateIfNeeded() } #else let observer2 = NotificationCenter.default.addObserver(forName: UIScene.didActivateNotification, object: nil, queue: .main) { [weak self] (note) in self?.updateIfNeeded() } #endif _notificationsEnabled.objectWillChange.sink { [weak self] _ in DispatchQueue.main.async { self?.lastUpdateDate = .distantPast self?.updateIfNeeded() } }.store(in: &subscriptions) __skillQueueNotificationOptions.objectWillChange.sink { [weak self] _ in DispatchQueue.main.async { self?.lastUpdateDate = .distantPast self?.updateIfNeeded() } }.store(in: &subscriptions) observers = [observer1, observer2] updateIfNeeded() } private var lastUpdateDate = Date.distantPast func updateIfNeeded() { guard lastUpdateDate.addingTimeInterval(600) < Date() else {return} if notificationsEnabled { guard let accounts = try? managedObjectContext.from(Account.self).fetch(), !accounts.isEmpty else {return} lastUpdateDate = Date() let task = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) update(Set(accounts)) { result in DispatchQueue.main.async { if case .failure = result { self.lastUpdateDate = .distantPast } UIApplication.shared.endBackgroundTask(task) } } } else { removeAllRequests() lastUpdateDate = Date() } } private func removeAllRequests() { let notificationCenter = UNUserNotificationCenter.current() notificationCenter.getPendingNotificationRequests { (pendingRequests) in notificationCenter.removePendingNotificationRequests(withIdentifiers: pendingRequests.map{$0.identifier}) } } private func update(_ accounts: Set<Account>, completion: ((Subscribers.Completion<AFError>) -> Void)?) { guard !accounts.isEmpty else { completion?(.finished) return } let notificationCenter = UNUserNotificationCenter.current() let notificationOptions = skillQueueNotificationOptions notificationCenter.getPendingNotificationRequests { (pendingRequests) in self.managedObjectContext.perform { var pendingRequests = pendingRequests var subscription: AnyCancellable? subscription = Publishers.Sequence(sequence: accounts).setFailureType(to: AFError.self) .compactMap{account in account.oAuth2Token.map{(account: account, esi: ESI(token: $0))}} .flatMap{ i in i.esi.characters.characterID(Int(i.account.characterID)).skillqueue().get().map{$0.value} .catch{_ in Empty()} .zip(i.esi.image.character(Int(i.account.characterID), size: .size256).replaceError(with: UIImage()).setFailureType(to: AFError.self)) .map{(i.account, $0.0, $0.1)} } .receive(on: self.managedObjectContext) .sink(receiveCompletion: {result in subscription?.cancel() completion?(result) if case .finished = result, !pendingRequests.isEmpty { notificationCenter.removePendingNotificationRequests(withIdentifiers: pendingRequests.map{$0.identifier}) } }) { (account, skillQueue, image) in let prefix = "\(account.uuid ?? "")." let i = pendingRequests.partition{$0.identifier.hasPrefix(prefix)} let toRemove = pendingRequests[i...] if !toRemove.isEmpty { notificationCenter.removePendingNotificationRequests(withIdentifiers: toRemove.map{$0.identifier}) } pendingRequests.removeLast(pendingRequests.count - i) let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(account.characterID).png") try? image.pngData()?.write(to: url) let date = Date() let items = skillQueue.filter{$0.finishDate != nil && $0.finishDate! > date} if let finishDate = items.map({$0.finishDate!}).max() { var requests = notificationOptions.contains(.skillTrainingComplete) ? items.map{self.notificationRequest(item: $0, account: account, characterImageURL: url)} : [] let checkpoints: [(SkillQueueNotificationOptions, Date)] = [(.inactive, finishDate), (.oneHour, finishDate.addingTimeInterval(-3600)), (.fourHours, finishDate.addingTimeInterval(-3600 * 4)), (.oneDay, finishDate.addingTimeInterval(-3600 * 24))] requests += checkpoints.filter{notificationOptions.contains($0.0) && $0.1 > date}.map { i -> UNNotificationRequest in let body: String switch i.0 { case .inactive: body = NSLocalizedString("Training Queue is inactive", comment: "") case .oneHour: body = NSLocalizedString("Training Queue will finish in 1 hour.", comment: "") case .fourHours: body = NSLocalizedString("Training Queue will finish in 4 hours.", comment: "") case .oneDay: body = NSLocalizedString("Training Queue will finish in 24 hours.", comment: "") default: body = "" } return self.notificationRequest(identifier: "\(account.uuid ?? "").timeLeft.\(i.0.rawValue)", account: account, subtitle: nil, body: body, date: i.1, characterImageURL: url) } for request in requests { notificationCenter.add(request, withCompletionHandler: nil) } } } } } } func remove(_ accounts: Set<String>, completion: (() -> Void)?) { guard !accounts.isEmpty else { completion?() return } let notificationCenter = UNUserNotificationCenter.current() let prefixes = accounts.map{"\($0)."} notificationCenter.getPendingNotificationRequests { (pendingRequests) in for prefix in prefixes { let toRemove = pendingRequests.filter{$0.identifier.hasPrefix(prefix)} if !toRemove.isEmpty { notificationCenter.removePendingNotificationRequests(withIdentifiers: toRemove.map{$0.identifier}) } } completion?() } } private func notificationRequest(item: ESI.SkillQueueItem, account: Account, characterImageURL: URL) -> UNNotificationRequest { let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(item.skillID)).first() let typeName = type?.typeName ?? String(format: NSLocalizedString("Skill %d", comment: ""), Int(item.skillID)) return notificationRequest(identifier: "\(account.uuid ?? "").\(item.skillID).\(item.finishedLevel)", account: account, subtitle: NSLocalizedString("Skill Training Complete", comment: ""), body: "\(typeName): \(item.finishedLevel)", date: item.finishDate!, characterImageURL: characterImageURL) } private func notificationRequest(identifier: String, account: Account, subtitle: String?, body: String, date: Date, characterImageURL: URL) -> UNNotificationRequest { let content = UNMutableNotificationContent() content.title = account.characterName ?? String(format: NSLocalizedString("Character %d", comment: ""), Int(account.characterID)) content.subtitle = subtitle ?? "" content.body = body content.userInfo["account"] = account.uuid content.sound = UNNotificationSound.default do { let attachmentURL = characterImageURL.deletingLastPathComponent().appendingPathComponent("\(identifier).png") try FileManager.default.linkItem(at: characterImageURL, to: attachmentURL) content.attachments = try [UNNotificationAttachment(identifier: "\(account.characterID)", url: attachmentURL, options: nil)] } catch {} let components = Calendar.current.dateComponents(Set([.year, .month, .day, .hour, .minute, .second, .timeZone]), from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false) return UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) } private func managedObjectContextDidSave(_ note: Notification) { guard let context = note.object as? NSManagedObjectContext else {return} guard context === managedObjectContext || context.persistentStoreCoordinator === managedObjectContext.persistentStoreCoordinator else {return} let toDelete = (note.userInfo?[NSDeletedObjectsKey] as? NSSet)?.compactMap{$0 as? Account}.compactMap{$0.uuid} managedObjectContext.perform { let toInsert = (note.userInfo?[NSInsertedObjectsKey] as? NSSet)?.compactMap{$0 as? Account}.map{self.managedObjectContext.object(with: $0.objectID) as! Account} self.remove(Set(toDelete ?? [])) { self.update(Set(toInsert ?? []), completion: nil) } } } } //case SkillQueueNotificationOptions.inactive.rawValue: // body = NSLocalizedString("Training Queue is inactive", comment: "") //case SkillQueueNotificationOptions.oneHour.rawValue: // body = NSLocalizedString("Training Queue will finish in 1 hour.", comment: "") //case SkillQueueNotificationOptions.fourHours.rawValue: // body = NSLocalizedString("Training Queue will finish in 4 hours.", comment: "") //case SkillQueueNotificationOptions.oneDay.rawValue: // body = NSLocalizedString("Training Queue will finish in 24 hours.", comment: "") //let content = UNMutableNotificationContent() //content.title = title //content.subtitle = NSLocalizedString("Skill Training Complete", comment: "") //content.body = body //content.userInfo["accountUUID"] = accountUUID // //let attachmentURL = imageURL.deletingLastPathComponent().appendingPathComponent("\(identifier).png") //try? FileManager.default.linkItem(at: imageURL, to: attachmentURL) //content.attachments = [try? UNNotificationAttachment(identifier: "uuid", url: attachmentURL, options: nil)].compactMap {$0} //content.sound = UNNotificationSound.default() // //let components = Calendar.current.dateComponents(Set([.year, .month, .day, .hour, .minute, .second, .timeZone]), from: date) //let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false) //let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) //return request
lgpl-2.1
a2fa34302c37482559889111740d9889
48.50519
186
0.599706
5.654941
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Controls/NTSegmentedControl.swift
1
10543
// // NTSegmentedControl.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 6/4/17. // public protocol NTSegmentedControlDelegate: class { func didSelect(_ segmentIndex: Int) } open class NTSegmentedControl: UIControl { open static let height: CGFloat = Constants.height + Constants.topBottomMargin * 2 private struct Constants { static let height: CGFloat = 30 static let topBottomMargin: CGFloat = 5 static let leadingTrailingMargin: CGFloat = 10 } class SliderView: UIView { // MARK: - Properties fileprivate let sliderMaskView = UIView() var cornerRadius: CGFloat! { didSet { layer.cornerRadius = cornerRadius sliderMaskView.layer.cornerRadius = cornerRadius } } override var frame: CGRect { didSet { sliderMaskView.frame = frame } } override var center: CGPoint { didSet { sliderMaskView.center = center } } init() { super.init(frame: .zero) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { layer.masksToBounds = true sliderMaskView.backgroundColor = .black sliderMaskView.setDefaultShadow() } } open weak var delegate: NTSegmentedControlDelegate? open var defaultTextColor: UIColor = Color.Default.Text.Disabled { didSet { updateLabelsColor(with: defaultTextColor, selected: false) } } open var highlightTextColor: UIColor = .white { didSet { updateLabelsColor(with: highlightTextColor, selected: true) } } open var segmentsBackgroundColor: UIColor = Color.Default.Background.View.darker(by: 5) { didSet { backgroundView.backgroundColor = segmentsBackgroundColor } } open var sliderBackgroundColor: UIColor = Color.Default.Tint.View { didSet { selectedContainerView.backgroundColor = sliderBackgroundColor } } open var font: UIFont = Font.Default.Subtitle { didSet { updateLabelsFont(with: font) } } private(set) open var selectedSegmentIndex: Int = 0 private var segments: [String] = [] open var numberOfSegments: Int { return segments.count } private var segmentWidth: CGFloat { return self.backgroundView.frame.width / CGFloat(numberOfSegments) } private var correction: CGFloat = 0 private lazy var containerView: UIView = UIView() private lazy var backgroundView: UIView = UIView() private lazy var selectedContainerView: UIView = UIView() private lazy var sliderView: SliderView = SliderView() // MARK: - Handlers open var onSelectionChanged: ((NTSegmentedControl) -> Void)? @discardableResult open func onSelectionChanged(_ handler: @escaping ((NTSegmentedControl) -> Void)) -> Self { onSelectionChanged = handler return self } public convenience init() { self.init(frame: .zero) } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: Setup private func setup() { addSubview(containerView) containerView.addSubview(backgroundView) containerView.addSubview(selectedContainerView) containerView.addSubview(sliderView) selectedContainerView.layer.mask = sliderView.sliderMaskView.layer addTapGesture() addDragGesture() } open func setSegmentItems(_ segments: [String]) { guard !segments.isEmpty else { fatalError("Segments array cannot be empty") } self.segments = segments configureViews() clearLabels() for (index, title) in segments.enumerated() { let baseLabel = createLabel(with: title, at: index, selected: false) let selectedLabel = createLabel(with: title, at: index, selected: true) backgroundView.addSubview(baseLabel) selectedContainerView.addSubview(selectedLabel) } setupAutoresizingMasks() } private func configureViews() { containerView.frame = CGRect(x: Constants.leadingTrailingMargin, y: Constants.topBottomMargin, width: bounds.width - Constants.leadingTrailingMargin * 2, height: Constants.height) let frame = containerView.bounds backgroundView.frame = frame selectedContainerView.frame = frame sliderView.frame = CGRect(x: 0, y: 0, width: segmentWidth, height: backgroundView.frame.height) let cornerRadius = backgroundView.frame.height / 2 [backgroundView, selectedContainerView].forEach { $0.layer.cornerRadius = cornerRadius } sliderView.cornerRadius = cornerRadius backgroundColor = .white backgroundView.backgroundColor = segmentsBackgroundColor selectedContainerView.backgroundColor = sliderBackgroundColor } private func setupAutoresizingMasks() { containerView.autoresizingMask = [.flexibleWidth] backgroundView.autoresizingMask = [.flexibleWidth] selectedContainerView.autoresizingMask = [.flexibleWidth] sliderView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] } // MARK: Labels private func clearLabels() { backgroundView.subviews.forEach { $0.removeFromSuperview() } selectedContainerView.subviews.forEach { $0.removeFromSuperview() } } private func createLabel(with text: String, at index: Int, selected: Bool) -> UILabel { let rect = CGRect(x: CGFloat(index) * segmentWidth, y: 0, width: segmentWidth, height: backgroundView.frame.height) let label = UILabel(frame: rect) label.text = text label.textAlignment = .center label.textColor = selected ? highlightTextColor : defaultTextColor label.font = font label.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] return label } private func updateLabelsColor(with color: UIColor, selected: Bool) { let containerView = selected ? selectedContainerView : backgroundView containerView.subviews.forEach { ($0 as? UILabel)?.textColor = color } } private func updateLabelsFont(with font: UIFont) { selectedContainerView.subviews.forEach { ($0 as? UILabel)?.font = font } backgroundView.subviews.forEach { ($0 as? UILabel)?.font = font } } // MARK: Tap gestures private func addTapGesture() { let tap = UITapGestureRecognizer(target: self, action: #selector(didTap)) addGestureRecognizer(tap) } private func addDragGesture() { let drag = UIPanGestureRecognizer(target: self, action: #selector(didPan)) sliderView.addGestureRecognizer(drag) } @objc private func didTap(tapGesture: UITapGestureRecognizer) { moveToNearestPoint(basedOn: tapGesture) } @objc private func didPan(panGesture: UIPanGestureRecognizer) { switch panGesture.state { case .cancelled, .ended, .failed: moveToNearestPoint(basedOn: panGesture, velocity: panGesture.velocity(in: sliderView)) case .began: correction = panGesture.location(in: sliderView).x - sliderView.frame.width/2 case .changed: let location = panGesture.location(in: self) sliderView.center.x = location.x - correction case .possible: () } } // MARK: Slider position private func moveToNearestPoint(basedOn gesture: UIGestureRecognizer, velocity: CGPoint? = nil) { var location = gesture.location(in: self) if let velocity = velocity { let offset = velocity.x / 12 location.x += offset } let index = segmentIndex(for: location) move(to: index) delegate?.didSelect(index) onSelectionChanged?(self) } open func move(to index: Int) { let correctOffset = center(at: index) animate(to: correctOffset) selectedSegmentIndex = index } private func segmentIndex(for point: CGPoint) -> Int { var index = Int(point.x / sliderView.frame.width) if index < 0 { index = 0 } if index > numberOfSegments - 1 { index = numberOfSegments - 1 } return index } private func center(at index: Int) -> CGFloat { let xOffset = CGFloat(index) * sliderView.frame.width + sliderView.frame.width / 2 return xOffset } private func animate(to position: CGFloat) { UIView.animate(withDuration: 0.2) { self.sliderView.center.x = position } } }
mit
10def568fbcd7f027a12f31cf25ef600
33.116505
123
0.629008
5.157534
false
false
false
false
iyubinest/Encicla
encicla/station/ui/StationViewController.swift
1
2146
import UIKit import RxSwift import RxCocoa import CoreLocation import GoogleMaps class StationViewController: BaseViewController, StationsViewDelegate { @IBOutlet var stationsView: StationsView! @IBOutlet var mapView: StationsMapView! @IBOutlet var loadingView: LoadingView! private let disposable = CompositeDisposable() private let stationsRepo = DefaultStations(locationRepo: DefaultGPS(), routesRepo: DefaultRoute(), stationsApiRepo: DefaultStationsAPI()) .near() override func viewDidLoad() { super.viewDidLoad() stationsView.onClickDelegate = self self.request() } override func onResume() { if disposable.count > 0 { loadingView.start() } } override func onPause() { loadingView.stop() } private func request() { loadingView.start() let subscription = stationsRepo .subscribeOn(MainScheduler.instance) .subscribe(onNext: { response in self.updateUI(location: response.0, stations: response.1); }, onError: { (error) -> Void in if error._code == CLError.denied.rawValue { self.settings() } else { self.showError() } }) disposable.insert(subscription) } private func updateUI(location: CLLocation, stations: [PolylineStation]) { stationsView.add(stations: stations) mapView.updateMap(location: location) mapView.updateMap(station: stations.first!) } private func showError() { loadingView.stop() Snackbar.show(view: self.view, message: "There is an error getting the results", buttonText: "Retry") { snackbar in self.request() snackbar.removeFromSuperview() } } private func settings() { loadingView.stop() Snackbar.show(view: self.view, message: "Please approve Location permission", buttonText: "Retry") { snackbar in let url = URL(string: UIApplicationOpenSettingsURLString) UIApplication.shared.openURL(url!) snackbar.removeFromSuperview() } } internal func stationSelected(station: PolylineStation) { mapView.updateMap(station: station) } }
mit
cf015d6eddb5f5af513bac5bd0eab2a1
24.855422
76
0.678938
4.634989
false
false
false
false
github641/testRepo
SwiftProgrammingLanguage/SwiftProgrammingLanguage/ASwiftTour_01.swift
1
40538
// // ViewController.swift // SwiftProgrammingLanguage // // Created by alldk on 2017/8/28. // Copyright © 2017年 alldk. All rights reserved. // /*lzy170905注: 这个类,对应的是 The Swift Programming Language第一章(A Swift Tour)的内容:欢迎使用Swift。 是Swift语言的整体概览。 */ import UIKit /*lzy170904注: 1、使用 protocol 来声明一个协议。 */ protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } /*lzy170904注: 练习: 给 Double 类型写一个扩展,添加 absoluteValue 功能。 */ extension Double { func absoluteValue() -> Double { var a :Double = 0.0 if self >= 0 { a = self } else if self < 0{ a = -self } return a } } /*lzy170904注: 2.2使用 extension 来为现有的类型添加功能,比如新的方法和计算属性。你可以使用扩展在别处修改定义,甚至是 从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。 */ extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } /*lzy170904注: 2.1类、枚举和结构体都可以实现协议。 注意声明 SimpleStructure 时候 mutating 关键字用来标记一个会修改结构体的方法。 SimpleClass 的声明不需要 标记任何方法,因为类中的方法通常可以修改类属性(类的性质)。 */ class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += "Now 100% adjusted." } } struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure." mutating func adjust() { simpleDescription += "(adjusted)" } } /*lzy170904注: 练习:写一个实现这个协议的枚举。 //作者:guoshengboy //链接:http://www.jianshu.com/p/abb731c4a91d //來源:简书 //著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ enum SimpleEnum: ExampleProtocol { case Buy, Sell var simpleDescription: String { switch self { case .Buy: return "We're buying something" case .Sell: return "We're selling something" } } // lzy170904注:left side of mutating operator isn’t mutable:’simpleDescription’ is a get-only property // mutating func adjust() { // simpleDescription += "(adjusted)" // } mutating func adjust() { print("left side of mutating operator isn’t mutable:’simpleDescription’ is a get-only property") } } /*lzy170831注: 如果你不需要计算属性,但是仍然需要在设置一个新值之前或者之后运行代码,使用 willSet 和 didSet 。 比如,下面的类确保三角形的边长总是和正方形的边长相同。 */ class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init (size: Double, name: String){ square = Square (sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } /*lzy170831注: 除了储存简单的属性之外,属性可以有 getter 和 setter 。 在 perimeter 的 setter 中,新值的名字是 newValue 。你可以在 set 之后显式的设置一个名字。 注意 EquilateralTriangle 类的构造器执行了三步: 1. 设置子类声明的属性值 2. 调用父类的构造器 3. 改变父类定义的属性值。其他的工作比如调用方法、getters 和 setters 也可以在这个阶段完成。 */ class EquilateralTriangle: NamedShape { var sideLength : Double = 0.0 init (sideLength: Double, name: String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } // lzy170831注:周长 var perimeter : Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triagle with sides of length \(sideLength)." } } /*lzy170831注: 练习: 创建 NamedShape 的另一个子类 Circle ,构造器接收两个参数,一个是半径一个是名称,在子类 Circle 中实现 area() 和 simpleDescription() 方法。 */ class Circle: NamedShape { var radius : Double init(radius : Double, name: String){ self.radius = radius super.init(name: name) } func area() -> Double{ return 3.14 * radius * radius } override func simpleDescription() -> String { return "A circle with radius \(radius)." } } /*lzy170831注: 子类的定义方法是在它们的类名后面加上父类的名字,用冒号分割。创建类的时候并不需要一个标准的根类,所 以你可以忽略父类。 子类如果要重写父类的方法的话,需要用 override 标记——如果没有添加 override 就重写父类方法的话编译器 会报错。编译器同样会检测 override 标记的方法是否确实在父类中。 */ class Square: NamedShape { var sideLength: Double init (sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double{ return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } /*lzy170831注: 使用 init 来创建一个构造器。 如果你需要在删除对象之前进行一些清理工作,使用 deinit 创建一个析构函数。 注意 self 被用来区别实例变量。当你创建实例的时候,像传入函数参数一样给类传入构造器的参数。每个属性都 需要赋值——无论是通过声明(就像 numberOfSides )还是通过构造器(就像 name )。 */ class NamedShape { var numberOfSides: Int = 0 var name : String init (name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } /*lzy170831注: 使用 class 和类名来创建一个类。类中属性的声明和常量、变量声明一样,唯一的区别就是它们的上下文是 类。同样,方法和函数声明也一样。 练习: 使用 let 添加一个常量属性,再添加一个接收一个参数的方法。 要创建一个类的实例,在类名后面加上括号。使用点语法来访问实例的属性和方法。 这个版本的 Shape 类缺少了一些重要的东西:一个构造函数来初始化类实例。使用 init 来创建一个构造器。 */ class Shape { var numberOfSides = 0 let constant = 9 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } func hasParamFunc(constantVar : Int) -> String { return "This is \(constantVar)." } } class ASwiftTour_01: UIViewController { override func viewDidLoad() { super.viewDidLoad() // MARK: - 常量、变量、类型自动推断 // lzy170829注:在屏幕上打印“Hello, world” /*lzy170829注: 这行代码就是一个完整的程 序。你不需要为了输入输出或者字符串处理导入一个单独的库。全局作用域中的代码会被自动当做程序的入口点,所以你也不需要 main() 函数。你同样不需要在每个语句结尾写上分号。 */ print("hello swift") /*lzy170829注: 使用 let 来声明常量,使用 var 来声明变量。 一个常量的值,在编译的时候,并不需要有明确的值,但是你只能 为它赋值一次。也就是说你可以用常量来表示这样一个值:你只需要决定一次,但是需要使用很多次。 常量或者变量的类型必须和你赋给它们的值一样。 然而,你不用明确地声明类型,声明的同时赋值的话,编译器 会自动推断类型。 在上面的例子中,编译器推断出 myVariable 是一个整数(integer)因为它的初始值是整数。 */ var myVaridalbe = 43 myVaridalbe = 55 let myConstant = 44 let implicitInteger = 80 let implicitDouble = 90.0 // MARK: - 显式指定类型、类型转换 /*lzy170829注: 如果初始值没有提供足够的信息(或者没有初始值),那你需要在变量后面声明类型,用冒号分割。 显式指定类型. 值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。 */ let explicitDouble: Double = 99 let aFloat: Float = 4 /*lzy170829注: 删除最后一行中的 String ,错误提示是什么? Binary operator ‘+’ cannot be applied to operands(n. [计] 操作数;[计] 操作对象;[计] 运算对象(operand的复数形式)) of type ‘String’ and ‘Int’ */ let label = "The width is" let width = 94 let widthLabel = label + String(width) /*lzy170829注: 有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠。例如: */ let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." /*lzy170829注: 练习: 使用 \() 来把一个浮点计算转换成字符串,并加上某人的名字,和他打个招呼。 */ let eyes = 3 let greet = "Hello, \(eyes) eyes Json" // MARK: - 数组和字典 /*lzy170829注: 使用方括号 [] 来创建数组和字典,并使用下标或者键(key)来访问元素。最后一个元素后面允许有个逗号。 */ var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm" : "Captain", "Kaylee" : "Mechanic", ] occupations["Jayne"] = "Public Relations" /*lzy170829注: 要创建一个空数组或者字典,使用初始化语法。 */ let emptyArray = [String]() let emptyDictionary = [String : Float]() /*lzy170829注: 如果类型信息可以被推断出来,你可以用 [] 和 [:] 来创建空数组和空字典——就像你声明变量或者给函数传参 数的时候一样。 */ shoppingList = [] occupations = [:] // MARK: - 控制流 /*lzy170829注: 使用 if 和 switch 来进行条件操作,使用 for-in 、 for 、 while 和 repeat-while 来进行循环。包裹条件和循环变量的括号可以省略,但是语句体的大括号是必须的。 */ let individualScores = [75, 22, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { // lzy170829注:+= 这个运算符,两边都要有空格 teamScore += 3 } else { teamScore += 1 } } print(teamScore) /*lzy170829注: 在 if 语句中,条件必须是一个布尔表达式——这意味着像 if score { ... } 这样的代码将报错,而不会隐形地 与 0 做对比。 */ // MARK: 可选值 /*lzy170829注: 你可以一起使用 if 和 let 来处理值缺失的情况。这些值可由可选值来代表。一个可选的值是一个具体的值或者 是 nil 以表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。 */ var optionalString : String? = "Hello" print(optionalString == nil) var optionalName: String? = "John Appleseed" var greeting = "Hello!" /*lzy170829注: 把optionalName改成 nil ,greeting会是什么?添加一个else语句,当optionalName是nil时给 greeting 赋一个不同的值。 如果变量的可选值是 nil ,条件会判断为 false,大括号中的代码会被跳过。如果不是 nil,会将值解包并赋给 let后面的常量,这样代码块中就可以使用这个值了。 */ optionalName = nil if let name = optionalName { greeting = "Hello \(name)" }else{ greeting = "Hello friend!" } print(greeting) /*lzy170829注: 另一种处理可选值的方法是通过使用 ?? 操作符来提供一个默认值。如果可选值缺失的话,可以使用默认值来代替。 */ let nickName : String? = nil let fullName : String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)" print(informalGreeting) // MARK: switch /*lzy170829注: switch 支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。 注意 let 在上述例子的等式中是如何使用的,它将匹配等式的值赋给常量 x 。 删除 default 语句,看看会有什么错误? switch must be exhaustive(详尽的、穷举的),consider adding a default clause(语句,条款) 运行 switch 中匹配到的子句之后,程序会退出 switch 语句,并不会继续向下运行,所以不需要在每个子句结尾 写 break 。 */ let vegetable = "red pepper" switch vegetable { case "celery" : print("Add some raisins and make ants on a log.") case "cucumber", "watercress" : print("That would make a good tea sandwich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup.") } // MARK: for-in /*lzy170829注: 你可以使用 for-in 来遍历字典,需要两个变量来表示每个键值对。字典是一个无序的集合,所以他们的键和值以 任意顺序迭代结束。 */ let interestingNumbers = [ "Prime" : [2, 3, 5, 7, 11, 13], "Fibonacci" : [1, 1, 2, 3, 5, 8], "Square" : [1, 4, 9, 16, 25], ] /*lzy170829注:这个题不理解 练习: 添加另一个变量来记录最大数字的种类(kind),同时仍然记录这个最大数字的值。 */ /*lzy170906注:理解了。 kind 和 numbers都是随意命名的。可以用任意的a,b之的替代。 */ var largest = 0 // TODO: Immutable value 'kind' was never used;consider replacing with '_' or removing it for (kind, numbers) in interestingNumbers{ for n in numbers{ if n > largest { largest = n } } } print(largest) // MARK: while /*lzy170829注: 使用 while 来重复运行一段代码直到不满足条件。循环条件也可以在结尾,保证能至少循环一次。 */ var n = 2 while n < 100 { n = n * 2 } print(n) var m = 2 repeat { m = m * 2 } while m < 100 print(m) /*lzy170829注: 你可以在循环中使用 ..< 来表示范围。 */ var total = 0 for i in 0 ..< 4{ total += i } print(total) // MARK: - 函数与闭包 // MARK: 函数的声明和调用 /*lzy170830注: 使用 func 来声明一个函数,使用名字和参数来调用函数。使用 -> 来指定函数返回值的类型。 */ func greetA(person: String, day: String) -> String{ return "Hello \(person), today is \(day)." } greetA(person: "John", day: "Wednesday") /*lzy170830注: 默认情况下,函数使用它们的参数名称作为它们参数的标签,在参数名称前可以自定义参数标签,或者使用 _ 表示不使用参数标签。 */ /*lzy170906注: 参数名前没有标签,默认使用参数名组成方法的一部分 参数名前有标签,使用标签。 使用 _ ,在参数名前使用它,则『参数名称不作为函数的参数标签』 _ 和 自定义参数标签不可同时存在。 */ func greetB(_ person:String,on day:String) -> String { return "Hello \(person), today is \(day)." } greetB("John", on: "wednesday") // MARK: 函数返回值为元组 /*lzy170830注: 使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示。 */ func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [111,22,33,3,784,66]) print(statistics.sum) print(statistics.2)// 取下标为2的元素,就是sum // MARK: 函数可以有可变个数的参数 /*lzy170830注: 函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式 */ func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } print(sumOf()) print(sumOf(numbers: 1, 2, 3, 4, 5, 6, 7, 8)) /*lzy170830注: 练习:写一个计算参数平均值的函数。 */ func calculateAverage(nums: [Int]) -> Int { var sum : Int = 0 for num in nums{ sum += num } return (sum / nums.count) } func calculateAverageDouble(nums: [Double]) -> Double { var sum : Double = 0 for num in nums{ sum += num } return (sum / Double(nums.count)) } print(calculateAverage(nums: [1, 2, 3, 4])) print(calculateAverageDouble(nums: [1.1, 1.2, 1.3, 1.4])) // MARK: 函数可以嵌套 /*lzy170830注: 函数可以嵌套。被嵌套的函数可以访问外侧函数的变量,你可以使用嵌套函数来重构一个太长或者太复杂的函数。 */ func returnFifteen() -> Int{ var y = 10 func add(){ y += 5 } add() return y } print(returnFifteen()) // MARK: 函数可以作为另一个函数的返回值 /*lzy170830注: 函数是第一等类型,这意味着函数可以作为另一个函数的返回值。 */ func makeIncrementer() -> ( (Int) -> Int ) { func addOne(number: Int) -> Int { return 1 + number } return addOne } func lessThanTen(number: Int) -> Bool{ return number < 10 } let increment = makeIncrementer() print(increment(9)) // MARK: 函数可以作为参数传入另一个函数 /*lzy170830注: 函数也可以当做参数传入另一个函数。 */ func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool{ for item in list { if condition(item){ return true } } return false } let arrayForClosure = [2, 44, 6, 09] let funcR1 = hasAnyMatches(list: arrayForClosure, condition: lessThanTen) print(funcR1) // MARK: 函数是一种特殊的闭包 /*lzy170830注: 函数实际上是一种特殊的闭包:它是一段能之后被调取的代码。闭包中的代码能访问闭包所建作用域中能得到的变量和函数,即使闭包是在一个不同的作用域被执行的 - 你已经在嵌套函数例子中所看到。 你可以使用 {} 来创建 一个匿名闭包。使用 in 将参数和返回值类型声明与闭包函数体进行分离。 */ let funcR2 = arrayForClosure.map { (number: Int) -> Int in let result = 3 * number return result } print(funcR2) /*lzy170830注: 练习: 重写闭包,对所有奇数返回 0。 */ let funcR3 = arrayForClosure.map { /*lzy170830注: (number : Int) -> Int 是匿名闭包声明 in 分割了 匿名闭包声明 和 匿名闭包函数体 */ (number : Int) -> Int in var res : Int if number % 2 == 0{ res = number }else { res = 0 } return res } print(funcR3) /*lzy170830注: 有很多种创建更简洁的闭包的方法。 如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型和返回值。 单个语句闭包会把它语句的值当做结果返回。 */ let mappedNumbers = arrayForClosure.map({ number in 3 * number}) print(mappedNumbers) /*lzy170830注: 你可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用。 当一个闭包作为最后一个参数传给一个函数的时候,它可以直接跟在括号后面。 当一个闭包是传给函数的唯一参数,你可以完全忽略括号。 */ let sortedNumbers = arrayForClosure.sorted{ $0 > $1} print(sortedNumbers) // lzy170830注:以上两个例子闭包都是作为参数传入的;mappedNumbers和sortedNumbers是map函数和sorted函数自身的返回值 // MARK: - 对象和类 /*lzy170831注: 要创建一个类的实例,在类名后面加上括号。使用点语法来访问实例的属性和方法。 */ let shape = Shape() shape.numberOfSides = 9 let shapeDescription = shape.simpleDescription() print(shapeDescription) let test = Square(sideLength: 5.2, name: "my test square") print(test.area()) print(test.simpleDescription()) let testCircle = Circle(radius: 9, name: "my test circle") print(testCircle.area()) print(testCircle.simpleDescription()) let triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength) let triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") print(triangleAndSquare.square.sideLength) print(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "larger square") print(triangleAndSquare.triangle.sideLength) /*lzy170831注: 处理变量的可选值时,你可以在操作(比如方法、属性和子脚本)之前加 ? 。如果 ? 之前的值是 nil , ? 后面 的东西都会被忽略,并且整个表达式返回 nil 。否则, ? 之后的东西都会被运行。在这两种情况下,整个表达式 的值也是一个可选值。 */ let optionalSquare: Square? = Square(sideLength: 2.5, name: "option square") let sideLength = optionalSquare?.sideLength // MARK: - 枚举和结构体 // MARK: 枚举 // lzy170901注:枚举似乎可以写在类中,也可以写在类外。这样的话,类将是枚举是否可以被发现被使用的范围 /*lzy170901注:因为需要写一个枚举 使用 enum 来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法。 */ enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String{ switch self { case .Ace: return "ace" case .Jack: return "jack" case .King: return "king" default: return String(self.rawValue) } } } func compareRank(rank1: Rank , rank2: Rank) -> Rank{ return rank1.rawValue > rank2.rawValue ? rank1 : rank2 } let ace = Rank.Ace print(ace.rawValue) /*lzy170901注: 练习: 写一个函数,通过比较它们的原始值来比较两个 Rank 值。 */ let rank1 = Rank.Ten let rank2 = Rank.Queen print(compareRank(rank1: rank1, rank2: rank2)) /*lzy170901注: 默认情况下,Swift 按照从 0 开始每次加 1 的方式为原始值进行赋值,不过你可以通过显式赋值进行改变。 在 上面的例子中, Ace 被显式赋值为 1,并且剩下的原始值会按照顺序赋值。 你也可以使用字符串或者浮点数作为 枚举的原始值。 使用 rawValue 属性来访问一个枚举成员的原始值。 */ /*lzy170901注: 使用 init?(rawValue:) 初始化构造器在原始值和枚举值之间进行转换。 */ if let convertedRank = Rank(rawValue: 4) { let fourDescription = convertedRank.simpleDescription() print(fourDescription) } /*lzy170901注: 枚举的成员值是实际值,并不是原始值的另一种表达方法。实际上,如果没有比较有意义的原始值,你就不需要提供原始值。 */ enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } /*lzy170901注: 练习: 给 Suit 添加一个 color() 方法,对 spades 和 clubs 返回“black”,对 hearts 和 diamonds 返回“red”。 */ func color() -> String{ switch self { case .Spades: return "black" case .Clubs: return "black" case .Hearts: return "red" case .Diamonds: return "red" } } } /*lzy170901注: 注意,有两种方式可以引用 Hearts 成员:给 hearts 常量赋值时,枚举成员 Suit.Hearts 需要用全名来引用,因为常量没有显式指定类型。 在 switch 里,枚举成员使用缩写 .Hearts 来引用,因为 self 的值已经知道是一个suit 。已知变量类型的情况下你可以使用缩写。 */ let hearts = Suit.Hearts print(hearts.simpleDescription()) print(Suit.Hearts.color()) /*lzy170901注: 一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。实例值 和原始值是不同的:枚举成员的原始值对于所有实例都是相同的,而且你是在定义枚举的时候设置原始值。 */ /*lzy170901注: 例如,考虑从服务器获取日出和日落的时间。服务器会返回正常结果或者错误信息。 练习: 给 ServerResponse 和 switch 添加第三种情况。 注意日升和日落时间是如何从 ServerResponse 中提取到并与 switch 的 case 相匹配的。 */ enum ServerResponse { case Result(String, String) case Failure(String) case CannotConnectToServerCode(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Failure("Out of cheese.") let code = ServerResponse.CannotConnectToServerCode("-1086") switch success { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Failure(message): print("Failure... \(message)") case let .CannotConnectToServerCode(code): print("Cannot Connect To Server Code:\(code)") } // MARK: 结构体 /*lzy170901注: 使用 struct 来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是结构体是传值,类是传引用。 */ // TODO: 练习: 给 Card 添加一个方法,创建一副完整的扑克牌并把每张牌的 rank 和 suit 对应起来。 struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) print(threeOfSpades.simpleDescription()) // MARK: - 协议和扩展 // lzy170904注:Protocol cannot be nested inside another declaration // protocol ExampleProtocol { // var simpleDescription: String { get } // mutating func adjust() // } /*lzy170904注: 使用 protocol 来声明一个协议。 类、枚举、结构体都可以实现协议。 */ var a = SimpleClass() print(a.simpleDescription) a.adjust() print(a.simpleDescription) var b = SimpleStructure() print(b.simpleDescription) b.adjust() print(b.simpleDescription) var c = SimpleEnum.Buy print(c.adjust()) // lzy170904注:使用 extension 来为现有的类型添加功能,比如新的方法和计算属性。你可以使用扩展在别处修改定义,甚至是 从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。 print(7.simpleDescription) // lzy170904注: 练习: 给 Double 类型写一个扩展,添加 absoluteValue 功能。 print((-0.3).absoluteValue()) /*lzy170904注: 你可以像使用其他命名类型一样使用协议名——例如,创建一个有不同类型但是都实现一个协议的对象集合。当你处理类型的是协议的值,协议外定义的方法不可用。 */ let protocolValue: ExampleProtocol = a print(protocolValue.simpleDescription) // print(protocolValue.anotherProperty)// 去掉注释可以看到错误value of type ‘ExampleProtocol’ has no member ‘anotherProperty’ // MARK: - 错误处理 /*lzy170904注: 使用 『采用Error协议的类型』来表示错误。 */ enum PrinterError: Error { case OutOfPaper case NoToner case OnFire } /*lzy170904注: 使用throws 来表示一个可以抛出错误的函数。 使用throw 来抛出一个错误。 如果在函数中抛出了一个错误,这个函数会立即返回,并且调用该函数的代码会进行错误处理。 */ func send(job: Int, toPrinter printerName: String) throws -> String { if printerName == "Never Has Toner" { throw PrinterError.NoToner } return "Job sent" } // MARK: do-catch /*lzy170904注: 有多种方式可以用来进行错误处理。一种方式是使用 do-catch 。 在 do 代码块中,使用 try 来标记可以抛出错误 的代码。 在 catch 代码块中,除非你另外命名,否则错误会自动命名为 error 。 */ do { let printerResponse = try send(job: 1040, toPrinter: "Bi sheng") print(printerResponse) }catch { print(error) } /*lzy170904注: 练习: 将 printer name 改为 "Never Has Toner" 使 send(job:toPrinter:) 函数抛出错误。 */ do { let printerResponse = try send(job: 110, toPrinter: "Never Has Toner") print(printerResponse) }catch { print(error) } /*lzy170904注: 可以使用多个 catch 块来处理特定的错误。参照 switch 中的 case 风格来写 catch 。 */ do { let printerResponse = try send(job: 100, toPrinter: "Gutenberg") print(printerResponse) }catch PrinterError.OnFire { print("I'll just put this over here, with the rest of the fire.") }catch let printerError as PrinterError { print("Printer error: \(printerError)") }catch { print(error) } /*lzy170904注:这里是翻译有问题。看英文的就好。要使得触发以上三个不同catch代码执行,需要在原函数中根据商定的判断标准,分别进行throw。 Add code to throw an error inside the do block. What kind of error do you need to throw so that the error is handled by the first catch block? What about the second and third blocks? 练习: 在 do 代码块中添加抛出错误的代码。你需要抛出哪种错误来使第一个 catch 块进行接收?怎么使第二 个和第三个 catch 进行接收呢? */ // MARK: try? /*lzy170904注: 另一种处理错误的方式使用 try? 将结果转换为可选的。如果函数抛出错误,该错误会被抛弃并且结果为 nil 。否则的话,结果会是一个包含函数返回值的可选值。 Optional("Job sent") nil */ let pSuccess = try? send(job: 1884, toPrinter: "Mergenthaler") let pFailure = try? send(job: 1885, toPrinter: "Never Has Toner") print(pSuccess) print(pFailure) /*lzy170904注: 使用 defer 代码块来表示在函数返回前,函数中最后执行的代码。无论函数是否会抛出错误,这段代码都将执行。 使用 defer ,可以把函数调用之初就要执行的代码和函数调用结束时的扫尾代码写在一起,虽然这两者的执 行时机截然不同。 */ var fridgeIsOpen = false let fridgeContent = ["milk", "eggs", "leftovers"] func fridgeContains(_ food: String) ->Bool { fridgeIsOpen = true defer { fridgeIsOpen = false } let result = fridgeContent.contains(food) return result } print(fridgeContains("banner")) print(fridgeContains("milk")) print(fridgeIsOpen) // MARK: - 泛型 /*lzy170904注: 在尖括号里写一个名字来创建一个泛型函数或者类型。 */ func repeatItem<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] { var result = [Item]() for _ in 0..<numberOfTimes { result.append(item) } return result } print(repeatItem(repeating: "knock", numberOfTimes: 4)) /*lzy170904注: 你也可以创建泛型函数、方法、类、枚举、结构体。 */ // TODO:这个压根没有概念,没有理解 // 重新实现Swift标准库中的可选类型 enum OptionalValue<Wrapped> { case None case Some(Wrapped) } var possibleInteger: OptionalValue<Int> = OptionalValue.None possibleInteger = OptionalValue.Some(100) /*lzy170904注: 在类型名后面使用 where 来指定对类型的需求, 比如,限定类型实现某一个协议,限定两个类型是相同的,或者 限定某个类必须有一个特定的父类。 练习: 修改 anyCommonElements(_:_:) 函数, 来创建一个函数,返回一个数组,内容是两个序列的共有元素。 <T: Equatable> 和 <T> ... where T: Equatable> 是等价的。 */ func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
b537bb8af1393c2bef166e71a6c51682
26.10131
191
0.514357
3.793521
false
false
false
false
Jezong/JZScrollTitleView
JZScrollTitleView/JZScrollTitleView/JZScrollTitleView.swift
1
5488
// // JZScrollTitleView.swift // JZScrollTitleView // // Created by jezong on 16/2/25. // Copyright © 2016年 jezong. All rights reserved. // import UIKit public class JZScrollTitleView: UIControl, UIScrollViewDelegate { /// 标题的颜色 public var titleColor: UIColor = UIColor(red: 0.05, green: 0.05, blue: 0.05, alpha: 1) /// 标题列表 public var titles = [String]() /// 当前游标位置 public var currentPos = 0 /// 游标高度 public var cursorHeight: CGFloat = 4 /// 两个标题之间的空隙 public var spaceBetweenTitles: CGFloat = 30 /// 当前选定的标题 public var currentTitle: String { return titles[currentPos] } private var containerScrollView: UIScrollView! private var cursorView: UIView! private var lineView: UIView! override init(frame: CGRect) { super.init(frame: frame) initSubviews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSubviews() } private func initSubviews() { cursorView = UIView() lineView = UIView() containerScrollView = UIScrollView() containerScrollView.bounces = false containerScrollView.delegate = self self.backgroundColor = .whiteColor() self.addSubview(lineView) self.addSubview(containerScrollView) } override public func drawRect(rect: CGRect) { for v in containerScrollView.subviews { v.removeFromSuperview() } //底部分割线条高度为1 lineView.frame = CGRectMake(0, bounds.height - 1, bounds.width, 1) lineView.backgroundColor = tintColor containerScrollView.frame = CGRectMake(0, 0, bounds.width, bounds.height-1) if titles.count == 0 { return } var offset:CGFloat = 0 var buttons = [UIButton]() for (i, title) in titles.enumerate() { let size = NSString(string: title).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize() + 3)]) let itemWidth = size.width + spaceBetweenTitles let button = UIButton(frame: CGRectMake(offset, 0, itemWidth, bounds.height-cursorHeight)) button.setTitle(title, forState: .Normal) button.setTitleColor(titleColor, forState: .Normal) button.setTitleColor(tintColor, forState: .Selected) button.selected = currentPos == i button.tag = 100 + i button.addTarget(self, action: "tapTitleButton:", forControlEvents: .TouchUpInside) containerScrollView.addSubview(button) buttons.append(button) offset += itemWidth } if offset < self.bounds.width { //如果buttons的长度小于屏幕宽度,则重新布局button的位置 let inc = (self.bounds.width - offset) / CGFloat(buttons.count) offset = 0 for button in buttons { button.frame = CGRectMake(offset, 0, button.bounds.width + inc, button.bounds.height) offset += button.bounds.width } } containerScrollView.contentSize = CGSizeMake(offset, containerScrollView.bounds.height) let button: UIButton if currentPos >= 0 || currentPos < buttons.count { button = buttons[currentPos] } else { button = buttons[0] } cursorView.frame = CGRectMake(button.frame.minX, bounds.height - cursorHeight, button.bounds.width, cursorHeight) cursorView.backgroundColor = tintColor self.addSubview(cursorView) } @objc private func tapTitleButton(button: UIButton) { setSelectedPosition(button.tag - 100, animated: true) //向目标发送事件消息 sendActionsForControlEvents(.ValueChanged) } //MARK: - Interface /** 设置游标位置 - parameter pos: 位置 - parameter animated: 是否使用动画 */ public func setSelectedPosition(pos: Int, animated: Bool) { if pos >= titles.count || currentPos == pos { return } if let currentButton = self.viewWithTag(100 + pos) as? UIButton { (self.viewWithTag(100 + currentPos) as? UIButton)?.selected = false currentButton.selected = true currentPos = pos let cursorX = currentButton.frame.minX - containerScrollView.contentOffset.x if animated { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.98, initialSpringVelocity: 0, options: .CurveLinear, animations: { self.cursorView.frame = CGRectMake(cursorX, self.cursorView.frame.minY, currentButton.bounds.width, self.cursorView.frame.height) }, completion: nil) } else { self.cursorView.frame = CGRectMake(cursorX, self.cursorView.frame.minY, currentButton.bounds.width, self.cursorView.frame.height) } scrollPointToNearCenter(currentButton.center, animated: animated) } } ///居中显示 public func scrollPointToNearCenter(point: CGPoint, animated: Bool) { let distance = containerScrollView.bounds.midX - point.x var targetPoint:CGPoint targetPoint = CGPointMake(containerScrollView.contentOffset.x - distance, 0) if targetPoint.x < 0 { targetPoint = CGPoint.zero } else if targetPoint.x > containerScrollView.contentSize.width - containerScrollView.bounds.width { targetPoint = CGPointMake(containerScrollView.contentSize.width - containerScrollView.bounds.width, 0) } containerScrollView.setContentOffset(targetPoint, animated: animated) } //MARK: - ScrollView delegate public func scrollViewDidScroll(scrollView: UIScrollView) { if let currentButton = self.viewWithTag(100 + currentPos) as? UIButton { let cursorX = currentButton.frame.minX - scrollView.contentOffset.x self.cursorView.frame = CGRectMake(cursorX, self.cursorView.frame.minY, self.cursorView.frame.width, self.cursorView.frame.height) } } }
mit
bac613f1813c282a3f1320e1ca14ced6
31.335366
138
0.729964
3.7058
false
false
false
false
jbannister/Stanford
2017/10 iOS/Faceit/Faceit/FaceView.swift
1
2445
// // FaceView.swift // Faceit // // Created by Jan Bannister on 21/03/2017. // Copyright © 2017 Jan Bannister. All rights reserved. // import UIKit class FaceView: UIView { var scale: CGFloat = 0.9 var eyesOpen : Bool = false private var skullRadius : CGFloat { return min(bounds.size.width, bounds.size.height) / 2 * scale } private var skullCenter : CGPoint { return CGPoint(x: bounds.midX, y: bounds.midY) } private enum Eye { case left case right } private func pathForEye(_ eye: Eye) -> UIBezierPath { func centerOfEye(_ eye: Eye) -> CGPoint { let eyeOffset = skullRadius / Ratios.skullRadiusToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset eyeCenter.x += ((eye == .left) ? -1 : 1) * eyeOffset return eyeCenter } let eyeRadius = skullRadius / Ratios.skullRadiusToEyeRadius let eyeCenter = centerOfEye(eye) let path : UIBezierPath if eyesOpen { path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) } else { path = UIBezierPath() path.move(to: CGPoint(x: eyeCenter.x - eyeRadius, y: eyeCenter.y)) path.addLine(to: CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y)) } path.lineWidth = 5.0 return path } private func pathForSkull() -> UIBezierPath { let path = UIBezierPath(arcCenter: skullCenter, radius: skullRadius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false) path.lineWidth = 5.0 return path } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing Code UIColor.blue.set() pathForSkull().stroke() pathForEye(.left).stroke() pathForEye(.right).stroke() } private struct Ratios { static let skullRadiusToEyeOffset: CGFloat = 3 static let skullRadiusToEyeRadius: CGFloat = 10 static let skullRadiusToMouthWidth: CGFloat = 1 static let skullRadiusToMouthHeight: CGFloat = 3 static let skullRadiusToMouthOffset: CGFloat = 3 } }
mit
9cf451500353f235b6eb4b36c525ccbf
28.445783
135
0.599018
4.41953
false
false
false
false
KoCMoHaBTa/MHAppKit
MHAppKit/Extensions/UIKit/UIImage/UIImage+Color.swift
1
1012
// // UIImage+Color.swift // MHAppKit // // Created by Milen Halachev on 6/9/16. // Copyright © 2016 Milen Halachev. All rights reserved. // #if canImport(UIKit) import Foundation import UIKit extension UIImage { ///Creates an instance of the receiver with a given color and size. Default size is 1x1 public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor) context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } } #endif
mit
08babdab1a39147a9eeeb4485c3b054b
24.275
91
0.593472
4.837321
false
false
false
false
bartekchlebek/Rosetta
Rosetta/Rosetta.swift
1
2357
import Foundation enum Mode { case decode case encode } enum Map<T> { case valueTypeMap((inout T, Rosetta) -> ()) case classTypeMap((T, Rosetta) -> ()) } public final class Rosetta { var testRun: Bool = false var dictionary: [String: AnyObject]! var keyPath: [String] = [] var logs: [Log] = [] var currentValue: AnyObject! { return valueForKeyPath(keyPath, inDictionary: dictionary) } var currentMode: Mode! public var logLevel: LogLevel = .errors public var logFormatter = defaultLogFormatter public var logHandler = defaultLogHandler public func setLogFormatter(_ formatter: @escaping LogFormatter) { logFormatter = formatter } public func setLogHandler(_ handler: @escaping LogHandler) { logHandler = handler } public init() { } public subscript(key: String) -> Rosetta { get { keyPath.append(key) return self } } func decode<T>(_ input: JSON, to object: inout T, usingMap map: Map<T>) throws { let jsonDictionary = try input.toDictionary() // perform test run (check if any mapping fail, to leave the object unchanged) currentMode = .decode dictionary = jsonDictionary switch map { case .classTypeMap(let map): self.testRun = true map(object, self) if LogsContainError(logs) { throw genericError } self.testRun = false map(object, self) case .valueTypeMap(let map): var tmpObject = object map(&tmpObject, self) if LogsContainError(logs) { throw genericError } object = tmpObject } self.cleanup() } func encode<T>(_ object: T, usingMap map: Map<T>) throws -> JSON { // prepare rosetta currentMode = .encode dictionary = [:] // parse var mutableObject = object switch map { case let .valueTypeMap(map): map(&mutableObject, self) case let .classTypeMap(map): map(mutableObject, self) } let result = dictionary let logs = self.logs let success = !LogsContainError(logs) switch logLevel { case .none: break case .errors: if success == false { logHandler(logFormatter(nil, logs)) } case .verbose: if logs.count > 0 { logHandler(logFormatter(nil, logs)) } } cleanup() if !success { throw genericError } return JSON(dictionary: result!) } //MARK: Helpers private func cleanup() { currentMode = nil dictionary = nil logs.removeAll(keepingCapacity: false) } }
mit
2f7b5b9562979cae48bae3e8feccbfa3
18.806723
94
0.678405
3.348011
false
false
false
false
material-foundation/material-automation
Sources/GithubAPI.swift
1
20083
/* Copyright 2018 the Material Automation authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import PerfectCURL import PerfectHTTP import PerfectLogger import PerfectCrypto import PerfectThread class GithubManager { static let shared = GithubManager() let githubManagerLock = Threading.RWLock() private var githubAPIs = [String: GithubAPI]() private func getCachedGithubAPI(for installation: String) -> GithubAPI? { var value: GithubAPI? githubManagerLock.doWithReadLock { value = githubAPIs[installation] } return value } func getGithubAPI(for installation: String) -> GithubAPI? { if let githubAPICached = getCachedGithubAPI(for: installation) { return githubAPICached } return githubManagerLock.doWithWriteLock { () -> GithubAPI? in guard let accessToken = GithubAuth.getAccessToken(installationID: installation) else { LogFile.error("couldn't get an access token for installation: \(installation)") return nil } let githubAPI = GithubAPI(accessToken: accessToken, installationID: installation, config: config) githubAPIs[accessToken] = githubAPI return githubAPI } } } class GithubCURLRequest: CURLRequest { override init(options: [CURLRequest.Option]) { super.init(options: options) var action = "unknown action" outer: for option in options { switch option { case .url(let urlString): action = urlString break outer default: break } } Analytics.trackEvent(category: "Github API", action: action) } } public class GithubAPI { var accessToken: String var installationID: String let curlAccessLock = Threading.Lock() var lastGithubAccess = time(nil) private let config: GithubAppConfig init(accessToken: String, installationID: String, config: GithubAppConfig) { self.accessToken = accessToken self.installationID = installationID self.config = config } /// This method adds labels to a Github issue through the API. /// /// - Parameters: /// - url: The url of the issue as a String /// - labels: The labels to add to the issue func addLabelsToIssue(url: String, labels: [String]) { LogFile.debug(labels.description) let performRequest = { () -> CURLResponse in let labelsURL = url + "/labels" let request = GithubCURLRequest(labelsURL, .postString(labels.description)) self.addAPIHeaders(to: request) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } /// This method creates and adds a comment to a Github issue through the API. /// /// - Parameters: /// - url: The url of the issue as a String /// - comment: The comment text func createComment(url: String, comment: String) { let performRequest = { () -> CURLResponse in let commentsURL = url + "/comments" let bodyDict = ["body": comment] let request = GithubCURLRequest(commentsURL, .postString(try bodyDict.jsonEncodedString())) self.addAPIHeaders(to: request) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } /// This method edits an existing Github issue through the API. /// /// - Parameters: /// - url: The url of the issue as a String /// - issueEdit: A dictionary where the keys are the items to edit in the issue, and the /// values are what they should be edited to. func editIssue(url: String, issueEdit: [String: Any]) { let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(url, .httpMethod(.patch), .postString(try issueEdit.jsonEncodedString())) self.addAPIHeaders(to: request) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } /// This method bulk updates all the existing Github issues to have labels through the API. func setLabelsForAllIssues(repoURL: String) { let performRequest = { () -> CURLResponse in let issuesURL = repoURL + "/issues" let params = "?state=all" let request = GithubCURLRequest(issuesURL + params) self.addAPIHeaders(to: request) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [[String: Any]] ?? [[:]] for issue in result { guard let issueData = IssueData.createIssueData(from: issue) else { continue } var labelsToAdd = [String]() if let titleLabel = LabelAnalysis.getTitleLabel(title: issueData.title) { labelsToAdd.append(titleLabel) } if let PRDict = issue["pull_request"] as? [String: Any] { if let diffURL = PRDict["diff_url"] as? String, diffURL.count > 0 { let paths = LabelAnalysis.getFilePaths(url: diffURL) LogFile.debug(paths.description) labelsToAdd.append(contentsOf: LabelAnalysis.grabLabelsFromPaths(paths: paths)) } } if (labelsToAdd.count > 0) { self.addLabelsToIssue(url: issueData.url, labels: Array(Set(labelsToAdd))) } } } } /// This method receives a relative path inside the repository source code and receives from the Github API /// a JSON containing an array of dictionaries showing the files info in that directory. We /// then return a list of all the file names that are directories. /// /// - Parameter relativePath: The relative path inside the repository source code /// - Returns: an array of all the file names that are directories in the specific path. func getDirectoryContentPathNames(relativePath: String, repoURL: String) -> [String] { var pathNames = [String]() let performRequest = { () -> CURLResponse in let contentsAPIPath = repoURL + "/contents/" + relativePath let request = GithubCURLRequest(contentsAPIPath) self.addAPIHeaders(to: request) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [[String: Any]] ?? [[:]] for path in result { if let type = path["type"] as? String, type == "dir", let pathName = path["name"] as? String { pathNames.append(pathName) } } } return pathNames } /// Get the project's column name by providing the column ID. /// /// - Parameter columnID: the column ID number. /// - Returns: the name of the column. func getProjectFromColumn(columnID: Int) -> [String: Any]? { guard let projectURL = getProjectColumn(columnID: columnID)?["project_url"] as? String else { return nil } return getObject(objectURL: projectURL, with: ["Accept": "application/vnd.github.inertia-preview+json"]) } /// Get the project column for a given column ID. /// /// - Parameter columnID: the column ID number. /// - Returns: the column. func getProjectColumn(columnID: Int) -> [String: Any]? { LogFile.debug("Fetching name for column ID: \(columnID)") var project: [String: Any]? let performRequest = { () -> CURLResponse in let columnsAPIPath = self.config.githubAPIBaseURL + "/projects/columns/\(columnID)" let request = GithubCURLRequest(columnsAPIPath) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in project = try response.bodyString.jsonDecode() as? [String: Any] ?? [:] } return project } /// Get the project's column name by providing the column ID. /// /// - Parameter columnID: the column ID number. /// - Returns: the name of the column. func getProjectColumnName(columnID: Int) -> String? { return getProjectColumn(columnID: columnID)?["name"] as? String } func createNewProject(url: String, name: String, body: String = "") -> String? { LogFile.debug("Creating new project with the name \(name), and body \(body)") var projectID: String? let performRequest = { () -> CURLResponse in let projectsURL = url + "/projects" let request = GithubCURLRequest(projectsURL, .postString(try ["name": name, "body": body].jsonEncodedString())) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [String: Any] ?? [:] if let projectIDNum = result["id"] as? Int { projectID = String(projectIDNum) } } return projectID } func updateProject(projectURL: String, projectUpdate: [String: Any]) { LogFile.debug("Updating a project with url: \(projectURL) and update: \(projectUpdate.description)") let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(projectURL, .httpMethod(.patch), .postString(try projectUpdate.jsonEncodedString())) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } func createProjectColumn(name: String, projectID: String) -> String? { LogFile.debug("Creating project column with name \(name)") var columnID: String? let performRequest = { () -> CURLResponse in let projectsURL = self.config.githubAPIBaseURL + "/projects/" + projectID + "/columns" let request = GithubCURLRequest(projectsURL, .postString(try ["name": name].jsonEncodedString())) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [String: Any] ?? [:] if let columnIDNum = result["id"] as? Int { columnID = String(columnIDNum) } } return columnID } func getProjectColumns(columnsURL: String) -> [[String: Any]] { LogFile.debug("listing project columns with url \(columnsURL)") var columns = [[String: Any]]() var url = columnsURL var shouldPaginate = false while true { let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(url) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [[String: Any]] ?? [[:]] for column in result { LogFile.debug(column.description) columns.append(column) } if let nextURL = self.paginate(response: response) { url = nextURL shouldPaginate = true } else { shouldPaginate = false } } if !shouldPaginate { break } } return columns } func getProjectsForRepo(repoURL: String) -> [[String: Any]] { var projects = [[String: Any]]() var url = "\(repoURL)/projects?state=open" var shouldPaginate = false while true { let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(url) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let results = try response.bodyString.jsonDecode() as? [[String: Any]] ?? [[:]] projects += results if let nextURL = self.paginate(response: response) { url = nextURL shouldPaginate = true } else { shouldPaginate = false } } if !shouldPaginate { break } } return projects } func getProjectColumnsCardsURLs(columnsURL: String) -> [String: String] { LogFile.debug("listing project columns with url \(columnsURL)") let columns = getProjectColumns(columnsURL: columnsURL) var columnNameToCardsURL = [String: String]() columns.forEach { column in if let columnName = column["name"] as? String, let cardsURL = column["cards_url"] as? String { columnNameToCardsURL[columnName] = cardsURL } } return columnNameToCardsURL } func listProjectCards(cardsURL: String) -> [[String: Any]] { LogFile.debug("list project cards with url \(cardsURL)") var cards = [[String: Any]]() var url = cardsURL var shouldPaginate = false while true { let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(url) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [[String: Any]] ?? [[:]] cards.append(contentsOf: result) if let nextURL = self.paginate(response: response) { url = nextURL shouldPaginate = true } else { shouldPaginate = false } } if !shouldPaginate { break } } return cards } func createProjectCard(cardsURL: String, contentID: Int?, contentType: String?, note: String?) { LogFile.debug("creating project card with content ID: \(contentID ?? -1), content type:" + "\(contentType ?? ""), and note: \(note ?? "")") let performRequest = { () -> CURLResponse in var requestBody = [String: Any]() if let note = note { requestBody = ["note": note] } else if let contentID = contentID, let contentType = contentType { requestBody = ["content_id": contentID, "content_type": contentType] } else { LogFile.error("missing the right params to create a project card") } let request = GithubCURLRequest(cardsURL, .postString(try requestBody.jsonEncodedString())) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } func deleteProjectCard(cardID: String) { LogFile.debug("deleting a project card with card ID: \(cardID)") let performRequest = { () -> CURLResponse in let url = self.config.githubAPIBaseURL + "/projects/columns/cards/" + cardID let request = GithubCURLRequest(url, .httpMethod(.delete)) self.addAPIHeaders(to: request, with: ["Accept": "application/vnd.github.inertia-preview+json"]) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function, resultFlow: nil) } /// Fetches a single GitHub object from the given url. /// /// - Parameter objectURL: Any singular result, e.g. an Issue, Pull Request, or User. /// - Returns: The returned object parsed into a dictionary, if the request succeeded. func getObject(objectURL: String, with customHeaderParams: [String: String]? = nil) -> [String: Any]? { LogFile.debug("getting object with url: \(objectURL)") var object: [String: Any]? let performRequest = { () -> CURLResponse in let request = GithubCURLRequest(objectURL) self.addAPIHeaders(to: request, with: customHeaderParams) return try request.perform() } githubRequestTemplate(requestFlow: performRequest, methodName: #function) { response in let result = try response.bodyString.jsonDecode() as? [String: Any] ?? [:] object = result } return object } /// Fetches a single GitHub Issue and returns it's unique identifier. /// /// - Parameter issueURL: A GitHub API issue URL. /// - Returns: The issue's identifier parsed as an Int. func getIssueID(issueURL: String) -> Int? { LogFile.debug("getting issue ID with url: \(issueURL)") let object = getObject(objectURL: issueURL) return object?["id"] as? Int } } // API Headers extension GithubAPI { func githubAPIHTTPHeaders(customHeaderParams: [String: String]?) -> [String: String] { var headers = [String: String]() headers["Authorization"] = "token \(self.accessToken)" LogFile.debug("the access token is: \(self.accessToken)") headers["Accept"] = "application/vnd.github.machine-man-preview+json" headers["User-Agent"] = config.userAgent if let customHeaderParams = customHeaderParams { customHeaderParams.forEach { (k,v) in headers[k] = v } } return headers } func addAPIHeaders(to request: CURLRequest, with customHeaderParams: [String: String]? = nil) { APIOneSecondDelay() let headersDict = githubAPIHTTPHeaders(customHeaderParams: customHeaderParams) for (k,v) in headersDict { request.addHeader(HTTPRequestHeader.Name.fromStandard(name: k), value: v) } } /// The Github API allows to send a request once a second, so we need to delay the request if /// a second hasn't passed yet. func APIOneSecondDelay() { self.curlAccessLock.lock() if time(nil) - self.lastGithubAccess < 1 { Threading.sleep(seconds: 1) } self.lastGithubAccess = time(nil) self.curlAccessLock.unlock() } func githubRequestTemplate(requestFlow: () throws -> CURLResponse, methodName: String, resultFlow: ((_ response: CURLResponse) throws -> ())?) { do { var response = try requestFlow() if GithubAuth.refreshCredentialsIfUnauthorized(response: response, githubAPI: self) { response = try requestFlow() } try resultFlow?(response) LogFile.info("request result for \(methodName): \(response.bodyString)") } catch { LogFile.error("error: \(error) desc: \(error.localizedDescription)") } } func paginate(response: CURLResponse) -> String? { if let links = response.get(HTTPResponseHeader.Name.custom(name: "Link")), let nextLink = links.components(separatedBy: ",").filter({ $0.contains("rel=\"next\"") }).first, let nextUrlAsString = nextLink.components(separatedBy: ";").first? .trimmingCharacters(in: .init(charactersIn: " ")) .trimmingCharacters(in: .init(charactersIn: "<>")) { return nextUrlAsString } return nil } }
apache-2.0
8e522d674b0af4acb5b18171952f8550
37.547025
109
0.648807
4.363024
false
false
false
false
tkremenek/swift
test/IDE/import_as_member.swift
13
7354
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.A -always-argument-labels > %t.printed.A.txt // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.B -always-argument-labels > %t.printed.B.txt // RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // RUN: %FileCheck %s -check-prefix=PRINTB -strict-whitespace < %t.printed.B.txt // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.APINotes -swift-version 4 -always-argument-labels | %FileCheck %s -check-prefix=PRINT-APINOTES-3 -strict-whitespace // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.APINotes -swift-version 5 -always-argument-labels | %FileCheck %s -check-prefix=PRINT-APINOTES-4 -strict-whitespace // RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules // Assertion failed: (I != F.TypeRemap.end() && "Invalid index into type index remap")) // REQUIRES: rdar70691386 // PRINT: struct Struct1 { // PRINT-NEXT: var x: Double // PRINT-NEXT: var y: Double // PRINT-NEXT: var z: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double, y y: Double, z z: Double) // PRINT-NEXT: } // Make sure the other extension isn't here. // PRINT-NOT: static var static1: Double // PRINT: extension Struct1 { // PRINT-NEXT: static var globalVar: Double // PRINT-NEXT: init(value value: Double) // PRINT-NEXT: init(specialLabel specialLabel: ()) // PRINT-NEXT: func inverted() -> Struct1 // PRINT-NEXT: mutating func invert() // PRINT-NEXT: func translate(radians radians: Double) -> Struct1 // PRINT-NEXT: func scale(_ radians: Double) -> Struct1 // PRINT-NEXT: var radius: Double { get nonmutating set } // PRINT-NEXT: var altitude: Double{{$}} // PRINT-NEXT: var magnitude: Double { get } // PRINT-NEXT: static func staticMethod() -> Int32 // PRINT-NEXT: static var property: Int32 // PRINT-NEXT: static var getOnlyProperty: Int32 { get } // PRINT-NEXT: func selfComesLast(x x: Double) // PRINT-NEXT: func selfComesThird(a a: Int32, b b: Float, x x: Double) // PRINT-NEXT: } // PRINT-NOT: static var static1: Double // Make sure the other extension isn't here. // PRINTB-NOT: static var globalVar: Double // PRINTB: extension Struct1 { // PRINTB: static var static1: Double // PRINTB-NEXT: static var static2: Float // PRINTB-NEXT: init(float value: Float) // PRINTB-NEXT: static var zero: Struct1 { get } // PRINTB-NEXT: } // PRINTB: var currentStruct1: Struct1 // PRINTB-NOT: static var globalVar: Double // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.oldApiNoteVar") // PRINT-APINOTES-3-NEXT: var IAMStruct1APINoteVar: Double // PRINT-APINOTES-3: extension Struct1 { // PRINT-APINOTES-3-NEXT: var oldApiNoteVar: Double // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4.2, renamed: "Struct1.oldApiNoteVar") // PRINT-APINOTES-3-NEXT: var newApiNoteVar: Double // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4.2, renamed: "IAMStruct1APINoteVarInSwift4") // PRINT-APINOTES-3-NEXT: var apiNoteVarInSwift4: Double // PRINT-APINOTES-3-NEXT: static func oldApiNoteMethod() // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4.2, renamed: "Struct1.oldApiNoteMethod()") // PRINT-APINOTES-3-NEXT: static func newApiNoteMethod() // PRINT-APINOTES-3-NEXT: init(oldLabel _: Int32) // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4.2, renamed: "Struct1.init(oldLabel:)") // PRINT-APINOTES-3-NEXT: init(newLabel _: Int32) // PRINT-APINOTES-3-NEXT: typealias OldApiNoteType = Struct1.NewApiNoteType // PRINT-APINOTES-3-NEXT: typealias NewApiNoteType = Double // PRINT-APINOTES-3-NEXT: } // PRINT-APINOTES-3-NOT: @available // PRINT-APINOTES-3: var IAMStruct1APINoteVarInSwift4: Double // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.oldApiNoteMethod()") // PRINT-APINOTES-3-NEXT: func IAMStruct1APINoteFunction() // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.init(oldLabel:)") // PRINT-APINOTES-3-NEXT: func IAMStruct1APINoteCreateFunction(_ _: Int32) -> Struct1 // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.OldApiNoteType") // PRINT-APINOTES-3-NEXT: typealias IAMStruct1APINoteType = Struct1.OldApiNoteType // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.newApiNoteVar") // PRINT-APINOTES-4-NEXT: var IAMStruct1APINoteVar: Double // PRINT-APINOTES-4: extension Struct1 { // PRINT-APINOTES-4-NEXT: var newApiNoteVar: Double // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4.2, renamed: "Struct1.newApiNoteVar") // PRINT-APINOTES-4-NEXT: var oldApiNoteVar: Double // PRINT-APINOTES-4-NEXT: var apiNoteVarInSwift4: Double // PRINT-APINOTES-4-NEXT: static func newApiNoteMethod() // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4.2, renamed: "Struct1.newApiNoteMethod()") // PRINT-APINOTES-4-NEXT: static func oldApiNoteMethod() // PRINT-APINOTES-4-NEXT: init(newLabel _: Int32) // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4.2, renamed: "Struct1.init(newLabel:)") // PRINT-APINOTES-4-NEXT: init(oldLabel _: Int32) // PRINT-APINOTES-4-NEXT: typealias NewApiNoteType = Double // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4.2, renamed: "Struct1.NewApiNoteType") // PRINT-APINOTES-4-NEXT: typealias OldApiNoteType = Struct1.NewApiNoteType // PRINT-APINOTES-4-NEXT: } // PRINT-APINOTES-4: @available(swift, obsoleted: 4.2, renamed: "Struct1.apiNoteVarInSwift4") // PRINT-APINOTES-4-NEXT: var IAMStruct1APINoteVarInSwift4: Double // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.newApiNoteMethod()") // PRINT-APINOTES-4-NEXT: func IAMStruct1APINoteFunction() // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.init(newLabel:)") // PRINT-APINOTES-4-NEXT: func IAMStruct1APINoteCreateFunction(_ _: Int32) -> Struct1 // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.NewApiNoteType") // PRINT-APINOTES-4-NEXT: typealias IAMStruct1APINoteType = Struct1.NewApiNoteType #if canImport(Foundation) import Foundation #endif import ImportAsMember.A import ImportAsMember.B import ImportAsMember.APINotes let iamStructFail = IAMStruct1CreateSimple() // expected-error@-1{{missing argument for parameter #1 in call}} var iamStruct = Struct1(x: 1.0, y: 1.0, z: 1.0) let gVarFail = IAMStruct1GlobalVar // expected-error@-1{{IAMStruct1GlobalVar' has been renamed to 'Struct1.globalVar'}} let gVar = Struct1.globalVar print("\(gVar)") let iamStructInitFail = IAMStruct1CreateSimple(42) // expected-error@-1{{'IAMStruct1CreateSimple' has been replaced by 'Struct1.init(value:)'}} let iamStructInitFail2 = Struct1(value: 42) let gVar2 = Struct1.static2 // Instance properties iamStruct.radius += 1.5 _ = iamStruct.magnitude // Static properties iamStruct = Struct1.zero // Global properties currentStruct1.x += 1.5
apache-2.0
1dfe04d4b1740309894b36490bec9b05
50.788732
277
0.72464
2.974919
false
false
false
false
annatovstyga/REA-Schedule
Raspisaniye/Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Math.swift
2
3693
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - DateInRegion Private Extension extension DateInRegion { /// Return a `DateComponent` object from a given set of `Calendar.Component` object with associated values and a specific region /// /// - parameter values: calendar components to set (with their values) /// - parameter multipler: optional multipler (by default is nil; to make an inverse component value it should be multipled by -1) /// - parameter region: optional region to set /// /// - returns: a `DateComponents` object internal static func componentsFrom(values: [Calendar.Component : Int], multipler: Int? = nil, setRegion region: Region? = nil) -> DateComponents { var cmps = DateComponents() if region != nil { cmps.calendar = region!.calendar cmps.calendar!.locale = region!.locale cmps.timeZone = region!.timeZone } values.forEach { key,value in if key != .timeZone && key != .calendar { cmps.setValue( (multipler == nil ? value : value * multipler!), for: key) } } return cmps } } // MARK: - DateInRegion Support for math operation // These functions allows us to make something like // `let newDate = (date - 3.days + 3.months)` // We can sum algebrically a `DateInRegion` object with a calendar component. public func + (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion { let nextDate = lhs.region.calendar.date(byAdding: rhs, to: lhs.absoluteDate) return DateInRegion(absoluteDate: nextDate!, in: lhs.region) } public func - (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion { return lhs + (-rhs) } public func + (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion { let cmps = DateInRegion.componentsFrom(values: rhs) return lhs + cmps } public func - (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion { var invertedCmps: [Calendar.Component : Int] = [:] rhs.forEach { invertedCmps[$0] = -$1 } return lhs + invertedCmps } public func - (lhs: DateInRegion, rhs: DateInRegion) -> TimeInterval { var interval: TimeInterval = 0 if #available(iOS 10.0, *) { if lhs.absoluteDate < rhs.absoluteDate { interval = -(DateTimeInterval(start: lhs.absoluteDate, end: rhs.absoluteDate)).duration } else { interval = (DateTimeInterval(start: rhs.absoluteDate, end: lhs.absoluteDate)).duration } } else { interval = rhs.absoluteDate.timeIntervalSince(lhs.absoluteDate) } return interval }
mit
f37b588b321e5917bbb4449fcbfb4fe2
38.287234
148
0.728405
3.928723
false
false
false
false
CanyFrog/HCComponent
HCSource/HCAnimation+CALayer.swift
1
10984
// // HCAnimation+CALayer.swift // HCComponents // // Created by Magee Huang on 5/12/17. // Copyright © 2017 Person Inc. All rights reserved. // import Foundation @available(iOS 10, *) extension CALayer: CAAnimationDelegate {} extension CALayer { /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ open func animate(_ animations: CAAnimation...) { animate(animations) } /** A function that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ open func animate(_ animations: [CAAnimation]) { for animation in animations { if nil == animation.delegate { animation.delegate = self } if let a = animation as? CABasicAnimation { a.fromValue = (presentation() ?? self).value(forKeyPath: a.keyPath!) } if let a = animation as? CAPropertyAnimation { add(a, forKey: a.keyPath!) } else if let a = animation as? CAAnimationGroup { add(a, forKey: nil) } else if let a = animation as? CATransition { add(a, forKey: kCATransition) } } } open func animationDidStart(_ anim: CAAnimation) {} /** A delegation function that is executed when the backing layer stops running an animation. - Parameter animation: The CAAnimation instance that stopped running. - Parameter flag: A boolean that indicates if the animation stopped because it was completed or interrupted. True if completed, false if interrupted. */ open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard let a = anim as? CAPropertyAnimation else { if let a = (anim as? CAAnimationGroup)?.animations { for x in a { animationDidStop(x, finished: true) } } return } guard let b = a as? CABasicAnimation else { return } guard let v = b.toValue else { return } guard let k = b.keyPath else { return } setValue(v, forKeyPath: k) removeAnimation(forKey: k) } /** A function that accepts a list of animateAnimation values and executes them. - Parameter animations: A list of animateAnimation values. */ open func animate(_ animations: HCAnimationArguments...) { animate(animations) } /** A function that accepts an Array of animateAnimation values and executes them. - Parameter animations: An Array of animateAnimation values. - Parameter completion: An optional completion block. */ open func animate(_ animations: [HCAnimationArguments], completion: (() -> Void)? = nil) { animate(delay: 0, duration: 0.35, timingFunction: .easeInEaseOut, animations: animations, completion: completion) } /** A function that executes an Array of animateAnimation values. - Parameter delay: The animation delay TimeInterval. - Parameter duration: The animation duration TimeInterval. - Parameter timingFunction: The animation animateAnimationTimingFunction. - Parameter animations: An Array of animateAnimations. - Parameter completion: An optional completion block. */ fileprivate func animate(delay: TimeInterval, duration: TimeInterval, timingFunction: HCAnimationTimingFunction, animations: [HCAnimationArguments], completion: (() -> Void)? = nil) { var t = delay for v in animations { switch v { case let .delay(time): t = time default:break } } HCAnimation.delay(t) { [weak self] in guard let s = self else { return } var a = [CABasicAnimation]() var tf = timingFunction var d = duration var w: CGFloat = s.bounds.width var h: CGFloat = s.bounds.height for v in animations { switch v { case let .width(width): w = width case let .height(height): h = height case let .size(width, height): w = width h = height default:break } } var px: CGFloat = s.position.x var py: CGFloat = s.position.y for v in animations { switch v { case let .x(x): px = x + w / 2 case let .y(y): py = y + h / 2 case let .point(x, y): px = x + w / 2 py = y + h / 2 default:break } } for v in animations { switch v { case let .timingFunction(timingFunction): tf = timingFunction case let .duration(duration): d = duration case let .custom(animation): a.append(animation) case let .backgroundColor(color): a.append(HCAnimation.background(color: color)) case let .barTintColor(color): a.append(HCAnimation.barTint(color: color)) case let .cornerRadius(radius): a.append(HCAnimation.corner(radius: radius)) case let .transform(transform): a.append(HCAnimation.transform(transform: transform)) case let .rotationAngle(angle): a.append(HCAnimation.rotation(angle: angle)) case let .rotationAngleX(angle): a.append(HCAnimation.rotationX(angle: angle)) case let .rotationAngleY(angle): a.append(HCAnimation.rotationY(angle: angle)) case let .rotationAngleZ(angle): a.append(HCAnimation.rotationZ(angle: angle)) case let .spin(rotations): a.append(HCAnimation.spin(rotations: rotations)) case let .spinX(rotations): a.append(HCAnimation.spinX(rotations: rotations)) case let .spinY(rotations): a.append(HCAnimation.spinY(rotations: rotations)) case let .spinZ(rotations): a.append(HCAnimation.spinZ(rotations: rotations)) case let .scale(to): a.append(HCAnimation.scale(to: to)) case let .scaleX(to): a.append(HCAnimation.scaleX(to: to)) case let .scaleY(to): a.append(HCAnimation.scaleY(to: to)) case let .scaleZ(to): a.append(HCAnimation.scaleZ(to: to)) case let .translate(x, y): a.append(HCAnimation.translate(to: CGPoint(x: x, y: y))) case let .translateX(to): a.append(HCAnimation.translateX(to: to)) case let .translateY(to): a.append(HCAnimation.translateY(to: to)) case let .translateZ(to): a.append(HCAnimation.translateZ(to: to)) case .x(_), .y(_), .point(_, _): a.append(HCAnimation.position(to: CGPoint(x: px, y: py))) case let .position(x, y): a.append(HCAnimation.position(to: CGPoint(x: x, y: y))) case let .fade(opacity): let fade = HCAnimation.fade(opacity: opacity) fade.fromValue = s.value(forKey: HCAnimationProperty.opacity.rawValue) ?? NSNumber(floatLiteral: 1) a.append(fade) case let .zPosition(index): let zPosition = HCAnimation.zPosition(index: index) zPosition.fromValue = s.value(forKey: HCAnimationProperty.zPosition.rawValue) ?? NSNumber(integerLiteral: 0) a.append(zPosition) case .width(_), .height(_), .size(_, _): a.append(HCAnimation.size(CGSize(width: w, height: h))) case let .shadowPath(path): let shadowPath = HCAnimation.shadow(path: path) shadowPath.fromValue = s.shadowPath a.append(shadowPath) case let .shadowOffset(offset): let shadowOffset = HCAnimation.shadow(offset: offset) shadowOffset.fromValue = s.shadowOffset a.append(shadowOffset) case let .shadowOpacity(opacity): let shadowOpacity = HCAnimation.shadow(opacity: opacity) shadowOpacity.fromValue = s.shadowOpacity a.append(shadowOpacity) case let .shadowRadius(radius): let shadowRadius = HCAnimation.shadow(radius: radius) shadowRadius.fromValue = s.shadowRadius a.append(shadowRadius) case let .depth(offset, opacity, radius): if let path = s.shadowPath { let shadowPath = HCAnimation.shadow(path: path) shadowPath.fromValue = s.shadowPath a.append(shadowPath) } let shadowOffset = HCAnimation.shadow(offset: offset) shadowOffset.fromValue = s.shadowOffset a.append(shadowOffset) let shadowOpacity = HCAnimation.shadow(opacity: opacity) shadowOpacity.fromValue = s.shadowOpacity a.append(shadowOpacity) let shadowRadius = HCAnimation.shadow(radius: radius) shadowRadius.fromValue = s.shadowRadius a.append(shadowRadius) default:break } } let g = HCAnimation.animate(group: a, duration: d) g.fillMode = HCAnimationFillMode.forwards.value g.isRemovedOnCompletion = false g.timingFunction = tf.value s.animate(g) guard let execute = completion else { return } HCAnimation.delay(d, execute: execute) } } }
mit
7b51b12a4bccd7dc29d84820aa83fec3
38.225
187
0.517527
5.270154
false
false
false
false
ReactiveKit/ReactiveGitter
Client/Client.swift
1
5176
// // The MIT License (MIT) // // Copyright (c) 2017 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation open class Client { public enum Error: Swift.Error { case network(Swift.Error, Int) case remote(Swift.Error, Int) case parser(Swift.Error) case client(String) } public let baseURL: String public let session: URLSession public var defaultHeaders: [String: String] = [:] public init(baseURL: String, session: URLSession = URLSession.shared) { self.baseURL = baseURL self.session = session } /// For example, authorize request with the token. open func prepare<T, E: Swift.Error>(request: Request<T, E>) -> Request<T, E> { return request } /// Perform request. @discardableResult open func perform<Resource, Error: Swift.Error>(_ request: Request<Resource, Error>, completion: @escaping (Result<Resource, Client.Error>) -> Void) -> URLSessionTask { let request = prepare(request: request) let headers = defaultHeaders.merging(contentsOf: request.headers ?? [:]) var urlRequest = URLRequest(url: URL(string: self.baseURL.appendingPathComponent(request.path))!) urlRequest.httpMethod = request.method.rawValue headers.forEach { urlRequest.addValue($1, forHTTPHeaderField: $0) } if let parameters = request.parameters { urlRequest = parameters.apply(urlRequest: urlRequest) } let task = self.session.dataTask(with: urlRequest) { (data, urlResponse, error) in guard let urlResponse = urlResponse as? HTTPURLResponse else { if let error = error { completion(.failure(.network(error, 0))) } else { completion(.failure(.client("Did not receive HTTPURLResponse. Huh?"))) } return } if let error = error { if let data = data, let serverError = try? request.error(data) { completion(.failure(.remote(serverError, urlResponse.statusCode))) } else { completion(.failure(.network(error, urlResponse.statusCode))) } return } guard (200..<300).contains(urlResponse.statusCode) else { if let data = data, let error = try? request.error(data) { completion(.failure(.remote(error, urlResponse.statusCode))) } else { var message = "Validation failed: HTTP status code \(urlResponse.statusCode)." if let data = data, let responseString = String(data: data, encoding: .utf8) { message += "\n" + responseString } let error = Client.Error.client(message) completion(.failure(.remote(error, urlResponse.statusCode))) } return } if let data = data { do { let resource = try request.resource(data) completion(.success(resource)) } catch let error as Client.Error { completion(.failure(error)) } catch let error { completion(.failure(.parser(error))) } } else { // no error, no data - valid empty response do { let resource = try request.resource(Data()) completion(.success(resource)) } catch let error as Client.Error { completion(.failure(error)) } catch let error { completion(.failure(.parser(error))) } } } task.resume() return task } } extension Client.Error { public var code: Int? { switch self { case .network(_, let code): return code case .remote(_, let code): return code default: return 0 } } }
mit
ecdf3d9ddb67e98ed8f2fb1fe0678ecc
37.340741
172
0.584815
4.972142
false
false
false
false
michael-lehew/swift-corelibs-foundation
TestFoundation/TestNSTextCheckingResult.swift
1
2211
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSTextCheckingResult: XCTestCase { static var allTests: [(String, (TestNSTextCheckingResult) -> () throws -> Void)] { return [ ("test_textCheckingResult", test_textCheckingResult), ] } func test_textCheckingResult() { let patternString = "(a|b)x|123|(c|d)y" do { let patternOptions: NSRegularExpression.Options = [] let regex = try NSRegularExpression(pattern: patternString, options: patternOptions) let searchString = "1x030cy" let searchOptions: NSMatchingOptions = [] let searchRange = NSMakeRange(0,7) let match: TextCheckingResult = regex.firstMatch(in: searchString, options: searchOptions, range: searchRange)! //Positive offset var result = match.resultByAdjustingRangesWithOffset(1) XCTAssertEqual(result.range(at: 0).location, 6) XCTAssertEqual(result.range(at: 1).location, NSNotFound) XCTAssertEqual(result.range(at: 2).location, 6) //Negative offset result = match.resultByAdjustingRangesWithOffset(-2) XCTAssertEqual(result.range(at: 0).location, 3) XCTAssertEqual(result.range(at: 1).location, NSNotFound) XCTAssertEqual(result.range(at: 2).location, 3) //ZeroOffset result = match.resultByAdjustingRangesWithOffset(0) XCTAssertEqual(result.range(at: 0).location, 5) XCTAssertEqual(result.range(at: 1).location, NSNotFound) XCTAssertEqual(result.range(at: 2).location, 5) } catch { XCTFail("Unable to build regular expression for pattern \(patternString)") } } }
apache-2.0
db1c71da52bef756f1e92d66fe93a74a
39.2
123
0.658526
4.540041
false
true
false
false
hejeffery/Animation
Animation/Animation/LayerAnimation/Controller/ReplicatorLayerAnimationController.swift
1
1323
// // ReplicatorLayerAnimationController.swift // Animation // // Created by HeJeffery on 2017/10/3. // Copyright © 2017年 JefferyHe. All rights reserved. // import UIKit class ReplicatorLayerAnimationController: UIViewController { private lazy var volumeView: VolumeView = { let volumeView = VolumeView() volumeView.frame = CGRect.zero volumeView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - 200) return volumeView }() private lazy var progressView: ProgressView = { let progressView = ProgressView() progressView.frame = CGRect.zero progressView.center = self.view.center return progressView }() private lazy var pulseView: PulseView = { let pulseView = PulseView() pulseView.frame = CGRect.zero pulseView.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 200) return pulseView }() override func viewDidLoad() { super.viewDidLoad() title = "ReplicatorLayer Animation" view.backgroundColor = UIColor.white view.addSubview(volumeView) view.addSubview(progressView) view.addSubview(pulseView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
eda1ac3f94accdff8d42cd38c56a7464
27.085106
87
0.653788
4.664311
false
false
false
false
robconrad/fledger-common
FledgerCommon/services/models/aggregate/Aggregate.swift
1
807
// // Aggregate.swift // fledger-ios // // Created by Robert Conrad on 4/12/15. // Copyright (c) 2015 TwoSpec Inc. All rights reserved. // import Foundation public class Aggregate { public let model: ModelType? public let id: Int64? public let name: String public let value: Double public let active: Bool public let section: String? public required init(model: ModelType?, id: Int64?, name: String, value: Double, active: Bool = true, section: String? = nil) { self.model = model self.id = id self.name = name self.value = value self.active = active self.section = section } public func toString() -> String { let v = String(format: "%.2f", value) return "\(name) - \(v)" } }
mit
63283d9d58e169d4c0145caf8425f106
22.085714
131
0.592317
3.879808
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/animation/AnimationProducer.swift
1
9210
import UIKit let animationProducer = AnimationProducer() class AnimationProducer { var storedAnimations = [Node: BasicAnimation]() var displayLink: CADisplayLink? struct ContentAnimationDesc { let animation: ContentsAnimation let layer: CALayer let cache: AnimationCache let startDate: Date let finishDate: Date let completion: (()->())? } var contentsAnimations = [ContentAnimationDesc]() func addAnimation(_ animation: BasicAnimation, withoutDelay: Bool = false) { // Delay - launching timer if animation.delay > 0.0 && !withoutDelay { let _ = Timer.schedule(delay: animation.delay, handler: { _ in self.addAnimation(animation, withoutDelay: true) }) return } // Empty - executing completion if animation.type == .empty { executeCompletion(animation) return } // Cycle - attaching "re-add animation" logic if animation.cycled { if animation.manualStop { return } let reAdd = EmptyAnimation { self.addAnimation(animation) } if let nextAnimation = animation.next { nextAnimation.next = reAdd } else { animation.next = reAdd } } // General case guard let node = animation.node else { return } guard let macawView = nodesMap.getView(node) else { storedAnimations[node] = animation return } guard let cache = macawView.animationCache else { return } switch animation.type { case .unknown: return case .affineTransformation: addTransformAnimation(animation, sceneLayer: macawView.layer, animationCache: cache, completion: { if let next = animation.next { self.addAnimation(next) } }) case .opacity: addOpacityAnimation(animation, sceneLayer: macawView.layer, animationCache: cache, completion: { if let next = animation.next { self.addAnimation(next) } }) case .sequence: addAnimationSequence(animation) case .combine: addCombineAnimation(animation) case .contents: addContentsAnimation(animation, cache: cache, completion: { if let next = animation.next { self.addAnimation(next) } }) case .empty: executeCompletion(animation) } } // MARK: - Sequence animation fileprivate func addAnimationSequence(_ animationSequnce: Animation) { guard let sequence = animationSequnce as? AnimationSequence else { return } // Generating sequence var sequenceAnimations = [BasicAnimation]() var cycleAnimations = sequence.animations if sequence.autoreverses { cycleAnimations.append(contentsOf: sequence.animations.reversed()) } if sequence.repeatCount > 0.0001 { for _ in 0..<Int(sequence.repeatCount) { sequenceAnimations.append(contentsOf: cycleAnimations) } } else { sequenceAnimations.append(contentsOf: cycleAnimations) } // Connecting animations for i in 0..<(sequenceAnimations.count - 1) { let animation = sequenceAnimations[i] animation.next = sequenceAnimations[i + 1] } // Completion if let completion = sequence.completion { let completionAnimation = EmptyAnimation(completion: completion) if let next = sequence.next { completionAnimation.next = next } sequenceAnimations.last?.next = completionAnimation } else { if let next = sequence.next { sequenceAnimations.last?.next = next } } // Launching if let firstAnimation = sequence.animations.first { self.addAnimation(firstAnimation) } } // MARK: - Combine animation fileprivate func addCombineAnimation(_ combineAnimation: Animation) { guard let combine = combineAnimation as? CombineAnimation else { return } // Reversing if combine.autoreverses { combine.animations.forEach { animation in animation.autoreverses = true } } // repeat count if combine.repeatCount > 0.00001 { var sequence = [Animation]() for _ in 0..<Int(combine.repeatCount) { sequence.append(combine) } combine.repeatCount = 0.0 addAnimationSequence(sequence.sequence()) return } // Looking for longest animation var longestAnimation: BasicAnimation? combine.animations.forEach { animation in guard let longest = longestAnimation else { longestAnimation = animation return } if longest.getDuration() < animation.getDuration() { longestAnimation = animation } } // Attaching completion empty animation and potential next animation if let completion = combine.completion { let completionAnimation = EmptyAnimation(completion: completion) if let next = combine.next { completionAnimation.next = next } longestAnimation?.next = completionAnimation } else { if let next = combine.next { longestAnimation?.next = next } } combine.removeFunc = { combine.animations.forEach { animation in animation.removeFunc?() } } // Launching combine.animations.forEach { animation in self.addAnimation(animation) } } // MARK: - Empty Animation fileprivate func executeCompletion(_ emptyAnimation: BasicAnimation) { emptyAnimation.completion?() } // MARK: - Stored animation func addStoredAnimations(_ node: Node) { if let animation = storedAnimations[node] { addAnimation(animation) storedAnimations.removeValue(forKey: node) } guard let group = node as? Group else { return } group.contents.forEach { child in addStoredAnimations(child) } } // MARK: - Contents animation func addContentsAnimation(_ animation: BasicAnimation, cache: AnimationCache, completion: @escaping (() -> ())) { guard let contentsAnimation = animation as? ContentsAnimation else { return } guard let node = contentsAnimation.node else { return } if animation.autoreverses { animation.autoreverses = false addAnimation([animation, animation.reverse()].sequence() as! BasicAnimation) return } if animation.repeatCount > 0.0001 { animation.repeatCount = 0.0 var animSequence = [Animation]() for i in 0...Int(animation.repeatCount) { animSequence.append(animation) } addAnimation(animSequence.sequence() as! BasicAnimation) return } let startDate = Date(timeInterval: contentsAnimation.delay, since: Date()) var unionBounds: Rect? = .none if let startBounds = contentsAnimation.getVFunc()(0.0).group().bounds(), let endBounds = contentsAnimation.getVFunc()(1.0).group().bounds() { unionBounds = startBounds.union(rect: endBounds) } let animationDesc = ContentAnimationDesc( animation: contentsAnimation, layer: cache.layerForNode(node, animation: contentsAnimation, customBounds: unionBounds), cache: cache, startDate: Date(), finishDate: Date(timeInterval: contentsAnimation.duration, since: startDate), completion: completion ) contentsAnimations.append(animationDesc) if displayLink == .none { displayLink = CADisplayLink(target: self, selector: #selector(updateContentAnimations)) displayLink?.frameInterval = 1 displayLink?.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode) } } @objc func updateContentAnimations() { if contentsAnimations.count == 0 { displayLink?.invalidate() displayLink = .none } let currentDate = Date() for (index, animationDesc) in contentsAnimations.enumerated() { let animation = animationDesc.animation guard let group = animation.node as? Group else { continue } defer { animationDesc.layer.setNeedsDisplay() animationDesc.layer.displayIfNeeded() } let progress = currentDate.timeIntervalSince(animationDesc.startDate) / animation.duration if progress >= 1.0 { // Final update group.contents = animation.getVFunc()(1.0) animation.onProgressUpdate?(1.0) // Finishing animation animation.completion?() contentsAnimations.remove(at: index) animationDesc.cache.freeLayer(group) animationDesc.completion?() continue } let t = progressForTimingFunction(animation.easing, progress: progress) group.contents = animation.getVFunc()(t) animation.onProgressUpdate?(progress) } } }
mit
8e93e0bc30550de871f8ee24a8a81686
26.657658
117
0.618458
4.651515
false
false
false
false
king7532/FinanceCurrencyFormatterTextfield
MyPlayground.playground/Contents.swift
1
1243
//: Playground - noun: a place where people can play import UIKit //var formatter = FinanceCurrencyFormatter() var cursorOffsetFromEndOfString = 0 var currencyScale = 0 var formatter :NSNumberFormatter = { let nf = NSNumberFormatter() nf.numberStyle = .CurrencyStyle nf.generatesDecimalNumbers = true currencyScale = -1 * nf.maximumFractionDigits return nf }() func stringDecimalDigits(s: String) -> String { return s.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("") } var str = "Hello, playground" let a = "123" let b = "123.4" let c = "123.45" let d = "$1234.56" let e = "$ 1,234.00" let f = "198 234,89 €" let g = "9.876,54 €" let h = "123abc" let i = "123abc789" let j = "546.00" let k = "0.00" let arr = [a,b,c,d,e,f,g,h,i,j,k] arr.map { NSDecimalNumber(string: $0) } arr.map { stringDecimalDigits($0) } let test = NSDecimalNumber(string: "0") formatter.stringFromNumber(0) var rightDigits = -1 var rightindex = 0 for in f.unicodeScalars { if rightDigits == -1 && f.value == 0x0a { rightDigits = 0 } if rightDigits >= 0 && charSet.longCharacterIsMember(ch.value) { rightDigits++ } rightindex++; }
mit
3917e782f98ec9ad3b64e10898178257
21.527273
126
0.674738
3.269129
false
false
false
false
gerram/aws-sdk-ios-samples
S3BackgroundTransfer-Sample/Swift/S3BackgroundTransferSampleSwift/FirstViewController.swift
4
6298
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 class FirstViewController: UIViewController, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate{ @IBOutlet var progressView: UIProgressView! @IBOutlet var statusLabel: UILabel! var session: NSURLSession? var uploadTask: NSURLSessionUploadTask? var uploadFileURL: NSURL? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. struct Static { static var session: NSURLSession? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(BackgroundSessionUploadIdentifier) Static.session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) } self.session = Static.session; self.progressView.progress = 0; self.statusLabel.text = "Ready" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func start(sender: UIButton) { if (self.uploadTask != nil) { return; } //Create a test file in the temporary directory self.uploadFileURL = NSURL.fileURLWithPath(NSTemporaryDirectory() + S3UploadKeyName) var dataString = "1234567890" for var i = 1; i < 22; i++ { //~20MB dataString += dataString } var error: NSError? = nil if NSFileManager.defaultManager().fileExistsAtPath(self.uploadFileURL!.path!) { NSFileManager.defaultManager().removeItemAtPath(self.uploadFileURL!.path!, error: &error) } dataString.writeToURL(self.uploadFileURL!, atomically: true, encoding: NSUTF8StringEncoding, error: &error) if (error) != nil { NSLog("Error: %@",error!); } let getPreSignedURLRequest = AWSS3GetPreSignedURLRequest() getPreSignedURLRequest.bucket = S3BucketName getPreSignedURLRequest.key = S3UploadKeyName getPreSignedURLRequest.HTTPMethod = AWSHTTPMethod.PUT getPreSignedURLRequest.expires = NSDate(timeIntervalSinceNow: 3600) //Important: must set contentType for PUT request let fileContentTypeStr = "text/plain" getPreSignedURLRequest.contentType = fileContentTypeStr AWSS3PreSignedURLBuilder.defaultS3PreSignedURLBuilder().getPreSignedURL(getPreSignedURLRequest) .continueWithBlock { (task:AWSTask!) -> (AnyObject!) in if (task.error != nil) { NSLog("Error: %@", task.error) } else { let presignedURL = task.result as! NSURL! if (presignedURL != nil) { NSLog("upload presignedURL is: \n%@", presignedURL) var request = NSMutableURLRequest(URL: presignedURL) request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData request.HTTPMethod = "PUT" //contentType in the URLRequest must be the same as the one in getPresignedURLRequest request .setValue(fileContentTypeStr, forHTTPHeaderField: "Content-Type") self.uploadTask = self.session?.uploadTaskWithRequest(request, fromFile: self.uploadFileURL!) self.uploadTask?.resume() } } return nil; } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend) NSLog("UploadTask progress: %lf", progress) dispatch_async(dispatch_get_main_queue()) { self.progressView.progress = progress self.statusLabel.text = "Uploading..." } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if (error == nil) { dispatch_async(dispatch_get_main_queue()) { self.statusLabel.text = "Upload Successfully" } NSLog("S3 UploadTask: %@ completed successfully", task); } else { dispatch_async(dispatch_get_main_queue()) { self.statusLabel.text = "Upload Failed" } NSLog("S3 UploadTask: %@ completed with error: %@", task, error!.localizedDescription); } dispatch_async(dispatch_get_main_queue()) { self.progressView.progress = Float(task.countOfBytesSent) / Float(task.countOfBytesExpectedToSend) } self.uploadTask = nil } func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if ((appDelegate.backgroundUploadSessionCompletionHandler) != nil) { let completionHandler:() = appDelegate.backgroundUploadSessionCompletionHandler!; appDelegate.backgroundUploadSessionCompletionHandler = nil completionHandler } NSLog("Completion Handler has been invoked, background upload task has finished."); } }
apache-2.0
d68ccb7cb4bf31a839a510b6e23bf971
37.638037
159
0.622579
5.481288
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Domains/Utility/DomainExpiryDateFormatter.swift
1
1503
import Foundation struct DomainExpiryDateFormatter { static func expiryDate(for domain: Domain) -> String { if domain.expiryDate.isEmpty { return Localized.neverExpires } else if domain.expired { return Localized.expired } else if domain.autoRenewing && domain.autoRenewalDate.isEmpty { return Localized.autoRenews } else if domain.autoRenewing { return String(format: Localized.renewsOn, domain.autoRenewalDate) } else { return String(format: Localized.expiresOn, domain.expiryDate) } } enum Localized { static let neverExpires = NSLocalizedString("Never expires", comment: "Label indicating that a domain name registration has no expiry date.") static let autoRenews = NSLocalizedString("Auto-renew enabled", comment: "Label indicating that a domain name registration will automatically renew") static let renewsOn = NSLocalizedString("Renews on %@", comment: "Label indicating the date on which a domain name registration will be renewed. The %@ placeholder will be replaced with a date at runtime.") static let expiresOn = NSLocalizedString("Expires on %@", comment: "Label indicating the date on which a domain name registration will expire. The %@ placeholder will be replaced with a date at runtime.") static let expired = NSLocalizedString("Expired", comment: "Label indicating that a domain name registration has expired.") } }
gpl-2.0
0c4733696ea1ad0675018cf2b23c3704
59.12
214
0.706587
5.182759
false
false
false
false
Boilertalk/VaporFacebookBot
Sources/VaporFacebookBot/Webhooks/FacebookReferral.swift
1
1413
// // FacebookReferral.swift // VaporFacebookBot // // Created by Koray Koska on 25/05/2017. // // import Foundation import Vapor public final class FacebookReferral: JSONConvertible { public var ref: String public var adId: String? public var source: FacebookReferralSource public var type: FacebookReferralType public init(json: JSON) throws { ref = try json.get("ref") adId = json["ad_id"]?.string guard let source = try FacebookReferralSource(rawValue: json.get("source")) else { throw Abort(.badRequest, metadata: "source was not set for FacebookReferral") } self.source = source guard let type = try FacebookReferralType(rawValue: json.get("type")) else { throw Abort(.badRequest, metadata: "type was not set for FacebookReferral") } self.type = type } public func makeJSON() throws -> JSON { var json = JSON() try json.set("ref", ref) if let adId = adId { try json.set("ad_id", adId) } try json.set("source", source.rawValue) try json.set("type", type.rawValue) return json } } public enum FacebookReferralSource: String { case shortlink = "SHORTLINK" case ads = "ADS" case messengerCode = "MESSENGER_CODE" } public enum FacebookReferralType: String { case openThread = "OPEN_THREAD" }
mit
40039f385cc676fa613830a491a478c1
23.362069
90
0.629158
4.025641
false
false
false
false
taktamur/BondSample
Pods/Bond/Bond/Extensions/iOS/UITextView+Bond.swift
26
3680
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension UITextView { private struct AssociatedKeys { static var TextKey = "bnd_TextKey" static var AttributedTextKey = "bnd_AttributedTextKey" } public var bnd_text: Observable<String?> { if let bnd_text: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.TextKey) { return bnd_text as! Observable<String?> } else { let bnd_text = Observable<String?>(self.text) objc_setAssociatedObject(self, &AssociatedKeys.TextKey, bnd_text, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) var updatingFromSelf: Bool = false bnd_text.observeNew { [weak self] (text: String?) in if !updatingFromSelf { self?.text = text } } NSNotificationCenter.defaultCenter().bnd_notification(UITextViewTextDidChangeNotification, object: self).observe { [weak bnd_text] notification in if let textView = notification.object as? UITextView, bnd_text = bnd_text { updatingFromSelf = true bnd_text.next(textView.text) updatingFromSelf = false } }.disposeIn(bnd_bag) return bnd_text } } public var bnd_attributedText: Observable<NSAttributedString?> { if let bnd_attributedText: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.AttributedTextKey) { return bnd_attributedText as! Observable<NSAttributedString?> } else { let bnd_attributedText = Observable<NSAttributedString?>(self.attributedText) objc_setAssociatedObject(self, &AssociatedKeys.AttributedTextKey, bnd_attributedText, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) var updatingFromSelf: Bool = false bnd_attributedText.observeNew { [weak self] (text: NSAttributedString?) in if !updatingFromSelf { self?.attributedText = text } } NSNotificationCenter.defaultCenter().bnd_notification(UITextViewTextDidChangeNotification, object: self).observe { [weak bnd_attributedText] notification in if let textView = notification.object as? UITextView, bnd_attributedText = bnd_attributedText { updatingFromSelf = true bnd_attributedText.next(textView.attributedText) updatingFromSelf = false } }.disposeIn(bnd_bag) return bnd_attributedText } } public var bnd_textColor: Observable<UIColor?> { return bnd_associatedObservableForValueForKey("textColor") } }
bsd-2-clause
86ac4cabd07bd445558a1b56607ed0c0
39.43956
162
0.70462
4.730077
false
false
false
false
iamyuiwong/swift-common
ds/CycleQueue.swift
1
3464
import Foundation private class CycleQ { func reinit () { self.count = 0 self.front = 0 self.rear = 0 } var count: Int = 0 var front: Int = 0; var rear:Int = 0; } public class CycleQueue<T>: Queue<T> { init () { super.init(noAlloc: true) self.cycleq.reinit() } override public func isEmpty () -> Int { var ret: Int? self.LOCK() let e = super.isEmpty() if (0 == e) { if (self.cycleq.count <= 0) { ret = 1 } else { ret = 0 } } else { ret = e } self.UNLOCK() return ret! } public func remaining () -> Int { var ret: Int? self.LOCK() let e = super.isEmpty() if (-1 == e) { ret = -1 } else { let cap = super.currentQueueSize() let c = self.cycleq.count if (c >= cap) { ret = 0 } else { ret = cap - c } } self.UNLOCK() return ret! } /* * NAME enqueue - append and after-old-tail (be-the-latest-one) */ override public func enqueue (v: T) -> Bool { var ret: Bool? self.LOCK() let cap = super.currentQueueSize() if (cap <= 0) { /* no q */ ret = false } else if (cap <= self.cycleq.count) { /* full */ ret = false } else { super.set(index: self.cycleq.rear, v: v) self.cycleq.rear = (self.cycleq.rear + 1) % cap self.cycleq.count = self.cycleq.count + 1 ret = true } self.UNLOCK() return ret! } /* * NAME enqueue - append and after-old-tail (be-the-latest) */ public func enqueue (all vs: [T]) -> Bool { var ret: Bool? self.LOCK() let cap = super.currentQueueSize() let c = self.cycleq.count if (cap <= 0) { /* no q */ ret = false } else if (cap <= c) { /* full */ ret = false } else if (cap <= (vs.count + c)) { /* no enough */ ret = false } else { for v in vs { super.set(index: self.cycleq.rear, v: v) self.cycleq.rear = (self.cycleq.rear + 1) % cap self.cycleq.count = self.cycleq.count + 1 } ret = true } self.UNLOCK() return ret! } /* * NAME dequeue - remove and get head (first is the dequeue head) */ override public func dequeue () -> T? { var ret: T? self.LOCK() let cap = super.currentQueueSize() if (cap <= 0) { /* no q */ ret = nil } else { let c = self.cycleq.count if (c <= 0) { /* empty q */ ret = nil } else { ret = super.get(index: self.cycleq.front) self.cycleq.front = (self.cycleq.front + 1) % cap self.cycleq.count = self.cycleq.count - 1 } } self.UNLOCK() return ret } public final func capacity () -> Int { return super.currentQueueSize() } public final func count () -> Int { var ret: Int? self.LOCK() ret = self.cycleq.count self.UNLOCK() return ret! } public func alloc (count c: UInt32, repeatedValue: T) -> Bool { var ret: Bool? self.LOCK() ret = super.reinit(count: c, repeatedValue: repeatedValue) if (ret!) { self.cycleq.reinit() } self.UNLOCK() return ret! } public func dealloc () { self.LOCK() self.cycleq.reinit() super.empty() self.UNLOCK() } /* * NAME LOCK - lock */ private final func LOCK () { while (self.LOCKED) { usleep(self.LOCK_SLICE) } self.LOCKED = true } /* * NAME UNLOCK - unlock */ private final func UNLOCK () { self.LOCKED = false } /* * NAME LOCKED - var locked */ private final var LOCKED: Bool = false private final let LOCK_SLICE: UInt32 = UInt32(5 * 1e3) private let cycleq: CycleQ = CycleQ() }
lgpl-3.0
e329ee678e4a7439b5f36ad4f9df7a6c
13.554622
66
0.566686
2.689441
false
false
false
false
BasThomas/MacOSX
BusyApp/BusyApp/MainWindowController.swift
1
2402
// // MainWindowController.swift // BusyApp // // Created by Bas Broek on 29/04/15. // Copyright (c) 2015 Bas Broek. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { @IBOutlet weak var secureField: NSSecureTextField! @IBOutlet weak var textField: NSTextField! @IBOutlet weak var checkbox: NSButton! @IBOutlet weak var verticalSlider: NSSlider! @IBOutlet weak var radioMatrix: NSMatrix! @IBOutlet weak var sliderLabel: NSTextFieldCell! var currentSliderValue = 0.0 override var windowNibName: String? { return "MainWindowController" } override func windowDidLoad() { super.windowDidLoad() } @IBAction func checkUncheck(sender: AnyObject) { let checkbox = sender as! NSButton if checkbox.state == 0 { checkbox.title = "Check me" } else if checkbox.state == 1 { checkbox.title = "Uncheck me" } } @IBAction func revealMessage(sender: AnyObject) { self.textField.stringValue = self.secureField.stringValue } @IBAction func radioButtonPressed(sender: AnyObject) { let matrix = sender as! NSMatrix let selected = matrix.selectedRow if selected == 0 { self.verticalSlider.numberOfTickMarks = 10 } else if selected == 1 { self.verticalSlider.numberOfTickMarks = 0 } } @IBAction func adjustSlider(sender: AnyObject) { if self.currentSliderValue < sender.doubleValue { self.sliderLabel.title = "going up" } else if self.currentSliderValue > sender.doubleValue { self.sliderLabel.title = "going down" } else { self.sliderLabel.title = "staying" } self.currentSliderValue = sender.doubleValue } @IBAction func resetControls(sender: AnyObject) { self.checkbox.state = 1 self.checkbox.title = "Uncheck me" self.secureField.stringValue = "" self.textField.stringValue = "" self.verticalSlider.doubleValue = 0.0 self.radioMatrix.selectCellAtRow(0, column: 0) self.verticalSlider.numberOfTickMarks = 10 } }
mit
87fa74759b8abf2f87e2af7997078e58
23.520408
65
0.589092
4.709804
false
false
false
false
kelonye/SwiftyDropbox
Source/Client.swift
1
9820
import Foundation import Alamofire public class Box<T> { public let unboxed : T init (_ v : T) { self.unboxed = v } } public enum CallError<ErrorType> : Printable { case InternalServerError(Int, String?) case BadInputError(String?) case RateLimitError case HTTPError(Int?, String?) case RouteError(Box<ErrorType>) public var description : String { switch self { case .InternalServerError(let code, let message): var ret = "Internal Server Error \(code)" if let m = message { ret += ": \(m)" } return ret case .BadInputError(let message): var ret = "Bad Input" if let m = message { ret += ": \(m)" } return ret case .RateLimitError: return "Rate limited" case .HTTPError(let code, let message): var ret = "HTTP Error" if let c = code { ret += "\(c)" } if let m = message { ret += ": \(m)" } return ret case .RouteError(let box): return "API route error - handle programmatically" } } } func utf8Decode(data: NSData) -> String { return NSString(data: data, encoding: NSUTF8StringEncoding)! as String } func asciiEscape(s: String) -> String { var out : String = "" for char in s.unicodeScalars { var esc = "\(char)" if !char.isASCII() { esc = NSString(format:"\\u%04x", char.value) as String } else { esc = "\(char)" } out += esc } return out } /// Represents a Babel request /// /// These objects are constructed by the SDK; users of the SDK do not need to create them manually. /// /// Pass in a closure to the `response` method to handle a response or error. public class BabelRequest<RType : JSONSerializer, EType : JSONSerializer> { let errorSerializer : EType let responseSerializer : RType let request : Request init(client: BabelClient, host: String, route: String, responseSerializer: RType, errorSerializer: EType, requestEncoder: (URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?)) { self.errorSerializer = errorSerializer self.responseSerializer = responseSerializer let url = "\(client.baseHosts[host]!)\(route)" self.request = client.manager.request(.POST, url, parameters: [:], encoding: .Custom(requestEncoder)) } func handleResponseError(response: NSHTTPURLResponse?, data: NSData) -> CallError<EType.ValueType> { if let code = response?.statusCode { switch code { case 500...599: let message = utf8Decode(data) return .InternalServerError(code, message) case 400: let message = utf8Decode(data) return .BadInputError(message) case 429: return .RateLimitError case 409: let json = parseJSON(data) switch json { case .Dictionary(let d): return .RouteError(Box(self.errorSerializer.deserialize(d["reason"]!))) default: fatalError("Failed to parse error type") } default: return .HTTPError(code, "An error occurred.") } } else { let message = utf8Decode(data) return .HTTPError(nil, message) } } } /// An "rpc-style" request public class BabelRpcRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { init(client: BabelClient, host: String, route: String, params: JSON, responseSerializer: RType, errorSerializer: EType) { super.init( client: client, host: host, route: route, responseSerializer: responseSerializer, errorSerializer: errorSerializer, requestEncoder: ({ convertible, _ in var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") mutableRequest.HTTPBody = dumpJSON(params) return (mutableRequest, nil) })) } /// Called when a request completes. /// /// :param: completionHandler A closure which takes a (response, error) and handles the result of the call appropriately. public func response(completionHandler: (RType.ValueType?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate().response { (request, response, dataObj, error) -> Void in let data = dataObj as! NSData if error != nil { completionHandler(nil, self.handleResponseError(response, data: data)) } else { completionHandler(self.responseSerializer.deserialize(parseJSON(data)), nil) } } return self } } public class BabelUploadRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { init(client: BabelClient, host: String, route: String, params: JSON, body: NSData, responseSerializer: RType, errorSerializer: EType) { super.init( client: client, host: host, route: route, responseSerializer: responseSerializer, errorSerializer: errorSerializer, requestEncoder: ({ convertible, _ in var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type") mutableRequest.HTTPBody = body if let data = dumpJSON(params) { let value = asciiEscape(utf8Decode(data)) mutableRequest.addValue(value, forHTTPHeaderField: "Dropbox-Api-Arg") } return (mutableRequest, nil) })) } /// Called as the upload progresses. /// /// :param: closure /// a callback taking three arguments (`bytesWritten`, `totalBytesWritten`, `totalBytesExpectedToWrite`) /// :returns: The request, for chaining purposes public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { self.request.progress(closure: closure) return self } /// Called when a request completes. /// /// :param: completionHandler /// A callback taking two arguments (`response`, `error`) which handles the result of the call appropriately. /// :returns: The request, for chaining purposes. public func response(completionHandler: (RType.ValueType?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate().response { (request, response, dataObj, error) -> Void in let data = dataObj as! NSData if error != nil { completionHandler(nil, self.handleResponseError(response, data: data)) } else { completionHandler(self.responseSerializer.deserialize(parseJSON(data)), nil) } } return self } } public class BabelDownloadRequest<RType : JSONSerializer, EType : JSONSerializer> : BabelRequest<RType, EType> { init(client: BabelClient, host: String, route: String, params: JSON, responseSerializer: RType, errorSerializer: EType) { super.init( client: client, host: host, route: route, responseSerializer: responseSerializer, errorSerializer: errorSerializer, requestEncoder: ({ convertible, _ in var mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest if let data = dumpJSON(params) { let value = asciiEscape(utf8Decode(data)) mutableRequest.addValue(value, forHTTPHeaderField: "Dropbox-Api-Arg") } return (mutableRequest, nil) })) } /// Called as the download progresses /// /// :param: closure /// a callback taking three arguments (`bytesRead`, `totalBytesRead`, `totalBytesExpectedToRead`) /// :returns: The request, for chaining purposes. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self { self.request.progress(closure: closure) return self } /// Called when a request completes. /// /// :param: completionHandler /// A callback taking two arguments (`response`, `error`) which handles the result of the call appropriately. /// :returns: The request, for chaining purposes. public func response(completionHandler: ( (RType.ValueType, NSData)?, CallError<EType.ValueType>?) -> Void) -> Self { self.request.validate().response { (request, response, dataObj, error) -> Void in let data = dataObj as! NSData if error != nil { completionHandler(nil, self.handleResponseError(response, data: data)) } else { let result = response!.allHeaderFields["Dropbox-Api-Result"] as! String let resultData = result.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let resultObject = self.responseSerializer.deserialize(parseJSON(resultData)) completionHandler( (resultObject, data), nil) } } return self } } /// A dropbox API client public class BabelClient { var baseHosts : [String : String] var manager : Manager public init(manager : Manager, baseHosts : [String : String]) { self.baseHosts = baseHosts self.manager = manager } }
mit
6d61884e3e2f594346431a148db5c838
37.210117
139
0.599389
5.02045
false
false
false
false
TwoRingSoft/SemVer
Vendor/Swiftline/SwiftlineTests/SwiftlineTests/ArgsTests.swift
1
5145
import Foundation import Quick import Nimble @testable import Swiftline class ArgsTests: QuickSpec { override func spec() { describe("Args") { it("returns the correct number of args passed") { expect(Args.all.count).to(beGreaterThan(0)) } it("returns the exact argument passed to the app") { ProcessInfo.internalProcessInfo = DummyProcessInfo("1", "2", "3") expect(Args.all).to(equal(["1", "2", "3"])) } it("creats a hash from passed args") { ProcessInfo.internalProcessInfo = DummyProcessInfo("excutable_name", "-f", "file.rb", "--integer", "1", "Some custom one", "one", "two", "--no-ff") let result = [ "f": "file.rb", "integer": "1", "no-ff": ""] expect(Args.parsed.flags).to(equal(result)) expect(Args.parsed.parameters).to(equal(["Some custom one", "one", "two"])) expect(Args.parsed.command).to(equal("excutable_name")) } } describe("ArgsParser") { it("returns empty for empty array") { let r = ArgsParser.parseFlags([]) expect(r.0.count).to(equal(0)) expect(r.1.count).to(equal(0)) } it("returns all leading non flag parameters") { let r = ArgsParser.parseFlags(["omar", "hello", "-f", "test", "--help"]) expect(r.1).to(equal(["omar", "hello"])) } it("returns all tailling non flag parameters") { let r = ArgsParser.parseFlags(["-f", "test", "--help", "x", "omar", "hello"]) expect(r.1).to(equal(["omar", "hello"])) } it("returns all mixed non flag parameters") { let r = ArgsParser.parseFlags(["-f", "test", "omar", "--help", "x", "hello"]) expect(r.1).to(equal(["omar", "hello"])) } it("returns all flags if they are all set") { let r = ArgsParser.parseFlags(["-f", "test", "omar", "--help", "x", "hello"]) expect(r.0[0].argument.name).to(equal("f")) expect(r.0[0].value).to(equal("test")) expect(r.0[1].argument.name).to(equal("help")) expect(r.0[1].value).to(equal("x")) } it("returns all flags if some are not set") { let r = ArgsParser.parseFlags(["-f", "-w", "omar", "--help", "x", "hello"]) expect(r.0[0].argument.name).to(equal("f")) expect(r.0[0].value).to(beNil()) expect(r.0[1].argument.name).to(equal("w")) expect(r.0[1].value).to(equal("omar")) expect(r.0[2].argument.name).to(equal("help")) expect(r.0[2].value).to(equal("x")) } it("parses complex flags configuration") { let r = ArgsParser.parseFlags(["one", "-f", "-w", "omar", "two", "--help", "x", "hello"]) expect(r.1).to(equal(["one", "two", "hello"])) expect(r.0[0].argument.name).to(equal("f")) expect(r.0[0].value).to(beNil()) expect(r.0[1].argument.name).to(equal("w")) expect(r.0[1].value).to(equal("omar")) expect(r.0[2].argument.name).to(equal("help")) expect(r.0[2].value).to(equal("x")) } it("stops parsing flags when -- is found") { let r = ArgsParser.parseFlags(["one", "-f", "-w", "omar", "two", "--", "--help", "x", "hello"]) expect(r.1).to(equal(["one", "two", "--help", "x", "hello"])) expect(r.0[0].argument.name).to(equal("f")) expect(r.0[0].value).to(beNil()) expect(r.0[1].argument.name).to(equal("w")) expect(r.0[1].value).to(equal("omar")) } } describe("Argument") { it("knows the arg type for a string") { expect(Argument.ArgumentType("-f")) .to(equal(Argument.ArgumentType.ShortFlag)) expect(Argument.ArgumentType("--force")) .to(equal(Argument.ArgumentType.LongFlag)) expect(Argument.ArgumentType("--no-repo-update")) .to(equal(Argument.ArgumentType.LongFlag)) expect(Argument.ArgumentType("not an arg")) .to(equal(Argument.ArgumentType.NotAFlag)) expect(Argument.ArgumentType("not-an-arg")) .to(equal(Argument.ArgumentType.NotAFlag)) } it("knows if an argument is a flag") { expect(Argument.ArgumentType.ShortFlag.isFlag) .to(beTrue()) expect(Argument.ArgumentType.LongFlag.isFlag) .to(beTrue()) expect(Argument.ArgumentType.NotAFlag.isFlag) .to(beFalse()) } it("normalize a flag") { expect(Argument("-f").name) .to(equal("f")) expect(Argument("--force").name) .to(equal("force")) expect(Argument("--no-repo-update").name) .to(equal("no-repo-update")) expect(Argument("not an arg").name) .to(equal("not an arg")) expect(Argument("not-an-arg").name) .to(equal("not-an-arg")) } } } }
apache-2.0
d514dd5a34f787c803945b06320e0306
31.15625
155
0.514091
3.656716
false
false
false
false
Bing0/ThroughWall
TodayEx/TodayViewController.swift
1
12560
// // TodayViewController.swift // TodayEx // // Created by Wu Bin on 16/11/2016. // Copyright © 2016 Wu Bin. All rights reserved. // import UIKit import NotificationCenter import NetworkExtension import Fabric import Crashlytics class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var upLoad: UILabel! @IBOutlet weak var downLoad: UILabel! @IBOutlet weak var vpnName: UILabel! @IBOutlet weak var controlSwitch: UISwitch! @IBOutlet weak var statusText: UILabel! @IBOutlet weak var tableview: UITableView! var proxyConfigs = [ProxyConfig]() var selectedServerIndex = 0 let notificaiton = CFNotificationCenterGetDarwinNotifyCenter() var observer: UnsafeRawPointer! var currentVPNManager: NETunnelProviderManager? { willSet { DispatchQueue.main.async { self.controlSwitch.isEnabled = true self.vpnName.text = (newValue?.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration?["description"] as? String } } } var currentVPNStatusIndicator: NEVPNStatus = .invalid { willSet { switch newValue { case .connecting: statusText.text = "Connecting..." // currentVPNStatusLamp.image = UIImage(named: "OrangeDot") break case .connected: statusText.text = "Connected" // currentVPNStatusLamp.image = UIImage(named: "GreenDot") controlSwitch.isOn = true break case .disconnecting: self.statusText.text = "Disconnecting..." // currentVPNStatusLamp.image = UIImage(named: "OrangeDot") break case .disconnected: self.statusText.text = "Disconnected" // currentVPNStatusLamp.image = UIImage(named: "GrayDot") controlSwitch.isOn = false self.downLoad.text = "0 B/s" self.upLoad.text = "0 B/s" break default: // on = false // currentVPNStatusLabel.text = "Not Connected" // currentVPNStatusLamp.image = UIImage(named: "GrayDot") break } } } // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) //// Fabric.with([Crashlytics.self]) // Crashlytics.start(withAPIKey: "ea6ae7041e03704c8768e183adaa548fa1192da8") // } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view from its nib. extensionContext?.widgetLargestAvailableDisplayMode = .expanded tableview.tableFooterView = UIView() // tableview.backgroundColor = UIColor.groupTableViewBackground RuleFileUpdateController().tryUpdateRuleFileFromBundleFile() SiteConfigController().convertOldServer { newManager in print("completed") if newManager != nil { self.currentVPNManager = newManager self.currentVPNStatusIndicator = self.currentVPNManager!.connection.status } self.proxyConfigs = SiteConfigController().readSiteConfigsFromConfigFile() if let index = SiteConfigController().getSelectedServerIndex() { self.selectedServerIndex = index } //TODO self.tableview.reloadData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()) let name = DarwinNotifications.updateWidget.rawValue CFNotificationCenterAddObserver(notificaiton, observer, { (_, observer, name, _, _) in if let observer = observer, let name = name { // Extract pointer to `self` from void pointer: let mySelf = Unmanaged<TodayViewController>.fromOpaque(observer).takeUnretainedValue() // Call instance method: mySelf.darwinNotification(name: name.rawValue as String) } }, name as CFString, nil, .deliverImmediately) NotificationCenter.default.addObserver(self, selector: #selector(TodayViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == .expanded { proxyConfigs = SiteConfigController().readSiteConfigsFromConfigFile() tableview.reloadData() preferredContentSize = CGSize(width: 0.0, height: Double(110 + 44 * proxyConfigs.count)) } else if activeDisplayMode == .compact { preferredContentSize = maxSize } } override func viewWillDisappear(_ animated: Bool) { CFNotificationCenterRemoveEveryObserver(notificaiton, observer) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NEVPNStatusDidChange, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func vpnSwitchClicked(_ sender: UISwitch) { let on = sender.isOn if let manager = self.currentVPNManager { manager.loadFromPreferences(completionHandler: { (_error) in if let error = _error { print(error) sender.isOn = false } else { if self.trigerVPNManager(withManager: manager, shouldON: on) == false { sender.isOn = false } } }) } else { // if proxyConfigs.count > selectedServerIndex { // let proxyConfig = proxyConfigs[selectedServerIndex] // SiteConfigController().forceSaveToManager(withConfig: proxyConfig, withCompletionHandler: { (_manager) in // if let manager = _manager { // self.currentVPNManager = manager // manager.loadFromPreferences(completionHandler: { (_error) in // if let error = _error { // print(error) // sender.isOn = false // } else { // if self.trigerVPNManager(withManager: manager, shouldON: on) == false { // sender.isOn = false // } // } // }) // } else { // sender.isOn = false // } // }) // } else { // sender.isOn = false // } } } func trigerVPNManager(withManager manger: NETunnelProviderManager, shouldON on: Bool) -> Bool { var result = true if on { do { try manger.connection.startVPNTunnel() } catch { print(error) result = false } } else { manger.connection.stopVPNTunnel() } return result } @objc func VPNStatusDidChange(_ notification: Notification?) { if let currentVPNManager = self.currentVPNManager { currentVPNStatusIndicator = currentVPNManager.connection.status } else { print("!!!!!") } } func widgetPerformUpdate(_ completionHandler: (@escaping (NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.newData) } func darwinNotification(name: String) { switch name { case DarwinNotifications.updateWidget.rawValue: updateWidget() default: break } } func updateWidget() { let defaults = UserDefaults(suiteName: groupName) if let downloadCount = defaults?.value(forKey: downloadCountKey) as? Int { DispatchQueue.main.async { self.downLoad.text = self.formatSpeed(downloadCount) } } if let uploadCount = defaults?.value(forKey: uploadCountKey) as? Int { DispatchQueue.main.async { self.upLoad.text = self.formatSpeed(uploadCount) } } } func formatSpeed(_ speed: Int) -> String { switch speed { case 0 ..< 1024: return String.init(format: "%d B/s", speed) case 1024 ..< 1048576: return String.init(format: "%.1f KB/s", Double(speed) / 1024) default: return String.init(format: "%.1f MB/s", Double(speed) / 1048576) } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return proxyConfigs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "vpnListCell", for: indexPath) as! VPNTableViewContTableViewCell cell.VPNNameLabel.text = proxyConfigs[indexPath.row].getValue(byItem: "description") if let delayValue = proxyConfigs[indexPath.row].getValue(byItem: "delay") { if let intDelayValue = Int(delayValue) { switch intDelayValue { case -1: cell.VPNPingValueLabel.attributedText = NSAttributedString(string: "Timeout", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red]) case 0 ..< 100: cell.VPNPingValueLabel.attributedText = NSAttributedString(string: "\(delayValue) ms", attributes: [NSAttributedStringKey.foregroundColor: UIColor.init(red: 0.24, green: 0.545, blue: 0.153, alpha: 1.0)]) default: cell.VPNPingValueLabel.attributedText = NSAttributedString(string: "\(delayValue) ms", attributes: [NSAttributedStringKey.foregroundColor: UIColor.black]) } } else { cell.VPNPingValueLabel.text = "" } // cell.VPNPingValueLabel.text = delayValue + " ms" } else { cell.VPNPingValueLabel.text = "Unknown" } if indexPath.row == selectedServerIndex { // cell.setSelected(true, animated: false) cell.accessoryType = .checkmark vpnName.text = cell.VPNNameLabel.text } else { cell.accessoryType = .none } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if let currentManager = currentVPNManager { if currentManager.connection.status == .connected || currentManager.connection.status == .connecting { return } else { let oldIndexPath = IndexPath(row: selectedServerIndex, section: 0) tableView.cellForRow(at: oldIndexPath)?.accessoryType = .none tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark selectedServerIndex = indexPath.row SiteConfigController().save(withConfig: proxyConfigs[indexPath.row], intoManager: currentManager, completionHander: { DispatchQueue.main.async { self.vpnName.text = (currentManager.protocolConfiguration as! NETunnelProviderProtocol).providerConfiguration?["description"] as? String } }) } } self.selectedServerIndex = indexPath.row SiteConfigController().setSelectedServerIndex(withValue: indexPath.row) tableView.reloadData() } }
gpl-3.0
664b845deb9204beb0e68e1e8482a045
37.882353
223
0.593837
5.145023
false
true
false
false
googlemaps/maps-sdk-for-ios-samples
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/VisibleRegionViewController.swift
1
2641
// Copyright 2020 Google LLC. All rights reserved. // // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF // ANY KIND, either express or implied. See the License for the specific language governing // permissions and limitations under the License. import GoogleMaps import UIKit class VisibleRegionViewController: UIViewController { static let overlayHeight: CGFloat = 140 private lazy var mapView: GMSMapView = { let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4) let mapView = GMSMapView(frame: .zero, camera: camera) mapView.settings.myLocationButton = true mapView.isMyLocationEnabled = true mapView.padding = UIEdgeInsets( top: 0, left: 0, bottom: VisibleRegionViewController.overlayHeight, right: 0) return mapView }() private lazy var overlay: UIView = { let overlay = UIView(frame: .zero) overlay.backgroundColor = UIColor(hue: 0, saturation: 1, brightness: 1, alpha: 0.5) return overlay }() private lazy var flyInButton: UIBarButtonItem = { return UIBarButtonItem( title: "Toggle Overlay", style: .plain, target: self, action: #selector(didTapToggleOverlay)) }() override func loadView() { view = mapView navigationItem.rightBarButtonItem = flyInButton let overlayFrame = CGRect( x: 0, y: -VisibleRegionViewController.overlayHeight, width: 0, height: VisibleRegionViewController.overlayHeight) overlay.frame = overlayFrame overlay.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] view.addSubview(overlay) } @objc func didTapToggleOverlay() { let padding = mapView.padding UIView.animate(withDuration: 2) { [unowned self] in let size = self.view.bounds.size if padding.bottom == 0 { self.overlay.frame = CGRect( x: 0, y: size.height - VisibleRegionViewController.overlayHeight, width: size.width, height: VisibleRegionViewController.overlayHeight) self.mapView.padding = UIEdgeInsets( top: 0, left: 0, bottom: VisibleRegionViewController.overlayHeight, right: 0) } else { self.overlay.frame = CGRect( x: 0, y: self.mapView.bounds.size.height, width: size.width, height: 0) self.mapView.padding = .zero } } } }
apache-2.0
d666b0de6d2f714378361c273951af37
37.275362
99
0.706551
4.287338
false
false
false
false
gabemdev/GMDKit
GMDKit/Classes/MKMapView+GMDKit.swift
1
3251
// // MKMapView+GMDKit.swift // Pods // // Created by Gabriel Morales on 3/8/17. // // import Foundation import MapKit let MERCATOR_OFFSET = 268435456.0 let MERCATOR_RADIUS = 85445659.44705395 let DEGREES = 180.0 public extension MKMapView { //MARK: Map Conversion Methods public func longitudeToPixelSpaceX(longitude:Double)->Double{ return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / DEGREES) } public func latitudeToPixelSpaceY(latitude:Double)->Double{ return round(MERCATOR_OFFSET - MERCATOR_RADIUS * log((1 + sin(latitude * M_PI / DEGREES)) / (1 - sin(latitude * M_PI / DEGREES))) / 2.0) } public func pixelSpaceXToLongitude(pixelX:Double)->Double{ return ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * DEGREES / M_PI } public func pixelSpaceYToLatitude(pixelY:Double)->Double{ return (M_PI / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * DEGREES / M_PI } public func coordinateSpanWithCenterCoordinate(centerCoordinate:CLLocationCoordinate2D, zoomLevel:Double)->MKCoordinateSpan{ // convert center coordiate to pixel space let centerPixelX = longitudeToPixelSpaceX(longitude: centerCoordinate.longitude) let centerPixelY = latitudeToPixelSpaceY(latitude: centerCoordinate.latitude) // determine the scale value from the zoom level let zoomExponent:Double = 20.0 - zoomLevel let zoomScale:Double = pow(2.0, zoomExponent) // scale the map’s size in pixel space let mapSizeInPixels = self.bounds.size let scaledMapWidth = Double(mapSizeInPixels.width) * zoomScale let scaledMapHeight = Double(mapSizeInPixels.height) * zoomScale // figure out the position of the top-left pixel let topLeftPixelX = centerPixelX - (scaledMapWidth / 2.0) let topLeftPixelY = centerPixelY - (scaledMapHeight / 2.0) // find delta between left and right longitudes let minLng = pixelSpaceXToLongitude(pixelX: topLeftPixelX) let maxLng = pixelSpaceXToLongitude(pixelX: topLeftPixelX + scaledMapWidth) let longitudeDelta = maxLng - minLng let minLat = pixelSpaceYToLatitude(pixelY: topLeftPixelY) let maxLat = pixelSpaceYToLatitude(pixelY: topLeftPixelY + scaledMapHeight) let latitudeDelta = -1.0 * (maxLat - minLat) return MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta) } public func setCenterCoordinate(centerCoordinate:CLLocationCoordinate2D, zoomLevel:Double, animated:Bool){ // clamp large numbers to 28 var zoomLevel = zoomLevel zoomLevel = min(zoomLevel, 28) // use the zoom level to compute the region let span = self.coordinateSpanWithCenterCoordinate(centerCoordinate: centerCoordinate, zoomLevel: zoomLevel) let region = MKCoordinateRegionMake(centerCoordinate, span) if region.center.longitude == -180.00000000{ debugPrint("Invalid Region") } else{ self.setRegion(region, animated: animated) } } }
mit
28994274877b753da30e1607836a5bf3
39.111111
144
0.675285
4.26378
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/User/UserSignUpViewController.swift
2
12503
// // UserSignUpViewController.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 30/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kUserSignUpViewControllerTitle = "SignUpTitle" let kUserSignUpViewControllerEmailKey = "Email" let kUserSignUpViewControllerPasswordKey = "Password" let kUserSignUpViewControllerSalutationKey = "Salutation" let kUserSignUpViewControllerFirstNameKey = "First name" let kUserSignUpViewControllerLastNameKey = "Last name" let kUserSignUpViewControllerAddressKey = "Address" let kUserSignUpViewControllerAddressOptionalKey = "Address optional" let kUserSignUpViewControllerZipCodeKey = "Zip" let kUserSignUpViewControllerCountryCodeKey = "Country" let kUserSignUpViewControllerStateKey = "State" let kUserSignUpViewControllerCityKey = "City" let kUserSignUpViewControllerPhoneKey = "Phone" let kUserSignUpViewControllerIncorrectDataKey = "WrongDataWasProvided" protocol UserSignUpViewControllerDelegate: AnyObject { func didFinishSignUp() } class UserSignUpViewController: BaseTableViewController, CountryPickerViewControllerDelegate { var model: SignUpModel? weak var delegate: UserSignUpViewControllerDelegate? @IBOutlet weak var salutationTextField: NormalTextField! @IBOutlet weak var firstNameTextField: NormalTextField! @IBOutlet weak var lastNameTextField: NormalTextField! @IBOutlet weak var addressTextField: NormalTextField! @IBOutlet weak var addressOptionalTextField: NormalTextField! @IBOutlet weak var countryCodeTextField: NormalTextField! @IBOutlet weak var stateCodeTextField: NormalTextField! @IBOutlet weak var cityTextField: NormalTextField! @IBOutlet weak var zipCodeTextField: NormalTextField! @IBOutlet weak var phoneTextField: NormalTextField! @IBOutlet weak var emailTextField: NormalTextField! @IBOutlet weak var passwordTextField: NormalTextField! @IBOutlet weak var privacyAndTermsTextView: UITextView! @IBOutlet weak var actionButton: UIButton! override func viewDidLoad() { super.viewDidLoad() //self.viewLoader?.hideNavigationBar(viewController: self) self.prepareUI() self.loadModel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Log user behaviour self.analyticsManager?.log(screenName: kAnalyticsScreen.userSignUp) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } func clearTextFields() { self.model?.clearData() self.salutationTextField.text = nil; self.firstNameTextField.text = nil; self.lastNameTextField.text = nil; self.addressTextField.text = nil; self.addressOptionalTextField.text = nil; self.zipCodeTextField.text = nil; self.countryCodeTextField.text = nil; self.stateCodeTextField.text = nil; self.cityTextField.text = nil; self.phoneTextField.text = nil; self.emailTextField.text = nil; self.passwordTextField.text = nil; self.salutationTextField.becomeFirstResponder() } // MARK: IBActions @IBAction func countryPressed(_ sender: AnyObject) { let vcDelegate = self let vc = self.viewControllerFactory?.countryPickerViewController(context: vcDelegate) self.presentModal(viewController: vc!, animated: true) } @IBAction func signUpPressed(_ sender: AnyObject) { self.updateModel() let validationError: ErrorEntity? = self.model?.validateData() if let validationError = validationError { DDLogDebug(log: "SignUpPressedWithWrongData") // Mark required but empty fields in red self.applyStyleForMissingRequiredFields() self.messageBarManager?.showMessage(title: nil, description: validationError.message, type: MessageBarMessageType.error) } else { // Reset previous warnings from fields self.resetStyleForMissingRequiredFields() self.viewLoader?.showScreenActivityIndicator(containerView: self.view) self.model?.signUp(callback: {[weak self] (success, result, context, error) in self?.viewLoader?.hideScreenActivityIndicator(containerView: (self?.view)!) if (success) { DDLogDebug(log: "UserSignUpSuccess") self?.clearTextFields() self?.delegate?.didFinishSignUp() } else { DDLogDebug(log: "UserSignUpFail: \(error?.message)") } }) } } // MARK: GenericViewControllerProtocol override func prepareUI() { super.prepareUI() self.title = localizedString(key: kUserSignUpViewControllerTitle) self.setupTextFields() self.setupTappablePrivacyAndTermsTextView() } override func renderUI() { super.renderUI() } override func loadModel() { self.renderUI() } // MARK: KeyboardControlDelegate override func didPressGo() { self.signUpPressed(self.actionButton) } // MARK: CountryPickerViewControllerDelegate func didSelectCountry(countryCode: String) { self.countryCodeTextField.text = countryCode } // MARK: // MARK: Internal // MARK: internal func updateModel() { let user: UserEntity = UserEntity() user.salutation = self.salutationTextField.text user.firstName = self.firstNameTextField.text user.lastName = self.lastNameTextField.text user.address = self.addressTextField.text user.addressOptional = self.addressOptionalTextField.text user.zipCode = self.zipCodeTextField.text user.countryCode = self.countryCodeTextField.text user.stateCode = self.stateCodeTextField.text user.city = self.cityTextField.text user.phone = self.phoneTextField.text user.email = self.emailTextField.text user.password = self.passwordTextField.text self.model?.updateWithData(data: user) } // Add toolbar with previous and next buttons for navigating between input fields internal func setupTextFields() { // Add placeholders self.salutationTextField.placeholder = localizedString(key: kUserSignUpViewControllerSalutationKey) self.firstNameTextField.placeholder = localizedString(key: kUserSignUpViewControllerFirstNameKey) self.lastNameTextField.placeholder = localizedString(key: kUserSignUpViewControllerLastNameKey) self.addressTextField.placeholder = localizedString(key: kUserSignUpViewControllerAddressKey) self.addressOptionalTextField.placeholder = localizedString(key: kUserSignUpViewControllerAddressOptionalKey) self.zipCodeTextField.placeholder = localizedString(key: kUserSignUpViewControllerZipCodeKey) self.countryCodeTextField.placeholder = localizedString(key: kUserSignUpViewControllerCountryCodeKey) self.stateCodeTextField.placeholder = localizedString(key: kUserSignUpViewControllerStateKey) self.cityTextField.placeholder = localizedString(key: kUserSignUpViewControllerCityKey) self.phoneTextField.placeholder = localizedString(key: kUserSignUpViewControllerPhoneKey) self.emailTextField.placeholder = localizedString(key: kUserSignUpViewControllerEmailKey) self.passwordTextField.placeholder = localizedString(key: kUserSignUpViewControllerPasswordKey) // Set required fields self.salutationTextField.isRequired = true self.firstNameTextField.isRequired = true self.lastNameTextField.isRequired = true self.addressTextField.isRequired = true self.addressOptionalTextField.isRequired = true self.zipCodeTextField.isRequired = true self.countryCodeTextField.isRequired = true self.stateCodeTextField.isRequired = true self.cityTextField.isRequired = true self.emailTextField.isRequired = true self.passwordTextField.isRequired = true // Apply style self.salutationTextField.position = TextFieldPosition.isFirst self.firstNameTextField.position = TextFieldPosition.isMiddle self.lastNameTextField.position = TextFieldPosition.isMiddle self.addressTextField.position = TextFieldPosition.isMiddle self.addressOptionalTextField.position = TextFieldPosition.isMiddle self.zipCodeTextField.position = TextFieldPosition.isMiddle self.countryCodeTextField.position = TextFieldPosition.isMiddle self.stateCodeTextField.position = TextFieldPosition.isMiddle self.cityTextField.position = TextFieldPosition.isMiddle self.phoneTextField.position = TextFieldPosition.isMiddle self.emailTextField.position = TextFieldPosition.isMiddle self.passwordTextField.position = TextFieldPosition.isLast // Setup keyboard controls let textFields: Array<UITextInput> = [self.salutationTextField, self.firstNameTextField, self.lastNameTextField, self.addressTextField, self.addressOptionalTextField, self.countryCodeTextField, self.stateCodeTextField, self.cityTextField, self.zipCodeTextField, self.phoneTextField, self.emailTextField, self.passwordTextField]; self.keyboardControls = self.newKeyboardControls(fields: textFields, actionTitle: localizedString(key: ConstLangKeys.done)) } internal func setupTappablePrivacyAndTermsTextView() { // Add rich style elements to privacy and terms and conditions let privacyString: String = "privacy" let termsString: String = "terms and conditions" let privacyAndTermsString: String = "This is an example of \(privacyString) and \(termsString)." self.privacyAndTermsTextView.text = privacyAndTermsString self.privacyAndTermsTextView.applyColor(withSubstring: privacyString, color: kColorBlue) self.privacyAndTermsTextView.applyColor(withSubstring: termsString, color: kColorBlue) //[_privacyAndTermsTextView applyBoldStyleWithSubstring:privacyString]; //[_privacyAndTermsTextView applyBoldStyleWithSubstring:termsString]; //[self.privacyAndTermsTextView applyUnderlineStyleWithSubstring:privacyString]; //[self.privacyAndTermsTextView applyUnderlineStyleWithSubstring:termsString]; self.privacyAndTermsTextView.addTapGesture(withSubstring: privacyString) { (success, result, error) in DDLogDebug(log: "Privacy clicked") } self.privacyAndTermsTextView.addTapGesture(withSubstring: termsString) { (success, result, error) in DDLogDebug(log: "Terms clicked") } } }
mit
368b2c231e61ee79c3d1334f99dafc88
39.986885
336
0.699064
5.435217
false
false
false
false
brunophilipe/tune
tune/Player Interfaces/iTunes/iTunesHandler.swift
1
11884
// // iTunesHandler.swift // tune // // Created by Bruno Philipe on 7/25/16. // Copyright © 2016 Bruno Philipe. All rights reserved. // // 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 ScriptingBridge // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } let kUnknownArtist = "Unknown Artist" let kUnknownTrack = "Unknown Track" let kUnknownAlbum = "Unknown Album" typealias Verb = (names: [String], brief: String, description: [String], extra: String?) class iTunesHandler { var currentTrack: MediaPlayerItem? { if let track = iTunesApp?.currentTrack, track.duration > 0 { return iTunesTrackMediaItem(track: track) } else { return nil } } var currentPlaylist: MediaPlayerPlaylist? { if let track = iTunesApp?.currentTrack, track.duration > 0, let playlist = track.container?.get() as? iTunesPlaylist, playlist.id!() > 0 { // This returns a playlist that's more likely to have the correct track `index` property, since it depends on the sorting. return iTunesMediaPlaylist(playlist: playlist) } else if let playlist = iTunesApp?.currentPlaylist?.get() as? iTunesPlaylist, playlist.id!() > 0 { return iTunesMediaPlaylist(playlist: playlist) } else if let playlist = iTunesApp?.currentPlaylist { return iTunesMediaPlaylist(playlist: playlist) } else { return nil } } var currentPlaybackInfo: MediaPlayerPlaybackInfo? { if let iTunesApp = self.iTunesApp, let progress = iTunesApp.playerPosition, let status = iTunesApp.playerState, let shuffle = iTunesApp.shuffleEnabled { let repeatOn = iTunesApp.songRepeat != .off return MediaPlayerPlaybackInfo(progress: progress, status: .init(status), shuffleOn: shuffle, repeatOn: repeatOn) } else { return nil } } fileprivate var iTunesApp: iTunesApplication? init() { iTunesApp = SBApplication(bundleIdentifier: "com.apple.iTunes") iTunesApp?.setFixedIndexing!(true) } fileprivate func runTrackSearch(_ searchString: String) -> [MediaPlayerItem] { if searchString.characters.count == 0 { return [] } if let libraryPlaylist = getLibraryPlaylist() { let results = libraryPlaylist.searchFor!(searchString, only: .all) if results.count == 0 { return [] } var processedResults = [MediaPlayerItem]() for result in results { if let track = result as? iTunesTrack { processedResults.append(iTunesTrackMediaItem(track: track)) } } return processedResults } else { return [] } } fileprivate func runAlbumSearch(_ searchString: String) { if let libraryPlaylist = getLibraryPlaylist() { let results = libraryPlaylist.searchFor!(searchString, only: .all) var albums: [(human: String, query: String)] = [] for result in results { if let track = result as? iTunesTrack, let albumDesc = track.prettyAlbumDescription, let albumQuery = track.searchableAlbumDescription, !albums.contains(where: { entry in return albumQuery == entry.query }) { albums.append((albumDesc, albumQuery)) } } /* print("\nInsert value [1-\(displayCount)] to pick album to play or 0 to cancel: ") if let input = getUserInput(), let number = Int(input) { if number == 0 { print("Exiting on user request.") return } else if number > 0 && number <= displayCount { let album = albums[number-1].query let albumResults = libraryPlaylist.searchFor!(album, only: .all) if albumResults.count > 0, let queue = getQueuePlaylist() { for i in 0 ..< results.count { let track = results[i] as! iTunesTrack if track.searchableAlbumDescription == albums[number-1].query { _ = track.duplicateTo!(queue as! SBObject) } } queue.playOnce!(true) print("Now playing \(albums[number-1].human). Enjoy the music!") return } else { print("Could not load album... Exiting.") return } } else { print("Invalid user input \"\(number)\". Exiting.") return } } */ print("Invalid user input.. Exiting.") return } else { print("Could not get iTunes library!\n") } } fileprivate func getLibraryPlaylist() -> iTunesLibraryPlaylist? { var librarySource: iTunesSource? = nil for sourceElement in iTunesApp?.sources!() as SBElementArray! { if let source = sourceElement as? iTunesSource, source.kind == .library { librarySource = source break } } if librarySource == nil { return nil } for playlistElement in librarySource?.playlists!() as SBElementArray! { if let playlist = playlistElement as? iTunesPlaylist, playlist.specialKind == .library, let libraryPlaylist = playlist.get() as? iTunesLibraryPlaylist { return libraryPlaylist } } return nil } fileprivate func getQueuePlaylist() -> iTunesPlaylist? { var librarySource: iTunesSource? = nil for sourceElement in iTunesApp?.sources!() as SBElementArray! { if let source = sourceElement as? iTunesSource, source.kind == .library { librarySource = source break } } if librarySource == nil { return nil } // Try using existing playlist for playlistElement in librarySource?.playlists!() as SBElementArray! { if let playlist = playlistElement as? iTunesPlaylist, playlist.name == "tune" { let tracks = playlist.tracks!() as NSMutableArray tracks.removeAllObjects() return playlist } } // Create new playlist if let object = iTunesTools.instantiateObject(from: iTunesApp as! SBApplication, typeName: "playlist", andProperties: ["name": "tune", "visible": false]) { let playlists = (librarySource?.playlists!() as SBElementArray!) as NSMutableArray playlists.add(object) return object as iTunesPlaylist } return nil } } private extension MediaPlayerPlaybackInfo.PlayerStatus { /// Maps from an iTunes internal `iTunesEPlS` type to the generic `MediaPlayerPlaybackInfo.PlayerStatus` type. init(_ status: iTunesEPlS) { switch status { case .playing: self = .playing case .paused: self = .paused case .stopped: self = .stopped // The MediaPlayer protocol doesn't yet support advanced states default: self = .playing } } } extension iTunesHandler: MediaPlayer { /// Internal identification of this media player, such as "itunes" var playerId: String { return "itunes" } // MARK: - Playback control functions func playPause() { iTunesApp?.playpause!() } func pause() { iTunesApp?.pause!() } func stop() { iTunesApp?.stop!() } func nextTrack() { iTunesApp?.nextTrack!() } func previousTrack() { iTunesApp?.previousTrack!() } func search(forTracks text: String) -> SearchResult { return SearchResult(withItems: runTrackSearch(text), forQuery: text) } func search(forAlbums text: String) -> SearchResult { return SearchResult(withItems: [], forQuery: text) } func search(forPlaylists text: String) -> SearchResult { return SearchResult(withItems: [], forQuery: text) } // MARK: - Media control functions func play(track: MediaPlayerItem) { if let iTunesItem = track as? iTunesTrackMediaItem { iTunesItem.track.playOnce!(true) } } } func pprint(_ string: String) { print(string.replacingOccurrences(of: "\t", with: " ")) } struct iTunesTrackMediaItem: MediaPlayerItem { fileprivate let track: iTunesTrack fileprivate init(track: iTunesTrack) { self.track = track self.hashFix = ((track.name ?? "fucking apple").hashValue + (track.index ?? 0).hashValue).hashValue } private var hashFix: Int var kind: MediaPlayerItemKind { return .track } var name: String { return track.name ?? kUnknownTrack } var artist: String { return track.artist ?? kUnknownArtist } var album: String { return track.album ?? kUnknownAlbum } var time: Double? { return track.duration } var index: Int? { return track.index } var year: String? { if let year = track.year, year > 0 { return "\(year)" } else { return nil } } func compare(_ otherItem: MediaPlayerItem?) -> Bool { if let otherItem = otherItem, otherItem.kind == kind, let otherTrack = otherItem as? iTunesTrackMediaItem { return otherTrack.track.persistentID == track.persistentID && hashFix == otherTrack.hashFix } return false } } struct iTunesAlbumMediaItem: MediaPlayerItem { var kind: MediaPlayerItemKind { return .album } var name: String { return "" } var artist: String { return "" } var album: String { return "" } var year: String? { return "" } var time: Double? { return nil } var index: Int? { return nil } func compare(_ otherItem: MediaPlayerItem?) -> Bool { return false } } struct iTunesMediaPlaylist: MediaPlayerPlaylist { fileprivate let playlist: iTunesPlaylist fileprivate init(playlist: iTunesPlaylist) { self.playlist = playlist } var name: String? { return playlist.name } var count: Int { return playlist.tracks?().count ?? 0 } var time: Double? { if let duration = playlist.duration { return Double(duration) } else { return nil } } func item(at index: Int) -> MediaPlayerItem? { if let tracks = playlist.tracks?(), index < tracks.count, let track = tracks.object(at: index) as? iTunesTrack { return iTunesTrackMediaItem(track: track) } else { return nil } } func compare(_ otherPlaylist: MediaPlayerPlaylist?) -> Bool { return (otherPlaylist as? iTunesMediaPlaylist)?.playlist.persistentID == playlist.persistentID } } private extension iTunesTrack { var prettyAlbumDescription: String? { var artistName = self.artist if artistName == nil || artistName == "" { artistName = kUnknownArtist } if let albumName = self.album, albumName.characters.count > 0 { let yearString = ((year != nil && year != 0) ? " (\(year!))" : "") return "\"\(albumName)\" by \(artistName!)\(yearString)" } else { return nil } } var searchableAlbumDescription: String? { var string = "" let artistName = self.artist if artistName != nil && artistName != "" { string += artistName! + " " } let albumName = self.album if albumName != nil && albumName != "" { string += albumName! + " " } if string == "" { return nil } else { return string } } }
gpl-3.0
39a122f7b3088ad492ca25c70631768d
19.038786
125
0.658251
3.530303
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/ReorderableViewController.swift
2
3303
/** Copyright (c) Facebook, Inc. and its affiliates. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class ReorderableViewController: UIViewController, ListAdapterDataSource, ListAdapterMoveDelegate { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) var data = Array(0..<20).map { "Cell: \($0 + 1)" } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() if #available(iOS 9.0, *) { let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(ReorderableViewController.handleLongGesture(gesture:))) collectionView.addGestureRecognizer(longPressGesture) } view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self if #available(iOS 9.0, *) { adapter.moveDelegate = self } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: - Interactive Reordering @available(iOS 9.0, *) @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: let touchLocation = gesture.location(in: self.collectionView) guard let selectedIndexPath = collectionView.indexPathForItem(at: touchLocation) else { break } collectionView.beginInteractiveMovementForItem(at: selectedIndexPath) case .changed: if let view = gesture.view { let position = gesture.location(in: view) collectionView.updateInteractiveMovementTargetPosition(position) } case .ended: collectionView.endInteractiveMovement() default: collectionView.cancelInteractiveMovement() } } // MARK: - ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return data as [ListDiffable] } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { return ReorderableSectionController() } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } // MARK: - ListAdapterMoveDelegate func listAdapter(_ listAdapter: ListAdapter, move object: Any, from previousObjects: [Any], to objects: [Any]) { guard let objects = objects as? [String] else { return } data = objects } }
apache-2.0
cec8d167c4e2b3060f3b6b2931fc45db
34.138298
151
0.680593
5.353323
false
false
false
false
bryanrezende/Audiobook-Player
Carthage/Checkouts/DeckTransition/Source/DeckPresentationController.swift
1
27238
// // DeckPresentationController.swift // DeckTransition // // Created by Harshil Shah on 15/10/16. // Copyright © 2016 Harshil Shah. All rights reserved. // import UIKit /// Delegate that communicates to the `DeckPresentationController` whether the /// dismiss by pan gesture is enabled protocol DeckPresentationControllerDelegate { func isDismissGestureEnabled() -> Bool } /// A protocol to communicate to the transition that an update of the snapshot /// view is required. This is adopted only by the presentation controller public protocol DeckSnapshotUpdater { /// For various reasons (performance, the way iOS handles safe area, /// layout issues, etc.) this transition uses a snapshot view of your /// `presentingViewController` and not the live view itself. /// /// In some cases this snapshot might become outdated before the dismissal, /// and for those cases you can request to have the snapshot updated. While /// the transition only shows a small portion of the presenting view, in /// some cases that might become inconsistent enough to demand an update. /// /// This is an expensive process and should only be used if necessary, for /// example if you are updating your entire app's theme. func requestPresentedViewSnapshotUpdate() } final class DeckPresentationController: UIPresentationController, UIGestureRecognizerDelegate, DeckSnapshotUpdater { // MARK:- Internal variables var transitioningDelegate: DeckPresentationControllerDelegate? // MARK:- Private variables private var pan: UIPanGestureRecognizer? private let backgroundView = UIView() private let presentingViewSnapshotView = UIView() private let roundedViewForPresentingView = RoundedView() private let roundedViewForPresentedView = RoundedView() private var snapshotViewTopConstraint: NSLayoutConstraint? private var snapshotViewWidthConstraint: NSLayoutConstraint? private var snapshotViewAspectRatioConstraint: NSLayoutConstraint? private var presentedViewFrameObserver: NSKeyValueObservation? private var presentedViewTransformObserver: NSKeyValueObservation? private var presentAnimation: (() -> ())? = nil private var presentCompletion: ((Bool) -> ())? = nil private var dismissAnimation: (() -> ())? = nil private var dismissCompletion: ((Bool) -> ())? = nil // MARK:- Initializers convenience init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?, presentAnimation: (() -> ())? = nil, presentCompletion: ((Bool) ->())? = nil, dismissAnimation: (() -> ())? = nil, dismissCompletion: ((Bool) -> ())? = nil) { self.init(presentedViewController: presentedViewController, presenting: presentingViewController) self.presentAnimation = presentAnimation self.presentCompletion = presentCompletion self.dismissAnimation = dismissAnimation self.dismissCompletion = dismissCompletion NotificationCenter.default.addObserver(self, selector: #selector(updateForStatusBar), name: .UIApplicationDidChangeStatusBarFrame, object: nil) } // MARK:- Public methods public func requestPresentedViewSnapshotUpdate() { updateSnapshotView() } // MARK:- Sizing private var statusBarHeight: CGFloat { return UIApplication.shared.statusBarFrame.height } private var scaleForPresentingView: CGFloat { guard let containerView = containerView else { return 0 } return 1 - (ManualLayout.presentingViewTopInset * 2 / containerView.frame.height) } override var frameOfPresentedViewInContainerView: CGRect { guard let containerView = containerView else { return .zero } let yOffset = ManualLayout.presentingViewTopInset + Constants.insetForPresentedView return CGRect(x: 0, y: yOffset, width: containerView.bounds.width, height: containerView.bounds.height - yOffset) } // MARK:- Presentation override func presentationTransitionWillBegin() { guard let containerView = containerView, let window = containerView.window else { return } /// A CGRect to be used as a proxy for the frame of the presentingView /// /// The actual frame isn't used directly because in the case of the /// double height status bar on non-X iPhones, the containerView has a /// reduced height let initialFrame: CGRect = { if presentingViewController.isPresentedWithDeck { return presentingViewController.view.frame } else { return containerView.bounds } }() /// The presented view's rounded view's frame is updated using KVO roundedViewForPresentedView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(roundedViewForPresentedView) setupPresentedViewKVO() /// The snapshot view initially has the same frame as the presentingView containerView.insertSubview(presentingViewSnapshotView, belowSubview: presentedViewController.view) presentingViewSnapshotView.frame = initialFrame updateSnapshotView() /// The following transforms are performed on the snapshot view: /// 1. It's frame's origin is reset to 0. This is done because for /// recursive Deck modals, the reference frame will not have its /// origin at `.zero` /// 2. It is translated down by `ManualLayout.presentingViewTopInset` /// points This is the desired inset from the top of the /// containerView /// 3. It is scaled down by `scaleForPresentingView` along both axes, /// such that it's top edge is at the same position. In order to do /// this, we translate it up by half it's height, perform the /// scaling, and then translate it back down by the same amount let transformForSnapshotView = CGAffineTransform.identity .translatedBy(x: 0, y: -presentingViewSnapshotView.frame.origin.y) .translatedBy(x: 0, y: ManualLayout.presentingViewTopInset) .translatedBy(x: 0, y: -presentingViewSnapshotView.frame.height / 2) .scaledBy(x: scaleForPresentingView, y: scaleForPresentingView) .translatedBy(x: 0, y: presentingViewSnapshotView.frame.height / 2) /// For a recursive modal, the `presentingView` already has rounded /// corners so the animation must respect that roundedViewForPresentingView.backgroundColor = UIColor.black.withAlphaComponent(0) roundedViewForPresentingView.cornerRadius = presentingViewController.isPresentedWithDeck ? Constants.cornerRadius : 0 containerView.insertSubview(roundedViewForPresentingView, aboveSubview: presentingViewSnapshotView) roundedViewForPresentingView.frame = initialFrame /// The background view is used to cover up the `presentedView` backgroundView.backgroundColor = .black backgroundView.translatesAutoresizingMaskIntoConstraints = false containerView.insertSubview(backgroundView, belowSubview: presentingViewSnapshotView) NSLayoutConstraint.activate([ backgroundView.topAnchor.constraint(equalTo: window.topAnchor), backgroundView.leftAnchor.constraint(equalTo: window.leftAnchor), backgroundView.rightAnchor.constraint(equalTo: window.rightAnchor), backgroundView.bottomAnchor.constraint(equalTo: window.bottomAnchor) ]) /// A snapshot view is used to represent the hierarchy of cards in the /// case of recursive presentation var rootSnapshotView: UIView? var rootSnapshotRoundedView: RoundedView? if presentingViewController.isPresentedWithDeck { guard let rootController = presentingViewController.presentingViewController, let snapshotView = rootController.view.snapshotView(afterScreenUpdates: false) else { return } containerView.insertSubview(snapshotView, aboveSubview: backgroundView) snapshotView.frame = initialFrame snapshotView.transform = transformForSnapshotView snapshotView.alpha = Constants.alphaForPresentingView rootSnapshotView = snapshotView let snapshotRoundedView = RoundedView() snapshotRoundedView.cornerRadius = Constants.cornerRadius containerView.insertSubview(snapshotRoundedView, aboveSubview: snapshotView) snapshotRoundedView.frame = initialFrame snapshotRoundedView.transform = transformForSnapshotView rootSnapshotRoundedView = snapshotRoundedView } presentedViewController.transitionCoordinator?.animate( alongsideTransition: { [unowned self] context in self.presentAnimation?() self.presentingViewSnapshotView.transform = transformForSnapshotView self.roundedViewForPresentingView.cornerRadius = Constants.cornerRadius self.roundedViewForPresentingView.transform = transformForSnapshotView self.roundedViewForPresentingView.backgroundColor = UIColor.black.withAlphaComponent(1 - Constants.alphaForPresentingView) }, completion: { _ in rootSnapshotView?.removeFromSuperview() rootSnapshotRoundedView?.removeFromSuperview() } ) } /// Method to ensure the layout is as required at the end of the /// presentation. This is required in case the modal is presented without /// animation. /// /// The various layout related functions performed by this method are: /// - Ensure that the view is in the same state as it would be after /// animated presentation /// - Create and add the `presentingViewSnapshotView` to the view hierarchy /// - Add a black background view to present to complete cover the /// `presentingViewController`'s view /// - Reset the `presentingViewController`'s view's `transform` so that /// further layout updates (such as status bar update) do not break the /// transform /// /// It also sets up the gesture recognizer to handle dismissal of the modal /// view controller by panning downwards override func presentationTransitionDidEnd(_ completed: Bool) { guard let containerView = containerView else { return } presentedViewController.view.frame = frameOfPresentedViewInContainerView presentingViewSnapshotView.transform = .identity presentingViewSnapshotView.translatesAutoresizingMaskIntoConstraints = false presentingViewSnapshotView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true updateSnapshotViewAspectRatio() roundedViewForPresentingView.transform = .identity roundedViewForPresentingView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ roundedViewForPresentingView.topAnchor.constraint(equalTo: presentingViewSnapshotView.topAnchor), roundedViewForPresentingView.leftAnchor.constraint(equalTo: presentingViewSnapshotView.leftAnchor), roundedViewForPresentingView.rightAnchor.constraint(equalTo: presentingViewSnapshotView.rightAnchor), roundedViewForPresentingView.bottomAnchor.constraint(equalTo: presentingViewSnapshotView.bottomAnchor) ]) pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) pan!.delegate = self pan!.maximumNumberOfTouches = 1 pan!.cancelsTouchesInView = false presentedViewController.view.addGestureRecognizer(pan!) presentCompletion?(completed) } // MARK:- Layout update methods /// This method updates the aspect ratio of the snapshot view /// /// The `snapshotView`'s aspect ratio needs to be updated here because even /// though it is updated with the `snapshotView` in `viewWillTransition:`, /// the transition is janky unless it's updated before, hence it's performed /// here as well, It's also an inexpensive method since constraints are /// modified only when a change is actually needed override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() updateSnapshotViewAspectRatio() containerView?.bringSubview(toFront: roundedViewForPresentedView) UIView.animate(withDuration: 0.1) { [weak self] in guard let `self` = self else { return } self.presentedViewController.view.frame = self.frameOfPresentedViewInContainerView } } /// Method to handle the modal setup's response to a change in /// orientation, size, etc. /// /// Everything else is handled by AutoLayout or `willLayoutSubviews`; the /// express purpose of this method is to update the snapshot view since that /// is a relatively expensive operation and only makes sense on orientation /// change override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate( alongsideTransition: nil, completion: { [weak self] _ in self?.updateSnapshotViewAspectRatio() self?.updateSnapshotView() } ) } /// Method to handle updating the view when the status bar's height changes /// /// The `containerView`'s frame is always supposed to be the go 20 pixels /// or 1 normal status bar height under the status bar itself, even when the /// status bar is of double height, to retain consistency with the system's /// default behaviour /// /// The containerView is the only thing that received layout updates; /// AutoLayout and the snapshotView method handle the rest. Additionally, /// the mask for the `presentedViewController` is also reset @objc private func updateForStatusBar() { guard let containerView = containerView else { return } /// The `presentingViewController.view` often animated "before" the mask /// view that should fully cover it, so it's hidden before altering the /// view hierarchy, and then revealed after the animations are finished presentingViewController.view.alpha = 0 let fullHeight = containerView.window!.frame.size.height let currentHeight = containerView.frame.height let newHeight = fullHeight - ManualLayout.containerViewTopInset UIView.animate( withDuration: 0.1, animations: { containerView.frame.origin.y -= newHeight - currentHeight }, completion: { [weak self] _ in self?.presentingViewController.view.alpha = 1 containerView.frame = CGRect(x: 0, y: ManualLayout.containerViewTopInset, width: containerView.frame.width, height: newHeight) self?.updateSnapshotView() } ) } // MARK:- Snapshot view update methods /// Method to update the snapshot view showing a representation of the /// `presentingViewController`'s view /// /// The method can only be fired when the snapshot view has been set up, and /// then only when the width of the container is updated /// /// It resets the aspect ratio constraint for the snapshot view first, and /// then generates a new snapshot of the `presentingViewController`'s view, /// and then replaces the existing snapshot with it private func updateSnapshotView() { if let snapshotView = presentingViewController.view.snapshotView(afterScreenUpdates: true) { presentingViewSnapshotView.subviews.forEach { $0.removeFromSuperview() } snapshotView.translatesAutoresizingMaskIntoConstraints = false presentingViewSnapshotView.addSubview(snapshotView) NSLayoutConstraint.activate([ snapshotView.topAnchor.constraint(equalTo: presentingViewSnapshotView.topAnchor), snapshotView.leftAnchor.constraint(equalTo: presentingViewSnapshotView.leftAnchor), snapshotView.rightAnchor.constraint(equalTo: presentingViewSnapshotView.rightAnchor), snapshotView.bottomAnchor.constraint(equalTo: presentingViewSnapshotView.bottomAnchor) ]) } } /// Thie method updates the aspect ratio and the height of the snapshot view /// used to represent the presenting view controller. /// /// The aspect ratio is only updated when the width of the container changes /// i.e. when just the status bar moves, nothing happens private func updateSnapshotViewAspectRatio() { guard let containerView = containerView, presentingViewSnapshotView.translatesAutoresizingMaskIntoConstraints == false else { return } snapshotViewTopConstraint?.isActive = false snapshotViewWidthConstraint?.isActive = false snapshotViewAspectRatioConstraint?.isActive = false let snapshotReferenceSize = presentingViewController.view.frame.size let topInset = ManualLayout.presentingViewTopInset let aspectRatio = snapshotReferenceSize.width / snapshotReferenceSize.height roundedViewForPresentingView.cornerRadius = Constants.cornerRadius * scaleForPresentingView snapshotViewTopConstraint = presentingViewSnapshotView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: topInset) snapshotViewWidthConstraint = presentingViewSnapshotView.widthAnchor.constraint(equalTo: containerView.widthAnchor, multiplier: scaleForPresentingView) snapshotViewAspectRatioConstraint = presentingViewSnapshotView.widthAnchor.constraint(equalTo: presentingViewSnapshotView.heightAnchor, multiplier: aspectRatio) snapshotViewTopConstraint?.isActive = true snapshotViewWidthConstraint?.isActive = true snapshotViewAspectRatioConstraint?.isActive = true } // MARK:- Presented view KVO + Rounded view update methods private func setupPresentedViewKVO() { presentedViewFrameObserver = presentedViewController.view.observe(\.frame, options: [.initial]) { [weak self] _, _ in self?.presentedViewWasUpdated() } presentedViewTransformObserver = presentedViewController.view.observe(\.transform, options: [.initial]) { [weak self] _, _ in self?.presentedViewWasUpdated() } } private func invalidatePresentedViewKVO() { presentedViewFrameObserver = nil presentedViewTransformObserver = nil } private func presentedViewWasUpdated() { let offset = presentedViewController.view.frame.origin.y roundedViewForPresentedView.frame = CGRect(x: 0, y: offset, width: containerView!.bounds.width, height: Constants.cornerRadius) } // MARK:- Dismissal /// Method to prepare the view hirarchy for the dismissal animation /// /// The stuff with snapshots and the black background should be invisible to /// the dismissal animation, so this method effectively removes them and /// restores the state of the `presentingViewController`'s view to the /// expected state at the end of the presenting animation override func dismissalTransitionWillBegin() { guard let containerView = containerView else { return } let initialFrame: CGRect = { if presentingViewController.isPresentedWithDeck { return presentingViewController.view.frame } else { return containerView.bounds } }() let initialTransform = CGAffineTransform.identity .translatedBy(x: 0, y: -initialFrame.origin.y) .translatedBy(x: 0, y: ManualLayout.presentingViewTopInset) .translatedBy(x: 0, y: -initialFrame.height / 2) .scaledBy(x: scaleForPresentingView, y: scaleForPresentingView) .translatedBy(x: 0, y: initialFrame.height / 2) roundedViewForPresentingView.translatesAutoresizingMaskIntoConstraints = true roundedViewForPresentingView.frame = initialFrame roundedViewForPresentingView.transform = initialTransform snapshotViewTopConstraint?.isActive = false snapshotViewWidthConstraint?.isActive = false snapshotViewAspectRatioConstraint?.isActive = false presentingViewSnapshotView.translatesAutoresizingMaskIntoConstraints = true presentingViewSnapshotView.frame = initialFrame presentingViewSnapshotView.transform = initialTransform let finalCornerRadius = presentingViewController.isPresentedWithDeck ? Constants.cornerRadius : 0 let finalTransform: CGAffineTransform = .identity var rootSnapshotView: UIView? var rootSnapshotRoundedView: RoundedView? if presentingViewController.isPresentedWithDeck { guard let rootController = presentingViewController.presentingViewController, let snapshotView = rootController.view.snapshotView(afterScreenUpdates: false) else { return } containerView.insertSubview(snapshotView, aboveSubview: backgroundView) snapshotView.frame = initialFrame snapshotView.transform = initialTransform rootSnapshotView = snapshotView let snapshotRoundedView = RoundedView() snapshotRoundedView.cornerRadius = Constants.cornerRadius snapshotRoundedView.backgroundColor = UIColor.black.withAlphaComponent(1 - Constants.alphaForPresentingView) containerView.insertSubview(snapshotRoundedView, aboveSubview: snapshotView) snapshotRoundedView.frame = initialFrame snapshotRoundedView.transform = initialTransform rootSnapshotRoundedView = snapshotRoundedView } presentedViewController.transitionCoordinator?.animate( alongsideTransition: { [unowned self] context in self.dismissAnimation?() self.presentingViewSnapshotView.transform = finalTransform self.roundedViewForPresentingView.transform = finalTransform self.roundedViewForPresentingView.cornerRadius = finalCornerRadius self.roundedViewForPresentingView.backgroundColor = .clear }, completion: { _ in rootSnapshotView?.removeFromSuperview() rootSnapshotRoundedView?.removeFromSuperview() } ) } /// Method to ensure the layout is as required at the end of the dismissal. /// This is required in case the modal is dismissed without animation. override func dismissalTransitionDidEnd(_ completed: Bool) { guard let containerView = containerView else { return } backgroundView.removeFromSuperview() presentingViewSnapshotView.removeFromSuperview() roundedViewForPresentingView.removeFromSuperview() let offscreenFrame = CGRect(x: 0, y: containerView.bounds.height, width: containerView.bounds.width, height: containerView.bounds.height) presentedViewController.view.frame = offscreenFrame presentedViewController.view.transform = .identity invalidatePresentedViewKVO() dismissCompletion?(completed) } // MARK:- Gesture handling @objc private func handlePan(gestureRecognizer: UIPanGestureRecognizer) { guard gestureRecognizer.isEqual(pan) else { return } switch gestureRecognizer.state { case .began: gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: containerView) case .changed: if let view = presentedView { /// The dismiss gesture needs to be enabled for the pan gesture /// to do anything. if transitioningDelegate?.isDismissGestureEnabled() ?? false { let translation = gestureRecognizer.translation(in: view) updatePresentedViewForTranslation(inVerticalDirection: translation.y) } else { gestureRecognizer.setTranslation(.zero, in: view) } } case .ended: UIView.animate( withDuration: 0.25, animations: { self.presentedView?.transform = .identity } ) default: break } } /// Method to update the modal view for a particular amount of translation /// by panning in the vertical direction. /// /// The translation of the modal view is proportional to the panning /// distance until the `elasticThreshold`, after which it increases at a /// slower rate, given by `elasticFactor`, to indicate that the /// `dismissThreshold` is nearing. /// /// Once the `dismissThreshold` is reached, the modal view controller is /// dismissed. /// /// - parameter translation: The translation of the user's pan gesture in /// the container view in the vertical direction private func updatePresentedViewForTranslation(inVerticalDirection translation: CGFloat) { let elasticThreshold: CGFloat = 120 let dismissThreshold: CGFloat = 240 let translationFactor: CGFloat = 1/2 /// Nothing happens if the pan gesture is performed from bottom /// to top i.e. if the translation is negative if translation >= 0 { let translationForModal: CGFloat = { if translation >= elasticThreshold { let frictionLength = translation - elasticThreshold let frictionTranslation = 30 * atan(frictionLength/120) + frictionLength/10 return frictionTranslation + (elasticThreshold * translationFactor) } else { return translation * translationFactor } }() presentedView?.transform = CGAffineTransform(translationX: 0, y: translationForModal) if translation >= dismissThreshold { presentedViewController.dismiss(animated: true, completion: nil) } } } // MARK: - UIGestureRecognizerDelegate methods func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer.isEqual(pan) else { return false } return true } } fileprivate extension UIViewController { /// A Boolean value indicating whether the view controller is presented /// using Deck. var isPresentedWithDeck: Bool { return transitioningDelegate is DeckTransitioningDelegate && modalPresentationStyle == .custom && presentingViewController != nil } }
gpl-3.0
0f2842d48268b65db57495c96c40f4ee
43.001616
275
0.692514
5.744991
false
false
false
false
Dsringari/scan4pase
Project/scan4pase/ProductCell.swift
1
1142
// // ProductCell.swift // scan4pase // // Created by Dhruv Sringari on 7/5/16. // Copyright © 2016 Dhruv Sringari. All rights reserved. // import UIKit class ProductCell: UITableViewCell { @IBOutlet var name: UILabel! @IBOutlet var sku: UILabel! @IBOutlet var pvBV: UILabel! @IBOutlet var retailCost: UILabel! @IBOutlet var iboCost: UILabel! func load(withProduct product: Product) { let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 formatter.minimumIntegerDigits = 1 name.text = product.name sku.text = product.sku pvBV.text = formatter.string(from: product.pv!)! + "/" + formatter.string(from: product.bv!)! formatter.numberStyle = .currency retailCost.text = formatter.string(from: product.retailCost!) iboCost.text = formatter.string(from: product.iboCost!) if product.custom!.boolValue { sku.textColor = UIColor(red: 97, green: 188, blue: 109) } else { sku.textColor = UIColor(red: 43, green: 130, blue: 201) } } }
apache-2.0
9902ff7693db23abf7a4e8bbcc6e1403
31.6
101
0.645048
3.920962
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/AwesomeData/AwesomeCoreParser.swift
1
4919
// // AwesomeCoreParser.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 6/2/16. // Copyright © 2016 It's Day Off. All rights reserved. // import UIKit open class AwesomeCoreParser: NSObject { /** It parses the Data object on **the main thread and you must wait** the result. ## Important Notes ## * If something goes wrong you receive **nil** as result. */ public static func jsonObject(_ data: Data?) -> AnyObject?{ if let data = data { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) return json as AnyObject? } catch { print("error serializing JSON: \(error)") } } return nil } /** It parses the Data object on a worker thread and bounces the result back to the main thread. ## Important Notes ## * If something goes wrong **nil** is returned on the success block. */ public static func jsonObjectAsync(_ data: Data?, success: @escaping (_ jsonObject: AnyObject?) -> Void) { if let data = data { DispatchQueue.global(qos: .default).async { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject? // Bounce back to the main thread to update the UI DispatchQueue.main.async { success(json) } } catch { print("error serializing JSON: \(error)") DispatchQueue.main.async { success(nil) } } } } } public static func doubleValue(_ jsonObject: [String: Any], key: String) -> Double{ if let value = jsonObject[key] as? Double { return value }else if let value = jsonObject[key] as? String { return Double(value.trimmed) ?? 0 }else if let array = jsonObject[key] as? [String] { return Double(array[0].trimmed) ?? 0 } return 0 } public static func intValue(_ jsonObject: [String: Any], key: String) -> Int{ if let value = jsonObject[key] as? Int { return value }else if let value = jsonObject[key] as? String { return Int(value.trimmed) ?? 0 }else if let array = jsonObject[key] as? [String] { return Int(array[0].trimmed) ?? 0 } return 0 } public static func boolValue(_ jsonObject: [String: Any], key: String) -> Bool{ if let value = jsonObject[key] as? Bool { return value }else if let value = jsonObject[key] as? String { return value.trimmed.toBool() ?? false }else if let array = jsonObject[key] as? [String] { return array[0].trimmed.toBool() ?? false } return false } public static func stringValue(_ jsonObject: [String: Any], key: String) -> String{ if let value = jsonObject[key] as? String { return value }else if let array = jsonObject[key] as? [String] { return array[0] }else if let object = jsonObject[key] { return "\(object)".removeNull() } return "" } public static func stringValues(_ jsonObject: [String: Any], key: String) -> [String] { if let value = jsonObject[key] as? [String] { return value } return [] } public static func dateValue(_ jsonObject: [String: Any], key: String, format: String = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") -> Date?{ let dateString = stringValue(jsonObject, key: key) let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: dateString) } public static func propertyNamesOfObject(_ object: Any) -> [String] { return Mirror(reflecting: object).children.filter { $0.label != nil }.map { $0.label! } } public static func propertyNamesOfClass(_ theClass: Any) -> [String] { return Mirror(reflecting: theClass).children.filter { $0.label != nil }.map { $0.label! } } } extension String { func toBool() -> Bool? { switch self { case "True", "true", "yes", "1": return true case "False", "false", "no", "0": return false default: return nil } } func removeNull() -> String{ if self == "<null>"{ return "" } return self } var trimmed: String{ return self.replacingOccurrences(of: " ", with: "") } }
mit
d553b94b9c4cce857fe0fb47d8cfe297
30.729032
131
0.52745
4.674905
false
false
false
false
werediver/parser
Sources/ParserCore/CountLimit.swift
2
1223
public enum CountLimit { case atLeast(Int) case atMost(Int) case times(Int, Int) public static func exactly(_ count: Int) -> CountLimit { return .times(count, count) } public func extends(past count: Int) -> Bool { switch self { case .atLeast: return true case let .atMost(atMost): return count < atMost case let .times(_, atMost): return count < atMost } } public func contains(_ count: Int) -> Bool { switch self { case let .atLeast(atLeast): return atLeast <= count case let .atMost(atMost): return count <= atMost case let .times(atLeast, atMost): return atLeast <= count && count <= atMost } } } extension CountLimit: CustomStringConvertible { public var description: String { switch self { case let .atLeast(atLeast): return "at least \(atLeast)" case let .atMost(atMost): return "at most \(atMost)" case let .times(atLeast, atMost): return atLeast != atMost ? "\(atLeast) to \(atMost)" : "exactly \(atLeast)" } } }
mit
18788522b2833c77bdc084217ab39b11
25.586957
87
0.537204
4.703846
false
false
false
false
LogTape/LogTape-iOS
LogTape/Classes/LogTapeVideoRecorder.swift
1
10104
// // LogTapeVideoRecorder.swift // Pods // // Created by Dan Nilsson on 2017-06-13. // // import Foundation import AVKit import AVFoundation class LogTapeVideoWriter : NSObject { var path : String? = nil var writerInput : AVAssetWriterInput? = nil var adaptor : AVAssetWriterInputPixelBufferAdaptor? = nil var curFrame = 0 var onCompleted : ((_ path : String?) -> ())? = nil var videoWriter : AVAssetWriter? = nil var videoSize = CGSize.zero var frames : [UIImage] init(onCompleted : @escaping ((_ path : String?) -> ()), size : CGSize, frames : [UIImage]) { self.onCompleted = onCompleted self.frames = frames self.videoSize = size } func startWriting() { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let path = documentsPath + "/out.mp4" let url = URL(fileURLWithPath: path) self.path = path let fileManager = FileManager.default do { if fileManager.isReadableFile(atPath: path) { try fileManager.removeItem(atPath: path) } let videoWriter = try AVAssetWriter(outputURL: url, fileType: convertToAVFileType("public.mpeg-4")) let videoSettings : [String : AnyObject] = [ AVVideoCodecKey : AVVideoCodecH264 as AnyObject, AVVideoWidthKey : videoSize.width as AnyObject, AVVideoHeightKey : videoSize.height as AnyObject ] let writerInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings) let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: nil) videoWriter.add(writerInput) videoWriter.startWriting() videoWriter.startSession(atSourceTime: CMTime.zero) self.videoWriter = videoWriter self.writerInput = writerInput self.adaptor = adaptor writerInput.addObserver(self, forKeyPath: "readyForMoreMediaData", options: [.initial, .new], context: nil) } catch _ { onCompleted?(nil) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { DispatchQueue.main.async { () -> Void in guard let writerInput = self.writerInput, let adaptor = self.adaptor, let videoWriter = self.videoWriter , self.frames.count > 0 else { return } while writerInput.isReadyForMoreMediaData { let frame = self.frames.removeFirst() var pixelbuffer: CVPixelBuffer? = nil CVPixelBufferCreate(kCFAllocatorDefault, Int(self.videoSize.width), Int(self.videoSize.height), kCVPixelFormatType_32ARGB, nil, &pixelbuffer) CVPixelBufferLockBaseAddress(pixelbuffer!, CVPixelBufferLockFlags(rawValue:0)) let colorspace = CGColorSpaceCreateDeviceRGB() let pixelBufferBase = CVPixelBufferGetBaseAddress(pixelbuffer!) let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelbuffer!) guard let bitmapContext = CGContext(data: pixelBufferBase, width: Int(self.videoSize.width), height: Int(self.videoSize.height), bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorspace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else { print("Failed to create bitmap context") DispatchQueue.main.async { self.onCompleted?(nil) } return } bitmapContext.draw(frame.cgImage!, in: CGRect(x: 0, y: 0, width: self.videoSize.width, height: self.videoSize.height)) let time = CMTimeMake(value: 10 * Int64(self.curFrame * LogTapeVideoRecorder.FPSPeriod), timescale: 600) if let pixelbuffer = pixelbuffer { adaptor.append(pixelbuffer, withPresentationTime: time) } self.curFrame += 1 if self.frames.count == 0 { writerInput.markAsFinished() writerInput.removeObserver(self, forKeyPath: "readyForMoreMediaData") videoWriter.finishWriting { DispatchQueue.main.async { self.onCompleted?(self.path) } } break } } } } } class LogTapeVideoRecorder : NSObject { var frames = [UIImage]() static let MaxNumFrames = 600 var captureFrameTimer : Foundation.Timer? = nil static let FPSPeriod = 4 static var CaptureInterval : TimeInterval { return 1.0 / (60.0 / TimeInterval(LogTapeVideoRecorder.FPSPeriod)) } static let TouchStrokeColor = UIColor.red static let TouchFillColor = UIColor.red.withAlphaComponent(0.4) static let TouchCircleSize = CGFloat(30.0) func start() { self.frames = [] self.captureFrameTimer = Foundation.Timer(timeInterval: LogTapeVideoRecorder.CaptureInterval, target: self, selector: #selector(LogTapeVideoRecorder.captureFrame), userInfo: nil, repeats: true) RunLoop.current.add(captureFrameTimer!, forMode: RunLoop.Mode.common) } func clear() { self.stop() self.frames = [] } func stop() { self.captureFrameTimer?.invalidate() self.captureFrameTimer = nil } deinit { self.captureFrameTimer?.invalidate() self.captureFrameTimer = nil } func handleTouch(_ touch : UITouch) { guard let window = touch.window, let lastFrame = self.frames.last else { return } // On each touch grab the latest captured frame and overlay the touch location // using a circle let screenSize = UIScreen.main.bounds.size let frameSize = self.frameSizeFromScreenSize(screenSize) let frameBounds = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height) UIGraphicsBeginImageContextWithOptions(frameSize, false, 1.0) guard let context = UIGraphicsGetCurrentContext() else { return } let touchLocation = touch.location(in: window) let ratio = screenSize.width / frameSize.width let locationInFrame = CGPoint(x : touchLocation.x / ratio, y : touchLocation.y / ratio) context.setStrokeColor(UIColor.black.cgColor) lastFrame.draw(in: frameBounds) context.setStrokeColor(LogTapeVideoRecorder.TouchStrokeColor.cgColor) context.setFillColor(LogTapeVideoRecorder.TouchFillColor.cgColor) let touchCircleOffset = LogTapeVideoRecorder.TouchCircleSize / 2.0 let touchCircleRect = CGRect(x: locationInFrame.x - touchCircleOffset, y: locationInFrame.y - touchCircleOffset, width: LogTapeVideoRecorder.TouchCircleSize, height: LogTapeVideoRecorder.TouchCircleSize) context.fillEllipse(in: touchCircleRect) context.strokeEllipse(in: touchCircleRect) let overlaidFrame = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() self.frames.removeLast() self.frames.append(overlaidFrame!) } @objc func captureFrame() { guard let window = UIApplication.shared.keyWindow else { return } let frameSize = self.frameSizeFromScreenSize(window.bounds.size) let frameBounds = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height); UIGraphicsBeginImageContextWithOptions(frameSize, false, 1.0) window.drawHierarchy(in: frameBounds, afterScreenUpdates: false) if let image = UIGraphicsGetImageFromCurrentImageContext() { self.frames.append(image) } UIGraphicsEndImageContext() if self.frames.count > LogTapeVideoRecorder.MaxNumFrames { self.frames.remove(at: 0) } } func frameSizeFromScreenSize(_ screenSize : CGSize) -> CGSize { let frameWidth = floor(min(screenSize.width, 512) / 16.0) * 16.0 let aspectRatio = screenSize.width / frameWidth let frameHeight = ceil(screenSize.height / aspectRatio) return CGSize(width: frameWidth, height: frameHeight) } var writer : LogTapeVideoWriter? = nil func writeToFile(_ onCompleted : @escaping ((_ path : String?) -> ())) { self.captureFrameTimer?.invalidate() self.captureFrameTimer = nil self.writer = LogTapeVideoWriter(onCompleted : onCompleted, size : self.frameSizeFromScreenSize(UIScreen.main.bounds.size), frames : self.frames) self.writer?.startWriting() self.frames = [] } func duration() -> TimeInterval { return LogTapeVideoRecorder.CaptureInterval * TimeInterval(self.frames.count); } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToAVFileType(_ input: String) -> AVFileType { return AVFileType(rawValue: input) }
mit
20961e00919d151544fdfeb9d2bd057c
37.564885
268
0.586006
5.346032
false
false
false
false
king7532/TaylorSource
examples/Gallery/Pods/HanekeSwift/Haneke/UIImage+Haneke.swift
47
3156
// // UIImage+Haneke.swift // Haneke // // Created by Hermes Pique on 8/10/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit extension UIImage { func hnk_imageByScalingToSize(toSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(toSize, !hnk_hasAlpha(), 0.0) drawInRect(CGRectMake(0, 0, toSize.width, toSize.height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } func hnk_hasAlpha() -> Bool { let alpha = CGImageGetAlphaInfo(self.CGImage) switch alpha { case .First, .Last, .PremultipliedFirst, .PremultipliedLast, .Only: return true case .None, .NoneSkipFirst, .NoneSkipLast: return false } } func hnk_data(compressionQuality: Float = 1.0) -> NSData! { let hasAlpha = self.hnk_hasAlpha() let data = hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, CGFloat(compressionQuality)) return data } func hnk_decompressedImage() -> UIImage! { let originalImageRef = self.CGImage let originalBitmapInfo = CGImageGetBitmapInfo(originalImageRef) let alphaInfo = CGImageGetAlphaInfo(originalImageRef) // See: http://stackoverflow.com/questions/23723564/which-cgimagealphainfo-should-we-use var bitmapInfo = originalBitmapInfo switch (alphaInfo) { case .None: bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue) case .PremultipliedFirst, .PremultipliedLast, .NoneSkipFirst, .NoneSkipLast: break case .Only, .Last, .First: // Unsupported return self } let colorSpace = CGColorSpaceCreateDeviceRGB() let pixelSize = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale) if let context = CGBitmapContextCreate(nil, Int(ceil(pixelSize.width)), Int(ceil(pixelSize.height)), CGImageGetBitsPerComponent(originalImageRef), 0, colorSpace, bitmapInfo) { let imageRect = CGRectMake(0, 0, pixelSize.width, pixelSize.height) UIGraphicsPushContext(context) // Flip coordinate system. See: http://stackoverflow.com/questions/506622/cgcontextdrawimage-draws-image-upside-down-when-passed-uiimage-cgimage CGContextTranslateCTM(context, 0, pixelSize.height) CGContextScaleCTM(context, 1.0, -1.0) // UIImage and drawInRect takes into account image orientation, unlike CGContextDrawImage. self.drawInRect(imageRect) UIGraphicsPopContext() let decompressedImageRef = CGBitmapContextCreateImage(context) let scale = UIScreen.mainScreen().scale let image = UIImage(CGImage: decompressedImageRef, scale:scale, orientation:UIImageOrientation.Up) return image } else { return self } } }
mit
f291924071a582df32ee1fdb1a028214
38.45
183
0.646071
5.098546
false
false
false
false
zmcartor/CollectionView-Zoo
CollectionViewFun/ViewController.swift
1
2384
// // ViewController.swift // CollectionViewFun // // Created by Zach McArtor on 3/20/15. // Copyright (c) 2015 HackaZach. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var items:[String]! var numberOfSections = 1 override func viewDidLoad() { super.viewDidLoad() // Customize FlowLayoutClass let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSizeMake(50, 50) layout.headerReferenceSize = CGSizeMake(collectionView.bounds.size.width, 50) automaticallyAdjustsScrollViewInsets = false NSLog("Section inset : %@", NSStringFromUIEdgeInsets(layout.sectionInset)); items = [] for char in "abcdefghijklmnopqrstuvwxyz" { items.append("\(char)") } for char in "abcdefghijklmnopqrstuvwxyz" { items.append("\(char)") } for char in "abcdefghijklmnopqrstuvwxyz" { items.append("\(char)") } for char in "abcdefghijklmnopqrstuvwxyz" { items.append("\(char)") } if numberOfSections != 0 { collectionView.registerNib(UINib(nibName: "StickyHeader", bundle: nil), forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "header") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } } // FlowLayout expects delegate methods to be implemeted here extension ViewController : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell:CustomCellCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("customCell", forIndexPath: indexPath) as! CustomCellCollectionViewCell cell.letterLabel.text = items[indexPath.row] return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numberOfSections } }
mit
ef4864965d589a31b680bbdddb2a085c
30.786667
179
0.66401
5.945137
false
false
false
false
sungkipyung/CodeSample
SimpleCameraApp/SimpleCameraApp/CGPoint+Extensions.swift
1
5944
// // CGPoint+Extensions.swift // SimpleCameraApp // // Created by 성기평 on 2016. 4. 27.. // Copyright © 2016년 hothead. All rights reserved. // import Foundation import CoreGraphics public extension CGPoint { /** * Creates a new CGPoint given a CGVector. */ public init(vector: CGVector) { self.init(x: vector.dx, y: vector.dy) } public func midOfPoint(_ other: CGPoint) -> CGPoint{ return CGPoint(x: 0.5 * (x + other.x), y: 0.5 * (y + other.y)) } /** * Given an angle in radians, creates a vector of length 1.0 and returns the * result as a new CGPoint. An angle of 0 is assumed to point to the right. */ public init(angle: CGFloat) { self.init(x: cos(angle), y: sin(angle)) } /** * Adds (dx, dy) to the point. */ public mutating func offset(dx: CGFloat, dy: CGFloat) -> CGPoint { x += dx y += dy return self } /** * Returns the length (magnitude) of the vector described by the CGPoint. */ public func length() -> CGFloat { return sqrt(x*x + y*y) } /** * Returns the squared length of the vector described by the CGPoint. */ public func lengthSquared() -> CGFloat { return x*x + y*y } /** * Normalizes the vector described by the CGPoint to length 1.0 and returns * the result as a new CGPoint. */ func normalized() -> CGPoint { let len = length() return len>0 ? self / len : CGPoint.zero } /** * Normalizes the vector described by the CGPoint to length 1.0. */ public mutating func normalize() -> CGPoint { self = normalized() return self } /** * Calculates the distance between two CGPoints. Pythagoras! */ public func distanceTo(_ point: CGPoint) -> CGFloat { return (self - point).length() } /** * Returns the angle in radians of the vector described by the CGPoint. * The range of the angle is -π to π; an angle of 0 points to the right. */ public var angle: CGFloat { return atan2(y, x) } } /** * Adds two CGPoint values and returns the result as a new CGPoint. */ public func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } /** * Increments a CGPoint with the value of another. */ public func += (left: inout CGPoint, right: CGPoint) { left = left + right } /** * Adds a CGVector to this CGPoint and returns the result as a new CGPoint. */ public func + (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x + right.dx, y: left.y + right.dy) } /** * Increments a CGPoint with the value of a CGVector. */ public func += (left: inout CGPoint, right: CGVector) { left = left + right } /** * Subtracts two CGPoint values and returns the result as a new CGPoint. */ public func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } /** * Decrements a CGPoint with the value of another. */ public func -= (left: inout CGPoint, right: CGPoint) { left = left - right } /** * Subtracts a CGVector from a CGPoint and returns the result as a new CGPoint. */ public func - (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x - right.dx, y: left.y - right.dy) } /** * Decrements a CGPoint with the value of a CGVector. */ public func -= (left: inout CGPoint, right: CGVector) { left = left - right } /** * Multiplies two CGPoint values and returns the result as a new CGPoint. */ public func * (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x * right.x, y: left.y * right.y) } /** * Multiplies a CGPoint with another. */ public func *= (left: inout CGPoint, right: CGPoint) { left = left * right } /** * Multiplies the x and y fields of a CGPoint with the same scalar value and * returns the result as a new CGPoint. */ public func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /** * Multiplies the x and y fields of a CGPoint with the same scalar value. */ public func *= (point: inout CGPoint, scalar: CGFloat) { point = point * scalar } /** * Multiplies a CGPoint with a CGVector and returns the result as a new CGPoint. */ public func * (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x * right.dx, y: left.y * right.dy) } /** * Multiplies a CGPoint with a CGVector. */ public func *= (left: inout CGPoint, right: CGVector) { left = left * right } /** * Divides two CGPoint values and returns the result as a new CGPoint. */ public func / (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x / right.x, y: left.y / right.y) } /** * Divides a CGPoint by another. */ public func /= (left: inout CGPoint, right: CGPoint) { left = left / right } /** * Divides the x and y fields of a CGPoint by the same scalar value and returns * the result as a new CGPoint. */ public func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } /** * Divides the x and y fields of a CGPoint by the same scalar value. */ public func /= (point: inout CGPoint, scalar: CGFloat) { point = point / scalar } /** * Divides a CGPoint by a CGVector and returns the result as a new CGPoint. */ public func / (left: CGPoint, right: CGVector) -> CGPoint { return CGPoint(x: left.x / right.dx, y: left.y / right.dy) } /** * Divides a CGPoint by a CGVector. */ public func /= (left: inout CGPoint, right: CGVector) { left = left / right } /** * Performs a linear interpolation between two CGPoint values. */ public func lerp(start: CGPoint, end: CGPoint, t: CGFloat) -> CGPoint { return start + (end - start) * t }
apache-2.0
b0d9ae7fab455417c5406407799f5194
24.246809
80
0.621271
3.628746
false
false
false
false
jakubholik/mi-ios
mi-ios/UIImageExtension.swift
1
2507
// // UIImageExtension.swift // Vacation 360 // // Created by Jakub Holík on 05.03.17. // Copyright © 2017 RayWenderlich. All rights reserved. // import Foundation extension UIImage{ //Crop the left part func cropLeftImage(image: UIImage, withPercentage percentage: CGFloat) -> UIImage { //first part let width = CGFloat(image.size.width * image.scale * percentage) let rect = CGRect(x: 0, y: 0, width: width, height: image.size.height*image.scale) return cropImage(image: image, toRect: rect) } // Crop the right part func cropRightImage(image: UIImage, withPercentage percentage: CGFloat) -> UIImage { let width = CGFloat(image.size.width * image.scale * percentage) let rect = CGRect(x: image.size.width * image.scale - width, y: 0, width: width, height: image.size.height*image.scale) return cropImage(image: image, toRect: rect) } func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{ let imageRef:CGImage = image.cgImage!.cropping(to: rect)! let croppedImage:UIImage = UIImage(cgImage:imageRef) return croppedImage } func imageByCombiningImage(firstImage: UIImage, withImage secondImage: UIImage) -> UIImage { let newImageWidth = firstImage.size.width + secondImage.size.width let newImageHeight = firstImage.size.height let newImageSize = CGSize(width : newImageWidth, height: newImageHeight) UIGraphicsBeginImageContextWithOptions(newImageSize, false, 1.0) let firstImageDrawX = CGFloat(0) let firstImageDrawY = CGFloat(0) let secondImageDrawX = firstImage.size.width let secondImageDrawY = CGFloat(0) firstImage .draw(at: CGPoint(x: firstImageDrawX, y: firstImageDrawY)) secondImage.draw(at: CGPoint(x: secondImageDrawX, y: secondImageDrawY)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } func repositionImage(basedOn cardinalPercentage: CGFloat)->UIImage { return self var correctPercentage = cardinalPercentage if (correctPercentage - 0.5) < 0 { correctPercentage += 0.5 } else { correctPercentage -= 0.5 } if cardinalPercentage == 0 || cardinalPercentage == 1{ correctPercentage = 0.5 } let leftSide = self.cropLeftImage(image: self, withPercentage: correctPercentage) let rightSide = self.cropRightImage(image: self, withPercentage: CGFloat(1-correctPercentage)) //return rightSide return self.imageByCombiningImage(firstImage: rightSide, withImage: leftSide) } }
mit
734f7ac538dc1293187aa23dbaffb644
28.127907
121
0.730938
3.640988
false
false
false
false
remind101/AutoGraph
AutoGraphTests/Requests/AllFilmsRequest.swift
1
2414
@testable import AutoGraphQL import Foundation import JSONValueRX class AllFilmsRequest: Request { /* query allFilms { film(id: "ZmlsbXM6MQ==") { id title episodeID director openingCrawl } } */ let queryDocument = Operation(type: .query, name: "allFilms", selectionSet: [ Object(name: "allFilms", arguments: nil, selectionSet: [ Object(name: "films", alias: nil, arguments: nil, selectionSet: [ "id", Scalar(name: "title", alias: nil), Scalar(name: "episodeID", alias: nil), Scalar(name: "director", alias: nil), Scalar(name: "openingCrawl", alias: nil)]) ]) ]) let variables: [AnyHashable : Any]? = nil let rootKeyPath: String = "data.allFilms.films" public func willSend() throws { } public func didFinishRequest(response: HTTPURLResponse?, json: JSONValue) throws { } public func didFinish(result: AutoGraphResult<[Film]>) throws { } } class AllFilmsStub: Stub { override var jsonFixtureFile: String? { get { return "AllFilms" } set { } } override var urlPath: String? { get { return "/graphql" } set { } } override var graphQLQuery: String { get { return "query allFilms {\n" + "allFilms {\n" + "films {\n" + "id\n" + "title\n" + "episodeID\n" + "director\n" + "openingCrawl\n" + "}\n" + "}\n" + "}\n" } set { } } }
mit
0ee8ad20927f1a6136c7e67bf4c27723
32.068493
94
0.349213
5.747619
false
false
false
false
rbailoni/SOSHospital
SOSHospital/SOSHospital/CLLocationManagerExtension.swift
1
2295
// // CLLocationManagerExtension.swift // SOSHospital // // Created by William kwong huang on 04/11/15. // Copyright © 2015 Quaddro. All rights reserved. // import UIKit import CoreLocation extension CLLocationManager { func requestAuthorization() -> Bool { var isAuthorization = false // Verifica se o serviço de localização está habilitado if CLLocationManager.locationServicesEnabled() { //locationManager = CLLocationManager() //self.locationManager?.delegate = self switch CLLocationManager.authorizationStatus() { // AuthorizedAlways: usuário permitiu sempre // AuthorizedWhenInUse: usuário permitiu quando app aberto case .AuthorizedAlways, .AuthorizedWhenInUse: isAuthorization = true self.desiredAccuracy = kCLLocationAccuracyHundredMeters self.requestAlwaysAuthorization() self.startUpdatingLocation() break // NotDetermined: usuário ainda não escolheu autorizar case .NotDetermined: self.requestWhenInUseAuthorization() break // Restricted: usuário tem restrição para ligar a localização // Denied: usuário negou a localização case .Restricted, .Denied: print("usuário negou a localização") break } } return isAuthorization } func showNegativeAlert() -> UIAlertController { let alerta = UIAlertController( title: "Localização Negada", message: "Habilite a localização em Ajustes > Privacidade > Serv. Localização", preferredStyle: .Alert ) alerta.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil)) alerta.addAction(UIAlertAction(title: "Ir para Ajustes", style: .Default) { action in let _ = UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } ) return alerta } }
mit
db1d796da73e56bae54bebac68e163a4
31.884058
113
0.576025
5.46747
false
false
false
false
eh1255/RedBallTracking
RedBallTrackingiOS/RedBallTrackingiOS/ViewController.swift
1
1730
// // ViewController.swift // RedBallTrackingiOS // // Created by Erik Hornberger on 2016/06/18. // Copyright © 2016年 EExT. All rights reserved. // import UIKit import MZFormSheetPresentationController class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var settingsButton: UIButton! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Starting the camera immediately in viewDidLoad, so I just tossed in a delay to give the views time to load up // You could do it in viewDidAppear as well, but that can get called multiple times. This solution doesn't require any extra variables performSelector(#selector(startCamera), withObject: nil, afterDelay: 2.5) } func startCamera() { OpenCVWrapper.sharedInstance().setupVideoCamera(imageView) } @IBAction func showSettings(sender: AnyObject) { // Present the settings controller in a popover view let settingsController = storyboard?.instantiateViewControllerWithIdentifier("Settings") as! SettingsViewController let formSheetController = MZFormSheetPresentationViewController(contentViewController: settingsController) formSheetController.presentationController?.shouldDismissOnBackgroundViewTap = true formSheetController.presentationController?.backgroundColor = UIColor.clearColor() formSheetController.presentationController?.contentViewSize = CGSizeMake(view.frame.width*0.85, view.frame.height*0.65) self.presentViewController(formSheetController, animated: true, completion: nil) } }
mit
f7423f1f22fd135bd2bb6bede17178d9
39.162791
142
0.735958
5.380062
false
false
false
false
leo150/Pelican
Sources/Pelican/Pelican/Files/CacheFile.swift
1
975
import Foundation import Vapor /** Represents a file that has been uploaded and is stored in the cache for. Used for obtaining and re-using the resource, as well as */ struct CacheFile: Equatable { /// The message file being stored var file: MessageFile /// The time it was last uploaded (useful for predicting when it needs to be uploaded again). var uploadTime: Date /** Attempts to create the type for the given file. Warning: This will fail if the file has no file ID, thus indicating it has never been uploaded to Telegram. A file must already be uploaded to be cached. */ init?(file: MessageFile) { if file.fileID == nil { return nil } self.file = file self.uploadTime = Date() } public static func ==(lhs: CacheFile, rhs: CacheFile) -> Bool { if lhs.uploadTime != rhs.uploadTime { return false } if lhs.file.fileID != rhs.file.fileID { return false } if lhs.file.url != rhs.file.url { return false } return true } }
mit
4c0440e6745326bdbdd6b364b0a726f8
24
106
0.699487
3.597786
false
false
false
false