repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nishimao/FeedbackKit
FeedbackKit/Classes/Feedback.swift
1
3995
// // Feedback.swift // FeedbackKit // // Created by Mao Nishi on 8/17/16. // Copyright © 2016 Mao Nishi. All rights reserved. // import Foundation import UIKit public enum Feedback { public class EmailConfig { var toList: [String] var mailSubject: String? var ccList: [String]? var bccList: [String]? public init(to: String) { toList = [to] } public init(toList: [String], mailSubject: String? = nil, ccList: [String]? = nil, bccList: [String]? = nil) { self.toList = toList self.mailSubject = mailSubject self.ccList = ccList self.bccList = ccList } } // feedback by email case Email(emailConfig: EmailConfig) // feedback by custom action. when custom action was finished successfully, need to call 'success' method. case Custom(action: ((feedbackViewController: FeedbackViewController, sendInformation: SendInformation, success:(()->Void)) -> Void)) public func show(dismissed:(()->Void)) { guard let callerViewController = UIApplication.sharedApplication().keyWindow?.rootViewController else { return } switch self { case .Email(let email): let feedbackMail = FeedbackMail() FeedbackViewController.presentFeedbackViewController(callerViewController, action: { (feedbackViewController: FeedbackViewController, sendInformation: SendInformation) in // send mail feedbackMail.send(email, sendInformation: sendInformation, callerViewController: feedbackViewController, mailSendCompletion: { // complete send mail and dismiss feedbackview feedbackViewController.dismissFeedbackViewController() // callback dismissed() }) }) case .Custom(let action): FeedbackViewController.presentFeedbackViewController(callerViewController, action: { (feedbackViewController: FeedbackViewController, sendInformation: SendInformation) in let success: (()->Void) = { dispatch_async(dispatch_get_main_queue(), { // dismiss feedbackview feedbackViewController.dismissFeedbackViewController() // callback dismissed() }) } // execute custom action action(feedbackViewController: feedbackViewController, sendInformation: sendInformation, success: success) }) } } public func addDoubleLongPressGestureRecognizer(dismissed:(()->Void)) { GestureFeedback.gestureFeedback.dismissed = dismissed GestureFeedback.gestureFeedback.feedback = self let gesture = UILongPressGestureRecognizer(target: GestureFeedback.gestureFeedback, action: #selector(GestureFeedback.pressGesture(_:))) gesture.numberOfTouchesRequired = 2 if let window = UIApplication.sharedApplication().delegate?.window { if let recognizers = window?.gestureRecognizers { for recognizer in recognizers { if recognizer is UILongPressGestureRecognizer { window?.removeGestureRecognizer(recognizer) } } } window?.addGestureRecognizer(gesture) } } } final class GestureFeedback: NSObject { var feedback: Feedback? var dismissed: (()->Void)? static let gestureFeedback = GestureFeedback() private override init() { } func pressGesture(sender: UIGestureRecognizer) { guard let feedback = feedback else { return } guard let dismissed = dismissed else { feedback.show({ // none }) return } feedback.show(dismissed) } }
mit
51afe6dafb9476af2243e28f18337de4
32.563025
182
0.601903
5.625352
false
false
false
false
mrommel/TreasureDungeons
TreasureDungeons/Source/OpenGL/ObjModel.swift
1
3387
// // ObjModel.swift // TreasureDungeons // // Created by Michael Rommel on 07.09.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation import GLKit public enum ObjModelError: Error { case noObjectFound } class ObjModel : Model { init(fileName: String, shader: BaseEffect) throws { // load obj file named "key.obj" let fixtureHelper = ObjLoading.FixtureHelper() let source = try? fixtureHelper.loadObjFixture(name: fileName) if let source = source { let loader = ObjLoading.ObjLoader(source: source, basePath: fixtureHelper.resourcePath) do { let shapes = try loader.read() if let shape = shapes.first { let (vertices, indices) = ObjModel.verticesAndIndicesFrom(shape: shape) super.init(name: shape.name!, shader: shader, vertices: vertices, indices: indices) self.loadTexture((shape.material?.diffuseTextureMapFilePath?.lastPathComponent)! as String) } else { throw ObjModelError.noObjectFound } } } else { throw ObjModelError.noObjectFound } } init(name: String, shape: ObjLoading.Shape, shader: BaseEffect) { let (vertices, indices) = ObjModel.verticesAndIndicesFrom(shape: shape) super.init(name: name, shader: shader, vertices: vertices, indices: indices) self.loadTexture((shape.material?.diffuseTextureMapFilePath?.lastPathComponent)! as String) } static func verticesAndIndicesFrom(shape: ObjLoading.Shape) -> ([Vertex], [GLuint]) { var vertices: [Vertex] = [] var indices: [GLuint] = [] var index: GLuint = 0 for vertexIndexes in shape.faces { for vertexIndex in vertexIndexes { // Will cause an out of bounds error // if vIndex, nIndex or tIndex is not normalized // to be local to the internal data of the shape // instead of global to the file as per the // .obj specification let (vertexVector, normalVector, textureVector) = shape.dataForVertexIndex(vertexIndex) var v = Vertex() if let vertexVector = vertexVector { v.x = GLfloat(vertexVector[0]) v.y = GLfloat(vertexVector[1]) v.z = GLfloat(vertexVector[2]) } if let normalVector = normalVector { v.nx = GLfloat(normalVector[0]) v.ny = GLfloat(normalVector[1]) v.nz = GLfloat(normalVector[2]) } if let textureVector = textureVector { v.u = GLfloat(textureVector[0]) v.v = GLfloat(textureVector[1]) } vertices.append(v) indices.append(index) index = index + 1 } } return (vertices, indices) } override func updateWithDelta(_ dt: TimeInterval) { self.rotationY = self.rotationY + Float(Double.pi * dt / 8) } }
apache-2.0
64c5dec6b8069a80140296d49f013a89
33.907216
111
0.533077
4.871942
false
false
false
false
bsmith11/ScoreReporter
ScoreReporter/Controllers/NavigationItemView.swift
1
1270
// // NavigationItemView.swift // ScoreReporter // // Created by Bradley Smith on 11/1/16. // Copyright © 2016 Brad Smith. All rights reserved. // import UIKit class NavigationItemView: UIView { fileprivate let titleLabel = UILabel(frame: .zero) var title: String? { return titleLabel.text } var centerPosition: CGPoint { let x = (superview?.bounds.width ?? 0.0) / 2.0 let y = layer.position.y return CGPoint(x: x, y: y) } init?(viewController: UIViewController) { guard let title = viewController.title else { return nil } let attributes = viewController.navigationController?.navigationBar.titleTextAttributes titleLabel.attributedText = NSAttributedString(string: title, attributes: attributes) titleLabel.sizeToFit() let width = titleLabel.bounds.width let height = max(27.0, titleLabel.bounds.height) let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height) super.init(frame: frame) titleLabel.center = CGPoint(x: width / 2.0, y: height / 2.0) addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
977bed48b79c0e87049dbb7a2994bbf7
27.2
95
0.640662
4.215947
false
false
false
false
iSapozhnik/FamilyPocket
FamilyPocket/Data/WatchSessionManager.swift
1
2456
// // WatchSessionManager.swift // FamilyPocket // // Created by Ivan Sapozhnik on 5/24/17. // Copyright © 2017 Ivan Sapozhnik. All rights reserved. // import Foundation import WatchConnectivity class WatchSessionManager: NSObject, WCSessionDelegate { static let sharedManager = WatchSessionManager() private override init() { super.init() } private let session: WCSession? = WCSession.isSupported() ? WCSession.default() : nil fileprivate var validSession: WCSession? { // paired - the user has to have their device paired to the watch // watchAppInstalled - the user must have your watch app installed // Note: if the device is paired, but your watch app is not installed // consider prompting the user to install it for a better experience if let session = session, session.isPaired && session.isWatchAppInstalled { return session } return nil } func startSession() { session?.delegate = self session?.activate() } // public func updateApplicationContext(applicationContext: [String : Any]) throws { // if let session = validSession { // do { // try session.updateApplicationContext(applicationContext) // } catch let error { // throw error // } // } // } //MARK: delegate @available(iOS 9.3, *) public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { print("activationDidCompleteWith state \(activationState.rawValue)") } public func sessionDidBecomeInactive(_ session: WCSession) { } public func sessionDidDeactivate(_ session: WCSession) { } } // MARK: Application Context // use when your app needs only the latest information // if the data was not sent, it will be replaced extension WatchSessionManager { // This is where the magic happens! // Yes, that's it! // Just updateApplicationContext on the session! func updateApplicationContext(applicationContext: [String : Any]) throws { if let session = validSession { do { try session.updateApplicationContext(applicationContext) } catch let error { throw error } } } }
mit
5f3d11d3df2f7f4cc6385bb8c4a9f2c9
27.882353
131
0.621996
5.146751
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Extensions/ItemViewController+iOS.swift
1
3124
import Foundation import struct PopcornKit.Show import struct PopcornKit.Movie import PopcornTorrent.PTTorrentDownloadManager extension ItemViewController { var watchlistButtonImage: UIImage? { return media.isAddedToWatchlist ? UIImage(named: "Watchlist On") : UIImage(named: "Watchlist Off") } override func viewDidLoad() { super.viewDidLoad() PTTorrentDownloadManager.shared().add(self) downloadButton.addTarget(self, action: #selector(stopDownload(_:)), for: .applicationReserved) titleLabel.text = media.title summaryTextView.text = media.summary if let image = media.mediumCoverImage, let url = URL(string: image) { imageView?.af_setImage(withURL: url) } if let movie = media as? Movie { let formatter = DateComponentsFormatter() formatter.unitsStyle = .short formatter.allowedUnits = [.hour, .minute] subtitleLabel.text = formatter.string(from: TimeInterval(movie.runtime) * 60) ?? "0 min" genreLabel?.text = movie.genres.first?.localizedCapitalized.localized ?? "" let info = NSMutableAttributedString(string: "\(movie.year)") attributedString(with: 10, between: movie.certification, "HD", "CC").forEach({info.append($0)}) infoLabel.attributedText = info ratingView.rating = Double(movie.rating)/20.0 movie.trailerCode == nil ? trailerButton.removeFromSuperview() : () } else if let show = media as? Show { subtitleLabel.text = show.network ?? "TV" genreLabel?.text = show.genres.first?.localizedCapitalized.localized ?? "" let info = NSMutableAttributedString(string: "\(show.year)") attributedString(with: 10, between: "HD", "CC").forEach({info.append($0)}) infoLabel.attributedText = info ratingView.rating = Double(show.rating)/20.0 trailerButton.isHidden = true downloadButton.isHidden = true } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { let isCompact = traitCollection.horizontalSizeClass == .compact for constraint in compactConstraints { constraint.priority = UILayoutPriority(rawValue: UILayoutPriority.RawValue(isCompact ? 999 : 240)) } for constraint in regularConstraints { constraint.priority = UILayoutPriority(rawValue: UILayoutPriority.RawValue(isCompact ? 240 : 999)) } titleLabel.font = isCompact ? UIFont.systemFont(ofSize: 40, weight: UIFont.Weight.heavy) : UIFont.systemFont(ofSize: 50, weight: UIFont.Weight.heavy) // Don't animate if when the view is being first presented. if previousTraitCollection != nil { UIView.animate(withDuration: .default, animations: { self.view.layoutIfNeeded() }) } } }
gpl-3.0
83a4e2b0fa95a900acc87edd6e8966f7
40.105263
157
0.618438
5.259259
false
false
false
false
myandy/shi_ios
shishi/Data/DataContainer.swift
1
1643
// // DataContainer.swift // shishi // // Created by tb on 2017/4/29. // Copyright © 2017年 andymao. All rights reserved. // import UIKit class DataContainer: NSObject { open static let `default`: DataContainer = { return DataContainer() }() lazy private(set) var duiShiNetwork: DuishiNetwork = { return AppConfig.isStubbingNetwork ? Networking.newDuishiStubbingNetwork() : Networking.newDuishiNetwork() }() //字体变化每次步径 private let increaseFontStep: CGFloat = AppConfig.Constants.increaseFontStep //调整字体大小 public var fontOffset: CGFloat = 0 override init() { self.fontOffset = CGFloat(SSUserDefaults.standard.float(forKey: SSUserDefaults.Keys.fontOffset)) } //增加字体大小 public func increaseFontOffset() -> CGFloat { return self.updateFontOffset(pointSizeStep: increaseFontStep) } //减少字体大小 public func reduceFontOffset() -> CGFloat { return self.updateFontOffset(pointSizeStep: -increaseFontStep) } public func updateFontOffset(pointSizeStep: CGFloat) -> CGFloat { let newFontSize = self.fontOffset + pointSizeStep self.fontOffset = newFontSize self.saveFontOffset() SSNotificationCenter.default.post(name: SSNotificationCenter.Names.updateFontSize, object: nil) return newFontSize } fileprivate func saveFontOffset() { SSUserDefaults.standard.set(self.fontOffset, forKey: SSUserDefaults.Keys.fontOffset) SSUserDefaults.standard.synchronize() } }
apache-2.0
354ca807cf8f61d141b3bc544b1643fe
26.859649
114
0.673804
4.411111
false
false
false
false
material-motion/material-motion-swift
src/operators/rewriteRange.swift
2
1345
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation extension MotionObservableConvertible where T: Subtractable, T: Lerpable { /** Linearly interpolate the incoming value along the given range to the destination range. */ public func rewriteRange<U> ( start: T, end: T, destinationStart: U, destinationEnd: U ) -> MotionObservable<U> where U: Lerpable, U: Subtractable, U: Addable { return _map { let position = $0 - start let vector = end - start let progress = position.progress(along: vector) let destinationVector = destinationEnd - destinationStart let destinationPosition = destinationVector.project(progress: progress) return destinationStart + destinationPosition } } }
apache-2.0
278198e498aad56940dc1e5da3471d59
30.27907
90
0.729368
4.52862
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/Services/RoleService.swift
4
2144
import Foundation import WordPressKit /// Service providing access to user roles /// struct RoleService { let blog: Blog fileprivate let context: NSManagedObjectContext fileprivate let remote: PeopleServiceRemote fileprivate let siteID: Int init?(blog: Blog, context: NSManagedObjectContext) { guard let api = blog.wordPressComRestApi(), let dotComID = blog.dotComID as? Int else { return nil } self.remote = PeopleServiceRemote(wordPressComRestApi: api) self.siteID = dotComID self.blog = blog self.context = context } /// Returns a role from Core Data with the given slug. /// func getRole(slug: String) -> Role? { let predicate = NSPredicate(format: "slug = %@ AND blog = %@", slug, blog) return context.firstObject(ofType: Role.self, matching: predicate) } /// Forces a refresh of roles from the api and stores them in Core Data. /// func fetchRoles(success: @escaping ([Role]) -> Void, failure: @escaping (Error) -> Void) { remote.getUserRoles(siteID, success: { (remoteRoles) in let roles = self.mergeRoles(remoteRoles) success(roles) }, failure: failure) } } private extension RoleService { func mergeRoles(_ remoteRoles: [RemoteRole]) -> [Role] { let existingRoles = blog.roles ?? [] var rolesToKeep = [Role]() for (order, remoteRole) in remoteRoles.enumerated() { let role: Role if let existingRole = existingRoles.first(where: { $0.slug == remoteRole.slug }) { role = existingRole } else { role = context.insertNewObject(ofType: Role.self) } role.blog = blog role.slug = remoteRole.slug role.name = remoteRole.name role.order = order as NSNumber rolesToKeep.append(role) } let rolesToDelete = existingRoles.subtracting(rolesToKeep) rolesToDelete.forEach(context.delete(_:)) ContextManager.sharedInstance().save(context) return rolesToKeep } }
gpl-2.0
7f2415192d9f59d1dc6f5b9ebef3ee5e
33.031746
95
0.616604
4.600858
false
false
false
false
mgadda/zig
Sources/MessagePackEncoder/MessagePackReferencingEncoder.swift
1
1786
// // MessagePackReferencingEncoder.swift // MessagePackEncoder // // Created by Matt Gadda on 9/27/17. // import Foundation import MessagePack internal class MessagePackReferencingEncoder : _MessagePackEncoder { private enum Reference { case array(MutableArrayReference<BoxedValue>, Int) case dictionary(MutableDictionaryReference<BoxedValue, BoxedValue>, String) } let encoder: _MessagePackEncoder private let reference: Reference init(referencing encoder: _MessagePackEncoder, at index: Int, wrapping array: MutableArrayReference<BoxedValue>) { self.encoder = encoder self.reference = .array(array, index) super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath) codingPath.append(MessagePackKey(index: index)) } init(referencing encoder: _MessagePackEncoder, at key: CodingKey, wrapping dictionary: MutableDictionaryReference<BoxedValue, BoxedValue>) { self.encoder = encoder self.reference = .dictionary(dictionary, key.stringValue) super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath) self.codingPath.append(key) } internal override var canEncodeNewValue: Bool { return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } deinit { let value: BoxedValue switch self.storage.count { case 0: value = BoxedValue.map(MutableDictionaryReference<BoxedValue, BoxedValue>()) case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let arrayRef, let index): arrayRef.insert(value, at: index) case .dictionary(let dictRef, let key): dictRef[BoxedValue.string(key)] = value } } }
mit
efb883f0b2f5d5a1b1989114a10a9204
30.892857
142
0.741321
4.377451
false
false
false
false
madeatsampa/MacMagazine-iOS
MacMagazine/SplashViewController.swift
1
1572
// // SplashViewController.swift // MacMagazine // // Created by Cassio Rossi on 08/06/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import UIKit class SplashViewController: UIViewController { @IBOutlet private weak var logo: UIImageView! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) view.backgroundColor = Settings().isDarkMode ? .black : .white logo.image = UIImage(named: "splash\(Settings().isDarkMode ? "_dark" : "")") delay(0.6) { let storyboard = UIStoryboard(name: "Main", bundle: nil) guard let controller = storyboard.instantiateViewController(withIdentifier: "main") as? UITabBarController, let appDelegate = UIApplication.shared.delegate as? AppDelegate, let splitViewController = controller.viewControllers?.first as? UISplitViewController, let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return } controller.delegate = appDelegate splitViewController.delegate = appDelegate splitViewController.preferredDisplayMode = .allVisible splitViewController.preferredPrimaryColumnWidthFraction = 0.33 UIView.transition(with: window, duration: 0.4, options: .transitionCrossDissolve, animations: { window.rootViewController = controller }) } } }
mit
2991b45ffc7bace37d662abd3370ca07
33.152174
119
0.619987
5.361775
false
false
false
false
mrscorpion/MRSwiftTarget
MSSwiftLessons/MSFundamentals/Day 04/08-News(解析展示数据)/News/Classes/Tools/NetworkTools.swift
1
1147
// // NetworkTools.swift // News // // Created by 1 on 16/9/28. // Copyright © 2016年 mr. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { // class方法 --> OC +开头 class func requestData(URLString : String, type : MethodType, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in // 1.校验是否有结果 /* if let result = response.result.value { finishedCallback(result) } else { print(response.result.error) } */ // 1.校验是否有结果 guard let result = response.result.value else { print(response.result.error ?? "error") return } // 2.将结果回调出去 finishedCallback(result) } } }
mit
acebe05cb2fb3d5632a93c8f408602be
25.047619
156
0.528336
4.483607
false
false
false
false
shopgun/shopgun-ios-sdk
Sources/TjekPublicationViewer/PagedPublication/PagedPublicationView+Verso.swift
1
7681
/// /// Copyright (c) 2018 Tjek. All rights reserved. /// import UIKit import Verso // MARK: - Verso DataSource extension PagedPublicationView: VersoViewDataSource { // Return how many pages are on each spread public func spreadConfiguration(with size: CGSize, for verso: VersoView) -> VersoSpreadConfiguration { let pageCount = self.pageCount let lastPageIndex = max(0, pageCount - 1) var totalPageCount = pageCount // there is an outro, and we have some pages, so add outro to the pages list if self.outroPageIndex != nil { totalPageCount += 1 } // how far between the page spreads let spreadSpacing: CGFloat = 20 // TODO: compare verso aspect ratio to publication aspect ratio let isLandscape: Bool = size.width > size.height return VersoSpreadConfiguration.buildPageSpreadConfiguration(pageCount: totalPageCount, spreadSpacing: spreadSpacing, spreadPropertyConstructor: { (_, nextPageIndex) in // it's the outro (has an outro, we have some real pages, and next page is after the last pageIndex if let outroProperties = self.outroViewProperties, nextPageIndex == self.outroPageIndex { return (1, outroProperties.maxZoom, outroProperties.width) } let spreadPageCount: Int if nextPageIndex == 0 || nextPageIndex == lastPageIndex || isLandscape == false { spreadPageCount = 1 } else { spreadPageCount = 2 } return (spreadPageCount, 3.0, 1.0) }) } public func pageViewClass(on pageIndex: Int, for verso: VersoView) -> VersoPageViewClass { if let outroProperties = self.outroViewProperties, pageIndex == self.outroPageIndex { return outroProperties.viewClass } else { return PagedPublicationView.PageView.self } } public func configure(pageView: VersoPageView, for verso: VersoView) { if let pubPageView = pageView as? PagedPublicationView.PageView { pubPageView.imageLoader = self.imageLoader pubPageView.delegate = self let pageProperties = self.pageViewProperties(forPageIndex: pubPageView.pageIndex) pubPageView.configure(with: pageProperties) } else if type(of: pageView) === self.outroViewProperties?.viewClass { dataSourceWithDefaults.configure(outroView: pageView, for: self) } } public func spreadOverlayView(overlaySize: CGSize, pageFrames: [Int: CGRect], for verso: VersoView) -> UIView? { // we have an outro and it is one of the pages we are being asked to add an overlay for if let outroPageIndex = self.outroPageIndex, pageFrames[outroPageIndex] != nil { return nil } let spreadHotspots = self.hotspotModels(onPageIndexes: IndexSet(pageFrames.keys)) // configure the overlay self.hotspotOverlayView.isHidden = self.pageCount == 0 self.hotspotOverlayView.delegate = self self.hotspotOverlayView.frame.size = overlaySize self.hotspotOverlayView.updateWithHotspots(spreadHotspots, pageFrames: pageFrames) // disable tap when double-tapping if let doubleTap = contentsView.versoView.zoomDoubleTapGestureRecognizer { self.hotspotOverlayView.tapGesture?.require(toFail: doubleTap) } return self.hotspotOverlayView } public func adjustPreloadPageIndexes(_ preloadPageIndexes: IndexSet, visiblePageIndexes: IndexSet, for verso: VersoView) -> IndexSet? { guard let outroPageIndex = self.outroPageIndex, let lastIndex = visiblePageIndexes.last, outroPageIndex - lastIndex < 10 else { return nil } // add outro to preload page indexes if we have scrolled close to it var adjustedPreloadPages = preloadPageIndexes adjustedPreloadPages.insert(outroPageIndex) return adjustedPreloadPages } } // MARK: - Verso Delegate extension PagedPublicationView: VersoViewDelegate { public func currentPageIndexesChanged(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) { // this is a bit of a hack to cancel the touch-gesture when we start scrolling self.hotspotOverlayView.touchGesture?.isEnabled = false self.hotspotOverlayView.touchGesture?.isEnabled = true // remove the outro index when refering to page indexes outside of PagedPub var currentExOutro = currentPageIndexes var oldExOutro = oldPageIndexes if let outroIndex = self.outroPageIndex { currentExOutro.remove(outroIndex) oldExOutro.remove(outroIndex) } delegate?.pageIndexesChanged(current: currentExOutro, previous: oldExOutro, in: self) // check if the outro has newly appeared or disappeared (not if it's in both old & current) if let outroIndex = outroPageIndex, let outroView = verso.getPageViewIfLoaded(outroIndex) { let addedIndexes = currentPageIndexes.subtracting(oldPageIndexes) let removedIndexes = oldPageIndexes.subtracting(currentPageIndexes) if addedIndexes.contains(outroIndex) { delegate?.outroDidAppear(outroView, in: self) outroOutsideTapGesture.isEnabled = true } else if removedIndexes.contains(outroIndex) { delegate?.outroDidDisappear(outroView, in: self) outroOutsideTapGesture.isEnabled = false } } updateContentsViewLabels(pageIndexes: currentPageIndexes, additionalLoading: contentsView.properties.showAdditionalLoading) } public func currentPageIndexesFinishedChanging(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) { // make a new spreadEventHandler (unless it's the outro) if self.isOutroPage(inPageIndexes: currentPageIndexes) == false { self.eventHandler?.didOpenPublicationPages(currentPageIndexes) } // remove the outro index when refering to page indexes outside of PagedPub var currentExOutro = currentPageIndexes var oldExOutro = oldPageIndexes if let outroIndex = self.outroPageIndex { currentExOutro.remove(outroIndex) oldExOutro.remove(outroIndex) } delegate?.pageIndexesFinishedChanging(current: currentExOutro, previous: oldExOutro, in: self) // cancel the loading of the zoomimage after a page disappears oldPageIndexes.subtracting(currentPageIndexes).forEach { if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView { pageView.clearZoomImage(animated: false) } } } public func didStartZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) { hotspotOverlayView.isZooming = true } public func didEndZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) { delegate?.didEndZooming(zoomScale: zoomScale) pageIndexes.forEach { if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView { pageView.startLoadingZoomImageIfNotLoaded() } } hotspotOverlayView.isZooming = false } }
mit
0ffd5193d14f645b49cb2a6acc942453
43.398844
176
0.66007
5.103654
false
false
false
false
FUNIKImegane/FunikiSDK
FunikiSDKExampleSwift/FunikiSDKExampleSwift/FunikiSDKMotionViewController.swift
1
4652
// // Created by Matilde Inc. // Copyright (c) 2015 FUN'IKI Project. All rights reserved. // import UIKit class FunikiSDKMotionViewController: UIViewController, MAFunikiManagerDelegate, MAFunikiManagerDataDelegate { let funikiManager = MAFunikiManager.sharedInstance() var baseSize:CGRect! var accXRect:CGRect! var accYRect:CGRect! var accZRect:CGRect! var rotXRect:CGRect! var rotYRect:CGRect! var rotZRect:CGRect! @IBOutlet var accXView:UIView! @IBOutlet var accYView:UIView! @IBOutlet var accZView:UIView! @IBOutlet var rotXView:UIView! @IBOutlet var rotYView:UIView! @IBOutlet var rotZView:UIView! @IBOutlet var sensorSwitch:UISwitch! // MARK: - UIViewController override func viewDidLoad() { baseSize = accXView.frame baseSize.size.width = baseSize.size.width / 2 accXRect = accXView.frame accYRect = accYView.frame accZRect = accZView.frame rotXRect = rotXView.frame rotYRect = rotYView.frame rotZRect = rotZView.frame setBarHidden(hidden: true) } override func viewWillAppear(_ animated: Bool) { funikiManager?.delegate = self funikiManager?.dataDelegate = self self.updateSensorSwitch() super.viewWillAppear(animated) } override var shouldAutorotate: Bool{ return false } // MARK: - func setBarHidden(hidden:Bool) { accXView.isHidden = hidden accYView.isHidden = hidden accZView.isHidden = hidden rotXView.isHidden = hidden rotYView.isHidden = hidden rotZView.isHidden = hidden } func updateSensorSwitch() { if (funikiManager?.isConnected)! { sensorSwitch.isEnabled = true } else { sensorSwitch.isEnabled = false sensorSwitch.setOn(false, animated: true) } } // MARK: - MAFunikiManagerDelegate func funikiManagerDidConnect(_ manager: MAFunikiManager!) { print("SDK Version\(String(describing: MAFunikiManager.funikiSDKVersionString()))") print("Firmware Revision\(String(describing: manager.firmwareRevision))") updateSensorSwitch() } func funikiManagerDidDisconnect(_ manager: MAFunikiManager!, error: Error!) { if let actualError = error { print(actualError) } updateSensorSwitch() } func funikiManager(_ manager: MAFunikiManager!, didUpdateCentralState state: CBCentralManagerState) { updateSensorSwitch() } // MARK: - MAFunikiManagerDataDelegate func funikiManager(_ manager: MAFunikiManager!, didUpdate motionData: MAFunikiMotionData!) { accXRect.size.width = CGFloat(motionData.acceleration.x) * baseSize.size.width accYRect.size.width = CGFloat(motionData.acceleration.y) * baseSize.size.width accZRect.size.width = CGFloat(motionData.acceleration.z) * baseSize.size.width rotXRect.size.width = ((CGFloat(motionData.rotationRate.x) * baseSize.size.width) / 250.0) * 2.0 rotYRect.size.width = ((CGFloat(motionData.rotationRate.y) * baseSize.size.width) / 250.0) * 2.0 rotZRect.size.width = ((CGFloat(motionData.rotationRate.z) * baseSize.size.width) / 250.0) * 2.0 self.accXView.frame = accXRect self.accYView.frame = accYRect self.accZView.frame = accZRect self.rotXView.frame = rotXRect self.rotYView.frame = rotYRect self.rotZView.frame = rotZRect } func funikiManager(_ manager: MAFunikiManager!, didPushButton buttonEventType: MAFunikiManagerButtonEventType) { var string = "ButtonEventType" switch (buttonEventType){ case .singlePush: string = "ButtonEventTypeSinglePush" break case .doublePush: string = "ButtonEventTypeDoublePush" default: string = "ButtonEventTypeUnknown" break } let alertView = UIAlertView(title: "DidPushButton", message: string, delegate: nil, cancelButtonTitle: "OK") alertView.show() } // MARK: - Action @IBAction func switchDidChange(_ sender:UISwitch) { if sensorSwitch.isOn { funikiManager?.startMotionSensor() setBarHidden(hidden: false) } else { funikiManager?.stopMotionSensor() setBarHidden(hidden: true) } } }
mit
f85c07dbc16950f239dce7e2f1893e50
29.807947
116
0.623603
4.260073
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
Example/iOSDFULibrary/View Controllers/MainNavigationViewController.swift
1
2453
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import UIKit class MainNavigationViewController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13.0, *) { let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.backgroundColor = UIColor.dynamicColor(light: .nordicBlue, dark: .black) navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] navigationBar.standardAppearance = navBarAppearance navigationBar.scrollEdgeAppearance = navBarAppearance } else { // Fallback on earlier versions } } }
bsd-3-clause
bafcccd76bb33c386d42b85cbe550419
44.425926
101
0.744802
5.208068
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Rest/RestClient.swift
1
16845
import Foundation import Alamofire open class RestClient: NSObject { typealias ResultCollectionHandler<T: Codable> = (_ result: ResultCollection<T>?, _ error: ErrorResponse?) -> Void typealias RequestHandler = (_ resultValue: Any?, _ error: ErrorResponse?) -> Void /** FitPay uses conventional HTTP response codes to indicate success or failure of an API request. In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that resulted from the provided information (e.g. a required parameter was missing, etc.), and codes in the 5xx range indicate an error with FitPay servers. Not all errors map cleanly onto HTTP response codes, however. When a request is valid but does not complete successfully (e.g. a card is declined), we return a 402 error code. - OK: Everything worked as expected - BadRequest: Often missing a required parameter - Unauthorized: No valid API key provided - RequestFailed: Parameters were valid but request failed - NotFound: The requested item doesn't exist - ServerError[0-3]: Something went wrong on FitPay's end */ public enum ErrorCode: Int, Error, RawIntValue { case ok = 200 case badRequest = 400 case unauthorized = 401 case requestFailed = 402 case notFound = 404 case serverError0 = 500 case serverError1 = 502 case serverError2 = 503 case serverError3 = 504 } static let fpKeyIdKey: String = "fp-key-id" var session: RestSession var keyPair: SECP256R1KeyPair = SECP256R1KeyPair() var key: EncryptionKey? var secret: Data { let secret = self.keyPair.generateSecretForPublicKey(key?.serverPublicKey ?? "") if secret == nil || secret?.count == 0 { log.warning("REST_CLIENT: Encription secret is empty.") } return secret ?? Data() } var restRequest: RestRequestable = RestRequest() /** Completion handler - parameter ErrorType?: Provides error object, or nil if no error occurs */ public typealias DeleteHandler = (_ error: ErrorResponse?) -> Void /** Completion handler - parameter ErrorType?: Provides error object, or nil if no error occurs */ public typealias ConfirmHandler = (_ error: ErrorResponse?) -> Void // MARK: - Lifecycle public init(session: RestSession, restRequest: RestRequestable? = nil) { self.session = session if let restRequest = restRequest { self.restRequest = restRequest } } // MARK: - Public Functions public func getRootLinks(completion: @escaping (_ rootLinks: RootLinks?, _ error: ErrorResponse?) -> Void) { let url = FitpayConfig.apiURL restRequest.makeRequest(url: url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in guard let resultValue = resultValue as? [String: Any] else { completion(nil, error) return } let rootLinks = try? RootLinks(resultValue) completion(rootLinks, error) } } public func confirm(_ url: String, executionResult: NonAPDUCommitState, completion: @escaping ConfirmHandler) { let params = ["result": executionResult.description] makePostCall(url, parameters: params, completion: completion) } public func acknowledge(_ url: String, completion: @escaping ConfirmHandler) { makePostCall(url, parameters: nil, completion: completion) } public func getPlatformConfig(completion: @escaping (_ platform: PlatformConfig?, _ error: ErrorResponse?) -> Void) { restRequest.makeRequest(url: FitpayConfig.apiURL + "/mobile/config", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in guard let resultValue = resultValue as? [String: Any] else { completion(nil, error) return } let config = try? PlatformConfig(resultValue["ios"]) completion(config, error) } } public func getCountries(completion: @escaping (_ countries: CountryCollection?, _ error: ErrorResponse?) -> Void) { let url = FitpayConfig.apiURL + "/iso/countries" restRequest.makeRequest(url: url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil) { (resultValue, error) in guard let resultValue = resultValue as? [String: Any] else { completion(nil, error) return } let countryCollection = try? CountryCollection(["countries": resultValue]) countryCollection?.client = self completion(countryCollection, error) } } // MARK: - Internal func collectionItems<T>(_ url: String, completion: @escaping (_ resultCollection: ResultCollection<T>?, _ error: ErrorResponse?) -> Void) -> T? { makeGetCall(url, parameters: nil, completion: completion) return nil } func makeDeleteCall(_ url: String, completion: @escaping DeleteHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(error) } return } self?.restRequest.makeRequest(url: url, method: .delete, parameters: nil, encoding: URLEncoding.default, headers: headers) { (_, error) in completion(error) } } } func makeGetCall<T: Codable>(_ url: String, limit: Int, offset: Int, overrideHeaders: [String: String]? = nil, completion: @escaping ResultCollectionHandler<T>) { let parameters = ["limit": "\(limit)", "offset": "\(offset)"] makeGetCall(url, parameters: parameters, overrideHeaders: overrideHeaders, completion: completion) } func makeGetCall<T: Serializable>(_ url: String, parameters: [String: Any]?, overrideHeaders: [String: String]? = nil, completion: @escaping (T?, ErrorResponse?) -> Void) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard var headers = headers else { DispatchQueue.main.async { completion(nil, error) } return } if let overrideHeaders = overrideHeaders { for key in overrideHeaders.keys { headers[key] = overrideHeaders[key] } } self?.restRequest.makeRequest(url: url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers) { (resultValue, error) in guard let strongSelf = self else { return } guard let resultValue = resultValue else { completion(nil, error) return } let result = try? T(resultValue) (result as? ClientModel)?.client = self (result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey]) completion(result, error) } } } func makePostCall(_ url: String, parameters: [String: Any]?, completion: @escaping ConfirmHandler) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(error) } return } self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (_, error) in completion(error) } } } func makePostCall<T: Serializable>(_ url: String, parameters: [String: Any]?, completion: @escaping (T?, ErrorResponse?) -> Void) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(nil, error) } return } self?.restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) { (resultValue, error) in guard let strongSelf = self else { return } guard let resultValue = resultValue else { completion(nil, error) return } let result = try? T(resultValue) (result as? ClientModel)?.client = self (result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey]) completion(result, error) } } } func makePatchCall<T: Serializable>(_ url: String, parameters: [String: Any]?, encoding: ParameterEncoding, completion: @escaping (T?, ErrorResponse?) -> Void) { prepareAuthAndKeyHeaders { [weak self] (headers, error) in guard let headers = headers else { DispatchQueue.main.async { completion(nil, error) } return } self?.restRequest.makeRequest(url: url, method: .patch, parameters: parameters, encoding: encoding, headers: headers) { (resultValue, error) in guard let strongSelf = self else { return } guard let resultValue = resultValue else { completion(nil, error) return } let result = try? T(resultValue) (result as? ClientModel)?.client = self (result as? SecretApplyable)?.applySecret(strongSelf.secret, expectedKeyId: headers[RestClient.fpKeyIdKey]) completion(result, error) } } } } // MARK: - Confirm package extension RestClient { /** Endpoint to allow for returning responses to APDU execution - parameter package: ApduPackage object - parameter completion: ConfirmAPDUPackageHandler closure */ public func confirmAPDUPackage(_ url: String, package: ApduPackage, completion: @escaping ConfirmHandler) { guard package.packageId != nil else { completion(ErrorResponse(domain: RestClient.self, errorCode: ErrorCode.badRequest.rawValue, errorMessage: "packageId should not be nil")) return } makePostCall(url, parameters: package.responseDictionary, completion: completion) } } // MARK: - Transactions extension RestClient { /** Completion handler - parameter transactions: Provides ResultCollection<Transaction> object, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias TransactionsHandler = (_ result: ResultCollection<Transaction>?, _ error: ErrorResponse?) -> Void } // MARK: - Encryption extension RestClient { /** Creates a new encryption key pair - parameter clientPublicKey: client public key - parameter completion: CreateEncryptionKeyHandler closure */ func createEncryptionKey(clientPublicKey: String, completion: @escaping EncryptionKeyHandler) { let parameters = ["clientPublicKey": clientPublicKey] restRequest.makeRequest(url: FitpayConfig.apiURL + "/config/encryptionKeys", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: session.defaultHeaders) { (resultValue, error) in guard let resultValue = resultValue else { completion(nil, error) return } completion(try? EncryptionKey(resultValue), error) } } /** Completion handler - parameter encryptionKey?: Provides EncryptionKey object, or nil if error occurs - parameter error?: Provides error object, or nil if no error occurs */ typealias EncryptionKeyHandler = (_ encryptionKey: EncryptionKey?, _ error: ErrorResponse?) -> Void /** Retrieve and individual key pair - parameter keyId: key id - parameter completion: EncryptionKeyHandler closure */ func encryptionKey(_ keyId: String, completion: @escaping EncryptionKeyHandler) { restRequest.makeRequest(url: FitpayConfig.apiURL + "/config/encryptionKeys/" + keyId, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: session.defaultHeaders) { (resultValue, error) in guard let resultValue = resultValue else { completion(nil, error) return } completion(try? EncryptionKey(resultValue), error) } } func createKeyIfNeeded(_ completion: @escaping EncryptionKeyHandler) { if let key = key, !key.isExpired { completion(key, nil) } else { createEncryptionKey(clientPublicKey: keyPair.publicKey!) { [weak self] (encryptionKey, error) in if let error = error { completion(nil, error) } else if let encryptionKey = encryptionKey { self?.key = encryptionKey completion(self?.key, nil) } } } } } // MARK: - Request Signature Helpers extension RestClient { typealias AuthHeaderHandler = (_ headers: [String: String]?, _ error: ErrorResponse?) -> Void func createAuthHeaders(_ completion: AuthHeaderHandler) { if session.isAuthorized { completion(session.defaultHeaders + ["Authorization": "Bearer " + session.accessToken!], nil) } else { completion(nil, ErrorResponse(domain: RestClient.self, errorCode: ErrorCode.unauthorized.rawValue, errorMessage: "\(ErrorCode.unauthorized)")) } } func prepareAuthAndKeyHeaders(_ completion: @escaping AuthHeaderHandler) { createAuthHeaders { [weak self] (headers, error) in if let error = error { completion(nil, error) } else { self?.createKeyIfNeeded { (encryptionKey, keyError) in if let keyError = keyError { completion(nil, keyError) } else { completion(headers! + [RestClient.fpKeyIdKey: encryptionKey!.keyId!], nil) } } } } } func preparKeyHeader(_ completion: @escaping AuthHeaderHandler) { createKeyIfNeeded { (encryptionKey, keyError) in if let keyError = keyError { completion(nil, keyError) } else { completion(self.session.defaultHeaders + [RestClient.fpKeyIdKey: encryptionKey!.keyId!], nil) } } } } // MARK: - Issuers extension RestClient { public typealias IssuersHandler = (_ issuers: Issuers?, _ error: ErrorResponse?) -> Void public func issuers(completion: @escaping IssuersHandler) { makeGetCall(FitpayConfig.apiURL + "/issuers", parameters: nil, completion: completion) } } // MARK: - Assets extension RestClient { /** Completion handler - parameter asset: Provides Asset object, or nil if error occurs - parameter error: Provides error object, or nil if no error occurs */ public typealias AssetsHandler = (_ asset: Asset?, _ error: ErrorResponse?) -> Void func assets(_ url: String, completion: @escaping AssetsHandler) { restRequest.makeDataRequest(url: url) { (resultValue, error) in guard let resultValue = resultValue as? Data else { completion(nil, error) return } var asset: Asset? if let image = UIImage(data: resultValue) { asset = Asset(image: image) } else if let string = resultValue.UTF8String { asset = Asset(text: string) } else { asset = Asset(data: resultValue) } completion(asset, nil) } } } /** Retrieve an individual asset (i.e. terms and conditions) - parameter completion: AssetsHandler closure */ public protocol AssetRetrivable { func retrieveAsset(_ completion: @escaping RestClient.AssetsHandler) }
mit
936c8c2b316c7c8014a7fae9ae650f00
37.993056
350
0.598753
5.022361
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Permission/CameraPrompting.swift
1
3405
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Localization import PlatformKit import ToolKit public protocol CameraPrompting: AnyObject { var permissionsRequestor: PermissionsRequestor { get set } var cameraPromptingDelegate: CameraPromptingDelegate? { get set } // Call this when an action requires camera usage func willUseCamera() func requestCameraPermissions() } extension CameraPrompting where Self: MicrophonePrompting { public func willUseCamera() { guard PermissionsRequestor.cameraRefused() == false else { cameraPromptingDelegate?.showCameraPermissionsDenied() return } guard PermissionsRequestor.shouldDisplayCameraPermissionsRequest() else { willUseMicrophone() return } cameraPromptingDelegate?.promptToAcceptCameraPermissions(confirmHandler: { self.requestCameraPermissions() }) } public func requestCameraPermissions() { permissionsRequestor.requestPermissions([.camera]) { [weak self] in guard let this = self else { return } switch PermissionsRequestor.cameraEnabled() { case true: this.willUseMicrophone() case false: this.cameraPromptingDelegate?.showCameraPermissionsDenied() } } } } public protocol CameraPromptingDelegate: AnyObject { var analyticsRecorder: AnalyticsEventRecorderAPI { get } func showCameraPermissionsDenied() func promptToAcceptCameraPermissions(confirmHandler: @escaping (() -> Void)) } extension CameraPromptingDelegate { public func showCameraPermissionsDenied() { let action = AlertAction(style: .confirm(LocalizationConstants.goToSettings)) let model = AlertModel( headline: LocalizationConstants.Errors.cameraAccessDenied, body: LocalizationConstants.Errors.cameraAccessDeniedMessage, actions: [action] ) let alert = AlertView.make(with: model) { output in switch output.style { case .confirm: guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return } UIApplication.shared.open(settingsURL) case .default, .dismiss: break } } alert.show() } public func promptToAcceptCameraPermissions(confirmHandler: @escaping (() -> Void)) { let okay = AlertAction(style: .confirm(LocalizationConstants.okString)) let notNow = AlertAction(style: .default(LocalizationConstants.KYC.notNow)) let model = AlertModel( headline: LocalizationConstants.KYC.allowCameraAccess, body: LocalizationConstants.KYC.enableCameraDescription, actions: [okay, notNow] ) let alert = AlertView.make(with: model) { [weak self] output in switch output.style { case .confirm: self?.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreCameraApprove) confirmHandler() case .default, .dismiss: self?.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreCameraDecline) } } alert.show() } }
lgpl-3.0
6e01fd08a84fc1a3d14a6845955018af
34.092784
108
0.650999
5.36063
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Models/Balance/PairExchangeService.swift
1
2963
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import MoneyKit import RxRelay import RxSwift public protocol PairExchangeServiceAPI: AnyObject { /// The current fiat exchange price. /// The implementer should implement this as a `.shared(replay: 1)` /// resource for efficiency among multiple clients. func fiatPrice(at time: PriceTime) -> Observable<FiatValue> /// A trigger that force the service to fetch the updated price. /// Handy to call on currency type and value changes var fetchTriggerRelay: PublishRelay<Void> { get } } public final class PairExchangeService: PairExchangeServiceAPI { // TODO: Network failure /// Fetches the fiat price, and shares its stream with other /// subscribers to keep external API usage count in check. /// Also handles currency code change public func fiatPrice(at time: PriceTime) -> Observable<FiatValue> { Observable .combineLatest( fiatCurrencyService.displayCurrencyPublisher.asObservable(), fetchTriggerRelay.asObservable().startWith(()) ) .throttle(.milliseconds(250), scheduler: ConcurrentDispatchQueueScheduler(qos: .background)) .map(\.0) .flatMapLatest(weak: self) { (self, fiatCurrency) -> Observable<PriceQuoteAtTime> in self.priceService .price(of: self.currency, in: fiatCurrency, at: time) .asSingle() .catchAndReturn( PriceQuoteAtTime( timestamp: time.date, moneyValue: .zero(currency: fiatCurrency), marketCap: nil ) ) .asObservable() } // There MUST be a fiat value here .map { $0.moneyValue.fiatValue! } .catchError(weak: self) { (self, _) -> Observable<FiatValue> in self.zero } .distinctUntilChanged() .share(replay: 1) } private var zero: Observable<FiatValue> { fiatCurrencyService .displayCurrencyPublisher .map(FiatValue.zero) .asObservable() } /// A trigger for a fetch public let fetchTriggerRelay = PublishRelay<Void>() // MARK: - Services /// The exchange service private let priceService: PriceServiceAPI /// The currency service private let fiatCurrencyService: FiatCurrencyServiceAPI /// The associated currency private let currency: Currency // MARK: - Setup public init( currency: Currency, priceService: PriceServiceAPI = resolve(), fiatCurrencyService: FiatCurrencyServiceAPI ) { self.currency = currency self.priceService = priceService self.fiatCurrencyService = fiatCurrencyService } }
lgpl-3.0
2a8a055c9370ebde9c98dc92fe874425
32.280899
104
0.604659
5.475046
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionDomain/Send/TradingToOnChainTransactionEngine.swift
1
11901
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import MoneyKit import PlatformKit import RxSwift import RxToolKit import ToolKit final class TradingToOnChainTransactionEngine: TransactionEngine { /// This might need to be `1:1` as there isn't a transaction pair. var transactionExchangeRatePair: Observable<MoneyValuePair> { .empty() } var fiatExchangeRatePairs: Observable<TransactionMoneyValuePairs> { sourceExchangeRatePair .map { pair -> TransactionMoneyValuePairs in TransactionMoneyValuePairs( source: pair, destination: pair ) } .asObservable() } let walletCurrencyService: FiatCurrencyServiceAPI let currencyConversionService: CurrencyConversionServiceAPI let isNoteSupported: Bool var askForRefreshConfirmation: AskForRefreshConfirmation! var sourceAccount: BlockchainAccount! var transactionTarget: TransactionTarget! var sourceTradingAccount: CryptoTradingAccount! { sourceAccount as? CryptoTradingAccount } var target: CryptoReceiveAddress { transactionTarget as! CryptoReceiveAddress } var targetAsset: CryptoCurrency { target.asset } // MARK: - Private Properties private let feeCache: CachedValue<CustodialTransferFee> private let transferRepository: CustodialTransferRepositoryAPI private let transactionLimitsService: TransactionLimitsServiceAPI // MARK: - Init init( isNoteSupported: Bool = false, walletCurrencyService: FiatCurrencyServiceAPI = resolve(), currencyConversionService: CurrencyConversionServiceAPI = resolve(), transferRepository: CustodialTransferRepositoryAPI = resolve(), transactionLimitsService: TransactionLimitsServiceAPI = resolve() ) { self.walletCurrencyService = walletCurrencyService self.currencyConversionService = currencyConversionService self.isNoteSupported = isNoteSupported self.transferRepository = transferRepository self.transactionLimitsService = transactionLimitsService feeCache = CachedValue( configuration: .periodic( seconds: 20, schedulerIdentifier: "TradingToOnChainTransactionEngine" ) ) feeCache.setFetch(weak: self) { (self) -> Single<CustodialTransferFee> in self.transferRepository.fees() .asSingle() } } func assertInputsValid() { precondition(transactionTarget is CryptoReceiveAddress) precondition(sourceAsset == targetAsset) } func restart( transactionTarget: TransactionTarget, pendingTransaction: PendingTransaction ) -> Single<PendingTransaction> { let memoModel = TransactionConfirmations.Memo( textMemo: target.memo, required: false ) return defaultRestart( transactionTarget: transactionTarget, pendingTransaction: pendingTransaction ) .map { [sourceTradingAccount] pendingTransaction -> PendingTransaction in guard sourceTradingAccount!.isMemoSupported else { return pendingTransaction } var pendingTransaction = pendingTransaction pendingTransaction.setMemo(memo: memoModel) return pendingTransaction } } func initializeTransaction() -> Single<PendingTransaction> { let memoModel = TransactionConfirmations.Memo( textMemo: target.memo, required: false ) let transactionLimits = transactionLimitsService .fetchLimits( source: LimitsAccount( currency: sourceAccount.currencyType, accountType: .custodial ), destination: LimitsAccount( currency: targetAsset.currencyType, accountType: .nonCustodial // even exchange accounts are considered non-custodial atm. ) ) return transactionLimits.eraseError() .zip(walletCurrencyService.displayCurrencyPublisher.eraseError()) .map { [sourceTradingAccount, sourceAsset, predefinedAmount] transactionLimits, walletCurrency -> PendingTransaction in let amount: MoneyValue if let predefinedAmount = predefinedAmount, predefinedAmount.currencyType == sourceAsset { amount = predefinedAmount } else { amount = .zero(currency: sourceAsset) } var pendingTransaction = PendingTransaction( amount: amount, available: .zero(currency: sourceAsset), feeAmount: .zero(currency: sourceAsset), feeForFullAvailable: .zero(currency: sourceAsset), feeSelection: .empty(asset: sourceAsset), selectedFiatCurrency: walletCurrency, limits: transactionLimits ) if sourceTradingAccount!.isMemoSupported { pendingTransaction.setMemo(memo: memoModel) } return pendingTransaction } .asSingle() } func update(amount: MoneyValue, pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { guard sourceTradingAccount != nil else { return .just(pendingTransaction) } return Single .zip( feeCache.valueSingle, sourceTradingAccount.withdrawableBalance.asSingle() ) .map { fees, withdrawableBalance -> PendingTransaction in let fee = fees[fee: amount.currency] let available = try withdrawableBalance - fee var pendingTransaction = pendingTransaction.update( amount: amount, available: available.isNegative ? .zero(currency: available.currency) : available, fee: fee, feeForFullAvailable: fee ) let transactionLimits = pendingTransaction.limits ?? .noLimits(for: amount.currency) pendingTransaction.limits = TransactionLimits( currencyType: transactionLimits.currencyType, minimum: fees[minimumAmount: amount.currency], maximum: transactionLimits.maximum, maximumDaily: transactionLimits.maximumDaily, maximumAnnual: transactionLimits.maximumAnnual, effectiveLimit: transactionLimits.effectiveLimit, suggestedUpgrade: transactionLimits.suggestedUpgrade ) return pendingTransaction } } func doBuildConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { fiatAmountAndFees(from: pendingTransaction) .map { [sourceTradingAccount, target, isNoteSupported] fiatAmountAndFees -> [TransactionConfirmation] in var confirmations: [TransactionConfirmation] = [ TransactionConfirmations.Source(value: sourceTradingAccount!.label), TransactionConfirmations.Destination(value: target.label), TransactionConfirmations.NetworkFee( primaryCurrencyFee: fiatAmountAndFees.fees.moneyValue, feeType: .withdrawalFee ), TransactionConfirmations.Total(total: fiatAmountAndFees.amount.moneyValue) ] if isNoteSupported { confirmations.append(TransactionConfirmations.Destination(value: "")) } if sourceTradingAccount!.isMemoSupported { confirmations.append( TransactionConfirmations.Memo(textMemo: target.memo, required: false) ) } return confirmations } .map { confirmations -> PendingTransaction in pendingTransaction.update(confirmations: confirmations) } } func doOptionUpdateRequest( pendingTransaction: PendingTransaction, newConfirmation: TransactionConfirmation ) -> Single<PendingTransaction> { defaultDoOptionUpdateRequest(pendingTransaction: pendingTransaction, newConfirmation: newConfirmation) .map { pendingTransaction -> PendingTransaction in var pendingTransaction = pendingTransaction if let memo = newConfirmation as? TransactionConfirmations.Memo { pendingTransaction.setMemo(memo: memo) } return pendingTransaction } } func doValidateAll(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { validateAmount(pendingTransaction: pendingTransaction) } func execute(pendingTransaction: PendingTransaction) -> Single<TransactionResult> { transferRepository .transfer( moneyValue: pendingTransaction.amount, destination: target.address, memo: pendingTransaction.memo?.value?.string ) .map { identifier -> TransactionResult in .hashed(txHash: identifier, amount: pendingTransaction.amount) } .asSingle() } func doUpdateFeeLevel( pendingTransaction: PendingTransaction, level: FeeLevel, customFeeAmount: MoneyValue ) -> Single<PendingTransaction> { .just(pendingTransaction) } // MARK: - Private Functions private func fiatAmountAndFees( from pendingTransaction: PendingTransaction ) -> Single<(amount: FiatValue, fees: FiatValue)> { Single.zip( sourceExchangeRatePair, .just(pendingTransaction.amount.cryptoValue ?? .zero(currency: sourceCryptoCurrency)), .just(pendingTransaction.feeAmount.cryptoValue ?? .zero(currency: sourceCryptoCurrency)) ) .map { (quote: $0.0.quote.fiatValue ?? .zero(currency: .USD), amount: $0.1, fees: $0.2) } .map { (quote: FiatValue, amount: CryptoValue, fees: CryptoValue) -> (FiatValue, FiatValue) in let fiatAmount = amount.convert(using: quote) let fiatFees = fees.convert(using: quote) return (fiatAmount, fiatFees) } .map { (amount: $0.0, fees: $0.1) } } private var sourceExchangeRatePair: Single<MoneyValuePair> { walletCurrencyService .displayCurrency .flatMap { [currencyConversionService, sourceAsset] fiatCurrency in currencyConversionService .conversionRate(from: sourceAsset, to: fiatCurrency.currencyType) .map { MoneyValuePair(base: .one(currency: sourceAsset), quote: $0) } } .asSingle() } } extension CryptoTradingAccount { fileprivate var isMemoSupported: Bool { switch asset { case .stellar: return true default: return false } } } extension PendingTransaction { fileprivate var memo: TransactionConfirmations.Memo? { engineState.value[.xlmMemo] as? TransactionConfirmations.Memo } fileprivate mutating func setMemo(memo: TransactionConfirmations.Memo) { engineState.mutate { $0[.xlmMemo] = memo } } }
lgpl-3.0
2f924607638ed02bc174ac28d61e4722
38.534884
116
0.612605
5.991944
false
false
false
false
hanangellove/Quick
Quick/DSL/World+DSL.swift
31
4076
/** Adds methods to World to support top-level DSL functions (Swift) and macros (Objective-C). These functions map directly to the DSL that test writers use in their specs. */ extension World { internal func beforeSuite(closure: BeforeSuiteClosure) { suiteHooks.appendBefore(closure) } internal func afterSuite(closure: AfterSuiteClosure) { suiteHooks.appendAfter(closure) } internal func sharedExamples(name: String, closure: SharedExampleClosure) { registerSharedExample(name, closure: closure) } internal func describe(description: String, flags: FilterFlags, closure: () -> ()) { let group = ExampleGroup(description: description, flags: flags) currentExampleGroup!.appendExampleGroup(group) currentExampleGroup = group closure() currentExampleGroup = group.parent } internal func context(description: String, flags: FilterFlags, closure: () -> ()) { self.describe(description, flags: flags, closure: closure) } internal func fdescribe(description: String, flags: FilterFlags, closure: () -> ()) { var focusedFlags = flags focusedFlags[Filter.focused] = true self.describe(description, flags: focusedFlags, closure: closure) } internal func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) { var pendingFlags = flags pendingFlags[Filter.pending] = true self.describe(description, flags: pendingFlags, closure: closure) } internal func beforeEach(closure: BeforeExampleClosure) { currentExampleGroup!.hooks.appendBefore(closure) } @objc(beforeEachWithMetadata:) internal func beforeEach(closure closure: BeforeExampleWithMetadataClosure) { currentExampleGroup!.hooks.appendBefore(closure) } internal func afterEach(closure: AfterExampleClosure) { currentExampleGroup!.hooks.appendAfter(closure) } @objc(afterEachWithMetadata:) internal func afterEach(closure closure: AfterExampleWithMetadataClosure) { currentExampleGroup!.hooks.appendAfter(closure) } @objc(itWithDescription:flags:file:line:closure:) internal func it(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) { let callsite = Callsite(file: file, line: line) let example = Example(description: description, callsite: callsite, flags: flags, closure: closure) currentExampleGroup!.appendExample(example) } @objc(fitWithDescription:flags:file:line:closure:) internal func fit(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) { var focusedFlags = flags focusedFlags[Filter.focused] = true self.it(description, flags: focusedFlags, file: file, line: line, closure: closure) } @objc(xitWithDescription:flags:file:line:closure:) internal func xit(description: String, flags: FilterFlags, file: String, line: Int, closure: () -> ()) { var pendingFlags = flags pendingFlags[Filter.pending] = true self.it(description, flags: pendingFlags, file: file, line: line, closure: closure) } @objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:flags:file:line:) internal func itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, flags: FilterFlags, file: String, line: Int) { let callsite = Callsite(file: file, line: line) let closure = World.sharedWorld().sharedExample(name) let group = ExampleGroup(description: name, flags: flags) currentExampleGroup!.appendExampleGroup(group) currentExampleGroup = group closure(sharedExampleContext) currentExampleGroup!.walkDownExamples { (example: Example) in example.isSharedExample = true example.callsite = callsite } currentExampleGroup = group.parent } internal func pending(description: String, closure: () -> ()) { print("Pending: \(description)") } }
apache-2.0
f6cc1cbc90140afbd4d6ea7101b81b52
38.960784
136
0.688911
4.863962
false
false
false
false
Azurelus/Swift-Useful-Files
Sources/Helpers/ConnectionStatusHandler.swift
1
1493
// // ConnectionStatusHandler.swift // Swift-Useful-Files // // Created by Maksym Husar on 12/28/17. // Copyright © 2017 Maksym Husar. All rights reserved. // import Foundation import PKHUD // just delete if not using class ConnectionStatusHandler { static let instance = ConnectionStatusHandler() private init() { } // MARK: - Public methods func start() { addNotifications() } func stop() { removeNotifications() } // MARK: - Private methods private func addNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(internetNotAvailable(_:)), name: .InternetNotAvailable, object: nil) } private func removeNotifications() { NotificationCenter.default.removeObserver(self) } @objc private func internetNotAvailable(_ notification: Notification) { if let currentVC = UIApplication.topViewController(), currentVC is UIAlertController == false { HUD.hide() // just delete if not using let title = "No Internet Connection" let message = "Make sure your device is connected to the Internet" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: { _ in }) alert.addAction(cancelAction) currentVC.present(alert, animated: true, completion: nil) } } }
mit
822bffe644663450672e7bfb9ccf56ac
32.155556
141
0.652145
4.812903
false
false
false
false
lukecharman/so-many-games
SoManyGames/Classes/View Controllers/ListViewController.swift
1
14501
// // ListViewController.swift // SoManyGames // // Created by Luke Charman on 18/03/2017. // Copyright © 2017 Luke Charman. All rights reserved. // import UIKit class ListViewController: UICollectionViewController { @IBOutlet var gradientView: GradientView! var games: [Game] = Backlog.manager.games { didSet { updateEmptyStateLabel() } } var button = ActionButton(title: "add") var sortButton = ActionButton(title: "sort") var listButton = ActionButton(title: "playing") var clearButton = ActionButton(title: "clear") var selectedGames = [Game]() var programmaticDeselection = false var emptyStateLabel = UILabel() } // MARK: Setup extension ListViewController { override func viewDidLoad() { super.viewDidLoad() collectionView?.allowsMultipleSelection = true collectionView?.backgroundColor = .clear button.titleLabel?.font = UIFont(name: fontName, size: Sizes.button) makeAddButton() makeSortButton() makeListButton() makeClearButton() makeEmptyStateLabel() updateEmptyStateLabel() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) games = Backlog.manager.games collectionView?.reloadData() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionView?.collectionViewLayout.invalidateLayout() for cell in collectionView!.visibleCells { guard let cell = cell as? GameCell else { continue } cell.calculateProgressOnRotation() } coordinator.animate(alongsideTransition: { _ in self.gradientView.resize() }, completion: nil) } } // MARK: Button extension ListViewController { func makeAddButton() { guard let collectionView = collectionView else { return } guard let superview = collectionView.superview else { return } superview.addSubview(button) button.anchor(to: collectionView, at: .bottomLeft) button.addTarget(self, action: #selector(buttonTapped), for: UIControl.Event.touchUpInside) } func makeSortButton() { guard let collectionView = collectionView else { return } guard let superview = collectionView.superview else { return } superview.addSubview(sortButton) sortButton.anchor(to: collectionView, at: .bottomRight) sortButton.addTarget(self, action: #selector(sortButtonTapped), for: UIControl.Event.touchUpInside) } func makeListButton() { guard let collectionView = collectionView else { return } guard let superview = collectionView.superview else { return } superview.addSubview(listButton) listButton.anchor(to: collectionView, at: .bottomCenter) listButton.addTarget(self, action: #selector(listButtonTapped), for: UIControl.Event.touchUpInside) } func makeClearButton() { guard let collectionView = collectionView else { return } guard let superview = collectionView.superview else { return } superview.addSubview(clearButton) clearButton.anchor(to: collectionView, at: .bottomRight) clearButton.addTarget(self, action: #selector(clearButtonTapped), for: UIControl.Event.touchUpInside) clearButton.isHidden = true } @objc func buttonTapped() { guard Backlog.manager.currentGameListType == .active else { return } if button.title(for: UIControl.State.normal) == "add" { performSegue(withIdentifier: "AddGame", sender: nil) } else { delete() } } @objc func sortButtonTapped() { guard Backlog.manager.currentGameListType == .active else { return } Backlog.manager.sort() collectionView?.performBatchUpdates({ self.animateReorder() }, completion: { _ in self.games = Backlog.manager.games self.collectionView?.reloadData() }) } @objc func listButtonTapped() { Backlog.manager.switchLists() games = Backlog.manager.games collectionView?.reloadData() let active = Backlog.manager.currentGameListType == .active let title = active ? "playing" : "finished" listButton.setTitle(title, for: UIControl.State.normal) button.isHidden = !active clearButton.isHidden = active || games.count == 0 } @objc func clearButtonTapped() { let alert = UIAlertController(title: "Clear Completed?", message: "Are you sure you want to clear all your completed games?", preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { _ in self.confirmClear() })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func confirmClear() { Backlog.manager.clearCompleted() games = Backlog.manager.games collectionView?.reloadData() } func animateReorder() { let old = self.games let new = Backlog.manager.games for index in 0..<old.count { let fromIndexPath = IndexPath(item: index, section: 0) let toIndexPath = IndexPath(item: new.index(of: old[index])!, section: 0) collectionView?.moveItem(at: fromIndexPath, to: toIndexPath) } } func updateButton() { if selectedGames.count > 0 { button.setTitle("delete", for: UIControl.State.normal) sortButton.isHidden = true listButton.isHidden = true } else { button.setTitle("add", for: UIControl.State.normal) sortButton.isHidden = false listButton.isHidden = false } } func makeEmptyStateLabel() { guard let collectionView = collectionView else { return } guard let superview = collectionView.superview else { return } superview.addSubview(button) emptyStateLabel = UILabel() emptyStateLabel.numberOfLines = 0 emptyStateLabel.translatesAutoresizingMaskIntoConstraints = false emptyStateLabel.font = UIFont(name: fontName, size: Sizes.emptyState) emptyStateLabel.textColor = Colors.darkest superview.addSubview(emptyStateLabel) emptyStateLabel.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true emptyStateLabel.centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: -41).isActive = true emptyStateLabel.widthAnchor.constraint(equalTo: superview.widthAnchor, multiplier: 0.9).isActive = true } func updateEmptyStateLabel() { emptyStateLabel.isHidden = games.count > 0 let active = Backlog.manager.currentGameListType == .active if active { emptyStateLabel.text = "Looks like your backlog is empty. Lucky you!\n\nIf you have games to add, tap the add button." sortButton.isHidden = !emptyStateLabel.isHidden } else { emptyStateLabel.text = "Looks like your completed games list is empty.\n\nWhen you mark a game as 100% complete, it'll show up here." sortButton.isHidden = true return } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "ShowDetails" else { return } guard let game = sender as? Game else { return } guard let dest = segue.destination as? GameViewController else { return } dest.game = game } } // MARK:- Deletion extension ListViewController { func delete() { let singular = "Would you like to delete this game?" let plural = "Would you like to delete these games?" let string = self.selectedGames.count > 1 ? plural : singular let alert = UIAlertController(title: "Delete?", message: string, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { _ in self.confirmDelete() })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { _ in self.cancelDelete() })) present(alert, animated: true, completion: nil) } func markAsCompleted(game: Game) { Backlog.manager.move(game, from: .active, to: .completed) games = Backlog.manager.games collectionView?.reloadData() } func markAsUncompleted(game: Game) { Backlog.manager.move(game, from: .completed, to: .active) games = Backlog.manager.games collectionView?.reloadData() } func confirmDelete() { guard let cv = collectionView, let indexPaths = collectionView!.indexPathsForSelectedItems else { fatalError("You're trying to delete items that don't exist.") } indexPaths.forEach { collectionView?.deselectItem(at: $0, animated: false) } cv.performBatchUpdates({ cv.deleteItems(at: indexPaths) Backlog.manager.remove(self.selectedGames) self.games = Backlog.manager.games self.selectedGames = [] }, completion: { success in cv.reloadData() self.updateButton() }) } func cancelDelete() { selectedGames = [] collectionView?.visibleCells.forEach { programmaticDeselection = true collectionView?.deselectItem(at: collectionView!.indexPath(for: $0)!, animated: false) collectionView(collectionView!, didDeselectItemAt: collectionView!.indexPath(for: $0)!) programmaticDeselection = false } updateButton() } } // MARK:- Selection extension ListViewController { func select(cell: GameCell, at indexPath: IndexPath) { selectedGames.append(games[indexPath.item]) updateButton() } func deselect(cell: GameCell, at indexPath: IndexPath) { if !programmaticDeselection { guard let index = selectedGames.index(of: games[indexPath.item]) else { return } selectedGames.remove(at: index) } updateButton() } } // MARK: UICollectionViewDataSource extension ListViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return games.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCell", for: indexPath) as? GameCell else { fatalError("Could not dequeue a reusable GameCell.") } cell.game = games[indexPath.item] cell.delegate = self return cell } } // MARK: UICollectionViewDelegateFlowLayout extension ListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if traitCollection.horizontalSizeClass == .regular { return CGSize(width: collectionView.bounds.size.width / 2, height: GameCell.height) } else { return CGSize(width: collectionView.bounds.size.width, height: GameCell.height) } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { collectionView?.collectionViewLayout.invalidateLayout() } } // MARK: UICollectionViewDelegate extension ListViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // guard let cell = collectionView.cellForItem(at: indexPath) as? GameCell else { return } // select(cell: cell, at: indexPath) performSegue(withIdentifier: "ShowDetails", sender: games[indexPath.item]) } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { // guard let cell = collectionView.cellForItem(at: indexPath) as? GameCell else { return } // deselect(cell: cell, at: indexPath) } override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard sourceIndexPath != destinationIndexPath else { return } let swap = games[sourceIndexPath.item] games[sourceIndexPath.item] = games[destinationIndexPath.item] games[destinationIndexPath.item] = swap Backlog.manager.reorder(sourceIndexPath.item, to: destinationIndexPath.item) } } // MARK: GameCellDelegate extension ListViewController: GameCellDelegate { func game(_ game: Game, didUpdateProgress progress: Double) { if progress >= 1 && Backlog.manager.currentGameListType == .active { askToDelete(game: game) } else if progress < 1 && Backlog.manager.currentGameListType == .completed { askToMoveBack(game: game) } } func askToDelete(game: Game) { guard Backlog.manager.currentGameListType == .active else { return } let alert = UIAlertController(title: "You're done?", message: "Want to move this game to your complete list?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in self.markAsCompleted(game: game) })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) show(alert, sender: nil) } func askToMoveBack(game: Game) { guard Backlog.manager.currentGameListType == .completed else { return } let alert = UIAlertController(title: "Back into it?", message: "Want to move this game back to your active list?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in self.markAsUncompleted(game: game) })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { _ in Backlog.manager.update(game) { game.completionPercentage = 1 } self.collectionView?.reloadData() })) show(alert, sender: nil) } }
mit
447bec4d0a7b354f4bb550b7bb8be9ee
34.714286
218
0.664828
4.903619
false
false
false
false
CNKCQ/oschina
Pods/SnapKit/Source/LayoutConstraintItem.swift
1
2944
// // SnapKit // // Copyright (c) 2011-Present 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 public protocol LayoutConstraintItem: class { } @available(iOS 9.0, OSX 10.11, *) extension ConstraintLayoutGuide: LayoutConstraintItem { } extension ConstraintView: LayoutConstraintItem { } extension LayoutConstraintItem { internal func prepare() { if let view = self as? ConstraintView { view.translatesAutoresizingMaskIntoConstraints = false } } internal var superview: ConstraintView? { if let view = self as? ConstraintView { return view.superview } if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { return guide.owningView } return nil } internal var constraints: [Constraint] { return constraintsSet.allObjects as! [Constraint] } internal func add(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.add(constraint) } } internal func remove(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.remove(constraint) } } private var constraintsSet: NSMutableSet { let constraintsSet: NSMutableSet if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { constraintsSet = existing } else { constraintsSet = NSMutableSet() objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraintsSet } } private var constraintsKey: UInt8 = 0
mit
24dbf30f427cb1e1e581297f410adcdb
31.351648
111
0.689198
4.7104
false
false
false
false
vexy/Fridge
Sources/Fridge/BSONConverter.swift
1
2309
// // BSONConverter.swift // Fridge // // Created by Veljko Tekelerovic on 19.2.22. // import Foundation import BSONCoder /// Internal helper struct that wraps generic array fileprivate struct WrappedObject<T: Codable>: Codable, Identifiable { var id = BSONObjectID.init() var array: [T] init(arrayObject: [T]) { array = arrayObject } } /// Utility class providing write/read BSON functionality final class BSONConverter { private let _rawFilePath: URL init(compartment: FridgeCompartment) { _rawFilePath = compartment.objectPath } /// Writes given object to a local system storage func write<T: Encodable>(object: T) throws { var rawData: Data do { rawData = try BSONEncoder().encode(object).toData() } catch let err { print("<BSONConverter> Error occured. Reason:\n\(err)") throw err } // flush the data to a file try rawData.write(to: _rawFilePath) } /// Writes given array of objects to a local system storage func write<T: Codable>(objects: [T]) throws { var rawData: Data let wrappedObject = WrappedObject<T>.init(arrayObject: objects) do { rawData = try BSONEncoder().encode(wrappedObject).toData() } catch let err { print("<BSONConverter> Error occured. Reason:\n\(err)") throw err } // flush the data to a file try rawData.write(to: _rawFilePath) } /// Reads object from compartment data storage and returns Foundation counterpart func read<T: Decodable>() throws -> T { //} -> BSONDoc { // prepare input stream let rawBSONData = try Data(contentsOf: _rawFilePath) let realObject = try BSONDecoder().decode(T.self, from: rawBSONData) return realObject } /// Reads array of objects from compartment data storage and returns Foundation counterpart func read<T: Codable>() throws -> [T] { // get raw data from the storage let rawBSONData = try Data(contentsOf: _rawFilePath) let wrappedObject = try BSONDecoder().decode(WrappedObject<T>.self, from: rawBSONData) return wrappedObject.array } }
mit
f9508a1b142c94fe3938010393ee21b2
28.987013
95
0.615418
4.431862
false
false
false
false
yotao/YunkuSwiftSDKTEST
YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/HTTPStatusCodes.swift
1
5011
// // HTTPStatusCodes.swift // // Created by Richard Hodgkins on 11/01/2015. // Copyright (c) 2015 Richard Hodgkins. All rights reserved. // import Foundation /** HTTP status codes as per http://en.wikipedia.org/wiki/List_of_HTTP_status_codes The RF2616 standard is completely covered (http://www.ietf.org/rfc/rfc2616.txt) */ @objc public enum HTTPStatusCode : Int { // Informational case `continue` = 100 case switchingProtocols = 101 case processing = 102 // Success case ok = 200 case created = 201 case accepted = 202 case nonAuthoritativeInformation = 203 case noContent = 204 case resetContent = 205 case partialContent = 206 case multiStatus = 207 case alreadyReported = 208 case imUsed = 226 // Redirections case multipleChoices = 300 case movedPermanently = 301 case found = 302 case seeOther = 303 case notModified = 304 case useProxy = 305 case switchProxy = 306 case temporaryRedirect = 307 case permanentRedirect = 308 // Client Errors case badRequest = 400 case unauthorized = 401 case paymentRequired = 402 case forbidden = 403 case notFound = 404 case methodNotAllowed = 405 case notAcceptable = 406 case proxyAuthenticationRequired = 407 case requestTimeout = 408 case conflict = 409 case gone = 410 case lengthRequired = 411 case preconditionFailed = 412 case requestEntityTooLarge = 413 case requestURITooLong = 414 case unsupportedMediaType = 415 case requestedRangeNotSatisfiable = 416 case expectationFailed = 417 case imATeapot = 418 case authenticationTimeout = 419 case unprocessableEntity = 422 case locked = 423 case failedDependency = 424 case upgradeRequired = 426 case preconditionRequired = 428 case tooManyRequests = 429 case requestHeaderFieldsTooLarge = 431 case loginTimeout = 440 case noResponse = 444 case retryWith = 449 case unavailableForLegalReasons = 451 case requestHeaderTooLarge = 494 case certError = 495 case noCert = 496 case httpToHTTPS = 497 case tokenExpired = 498 case clientClosedRequest = 499 // Server Errors case internalServerError = 500 case notImplemented = 501 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeout = 504 case httpVersionNotSupported = 505 case variantAlsoNegotiates = 506 case insufficientStorage = 507 case loopDetected = 508 case bandwidthLimitExceeded = 509 case notExtended = 510 case networkAuthenticationRequired = 511 case networkTimeoutError = 599 } public extension HTTPStatusCode { /// Informational - Request received, continuing process. // public var isInformational: Bool { // return inRange(100...200) // } // /// Success - The action was successfully received, understood, and accepted. // public var isSuccess: Bool { // return inRange(200...299) // } // /// Redirection - Further action must be taken in order to complete the request. // public var isRedirection: Bool { // return inRange(300...399) // } // /// Client Error - The request contains bad syntax or cannot be fulfilled. // public var isClientError: Bool { // return inRange(400...499) // } // /// Server Error - The server failed to fulfill an apparently valid request. // public var isServerError: Bool { // return inRange(500...599) // } /// - returns: true if the status code is in the provided range, false otherwise. fileprivate func inRange(_ range: Range<Int>) -> Bool { return range.contains(rawValue) } } public extension HTTPStatusCode { public var localizedReasonPhrase: String { return HTTPURLResponse.localizedString(forStatusCode: rawValue) } } // MARK: - Printing extension HTTPStatusCode: CustomDebugStringConvertible, CustomStringConvertible { public var description: String { return "\(rawValue) - \(localizedReasonPhrase)" } public var debugDescription: String { return "HTTPStatusCode:\(description)" } } // MARK: - HTTP URL Response public extension HTTPStatusCode { /// Obtains a possible status code from an optional HTTP URL response. public init?(HTTPResponse: HTTPURLResponse?) { if let value = HTTPResponse?.statusCode { self.init(rawValue: value) } else { return nil } } } //public extension NSHTTPURLResponse { // public var statusCodeValue: HTTPStatusCode? { // return HTTPStatusCode(HTTPResponse: self) // } // // @availability(iOS, introduced=7.0) // public convenience init?(URL url: NSURL, statusCode: HTTPStatusCode, HTTPVersion: String?, headerFields: [NSObject : AnyObject]?) { // self.init(URL: url, statusCode: statusCode.rawValue, HTTPVersion: HTTPVersion, headerFields: headerFields) // } //}
mit
7212ccd932d056e62bca1be563211bf7
29.186747
137
0.67731
4.648423
false
false
false
false
akio0911/handMadeCalendarAdvance
handMadeCalendarAdvance/ViewController.swift
1
10834
// // ViewController.swift // handMadeCalendarAdvance // // Created by 酒井文也 on 2016/04/23. // Copyright © 2016年 just1factory. All rights reserved. // import UIKit import CalculateCalendarLogic //カレンダーに関する定数やメソッドを定義した構造体 struct CalendarSetting { //カレンダーのセクション数やアイテム数に関するセッティング static let sectionCount = 2 static let firstSectionItemCount = 7 static let secondSectionItemCount = 42 //カレンダーの日付に関するセッティング static let weekList: [String] = ["日","月","火","水","木","金","土"] //カレンダーのカラー表示に関するセッティング static func getCalendarColor(weekdayIndex: Int, holiday: Bool) -> UIColor { //日曜日または祝祭日の場合の色 if (weekdayIndex % 7 == Weekday.Sun.rawValue || holiday == true) { return UIColor(red: CGFloat(0.831), green: CGFloat(0.349), blue: CGFloat(0.224), alpha: CGFloat(1.0)) //土曜日の場合の色 } else if (weekdayIndex % 7 == Weekday.Sat.rawValue) { return UIColor(red: CGFloat(0.400), green: CGFloat(0.471), blue: CGFloat(0.980), alpha: CGFloat(1.0)) //平日の場合の色 } else { return UIColor.darkGrayColor() } } } //カレンダー表示&計算用の値を取得するための構造体 struct TargetDateSetting { static func getTargetYearAndMonthCalendar(year: Int, month: Int) -> (Int, Int) { /************* * (重要ポイント) * 現在月の1日のdayOfWeek(曜日の値)を使ってカレンダーの始まる位置を決めるので'yyyy年mm月1日'のデータを作成する。 *************/ //NSCalendarクラスのインスタンスを初期化する let targetCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let targetComps: NSDateComponents = NSDateComponents() targetComps.year = year targetComps.month = month targetComps.day = 1 let targetDate: NSDate = targetCalendar.dateFromComponents(targetComps)! //引数で渡されたNSCalendarクラスのインスタンスとNSDateクラスのインスタンスをもとに日付の情報を取得する let range: NSRange = targetCalendar.rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: targetDate) let comps: NSDateComponents = targetCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Weekday],fromDate: targetDate) //指定の年月の1日時点の日付と日数を取得してタプルで返す return (Int(comps.weekday), Int(range.length)) } } //現在日付を取得するための構造体 struct CurrentDateSetting { static func getCurrentYearAndMonth() -> (Int, Int) { //NSCalendarクラスのインスタンスを初期化する let currentCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! //引数で渡されたNSCalendarクラスのインスタンスとNSDateクラスのインスタンスをもとに日付の情報を取得する let comps: NSDateComponents = currentCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month],fromDate: NSDate()) //年と月をタプルで返す return (Int(comps.year), Int(comps.month)) } } class ViewController: UIViewController { //ラベルに表示するための年と月の変数 var targetYear: Int! = CurrentDateSetting.getCurrentYearAndMonth().0 var targetMonth: Int! = CurrentDateSetting.getCurrentYearAndMonth().1 //カレンダー用のUICollectionView @IBOutlet weak var calendarCollectionView: UICollectionView! //Outlet接続をしたUI部品の一覧 @IBOutlet weak var prevMonthButton: UIButton! @IBOutlet weak var nextMonthButton: UIButton! @IBOutlet weak var currentMonthLabel: UILabel! @IBOutlet weak var backgroundView: UIView! //該当年月の日のリスト var dayCellLists: [String?] = [] //日本の祝祭日判定用のインスタンス var holidayObj: CalculateCalendarLogic = CalculateCalendarLogic() override func viewDidLoad() { super.viewDidLoad() //Cellに使われるクラスを登録 calendarCollectionView.registerClass(CalendarCell.self, forCellWithReuseIdentifier: "CalendarCell") //UICollectionViewDelegate,UICollectionViewDataSourceの拡張宣言 calendarCollectionView.delegate = self calendarCollectionView.dataSource = self changeCalendar() } //前の月のボタンが押された際のアクション @IBAction func displayPrevMonth(sender: AnyObject) { //現在の月に対して-1をする if (targetMonth == 1) { targetYear = targetYear - 1 targetMonth = 12 } else { targetMonth = targetMonth - 1 } changeCalendar() } //次の月のボタンが押された際のアクション @IBAction func displayNextMonth(sender: AnyObject) { //現在の月に対して+1をする if (targetMonth == 12) { targetYear = targetYear + 1 targetMonth = 1 } else { targetMonth = targetMonth + 1 } changeCalendar() } //カレンダー表記を変更する private func changeCalendar() { updateDataSource() calendarCollectionView.reloadData() displaySelectedCalendar() } //表示対象のカレンダーの年月を表示する private func displaySelectedCalendar() { currentMonthLabel.text = "\(targetYear)年\(targetMonth)月" } //CollectionViewCellに格納する日のデータを作成する private func updateDataSource() { var day = 1 dayCellLists = [] for i in 0..<(CalendarSetting.secondSectionItemCount) { if isCellUsing(i) { dayCellLists.append(String(day)) day += 1 } else { dayCellLists.append(nil) } } } //セルに値が格納されるかを判定する private func isCellUsing(index: Int) -> Bool { //該当の年と月から1日の曜日と最大日数のタプルを取得する let targetConcern: (Int, Int) = TargetDateSetting.getTargetYearAndMonthCalendar(targetYear, month: targetMonth) let targetWeekdayIndex: Int = targetConcern.0 let targetMaxDay: Int = targetConcern.1 //CollectionViewの該当セルインデックスに値が入るかを判定する if (index < targetWeekdayIndex - 1) { return false } else if (index == targetWeekdayIndex - 1 || index < targetWeekdayIndex + targetMaxDay - 1) { return true } else if (index == targetWeekdayIndex + targetMaxDay - 1 || index < CalendarSetting.secondSectionItemCount) { return false } return false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - UICollectionViewDataSource extension ViewController: UICollectionViewDataSource { //配置したCollectionViewのセクション数を返す func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return CalendarSetting.sectionCount } //配置したCollectionViewの各セクションのアイテム数を返す func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return CalendarSetting.firstSectionItemCount case 1: return CalendarSetting.secondSectionItemCount default: return 0 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CalendarCell", forIndexPath: indexPath) as! CalendarCell switch indexPath.section { case 0: //曜日を表示する cell.textLabel!.text = CalendarSetting.weekList[indexPath.row] cell.textLabel!.textColor = CalendarSetting.getCalendarColor(indexPath.row, holiday: false) return cell case 1: //該当年月の日付を表示する let day: String? = dayCellLists[indexPath.row] if isCellUsing(indexPath.row) { let holiday: Bool = holidayObj.judgeJapaneseHoliday(targetYear, month: targetMonth, day: Int(day!)!) cell.textLabel!.textColor = CalendarSetting.getCalendarColor(indexPath.row, holiday: holiday) cell.textLabel!.text = day } else { cell.textLabel!.text = "" } return cell default: return cell } } } // MARK: - UICollectionViewDelegate extension ViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { //日付が入るセルならば処理をする if isCellUsing(indexPath.row) { let day: String? = dayCellLists[indexPath.row] print("\(targetYear)年\(targetMonth)月\(day!)日") } } } // MARK: - UIScrollViewDelegate extension ViewController: UIScrollViewDelegate { //セルのサイズを設定 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let numberOfMargin: CGFloat = 8.0 let width: CGFloat = (collectionView.frame.size.width - CGFloat(1.0) * numberOfMargin) / CGFloat(7) let height: CGFloat = width * 1.0 return CGSizeMake(width, height) } //セルの垂直方向のマージンを設定 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return CGFloat(1.0) } //セルの水平方向のマージンを設定 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return CGFloat(1.0) } }
mit
89cac7c9841b040b36dc3cdca619a1f6
28.382445
178
0.654646
4.637803
false
false
false
false
cam-hop/APIUtility
RxSwiftFluxDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositories.swift
4
5426
// // GitHubSearchRepositories.swift // RxExample // // Created by Krunoslav Zaher on 3/18/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // enum GitHubCommand { case changeSearch(text: String) case loadMoreItems case gitHubResponseReceived(SearchRepositoriesResponse) } struct GitHubSearchRepositoriesState { // control var searchText: String var shouldLoadNextPage: Bool var repositories: Version<[Repository]> // Version is an optimization. When something unrelated changes, we don't want to reload table view. var nextURL: URL? var failure: GitHubServiceError? init(searchText: String) { self.searchText = searchText shouldLoadNextPage = true repositories = Version([]) nextURL = URL(string: "https://api.github.com/search/repositories?q=\(searchText.URLEscaped)") failure = nil } } extension GitHubSearchRepositoriesState { static let initial = GitHubSearchRepositoriesState(searchText: "") static func reduce(state: GitHubSearchRepositoriesState, command: GitHubCommand) -> GitHubSearchRepositoriesState { switch command { case .changeSearch(let text): return GitHubSearchRepositoriesState(searchText: text).mutateOne { $0.failure = state.failure } case .gitHubResponseReceived(let result): switch result { case let .success((repositories, nextURL)): return state.mutate { $0.repositories = Version($0.repositories.value + repositories) $0.shouldLoadNextPage = false $0.nextURL = nextURL $0.failure = nil } case let .failure(error): return state.mutateOne { $0.failure = error } } case .loadMoreItems: return state.mutate { if $0.failure == nil { $0.shouldLoadNextPage = true } } } } } import RxSwift import RxCocoa /** This method contains the gist of paginated GitHub search. */ func githubSearchRepositories( searchText: Driver<String>, loadNextPageTrigger: @escaping (Driver<GitHubSearchRepositoriesState>) -> Driver<()>, performSearch: @escaping (URL) -> Observable<SearchRepositoriesResponse> ) -> Driver<GitHubSearchRepositoriesState> { let searchPerformerFeedback: (Driver<GitHubSearchRepositoriesState>) -> Driver<GitHubCommand> = { state in // this is a general pattern how to model a most common feedback loop // first select part of state describing feedback control return state.map { (searchText: $0.searchText, shouldLoadNextPage: $0.shouldLoadNextPage, nextURL: $0.nextURL) } // only propagate changed control values since there could be multiple feedback loops working in parallel .distinctUntilChanged { $0 == $1 } // perform feedback loop effects .flatMapLatest { (searchText, shouldLoadNextPage, nextURL) -> Driver<GitHubCommand> in if !shouldLoadNextPage { return Driver.empty() } if searchText.isEmpty { return Driver.just(GitHubCommand.gitHubResponseReceived(.success(repositories: [], nextURL: nil))) } guard let nextURL = nextURL else { return Driver.empty() } return performSearch(nextURL) .asDriver(onErrorJustReturn: .failure(GitHubServiceError.networkError)) .map(GitHubCommand.gitHubResponseReceived) } } // this is degenerated feedback loop that doesn't depend on output state let inputFeedbackLoop: (Driver<GitHubSearchRepositoriesState>) -> Driver<GitHubCommand> = { state in let loadNextPage = loadNextPageTrigger(state).map { _ in GitHubCommand.loadMoreItems } let searchText = searchText.map(GitHubCommand.changeSearch) return Driver.merge(loadNextPage, searchText) } // Create a system with two feedback loops that drive the system // * one that tries to load new pages when necessary // * one that sends commands from user input return Driver.system(GitHubSearchRepositoriesState.initial, accumulator: GitHubSearchRepositoriesState.reduce, feedback: searchPerformerFeedback, inputFeedbackLoop) } func == ( lhs: (searchText: String, shouldLoadNextPage: Bool, nextURL: URL?), rhs: (searchText: String, shouldLoadNextPage: Bool, nextURL: URL?) ) -> Bool { return lhs.searchText == rhs.searchText && lhs.shouldLoadNextPage == rhs.shouldLoadNextPage && lhs.nextURL == rhs.nextURL } extension GitHubSearchRepositoriesState { var isOffline: Bool { guard let failure = self.failure else { return false } if case .offline = failure { return true } else { return false } } var isLimitExceeded: Bool { guard let failure = self.failure else { return false } if case .githubLimitReached = failure { return true } else { return false } } } extension GitHubSearchRepositoriesState: Mutable { }
mit
646f3505e6d0e606df470c06397caacf
34
144
0.627465
5.236486
false
false
false
false
richardpiazza/LCARSDisplayKit
Sources/LCARSDisplayKitUI/CommandSequencer.swift
1
3433
#if (os(iOS) || os(tvOS)) import UIKit import LCARSDisplayKit public protocol CommandSequencerDelegate { func neutralBeep() func successBeep() func failureBeep() } public typealias CommandSequenceCompletion = () -> Void public struct CommandSequence { public var path: [Button] public var completion: CommandSequenceCompletion? public init(_ path: [Button], completion: CommandSequenceCompletion? = nil) { self.path = path self.completion = completion } } public class CommandSequencer { public static var `default`: CommandSequencer = CommandSequencer() public var delegate: CommandSequencerDelegate? private var commandSequences: [CommandSequence] = [] private var currentPath: [Button] = [] public func register(commandSequence sequence: CommandSequence) { if commandSequences.contains(where: { (cs) -> Bool in return cs.path == sequence.path }) { return } print("Registering Command Sequence") commandSequences.append(sequence) } public func unregister(commandSequence sequence: CommandSequence) { var index: Int = -1 for (idx, cs) in commandSequences.enumerated() { if cs.path == sequence.path { index = idx break } } guard index != -1 else { return } print("Unregistering Comannd Sequence") commandSequences.remove(at: index) } private func completion(for commandSequence: [Button]) -> CommandSequenceCompletion? { let sequence = commandSequences.first(where: { (cs) -> Bool in return cs.path == commandSequence }) return sequence?.completion } private func sequencesContainingPrefix(_ commandSequence: [Button]) -> [CommandSequence] { guard commandSequence.count > 0 else { return [] } var sequences = [CommandSequence]() for sequence in commandSequences { guard sequence.path.count >= commandSequence.count else { break } var prefixed = true for i in 0..<commandSequence.count { if sequence.path[i] != commandSequence[i] { prefixed = false } } if prefixed { sequences.append(sequence) } } return sequences } public func didTouch(_ sender: Button) { currentPath.append(sender) guard commandSequences.count > 0 else { print("No Command Sequences") delegate?.failureBeep() currentPath.removeAll() return } if let completion = completion(for: currentPath) { print("Command Sequence Complete") completion() delegate?.successBeep() currentPath.removeAll() return } guard sequencesContainingPrefix(currentPath).count > 0 else { print("Command Sequence Failed") delegate?.failureBeep() currentPath.removeAll() return } print("Command Sequence In Progress") delegate?.neutralBeep() } } #endif
mit
5a09e68a6a75a6c6e498a813593fa3bb
26.910569
94
0.558986
5.322481
false
false
false
false
mbigatti/StatusApp
StatusApp/ZoomAnimatedController.swift
1
4435
// // ZoomingViewControllerAnimatedTransitioning.swift // StatusApp // // Created by Massimiliano Bigatti on 30/09/14. // Copyright (c) 2014 Massimiliano Bigatti. All rights reserved. // import Foundation class ZoomAnimatedController : NSObject, UIViewControllerAnimatedTransitioning { var presenting = true var animatingIndexPath : NSIndexPath? /// duration of the animation private let animationDuration : Double = 0.35 func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return animationDuration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if presenting { animatePresenting(transitionContext) } else { animateDismissing(transitionContext) } } func animatePresenting(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as UITableViewController! let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! // // configure the destination controller initial frame // let tableView = fromViewController.tableView animatingIndexPath = tableView.indexPathForSelectedRow() if animatingIndexPath == nil { let lastRow = tableView.dataSource!.tableView(tableView, numberOfRowsInSection: 0) - 1 animatingIndexPath = NSIndexPath(forRow: lastRow, inSection: 0) toViewController.view.backgroundColor = UIColor.blackColor() } let originFrame = tableView.rectForRowAtIndexPath(animatingIndexPath!) toViewController.view.frame = originFrame // // add destination controller to content view // toViewController.view.clipsToBounds = true transitionContext.containerView().addSubview(toViewController.view) // // perform animation // tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 0 UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in toViewController.view.frame = transitionContext.finalFrameForViewController(toViewController) //fromViewController.view.transform = CGAffineTransformMakeTranslation(-toViewController.view.frame.size.width, 0) }) { (finished) -> Void in // // restore original properties and complete transition // //fromViewController.view.transform = CGAffineTransformIdentity tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 1 toViewController.view.clipsToBounds = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } func animateDismissing(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as UITableViewController! transitionContext.containerView().addSubview(toViewController.view) transitionContext.containerView().bringSubviewToFront(fromViewController.view) fromViewController.view.clipsToBounds = true let tableView = toViewController.tableView tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 0 // // perform animation // UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in let frame = tableView.rectForRowAtIndexPath(self.animatingIndexPath!) fromViewController.view.frame = frame }) { (finished) -> Void in // // restore original properties and complete transition // tableView.cellForRowAtIndexPath(self.animatingIndexPath!)?.contentView.alpha = 1 fromViewController.view.clipsToBounds = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } }
mit
17142a04462600bdadf65234db6fd62b
42.920792
139
0.698985
6.929688
false
false
false
false
Vostro162/VaporTelegram
Sources/App/File.swift
1
944
// // File.swift // VaporTelegramBot // // Created by Marius Hartig on 08.05.17. // // import Foundation /* * * * This object represents a file ready to be downloaded. * The file can be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>. * It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile. * */ public struct File: DataSet { // Unique identifier for this file public let fileId: FileId // Optional. File size, if known public let fileSize: Int? // Optional. File path. Use https://api.telegram.org/file/bot<token>/<file_path> to get the file. public let filePath: String? public init(fileId: FileId, fileSize: Int? = nil, filePath: String? = nil) { self.fileId = fileId self.fileSize = fileSize self.filePath = filePath } }
mit
cf053202879edbd49b7aa71243fdd4ff
23.205128
138
0.643008
3.853061
false
false
false
false
butterproject/butter-ios
Butter/UI/Views/PlaceholderTextView.swift
1
4239
// // PlaceholderTextView.swift // // Copyright (c) 2015 Zhouqi Mo (https://github.com/MoZhouqi) // // 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 @IBDesignable public class PlaceholderTextView: UITextView { struct Constants { static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22) } @IBInspectable public var placeholder: String = "" { didSet { placeholderLabel.text = placeholder } } @IBInspectable public var placeholderColor: UIColor = PlaceholderTextView.Constants.defaultiOSPlaceholderColor { didSet { placeholderLabel.textColor = placeholderColor } } public let placeholderLabel: UILabel = UILabel() override public var font: UIFont! { didSet { placeholderLabel.font = font } } override public var textAlignment: NSTextAlignment { didSet { placeholderLabel.textAlignment = textAlignment } } override public var text: String! { didSet { textDidChange() } } override public var attributedText: NSAttributedString! { didSet { textDidChange() } } override public var textContainerInset: UIEdgeInsets { didSet { updateConstraintsForPlaceholderLabel() } } var placeholderLabelConstraints = [NSLayoutConstraint]() override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil) placeholderLabel.font = font placeholderLabel.textColor = placeholderColor placeholderLabel.textAlignment = textAlignment placeholderLabel.text = placeholder placeholderLabel.numberOfLines = 0 placeholderLabel.backgroundColor = UIColor.clearColor() placeholderLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(placeholderLabel) updateConstraintsForPlaceholderLabel() } func updateConstraintsForPlaceholderLabel() { var newConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]-(\(textContainerInset.right + textContainer.lineFragmentPadding))-|", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-(\(textContainerInset.top))-[placeholder]-(>=\(textContainerInset.bottom))-|", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) removeConstraints(placeholderLabelConstraints) addConstraints(newConstraints) placeholderLabelConstraints = newConstraints } func textDidChange() { placeholderLabel.hidden = !text.isEmpty } override public func layoutSubviews() { super.layoutSubviews() placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0 } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: nil) } }
gpl-3.0
43bbfa77008acf457daeff66b3733d76
29.948905
223
0.75631
4.607609
false
false
false
false
ello/ello-ios
Sources/Utilities/Onboarding.swift
1
822
//// /// Onboarding.swift // import SwiftyUserDefaults class Onboarding { static let currentVersion = 3 static let minCreatorTypeVersion = 1 static let shared = Onboarding() func updateVersionToLatest() { ProfileService().updateUserProfile([.webOnboardingVersion: Onboarding.currentVersion]) .ignoreErrors() } // only show if onboardingVersion is nil func shouldShowOnboarding(_ user: User) -> Bool { return user.onboardingVersion == nil } // only show if onboardingVersion is set and < 3 // (if it isn't set, we will show the entire onboarding flow) func shouldShowCreatorType(_ user: User) -> Bool { if let onboardingVersion = user.onboardingVersion { return onboardingVersion < 3 } return false } }
mit
5d0269711d14cca5956402a749c6653c
24.6875
94
0.655718
4.892857
false
false
false
false
qxuewei/XWPageView
XWPageViewDemo/XWPageViewDemo/XWPageView/XWTitleStyle.swift
1
1317
// // XWTitleStyle.swift // XWPageViewDemo // // Created by 邱学伟 on 2016/12/10. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class XWTitleStyle { /// 是否是滚动的Title var isScrollEnable : Bool = false /// 普通Title颜色 var normalColor : UIColor = UIColor(R: 0, G: 0, B: 0) /// 选中Title颜色 var selectedColor : UIColor = UIColor(R: 255, G: 127, B: 0) /// Title字体大小 var font : UIFont = UIFont.systemFont(ofSize: 14.0) /// 滚动Title的字体间距 var titleMargin : CGFloat = 20 /// title的高度 var titleHeight : CGFloat = 44 /// 是否显示底部滚动条 var isShowBottomLine : Bool = false /// 底部滚动条的颜色 var bottomLineColor : UIColor = UIColor.orange /// 底部滚动条的高度 var bottomLineH : CGFloat = 2 /// 是否进行缩放 var isNeedScale : Bool = false var scaleRange : CGFloat = 1.2 /// 是否显示遮盖 var isShowCover : Bool = false /// 遮盖背景颜色 var coverBgColor : UIColor = UIColor.lightGray /// 文字&遮盖间隙 var coverMargin : CGFloat = 5 /// 遮盖的高度 var coverH : CGFloat = 25 /// 设置圆角大小 var coverRadius : CGFloat = 12 }
apache-2.0
fc6f91a09d9734a7fa41444f6bca2cb0
21.52
63
0.598579
3.843003
false
false
false
false
open-telemetry/opentelemetry-swift
Examples/Network Sample/main.swift
1
1594
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk import StdoutExporter import URLSessionInstrumentation func simpleNetworkCall() { let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let semaphore = DispatchSemaphore(value: 0) let task = URLSession.shared.dataTask(with: request) { data, _, _ in if let data = data { let string = String(decoding: data, as: UTF8.self) print(string) } semaphore.signal() } task.resume() semaphore.wait() } class SessionDelegate: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate { let semaphore = DispatchSemaphore(value: 0) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { semaphore.signal() } } let delegate = SessionDelegate() func simpleNetworkCallWithDelegate() { let session = URLSession(configuration: .default, delegate: delegate, delegateQueue:nil) let url = URL(string: "http://httpbin.org/get")! let request = URLRequest(url: url) let task = session.dataTask(with: request) task.resume() delegate.semaphore.wait() } let spanProcessor = SimpleSpanProcessor(spanExporter: StdoutExporter(isDebug: true)) OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor) let networkInstrumentation = URLSessionInstrumentation(configuration: URLSessionInstrumentationConfiguration()) simpleNetworkCall() simpleNetworkCallWithDelegate() sleep(1)
apache-2.0
5e1b657b7b614a2e5f8b84d28e567185
25.566667
111
0.725847
4.502825
false
false
false
false
maxim-pervushin/Overlap
Overlap/App/Editors/IntervalEditor.swift
1
1806
// // Created by Maxim Pervushin on 29/04/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import Foundation class IntervalEditor { var timeZone: NSTimeZone? = nil { didSet { updated?() } } var start: Double? = nil { didSet { updated?() } } var end: Double? = nil { didSet { updated?() } } var updated: (Void -> Void)? = nil { didSet { updated?() } } var interval: Interval? { set { if let newValue = newValue { originalTimeZone = newValue.timeZone timeZone = newValue.timeZone originalStart = newValue.start start = newValue.start originalEnd = newValue.end end = newValue.end } else { originalTimeZone = nil timeZone = nil originalStart = nil start = nil originalEnd = nil end = nil } } get { if let timeZone = timeZone, start = start, end = end { return Interval(timeZone: timeZone, start: start, end: end) } else { return nil } } } private var originalTimeZone: NSTimeZone? = nil { didSet { updated?() } } private var originalStart: Double? = nil { didSet { updated?() } } private var originalEnd: Double? = nil { didSet { updated?() } } var hasChanges: Bool { return originalTimeZone != timeZone || originalStart != start || originalEnd != end } }
mit
c1d496a90fea89757d039cc71a13e72c
21.02439
91
0.451274
5.204611
false
false
false
false
newtonstudio/cordova-plugin-device
imgly-sdk-ios-master/imglyKit/Backend/Processing/IMGLYStickerFilter.swift
1
4146
// // IMGLYStickerFilter.swift // imglyKit // // Created by Sascha Schwabbauer on 24/03/15. // Copyright (c) 2015 9elements GmbH. All rights reserved. // #if os(iOS) import UIKit import CoreImage #elseif os(OSX) import AppKit import QuartzCore #endif import CoreGraphics public class IMGLYStickerFilter: CIFilter { /// A CIImage object that serves as input for the filter. public var inputImage: CIImage? /// The sticker that should be rendered. #if os(iOS) public var sticker: UIImage? #elseif os(OSX) public var sticker: NSImage? #endif /// The transform to apply to the sticker public var transform = CGAffineTransformIdentity /// The relative center of the sticker within the image. public var center = CGPoint() /// The relative size of the sticker within the image. public var size = CGSize() override init() { super.init() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Returns a CIImage object that encapsulates the operations configured in the filter. (read-only) public override var outputImage: CIImage! { if inputImage == nil { return CIImage.emptyImage() } if sticker == nil { return inputImage } var stickerImage = createStickerImage() var stickerCIImage = CIImage(CGImage: stickerImage.CGImage) var filter = CIFilter(name: "CISourceOverCompositing") filter.setValue(inputImage, forKey: kCIInputBackgroundImageKey) filter.setValue(stickerCIImage, forKey: kCIInputImageKey) return filter.outputImage } #if os(iOS) private func createStickerImage() -> UIImage { let rect = inputImage!.extent() let imageSize = rect.size UIGraphicsBeginImageContext(imageSize) UIColor(white: 1.0, alpha: 0.0).setFill() UIRectFill(CGRect(origin: CGPoint(), size: imageSize)) let context = UIGraphicsGetCurrentContext() drawStickerInContext(context, withImageOfSize: imageSize) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } #elseif os(OSX) private func createStickerImage() -> NSImage { let rect = inputImage!.extent() let imageSize = rect.size let image = NSImage(size: imageSize) image.lockFocus() NSColor(white: 1, alpha: 0).setFill() NSRectFill(CGRect(origin: CGPoint(), size: imageSize)) let context = NSGraphicsContext.currentContext()!.CGContext drawStickerInContext(context, withImageOfSize: imageSize) image.unlockFocus() return image } #endif private func drawStickerInContext(context: CGContextRef, withImageOfSize imageSize: CGSize) { CGContextSaveGState(context) let center = CGPoint(x: self.center.x * imageSize.width, y: self.center.y * imageSize.height) let size = CGSize(width: self.size.width * imageSize.width, height: self.size.height * imageSize.height) let imageRect = CGRect(origin: center, size: size) // Move center to origin CGContextTranslateCTM(context, imageRect.origin.x, imageRect.origin.y) // Apply the transform CGContextConcatCTM(context, self.transform) // Move the origin back by half CGContextTranslateCTM(context, imageRect.size.width * -0.5, imageRect.size.height * -0.5) sticker?.drawInRect(CGRect(origin: CGPoint(), size: size)) CGContextRestoreGState(context) } } extension IMGLYStickerFilter: NSCopying { public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! IMGLYStickerFilter copy.inputImage = inputImage?.copyWithZone(zone) as? CIImage copy.sticker = sticker copy.center = center copy.size = size copy.transform = transform return copy } }
apache-2.0
029022a70754fd04df8183c73f2e0770
30.172932
112
0.644959
4.889151
false
false
false
false
shahabc/ProjectNexus
Mobile Buy SDK Sample Apps/Advanced App - ObjC/Mobile Buy SDK Advanced Sample/ProductCollectionViewController.swift
1
4364
// // ProductCollectionViewController.swift // Mobile Buy SDK Advanced Sample // // Created by Victor Hong on 15/12/2016. // Copyright © 2016 Shopify. All rights reserved. // import UIKit import SDWebImage class ProductCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var collection: BUYCollection? //var collections: [BUYCollection] = [] var products: [BUYProduct] = [] var collectionOperation : Operation? //var cart: BUYCart? let singleton = Singleton.sharedInstance @IBOutlet weak var productCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.title = collection?.title self.getCollectionWithSortOrder(collectionSort:.collectionDefault) } // MARK: - UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = productCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? ProductCollectionViewCell let product = self.products[indexPath.row] //cell?.backgroundColor = .randomColor() if let image = product.images[0] as? BUYImageLink { if let imageurl = image.sourceURL { cell?.productCollectionImageView.sd_setImage(with: imageurl, placeholderImage: UIImage(named: "placeholder.png")) } } cell?.productCollectionLabel.text = product.title cell?.productCollectionLabel.sizeToFit() if let productPrice = product.minimumPrice { cell?.priceCollectionLabel.text = "$\(productPrice)" cell?.priceCollectionLabel.sizeToFit() } return cell! } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let product = products[indexPath.row] let productViewController = setThemeVC() productViewController.load(with: product) { success, error in if (error == nil) { self.navigationController?.pushViewController(productViewController, animated: true) } } } func setThemeVC() -> ProductViewController { let theme = Theme() theme.style = ThemeStyle(rawValue: 0)! theme.tintColor = UIColor(red: 0.47999998927116394, green: 0.70999997854232788, blue: 0.36000001430511475, alpha: 1) theme.showsProductImageBackground = true let productViewController = ProductViewController(client: singleton.client, cart: singleton.cart) productViewController?.merchantId = "" return productViewController! } func getCollectionWithSortOrder(collectionSort: BUYCollectionSort){ self.collectionOperation?.cancel() UIApplication.shared.isNetworkActivityIndicatorVisible = true self.collectionOperation = (singleton.client.getProductsPage(1, inCollection: self.collection?.identifier, withTags: nil, sortOrder: collectionSort, completion: { products, page, reachedEnd, error in UIApplication.shared.isNetworkActivityIndicatorVisible = false if (error == nil && (products != nil)) { self.products = products! self.productCollectionView.reloadData() } else { print("Error fetching products: \(error)") } })) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
946cbf5eb6e93a79fa1da84c21cad696
32.821705
170
0.639697
5.481156
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/SettingsHistory.swift
1
8582
// // SettingsHistory.swift // Slide for Reddit // // Created by Carlos Crane on 7/17/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import UIKit class SettingsHistory: BubbleSettingTableViewController { var saveHistoryCell: UITableViewCell = InsetCell() var saveHistory = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } var saveNSFWHistoryCell: UITableViewCell = InsetCell() var saveNSFWHistory = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } var hideSeenCell: UITableViewCell = InsetCell() var hideSeen = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } var readOnScrollCell: UITableViewCell = InsetCell() var readOnScroll = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } var dotCell: UITableViewCell = InsetCell() var dot = UISwitch().then { $0.onTintColor = ColorUtil.baseAccent } var exportCollectionsCell: UITableViewCell = InsetCell() var clearHistory: UITableViewCell = InsetCell() var clearSubs: UITableViewCell = InsetCell() @objc func switchIsChanged(_ changed: UISwitch) { if changed == saveHistory { SettingValues.saveHistory = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_saveHistory) } else if changed == saveNSFWHistory { SettingValues.saveNSFWHistory = !changed.isOn UserDefaults.standard.set(!changed.isOn, forKey: SettingValues.pref_saveNSFWHistory) } else if changed == hideSeen { SettingValues.hideSeen = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_hideSeen) } else if changed == dot { SettingValues.newIndicator = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_newIndicator) } else if changed == readOnScroll { SettingValues.markReadOnScroll = changed.isOn UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_markReadOnScroll) } UserDefaults.standard.synchronize() doDisables() tableView.reloadData() } public func createCell(_ cell: UITableViewCell, _ switchV: UISwitch? = nil, isOn: Bool, text: String) { cell.textLabel?.text = text cell.textLabel?.textColor = ColorUtil.theme.fontColor cell.backgroundColor = ColorUtil.theme.foregroundColor cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let s = switchV { s.isOn = isOn s.addTarget(self, action: #selector(SettingsLayout.switchIsChanged(_:)), for: UIControl.Event.valueChanged) cell.accessoryView = s } cell.selectionStyle = UITableViewCell.SelectionStyle.none } override func loadView() { super.loadView() self.view.backgroundColor = ColorUtil.theme.backgroundColor // set the title self.title = "History" self.headers = ["Settings", "Clear history", "Export data"] createCell(saveHistoryCell, saveHistory, isOn: SettingValues.saveHistory, text: "Save submission and subreddit history") createCell(saveNSFWHistoryCell, saveNSFWHistory, isOn: !SettingValues.saveNSFWHistory, text: "Hide NSFW submission and subreddit history") createCell(readOnScrollCell, readOnScroll, isOn: SettingValues.markReadOnScroll, text: "Mark submissions as read when scrolled off screen") createCell(dotCell, dot, isOn: SettingValues.newIndicator, text: "New submissions indicator") createCell(exportCollectionsCell, nil, isOn: false, text: "Export your Slide collections as .csv") exportCollectionsCell.accessoryType = .disclosureIndicator dotCell.detailTextLabel?.numberOfLines = 0 dotCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor dotCell.detailTextLabel?.text = "Enabling this will disable the 'grayed out' effect of read submissions" createCell(hideSeenCell, hideSeen, isOn: SettingValues.hideSeen, text: "Hide read posts automatically") hideSeenCell.detailTextLabel?.numberOfLines = 0 hideSeenCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor hideSeenCell.detailTextLabel?.text = "Enabling this may lead to no posts loading in a subreddit" clearHistory.textLabel?.text = "Clear submission history" clearHistory.backgroundColor = ColorUtil.theme.foregroundColor clearHistory.textLabel?.textColor = ColorUtil.theme.fontColor clearHistory.selectionStyle = UITableViewCell.SelectionStyle.none clearHistory.accessoryType = .disclosureIndicator clearSubs.textLabel?.text = "Clear subreddit history" clearSubs.backgroundColor = ColorUtil.theme.foregroundColor clearSubs.textLabel?.textColor = ColorUtil.theme.fontColor clearSubs.selectionStyle = UITableViewCell.SelectionStyle.none clearSubs.accessoryType = .disclosureIndicator doDisables() self.tableView.tableFooterView = UIView() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 { if indexPath.row == 0 { History.clearHistory() BannerUtil.makeBanner(text: "Submission history cleared!", color: GMColor.green500Color(), seconds: 5, context: self) } else { Subscriptions.clearSubHistory() BannerUtil.makeBanner(text: "Subreddit history cleared!", color: GMColor.green500Color(), seconds: 5, context: self) } } if indexPath.section == 2 { exportCollectionsCSV(from: Collections.collectionIDs) } tableView.deselectRow(at: indexPath, animated: true) } func doDisables() { if SettingValues.saveHistory { saveNSFWHistory.isEnabled = true readOnScroll.isEnabled = true } else { saveNSFWHistory.isEnabled = false readOnScroll.isEnabled = false } } func exportCollectionsCSV(from: NSDictionary) { var csvString = "\("Collection Name"),\("Reddit permalink")\n\n" for key in from.allKeys { csvString += "\(from[key] ?? "") , https://redd.it/\((key as! String).replacingOccurrences(of: "t3_", with: ""))\n" } let fileManager = FileManager.default do { let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false) let fileURL = path.appendingPathComponent("Slide-Collections\(Date().dateString().replacingOccurrences(of: " ", with: "-").replacingOccurrences(of: ",", with: "-")).csv") try csvString.write(to: fileURL, atomically: true, encoding: .utf8) var filesToShare = [Any]() filesToShare.append(fileURL) let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil) self.present(activityViewController, animated: true, completion: nil) } catch { print("error creating file") } } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: switch indexPath.row { case 0: return self.saveHistoryCell case 1: return self.saveNSFWHistoryCell case 2: return self.readOnScrollCell case 3: return self.dotCell case 4: return self.hideSeenCell default: fatalError("Unknown row in section 0") } case 1: switch indexPath.row { case 0: return self.clearHistory case 1: return self.clearSubs default: fatalError("Unknown row in section 0") } case 2: return exportCollectionsCell default: fatalError("Unknown section") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 5 // section 0 has 2 rows case 1: return 2 case 2: return 1 default: fatalError("Unknown number of sections") } } }
apache-2.0
381af00c9ad9e2a7b7f0182e5861b5c1
40.858537
182
0.656916
5.012266
false
false
false
false
masters3d/xswift
exercises/gigasecond/Sources/GigasecondExample.swift
1
2778
import Foundation private extension tm { var year: Int32 { return tm_year + 1900 } var month: Int32 { return tm_mon + 1 } var day: Int32 { return tm_mday } var time:(hour: Int32, mins: Int32, secs: Int32) { return (hour: tm_hour, mins: tm_min, secs:tm_sec) } init(year: Int32, month: Int32, day: Int32, hour: Int32 = 0, mins: Int32 = 0, secs: Int32 = 0) { self.init() self.tm_year = year - 1900 self.tm_mon = month - 1 self.tm_mday = day self.tm_hour = hour self.tm_min = mins self.tm_sec = secs } mutating func dateByAddingSeconds(_ seconds: Int) -> tm { var d1 = timegm(&self) + seconds return gmtime(&d1).pointee } private func addLeadingZero(_ input: Int32) -> String { var addZero = false (0...9).forEach { if $0 == Int(input) { addZero = true } } if addZero { return "0\(input)" } else { return String(input) } } var description: String { let date = [year, month, day, time.hour, time.mins, time.secs].map { addLeadingZero($0) } return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5] } } func == (lhs: Gigasecond, rhs: Gigasecond) -> Bool { return lhs.description == rhs.description } func == (lhs: String, rhs: Gigasecond) -> Bool { return lhs == rhs.description } struct Gigasecond: Equatable, CustomStringConvertible { private var startDate: tm! private var gigasecondDate: tm! init?(from: String) { if let result = parse(from) { var start = result self.startDate = start self.gigasecondDate = start.dateByAddingSeconds(1_000_000_000) } else { return nil } } private func parse(_ input: String) -> tm? { let dateTime = input.characters.split(separator: "T").map { String($0) } if dateTime.count > 1 { let date = dateTime[0].characters.split(separator: "-").map { String($0) } let time = dateTime[1].characters.split(separator: ":").map { String($0) } if date.count == 3 && time.count == date.count { let year = Int32(date[0]) ?? 0 let month = Int32(date[1]) ?? 0 let day = Int32(date[2]) ?? 0 let hour = Int32(time[0]) ?? 0 let minute = Int32(time[1]) ?? 0 let second = Int32(time[2]) ?? 0 return tm(year: year, month: month, day: day, hour: hour, mins: minute, secs: second) } } return nil } var description: String { return gigasecondDate.description } }
mit
aacfd9af37aa8de8021af33736cb4ad5
27.9375
102
0.529518
3.621904
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/different-ways-to-add-parentheses.swift
1
3121
class Solution { /// - Complexity: /// - Time: O(2 ^ n), n = number of operator in expression. Since, at each operator, we could split the expr there or not. /// - Space: O(m), m = possible result for current expression. func diffWaysToCompute(_ expression: String) -> [Int] { if let num = Int(expression) { return [num] } var result = [Int]() for index in expression.indices { if "+-*".contains(expression[index]) { let left = diffWaysToCompute(String(expression[..<index])) let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex])) if expression[index] == Character("+") { for l in left { for r in right { result.append(l + r) } } } else if expression[index] == Character("-") { for l in left { for r in right { result.append(l - r) } } } else if expression[index] == Character("*") { for l in left { for r in right { result.append(l * r) } } } } } // print(expression, result) return result } } class Solution { /// Recursive solution with memorization. private var memo: [String : [Int]]! func diffWaysToCompute(_ expression: String) -> [Int] { memo = [String : [Int]]() return helper(expression) } private func helper(_ expression: String) -> [Int] { if let ret = self.memo[expression] { return ret } if let num = Int(expression) { return [num] } var result = [Int]() for index in expression.indices { if "+-*".contains(expression[index]) { let left = diffWaysToCompute(String(expression[..<index])) let right = diffWaysToCompute(String(expression[expression.index(after: index) ..< expression.endIndex])) if expression[index] == Character("+") { for l in left { for r in right { result.append(l + r) } } } else if expression[index] == Character("-") { for l in left { for r in right { result.append(l - r) } } } else if expression[index] == Character("*") { for l in left { for r in right { result.append(l * r) } } } } } self.memo[expression] = result return result } }
mit
90a62fd0e224e93f39b54634901bc4a8
34.067416
130
0.416854
5.219064
false
false
false
false
jzucker2/SwiftyKit
Example/SwiftyKit/AppDelegate.swift
1
2762
// // AppDelegate.swift // SwiftyKit // // Created by jzucker2 on 07/27/2017. // Copyright (c) 2017 jzucker2. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let bounds = UIScreen.main.bounds let window = UIWindow(frame: bounds) self.window = window let tabBarController = UITabBarController() let plainNavController = UINavigationController(rootViewController: PlainViewController()) let errorNavController = UINavigationController(rootViewController: ErrorViewController()) errorNavController.title = "Errors" tabBarController.viewControllers = [plainNavController, errorNavController] self.window?.rootViewController = tabBarController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
4b819c7817a45cf6d298c3d139b2242d
49.218182
285
0.747647
5.706612
false
false
false
false
xusader/firefox-ios
Storage/SQL/SQLiteReadingList.swift
2
2285
/* 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 /** * The SQLite-backed implementation of the ReadingList protocol. */ public class SQLiteReadingList: ReadingList { let db: BrowserDB let table = ReadingListTable<ReadingListItem>() required public init(db: BrowserDB) { self.db = db db.createOrUpdate(table) } public func clear(complete: (success: Bool) -> Void) { var err: NSError? = nil db.delete(&err) { (conn, inout err: NSError?) -> Int in return self.table.delete(conn, item: nil, err: &err) } dispatch_async(dispatch_get_main_queue()) { if err != nil { self.debug("Clear failed: \(err!.localizedDescription)") complete(success: false) } else { complete(success: true) } } } public func get(complete: (data: Cursor) -> Void) { var err: NSError? = nil let res = db.query(&err) { (conn: SQLiteDBConnection, inout err: NSError?) -> Cursor in return self.table.query(conn, options: nil) } dispatch_async(dispatch_get_main_queue()) { complete(data: res) } } public func add(#item: ReadingListItem, complete: (success: Bool) -> Void) { var err: NSError? = nil let inserted = db.insert(&err) { (conn, inout err: NSError?) -> Int in return self.table.insert(conn, item: item, err: &err) } dispatch_async(dispatch_get_main_queue()) { if err != nil { self.debug("Add failed: \(err!.localizedDescription)") } complete(success: err == nil) } } public func shareItem(item: ShareItem) { add(item: ReadingListItem(url: item.url, title: item.title)) { (success) -> Void in // Nothing we can do here when items are added from an extension. } } private let debug_enabled = false private func debug(msg: String) { if debug_enabled { println("SQLiteReadingList: " + msg) } } }
mpl-2.0
a5dda891a3c6c444996002ad8fcbda8b
31.642857
95
0.571116
4.147005
false
false
false
false
willlarche/material-components-ios
components/Buttons/examples/ButtonsDynamicTypeViewController.swift
2
3166
/* Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialButtons class ButtonsDynamicTypeViewController: UIViewController { @objc class func catalogBreadcrumbs() -> [String] { return ["Buttons", "Buttons (DynamicType)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha:1.0) let titleColor = UIColor.white let backgroundColor = UIColor(white: 0.1, alpha: 1.0) let flatButtonStatic = MDCRaisedButton() flatButtonStatic.setTitleColor(titleColor, for: .normal) flatButtonStatic.setBackgroundColor(backgroundColor, for: .normal) flatButtonStatic.setTitle("Static", for: UIControlState()) flatButtonStatic.sizeToFit() flatButtonStatic.translatesAutoresizingMaskIntoConstraints = false flatButtonStatic.addTarget(self, action: #selector(tap), for: .touchUpInside) view.addSubview(flatButtonStatic) let flatButtonDynamic = MDCRaisedButton() flatButtonDynamic.setTitleColor(titleColor, for: .normal) flatButtonDynamic.setBackgroundColor(backgroundColor, for: .normal) flatButtonDynamic.setTitle("Dynamic", for: UIControlState()) flatButtonDynamic.sizeToFit() flatButtonDynamic.translatesAutoresizingMaskIntoConstraints = false flatButtonDynamic.addTarget(self, action: #selector(tap), for: .touchUpInside) flatButtonDynamic.mdc_adjustsFontForContentSizeCategory = true view.addSubview(flatButtonDynamic) let views = [ "flatStatic": flatButtonStatic, "flatDynamic": flatButtonDynamic ] centerView(view: flatButtonDynamic, onView: self.view) view.addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:[flatStatic]-40-[flatDynamic]", options: .alignAllCenterX, metrics: nil, views: views)) } // MARK: Private func centerView(view: UIView, onView: UIView) { onView.addConstraint(NSLayoutConstraint( item: view, attribute: .centerX, relatedBy: .equal, toItem: onView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) onView.addConstraint(NSLayoutConstraint( item: view, attribute: .centerY, relatedBy: .equal, toItem: onView, attribute: .centerY, multiplier: 1.0, constant: 0.0)) } @objc func tap(_ sender: Any) { print("\(type(of: sender)) was tapped.") } }
apache-2.0
b4f7ae481e304f53d362f8518aa84784
31.639175
89
0.703095
4.931464
false
false
false
false
kvvzr/Twinkrun-iOS
Twinkrun/Models/TWRPlayer.swift
2
4778
// // TWRPlayer.swift // Twinkrun // // Created by Kawazure on 2014/10/09. // Copyright (c) 2014年 Twinkrun. All rights reserved. // import Foundation import CoreBluetooth class TWRPlayer: NSObject, NSCoding { let identifier: NSUUID? var playWith: Bool, countedScore: Bool var name: NSString var colorSeed: UInt32, RSSI: Int? var score: Int? var roles: [TWRRole]? var option: TWRGameOption? let version = "2.0" init(playerName: NSString, identifier: NSUUID?, colorSeed: UInt32) { self.name = playerName self.identifier = identifier self.colorSeed = colorSeed % 1024 self.option = TWROption.sharedInstance.gameOption playWith = true countedScore = false super.init() createRoleList() } init(advertisementDataLocalName: String, identifier: NSUUID) { var data: [String] = advertisementDataLocalName.componentsSeparatedByString(",") self.name = data[0] self.colorSeed = UInt32(Int(data[1])!) self.identifier = identifier self.option = TWROption.sharedInstance.gameOption playWith = true countedScore = true super.init() } required init(coder aDecoder: NSCoder) { playWith = true countedScore = false if let _ = aDecoder.decodeObjectForKey("version") as? String { self.name = aDecoder.decodeObjectForKey("name") as! NSString self.identifier = aDecoder.decodeObjectForKey("identifier") as? NSUUID self.colorSeed = UInt32(aDecoder.decodeIntegerForKey("colorSeed")) self.score = aDecoder.decodeIntegerForKey("score") super.init() } else { self.name = aDecoder.decodeObjectForKey("playerName") as! NSString self.identifier = nil self.colorSeed = UInt32((aDecoder.decodeObjectForKey("colorListSeed") as! NSNumber).integerValue) super.init() } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(identifier, forKey: "identifier") aCoder.encodeInteger(Int(colorSeed), forKey: "colorSeed") if let score = score { aCoder.encodeInteger(score, forKey: "score") } aCoder.encodeObject(version, forKey: "version") } func createRoleList() { roles = [] for role in option!.roles { for _ in 0 ..< role.count { roles!.append(role) } } roles!.shuffle(colorSeed) } func advertisementData(UUID: CBUUID) -> [String: AnyObject] { return [ CBAdvertisementDataServiceUUIDsKey: [UUID], CBAdvertisementDataLocalNameKey: (splitString(name, bytes: 12) as String) + "," + String(colorSeed) ] } func previousRole(second: UInt) -> TWRRole? { let sec = second % option!.gameTime() var progress: UInt = 0 for i in 0 ..< roles!.count { let nextLimit = progress + roles![i].time if nextLimit > sec { return i == 0 ? roles!.last! : roles![i - 1] } progress = nextLimit } return nil } func currentRole(second: UInt) -> TWRRole { let sec = second % option!.gameTime() var progress: UInt = 0 var current: TWRRole? for i in 0 ..< roles!.count { let nextLimit = progress + roles![i].time if nextLimit > sec { current = roles![i] break } progress = nextLimit } return current! } func nextRole(second: UInt) -> TWRRole? { var progress: UInt = 0 for i in 0 ..< roles!.count - 1 { let nextLimit = progress + roles![i].time if nextLimit > second { return roles![i + 1] } progress = nextLimit } return nil } private func splitString(input: NSString, bytes length: Int) -> NSString { let data = input.dataUsingEncoding(NSUTF8StringEncoding) for i in (0...min(length, data!.length)).reverse() { if let result:NSString = NSString(data: data!.subdataWithRange(NSRange(location: 0, length: i)), encoding: NSUTF8StringEncoding) { if result.length > 0 { return result } } } return "" } } func ==(this: TWRPlayer, that: TWRPlayer) -> Bool { return this.identifier == that.identifier }
mit
37db362fad8d5707b70a85871ce7967d
28.670807
142
0.553392
4.614493
false
false
false
false
HaloWang/FangYuan
FangYuan/OnlyForDemo/DemoSpecific.swift
1
1787
import Foundation /// This class is used to provide FangYuan.Ruler's logic /// /// - Warning: Only available in demo codes open class EnableConstraintHolder { public enum Section { case left case right case width case top case bottom case height } fileprivate static let holderView = UIView() open static var validSections = [Section]() open class func validAt(_ section:Section) -> Bool { for _section in validSections { if section == _section { return true } } return false } open class func pushConstraintAt(_ section: EnableConstraintHolder.Section) { var sections = [Section]() let rx = holderView.rulerX let ry = holderView.rulerY switch section { case .bottom: ry.c = 0 case .height: ry.b = 0 case .top: ry.a = 0 case .left: rx.a = 0 case .width: rx.b = 0 case .right: rx.c = 0 } if rx.a != nil { sections.append(.left) } if rx.b != nil { sections.append(.width) } if rx.c != nil { sections.append(.right) } if ry.a != nil { sections.append(.top) } if ry.b != nil { sections.append(.height) } if ry.c != nil { sections.append(.bottom) } validSections = sections } open class func randomSections() { } open class func clearSections() { } }
mit
7b1ae473576157150fe8b161e36a6c23
19.54023
81
0.453274
4.922865
false
false
false
false
nguyenantinhbk77/practice-swift
CoreGraphics/QuartzFun/QuartzFun/ViewController.swift
2
1961
// // ViewController.swift // QuartzFun // // Created by Domenico on 01/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var colorControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeColor(sender: UISegmentedControl) { let drawingColorSelection = DrawingColor(rawValue: UInt(sender.selectedSegmentIndex)) if let drawingColor = drawingColorSelection { let funView = view as! QuartzFunView; switch drawingColor { case .Red: funView.currentColor = UIColor.redColor() funView.useRandomColor = false case .Blue: funView.currentColor = UIColor.blueColor() funView.useRandomColor = false case .Yellow: funView.currentColor = UIColor.yellowColor() funView.useRandomColor = false case .Green: funView.currentColor = UIColor.greenColor() funView.useRandomColor = false case .Random: funView.useRandomColor = true default: break; } } } @IBAction func changeShape(sender: UISegmentedControl) { let shapeSelection = Shape(rawValue: UInt(sender.selectedSegmentIndex)) if let shape = shapeSelection { let funView = view as! QuartzFunView; funView.shape = shape; colorControl.hidden = shape == Shape.Image } } }
mit
654141d235bf0fee51def43f3939fe0c
28.712121
80
0.570627
5.372603
false
false
false
false
alblue/swift
test/Inputs/conditional_conformance_subclass.swift
1
12240
public func takes_p1<T: P1>(_: T.Type) {} public protocol P1 { func normal() func generic<T: P3>(_: T) } public protocol P2 {} public protocol P3 {} public struct IsP2: P2 {} public class Base<A> {} extension Base: P1 where A: P2 { public func normal() {} public func generic<T: P3>(_: T) {} } // witness method for Base.normal // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T32conditional_conformance_subclass4BaseC.0** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.0*, %T32conditional_conformance_subclass4BaseC.0** %0 // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE6normalyyF"(i8** %"\CF\84_0_0.P2", %T32conditional_conformance_subclass4BaseC.0* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // witness method for Base.generic // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1** noalias nocapture swiftself dereferenceable(8), %swift.type* %Self, i8** %SelfWitnessTable) // CHECK-NEXT: entry: // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8 // CHECK-NEXT: %"\CF\84_0_0.P2" = bitcast i8* [[A_P2]] to i8** // CHECK-NEXT: [[SELF:%.]] = load %T32conditional_conformance_subclass4BaseC.1*, %T32conditional_conformance_subclass4BaseC.1** %1, align 8 // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass4BaseCA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_0_0.P2", i8** %"\CF\84_1_0.P3", %T32conditional_conformance_subclass4BaseC.1* swiftself [[SELF]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public class SubclassGeneric<T>: Base<T> {} public class SubclassConcrete: Base<IsP2> {} public class SubclassGenericConcrete: SubclassGeneric<IsP2> {} public func subclassgeneric_generic<T: P2>(_: T.Type) { takes_p1(SubclassGeneric<T>.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgeneric_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2) // CHECK-NEXT: entry: // CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCMa"(i64 0, %swift.type* %T) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } public func subclassgeneric_concrete() { takes_p1(SubclassGeneric<IsP2>.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass24subclassgeneric_concreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGeneric_TYPE]], %swift.type* [[SubclassGeneric_TYPE]], i8** [[Base_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // Lazy witness table accessor for the concrete SubclassGeneric<IsP2> : Base. // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGMa"(i64 0) // CHECK-NEXT: [[SubclassGeneric_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass15SubclassGenericCyAA4IsP2VGAA4BaseCyxGAA2P1A2A0G0RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassconcrete() { takes_p1(SubclassConcrete.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass16subclassconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassConcrete_TYPE]], %swift.type* [[SubclassConcrete_TYPE]], i8** [[SubclassConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass16SubclassConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass16SubclassConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } public func subclassgenericconcrete() { takes_p1(SubclassGenericConcrete.self) } // CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s32conditional_conformance_subclass23subclassgenericconcreteyyF"() // CHECK-NEXT: entry: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[SubclassGenericConcrete_P1:%.*]] = call i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: call swiftcc void @"$s32conditional_conformance_subclass8takes_p1yyxmAA2P1RzlF"(%swift.type* [[SubclassGenericConcrete_TYPE]], %swift.type* [[SubclassGenericConcrete_TYPE]], i8** [[SubclassGenericConcrete_P1]]) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define linkonce_odr hidden i8** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWl"() // CHECK-NEXT: entry: // CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8 // CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL", align 8 // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s32conditional_conformance_subclass23SubclassGenericConcreteCMa"(i64 0) // CHECK-NEXT: [[SubclassGenericConcrete_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0 // CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0 // CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s32conditional_conformance_subclass4IsP2VAA0E0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8 // CHECK-NEXT: [[Base_P1:%.*]] = call i8** @swift_getWitnessTable // CHECK-NEXT: store atomic i8** [[Base_P1]], i8*** @"$s32conditional_conformance_subclass23SubclassGenericConcreteCAA4BaseCyxGAA2P1A2A2P2RzlWL" release, align 8 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Base_P1]], %cacheIsNull ] // CHECK-NEXT: ret i8** [[T0]] // CHECK-NEXT: } // witness tabel instantiation function for Base : P1 // CHECK-LABEL: define internal void @"$s32conditional_conformance_subclass4BaseCyxGAA2P1A2A2P2RzlWI"(i8**, %swift.type* %"Base<A>", i8**) // CHECK-NEXT: entry: // CHECK-NEXT: [[TABLES:%.*]] = bitcast i8** %1 to i8*** // CHECK-NEXT: [[A_P2_SRC:%.*]] = getelementptr inbounds i8**, i8*** [[TABLES]], i32 0 // CHECK-NEXT: [[A_P2_DEST:%.*]] = getelementptr inbounds i8*, i8** %0, i32 -1 // CHECK-NEXT: [[A_P2:%.*]] = load i8**, i8*** [[A_P2_SRC]], align 8 // CHECK-NEXT: [[CAST_A_P2_DEST:%.*]] = bitcast i8** [[A_P2_DEST]] to i8*** // CHECK-NEXT: store i8** [[A_P2]], i8*** [[CAST_A_P2_DEST]], align 8 // CHECK-NEXT: ret void // CHECK-NEXT: }
apache-2.0
555b8a8f6823ffc300abbdd2cab1b1cc
64.806452
373
0.684069
3.160341
false
false
false
false
Samiabo/Weibo
Weibo/Weibo/Classes/Home/LSPresentationController.swift
1
1080
// // LSPresentationController.swift // Weibo // // Created by han xuelong on 2016/12/31. // Copyright © 2016年 han xuelong. All rights reserved. // import UIKit class LSPresentationController: UIPresentationController { lazy var coverView: UIView = UIView() var presentedFrame: CGRect = .zero override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() presentedView?.frame = presentedFrame setupCoverView() } } // MARK: - UI extension LSPresentationController { func setupCoverView() { containerView?.insertSubview(coverView, at: 0) coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.2) coverView.frame = containerView!.bounds let tap = UITapGestureRecognizer(target: self, action:#selector(LSPresentationController.coverViewClick)) coverView.addGestureRecognizer(tap) } } // MARK: - 事件监听 extension LSPresentationController { func coverViewClick() { presentedViewController.dismiss(animated: true, completion: nil) } }
mit
3ee968e9a5c8e21dfd6511b96ccce976
27.131579
113
0.708138
4.793722
false
false
false
false
mozilla-mobile/firefox-ios
Tests/ClientTests/Helpers/RatingPromptManagerTests.swift
2
11218
// 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 XCTest import StoreKit import Shared import Storage @testable import Client class RatingPromptManagerTests: XCTestCase { var urlOpenerSpy: URLOpenerSpy! var promptManager: RatingPromptManager! var mockProfile: MockProfile! var createdGuids: [String] = [] var sentry: CrashingMockSentryClient! override func setUp() { super.setUp() if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) } urlOpenerSpy = URLOpenerSpy() } override func tearDown() { super.tearDown() createdGuids = [] promptManager?.reset() promptManager = nil mockProfile?.shutdown() mockProfile = nil sentry = nil urlOpenerSpy = nil } func testShouldShowPrompt_requiredAreFalse_returnsFalse() { setupEnvironment(numberOfSession: 0, hasCumulativeDaysOfUse: false) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_requiredTrueWithoutOptional_returnsFalse() { setupEnvironment() promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_withRequiredRequirementsAndOneOptional_returnsTrue() { setupEnvironment(isBrowserDefault: true) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 1) } func testShouldShowPrompt_lessThanSession5_returnsFalse() { setupEnvironment(numberOfSession: 4, hasCumulativeDaysOfUse: true, isBrowserDefault: true) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_cumulativeDaysOfUseFalse_returnsFalse() { setupEnvironment(numberOfSession: 5, hasCumulativeDaysOfUse: false, isBrowserDefault: true) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_sentryHasCrashedInLastSession_returnsFalse() { setupEnvironment(isBrowserDefault: true) sentry?.enableCrashOnLastLaunch = true promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_isBrowserDefaultTrue_returnsTrue() { setupEnvironment(isBrowserDefault: true) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 1) } func testShouldShowPrompt_hasTPStrict_returnsTrue() { setupEnvironment() mockProfile.prefs.setString(BlockingStrength.strict.rawValue, forKey: ContentBlockingConfig.Prefs.StrengthKey) promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 1) } // MARK: Bookmarks func testShouldShowPrompt_hasNotMinimumMobileBookmarksCount_returnsFalse() { setupEnvironment() createBookmarks(bookmarkCount: 2, withRoot: BookmarkRoots.MobileFolderGUID) updateData(expectedRatingPromptOpenCount: 0) } func testShouldShowPrompt_hasMinimumMobileBookmarksCount_returnsTrue() { setupEnvironment() createBookmarks(bookmarkCount: 5, withRoot: BookmarkRoots.MobileFolderGUID) updateData(expectedRatingPromptOpenCount: 1) } func testShouldShowPrompt_hasOtherBookmarksCount_returnsFalse() { setupEnvironment() createBookmarks(bookmarkCount: 5, withRoot: BookmarkRoots.ToolbarFolderGUID) updateData(expectedRatingPromptOpenCount: 0) } func testShouldShowPrompt_has5FoldersInMobileBookmarks_returnsFalse() { setupEnvironment() createFolders(folderCount: 5, withRoot: BookmarkRoots.MobileFolderGUID) updateData(expectedRatingPromptOpenCount: 0) } func testShouldShowPrompt_has5SeparatorsInMobileBookmarks_returnsFalse() { setupEnvironment() createSeparators(separatorCount: 5, withRoot: BookmarkRoots.MobileFolderGUID) updateData(expectedRatingPromptOpenCount: 0) } func testShouldShowPrompt_hasRequestedTwoWeeksAgo_returnsTrue() { setupEnvironment(isBrowserDefault: true) promptManager.showRatingPromptIfNeeded(at: Date().lastTwoWeek) XCTAssertEqual(ratingPromptOpenCount, 1) } // MARK: Number of times asked func testShouldShowPrompt_hasRequestedInTheLastTwoWeeks_returnsFalse() { setupEnvironment() promptManager.showRatingPromptIfNeeded(at: Date().lastTwoWeek) XCTAssertEqual(ratingPromptOpenCount, 0) } func testShouldShowPrompt_requestCountTwiceCountIsAtOne() { setupEnvironment(isBrowserDefault: true) promptManager.showRatingPromptIfNeeded() promptManager.showRatingPromptIfNeeded() XCTAssertEqual(ratingPromptOpenCount, 1) } // MARK: App Store func testGoToAppStoreReview() { RatingPromptManager.goToAppStoreReview(with: urlOpenerSpy) XCTAssertEqual(urlOpenerSpy.openURLCount, 1) XCTAssertEqual(urlOpenerSpy.capturedURL?.absoluteString, "https://itunes.apple.com/app/id\(AppInfo.appStoreId)?action=write-review") } } // MARK: - Places helpers private extension RatingPromptManagerTests { func createFolders(folderCount: Int, withRoot root: String, file: StaticString = #filePath, line: UInt = #line) { (1...folderCount).forEach { index in mockProfile.places.createFolder(parentGUID: root, title: "Folder \(index)", position: nil).uponQueue(.main) { guid in guard let guid = guid.successValue else { XCTFail("CreateFolder method did not return GUID", file: file, line: line) return } self.createdGuids.append(guid) } } // Make sure the folders we create are deleted at the end of the test addTeardownBlock { [weak self] in self?.createdGuids.forEach { guid in _ = self?.mockProfile.places.deleteBookmarkNode(guid: guid) } } } func createSeparators(separatorCount: Int, withRoot root: String, file: StaticString = #filePath, line: UInt = #line) { (1...separatorCount).forEach { index in mockProfile.places.createSeparator(parentGUID: root, position: nil).uponQueue(.main) { guid in guard let guid = guid.successValue else { XCTFail("CreateFolder method did not return GUID", file: file, line: line) return } self.createdGuids.append(guid) } } // Make sure the separators we create are deleted at the end of the test addTeardownBlock { [weak self] in self?.createdGuids.forEach { guid in _ = self?.mockProfile.places.deleteBookmarkNode(guid: guid) } } } func createBookmarks(bookmarkCount: Int, withRoot root: String) { (1...bookmarkCount).forEach { index in let bookmark = ShareItem(url: "http://www.example.com/\(index)", title: "Example \(index)", favicon: nil) _ = mockProfile.places.createBookmark(parentGUID: root, url: bookmark.url, title: bookmark.title, position: nil).value } // Make sure the bookmarks we create are deleted at the end of the test addTeardownBlock { [weak self] in self?.deleteBookmarks(bookmarkCount: bookmarkCount) } } func deleteBookmarks(bookmarkCount: Int) { (1...bookmarkCount).forEach { index in _ = mockProfile.places.deleteBookmarksWithURL(url: "http://www.example.com/\(index)") } } func updateData(expectedRatingPromptOpenCount: Int, file: StaticString = #filePath, line: UInt = #line) { let expectation = self.expectation(description: "Rating prompt manager data is loaded") promptManager.updateData(dataLoadingCompletion: { [weak self] in guard let promptManager = self?.promptManager else { XCTFail("Should have reference to promptManager", file: file, line: line) return } promptManager.showRatingPromptIfNeeded() XCTAssertEqual(self?.ratingPromptOpenCount, expectedRatingPromptOpenCount, file: file, line: line) expectation.fulfill() }) waitForExpectations(timeout: 5, handler: nil) } } // MARK: - Setup helpers private extension RatingPromptManagerTests { func setupEnvironment(numberOfSession: Int32 = 5, hasCumulativeDaysOfUse: Bool = true, isBrowserDefault: Bool = false, functionName: String = #function) { mockProfile = MockProfile(databasePrefix: functionName) mockProfile.reopen() mockProfile.prefs.setInt(numberOfSession, forKey: PrefsKeys.SessionCount) setupPromptManager(hasCumulativeDaysOfUse: hasCumulativeDaysOfUse) RatingPromptManager.isBrowserDefault = isBrowserDefault } func setupPromptManager(hasCumulativeDaysOfUse: Bool) { let mockCounter = CumulativeDaysOfUseCounterMock(hasCumulativeDaysOfUse) sentry = CrashingMockSentryClient() promptManager = RatingPromptManager(profile: mockProfile, daysOfUseCounter: mockCounter, sentry: sentry) } func createSite(number: Int) -> Site { let site = Site(url: "http://s\(number)ite\(number).com/foo", title: "A \(number)") site.id = number site.guid = "abc\(number)def" return site } var ratingPromptOpenCount: Int { UserDefaults.standard.object(forKey: RatingPromptManager.UserDefaultsKey.keyRatingPromptRequestCount.rawValue) as? Int ?? 0 } } // MARK: - CumulativeDaysOfUseCounterMock class CumulativeDaysOfUseCounterMock: CumulativeDaysOfUseCounter { private let hasMockRequiredDaysOfUse: Bool init(_ hasRequiredCumulativeDaysOfUse: Bool) { self.hasMockRequiredDaysOfUse = hasRequiredCumulativeDaysOfUse } override var hasRequiredCumulativeDaysOfUse: Bool { return hasMockRequiredDaysOfUse } } // MARK: - CrashingMockSentryClient class CrashingMockSentryClient: SentryProtocol { var enableCrashOnLastLaunch = false var crashedLastLaunch: Bool { return enableCrashOnLastLaunch } } // MARK: - URLOpenerSpy class URLOpenerSpy: URLOpenerProtocol { var capturedURL: URL? var openURLCount = 0 func open(_ url: URL) { capturedURL = url openURLCount += 1 } }
mpl-2.0
f5909db4ecd927a287b2beb5eeda646f
35.304207
140
0.665181
4.881636
false
true
false
false
AlexRamey/mbird-iOS
iOS Client/DevotionsController/DevotionScheduler.swift
1
2874
// // DevotionScheduler.swift // iOS Client // // Created by Alex Ramey on 5/17/18. // Copyright © 2018 Mockingbird. All rights reserved. // import Foundation import UserNotifications enum NotificationPermission { case allowed, denied, error } protocol DevotionScheduler { func cancelNotifications() func promptForNotifications(withDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int, completion: @escaping (NotificationPermission) -> Void) } class Scheduler: DevotionScheduler { let center = UNUserNotificationCenter.current() func cancelNotifications() { self.center.removeAllPendingNotificationRequests() } func promptForNotifications(withDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int, completion: @escaping (NotificationPermission) -> Void) { center.requestAuthorization(options: [.alert, .sound]) { granted, error in if granted { self.scheduleNotifications(withCenter: self.center, forDevotions: devotions, atHour: hour, minute: minute) completion(.allowed) } else if error != nil { completion(.error) } else { completion(.denied) } } } private func scheduleNotifications(withCenter center: UNUserNotificationCenter, forDevotions devotions: [LoadedDevotion], atHour hour: Int, minute: Int) { let startDate = Date().toMMddString() let sortedDevotions = devotions.sorted {$0.date < $1.date} guard let startIndex = (sortedDevotions.index { $0.dateAsMMdd == startDate }) else { return } var index = startIndex var outstandingNotifications: Int = 0 while outstandingNotifications < MBConstants.DEVOTION_NOTIFICATION_WINDOW_SIZE { outstandingNotifications += 1 let devotion = sortedDevotions[index] let notificationId = "daily-devotion-\(devotion.dateAsMMdd)" if let dateComponents = devotion.dateComponentsForNotification(hour: hour, minute: minute) { let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) let content = DevotionNotificationContent(devotion: devotion) let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger) center.add(request) } index = (index + 1) % sortedDevotions.count } } } extension Date { static let ddMMFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MM-dd" return formatter }() func toMMddString() -> String { return Date.ddMMFormatter.string(from: self) } }
mit
c1c699ec175b2b5e715de12ebe73ae1a
34.9125
163
0.642186
5.049209
false
false
false
false
xwu/swift
stdlib/public/Concurrency/AsyncPrefixSequence.swift
1
3777
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns an asynchronous sequence, up to the specified maximum length, /// containing the initial elements of the base asynchronous sequence. /// /// Use `prefix(_:)` to reduce the number of elements produced by the /// asynchronous sequence. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `prefix(_:)` method causes the modified /// sequence to pass through the first six values, then end. /// /// for await number in Counter(howHigh: 10).prefix(6) { /// print("\(number) ") /// } /// // prints "1 2 3 4 5 6" /// /// If the count passed to `prefix(_:)` exceeds the number of elements in the /// base sequence, the result contains all of the elements in the sequence. /// /// - Parameter count: The maximum number of elements to return. The value of /// `count` must be greater than or equal to zero. /// - Returns: An asynchronous sequence starting at the beginning of the /// base sequence with at most `count` elements. @inlinable public __consuming func prefix( _ count: Int ) -> AsyncPrefixSequence<Self> { precondition(count >= 0, "Can't prefix a negative number of elements from an async sequence") return AsyncPrefixSequence(self, count: count) } } /// An asynchronous sequence, up to a specified maximum length, /// containing the initial elements of a base asynchronous sequence. @available(SwiftStdlib 5.5, *) public struct AsyncPrefixSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let count: Int @usableFromInline init(_ base: Base, count: Int) { self.base = base self.count = count } } @available(SwiftStdlib 5.5, *) extension AsyncPrefixSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The prefix sequence produces whatever type of element its base iterator /// produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the prefix sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline var remaining: Int @usableFromInline init(_ baseIterator: Base.AsyncIterator, count: Int) { self.baseIterator = baseIterator self.remaining = count } /// Produces the next element in the prefix sequence. /// /// Until reaching the number of elements to include, this iterator calls /// `next()` on its base iterator and passes through the result. After /// reaching the maximum number of elements, subsequent calls to `next()` /// return `nil`. @inlinable public mutating func next() async rethrows -> Base.Element? { if remaining != 0 { remaining &-= 1 return try await baseIterator.next() } else { return nil } } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), count: count) } }
apache-2.0
1b2a3c3ac55f7bcaea0504bdf56bc416
33.027027
80
0.6574
4.744975
false
false
false
false
mikekavouras/Glowb-iOS
Glowb/Wizard/Models/DeviceCommunicationManager.swift
1
4907
// // ParticleSetupCommunicationManager.swift // ParticleConnect // // Created by Mike Kavouras on 8/28/16. // Copyright © 2016 Mike Kavouras. All rights reserved. // import Foundation enum DeviceType: String { case core = "Core" case photon = "Photon" case electron = "Electron" } class DeviceCommunicationManager { static let ConnectionEndpointAddress = "192.168.0.1" static let ConnectionEndpointPortString = "5609" static let ConnectionEndpointPort = 5609; var connection: DeviceConnection? var connectionCommand: (() -> Void)? var completionCommand: ((ResultType<JSON, ConnectionError>) -> Void)? // MARK: Public API func sendCommand<T: ParticleCommunicable>(_ type: T.Type, completion: @escaping (ResultType<T.ResponseType, ConnectionError>) -> Void) { runCommand(onConnection: { connection in connection.writeString(T.command) }, onCompletion: { result in switch result { case .success(let json): if let stuff = T.parse(json) { completion(.success(stuff)) } case .failure(let error): completion(.failure(error)) } }) } func configureAP(network: Network, completion: @escaping (ResultType<JSON, ConnectionError>) -> Void) { runCommand(onConnection: { connection in guard let json = network.asJSON, let data = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted), let jsonString = String(data: data, encoding: String.Encoding.utf8) else { completion(.failure(ConnectionError.couldNotConnect)) return } let command = String(format: "configure-ap\n%ld\n\n%@", jsonString.count, jsonString) connection.writeString(command) }, onCompletion: completion) } func connectAP(completion: @escaping (ResultType<JSON, ConnectionError>) -> Void) { runCommand(onConnection: { connection in let request: JSON = ["idx":0] guard let json = try? JSONSerialization.data(withJSONObject: request, options: .prettyPrinted), let jsonString = String(data: json, encoding: String.Encoding.utf8) else { completion(.failure(ConnectionError.couldNotConnect)) return } let command = String(format: "connect-ap\n%ld\n\n%@", jsonString.count, jsonString) connection.writeString(command) }, onCompletion: completion) } // MARK: Run commands private func runCommand(onConnection: @escaping (DeviceConnection) -> Void, onCompletion: @escaping (ResultType<JSON, ConnectionError>) -> Void) { guard DeviceCommunicationManager.canSendCommandCall() else { return } completionCommand = onCompletion openConnection { connection in onConnection(connection) } } private func openConnection(withCommand command: @escaping (DeviceConnection) -> Void) { let ipAddress = DeviceCommunicationManager.ConnectionEndpointAddress let port = DeviceCommunicationManager.ConnectionEndpointPort connection = DeviceConnection(withIPAddress: ipAddress, port: port) connection!.delegate = self; connectionCommand = { [unowned self] in command(self.connection!) } } // MARK: Wifi connection class func canSendCommandCall() -> Bool { // TODO: refer to original source if !Wifi.isDeviceConnected(.photon) { return false } return true } } // MARK: - Connection delegate extension DeviceCommunicationManager: DeviceConnectionDelegate { func deviceConnection(connection: DeviceConnection, didReceiveData data: String) { do { guard let json = try JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: .allowFragments) as? JSON else { completionCommand?(.failure(ConnectionError.jsonParseError)) return } completionCommand?(.success(json)) } catch { completionCommand?(.failure(ConnectionError.jsonParseError)) } } func deviceConnection(connection: DeviceConnection, didUpdateState state: DeviceConnectionState) { switch state { case .opened: connectionCommand?() case .openTimeout: completionCommand?(.failure(ConnectionError.timeout)) case .error: completionCommand?(.failure(ConnectionError.couldNotConnect)) default: break } } }
mit
46d5e9595eb21cce8fa3fd3f8dbbc975
32.834483
140
0.613738
5.15878
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/Extensions/String+RegEx.swift
1
2882
import Foundation // MARK: - String: RegularExpression Helpers // extension String { /// Find all matches of the specified regex. /// /// - Parameters: /// - regex: the regex to use. /// - options: the regex options. /// /// - Returns: the requested matches. /// func matches(regex: String, options: NSRegularExpression.Options = []) -> [NSTextCheckingResult] { let regex = try! NSRegularExpression(pattern: regex, options: options) let fullRange = NSRange(location: 0, length: characters.count) return regex.matches(in: self, options: [], range: fullRange) } /// Replaces all matches of a given RegEx, with a template String. /// /// - Parameters: /// - regex: the regex to use. /// - template: the template string to use for the replacement. /// - options: the regex options. /// /// - Returns: a new string after replacing all matches with the specified template. /// func replacingMatches(of regex: String, with template: String, options: NSRegularExpression.Options = []) -> String { let regex = try! NSRegularExpression(pattern: regex, options: options) let fullRange = NSRange(location: 0, length: characters.count) return regex.stringByReplacingMatches(in: self, options: [], range: fullRange, withTemplate: template) } /// Replaces all matches of a given RegEx using a provided block. /// /// - Parameters: /// - regex: the regex to use for pattern matching. /// - options: the regex options. /// - block: the block that will be used for the replacement logic. /// /// - Returns: the new string. /// func replacingMatches(of regex: String, options: NSRegularExpression.Options = [], using block: (String, [String]) -> String) -> String { let regex = try! NSRegularExpression(pattern: regex, options: options) let fullRange = NSRange(location: 0, length: characters.count) let matches = regex.matches(in: self, options: [], range: fullRange) var newString = self for match in matches.reversed() { let matchRange = range(from: match.range) let matchString = substring(with: matchRange) var submatchStrings = [String]() for submatchIndex in 0 ..< match.numberOfRanges { let submatchRange = self.range(from: match.rangeAt(submatchIndex)) let submatchString = self.substring(with: submatchRange) submatchStrings.append(submatchString) } newString.replaceSubrange(matchRange, with: block(matchString, submatchStrings)) } return newString } }
gpl-2.0
5973747ea8c5a4cf5900a1307b32c56d
36.428571
141
0.596808
4.860034
false
false
false
false
Cristian-A/tigress.cli
Tigress/Terminal/ConsoleIO.swift
1
2035
// + -------------------------------------- + // | ConsoleIO.swift | // | | // | Class ConsoleIO | // | | // | Created by Cristian A. | // | Copyright © cr. All rights reserved. | // + -------------------------------------- + import Foundation class ConsoleIO { /// Options available to the user. enum OptionType: String { // TODO: Add File Option case text = "t" // case file = "f" case help = "h" case unknown init(value: String) { switch value { case "t", "text": self = .text // case "f", "file": self = .file case "h", "help": self = .help default: self = .unknown } } } /// Initializes the IO /// information module. init() { let argc = CommandLine.argc let args = CommandLine.arguments if args.count < 2 { printUsage() return } let argument = args[1] let (option, value) = getOption(argument.substring(from: argument.characters.index(argument.startIndex, offsetBy: 1))) switch option { case .text: if argc != 3 { if argc > 3 { print("Syntax Error: Too many arguments for option \(option.rawValue).") } else { print("Syntax Error: Too few arguments for option \(option.rawValue).") } print("Type 'tigress -h' to open the help page.") } else { let text = args[2] let stripe = Tigress.stripeHash(of: text) let paw = Tigress.pawHash(of: text) print("") print("Hash (Stripe): \(stripe)") print("Paw Shorthand: \(paw)") print("") } // case .file: break case .help: printUsage() case .unknown: print("Syntax Error: Unknown option '\(value)'") printUsage() } } /// Prints the usage. func printUsage() { print("") print("Usage: tigress [-t text]") print("") } /// Gets the selected option. func getOption(_ option: String) -> (option: OptionType, value: String) { return (OptionType(value: option), option) } }
mit
defd46d5275ece42bc18089671c59b87
21.6
120
0.531465
3.435811
false
false
false
false
cezarywojcik/Operations
Sources/Core/Shared/AdvancedOperation.swift
1
31635
// // AdvancedOperation.swift // YapDB // // Created by Daniel Thorpe on 25/06/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // // swiftlint:disable file_length import Foundation // swiftlint:disable type_body_length /** Abstract base AdvancedOperation class which subclasses `NSOperation`. Operation builds on `NSOperation` in a few simple ways. 1. For an instance to become `.Ready`, all of its attached `OperationCondition`s must be satisfied. 2. It is possible to attach `OperationObserver`s to an instance, to be notified of lifecycle events in the operation. */ open class AdvancedOperation: Operation, OperationDebuggable { fileprivate enum State: Int, Comparable { // The initial state case initialized // Ready to begin evaluating conditions case pending // It is executing case executing // Execution has completed, but not yet notified queue case finishing // The operation has finished. case finished func canTransitionToState(_ other: State, whenCancelled cancelled: Bool) -> Bool { switch (self, other) { case (.initialized, .pending), (.pending, .executing), (.executing, .finishing), (.finishing, .finished): return true case (.pending, .finishing) where cancelled: // When an operation is cancelled it can go from pending direct to finishing. return true default: return false } } } /** Type to express the intent of the user in regards to executing an Operation instance - see: https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html#//apple_ref/doc/uid/TP40015243-CH39 */ @objc public enum UserIntent: Int { case none = 0, sideEffect, initiated internal var qos: QualityOfService { switch self { case .initiated, .sideEffect: return .userInitiated default: return .default } } } /// - returns: a unique String which can be used to identify the operation instance public let identifier = UUID().uuidString fileprivate let stateLock = NSRecursiveLock() fileprivate var _log = Protector<LoggerType>(Logger()) fileprivate var _state = State.initialized fileprivate var _internalErrors = [Error]() fileprivate var _isTransitioningToExecuting = false fileprivate var _isHandlingFinish = false fileprivate var _isHandlingCancel = false fileprivate var _observers = Protector([OperationObserverType]()) fileprivate let disableAutomaticFinishing: Bool internal fileprivate(set) var directDependencies = Set<Operation>() internal fileprivate(set) var conditions = Set<Condition>() internal var indirectDependencies: Set<Operation> { return Set(conditions.flatMap { $0.directDependencies }) } // Internal operation properties which are used to manage the scheduling of dependencies internal fileprivate(set) var evaluateConditionsOperation: GroupOperation? = .none fileprivate var _cancelled = false // should always be set by .cancel() /// Access the internal errors collected by the Operation open var errors: [Error] { return stateLock.withCriticalScope { _internalErrors } } /** Expresses the user intent in regards to the execution of this Operation. Setting this property will set the appropriate quality of service parameter on the Operation. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. */ open var userIntent: UserIntent = .none { didSet { setQualityOfServiceFromUserIntent(userIntent) } } /** Modifies the quality of service of the underlying operation. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - returns: a Bool indicating whether or not the quality of service is .UserInitiated */ @available(*, unavailable, message: "This property has been deprecated in favor of userIntent.") open var userInitiated: Bool { get { return qualityOfService == .userInitiated } set { precondition(state < .executing, "Cannot modify userInitiated after execution has begun.") qualityOfService = newValue ? .userInitiated : .default } } /** # Access the logger for this Operation The `log` property can be used as the interface to access the logger. e.g. to output a message with `LogSeverity.Info` from inside the `Operation`, do this: ```swift log.info("This is my message") ``` To adjust the instance severity of the LoggerType for the `Operation`, access it via this property too: ```swift log.severity = .Verbose ``` The logger is a very simple type, and all it does beyond manage the enabled status and severity is send the String to a block on a dedicated serial queue. Therefore to provide custom logging, set the `logger` property: ```swift log.logger = { message in sendMessageToAnalytics(message) } ``` By default, the Logger's logger block is the same as the global LogManager. Therefore to use a custom logger for all Operations: ```swift LogManager.logger = { message in sendMessageToAnalytics(message) } ``` */ open var log: LoggerType { get { let operationName = self.operationName return _log.read { _LoggerOperationContext(parentLogger: $0, operationName: operationName) } } set { _log.write { (ward: inout LoggerType) in ward = newValue } } } // MARK: - Initialization public override init() { self.disableAutomaticFinishing = false super.init() } // MARK: - Disable Automatic Finishing /** Ability to override Operation's built-in finishing behavior, if a subclass requires full control over when finish() is called. Used for GroupOperation to implement proper .Finished state-handling (only finishing after all child operations have finished). The default behavior of Operation is to automatically call finish() when: (a) it's cancelled, whether that occurs: - prior to the Operation starting (in which case, Operation will skip calling execute()) - on another thread at the same time that the operation is executing (b) when willExecuteObservers log errors To ensure that an Operation subclass does not finish until the subclass calls finish(): call `super.init(disableAutomaticFinishing: true)` in the init. IMPORTANT: If disableAutomaticFinishing == TRUE, the subclass is responsible for calling finish() in *ALL* cases, including when the operation is cancelled. You can react to cancellation using WillCancelObserver/DidCancelObserver and/or checking periodically during execute with something like: ```swift guard !cancelled else { // do any necessary clean-up finish() // always call finish if automatic finishing is disabled return } ``` */ public init(disableAutomaticFinishing: Bool) { self.disableAutomaticFinishing = disableAutomaticFinishing super.init() } // MARK: - Add Condition /** Add a condition to the to the operation, can only be done prior to the operation starting. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter condition: type conforming to protocol `OperationCondition`. */ @available(iOS, deprecated: 8, message: "Refactor OperationCondition types as Condition subclasses.") @available(OSX, deprecated: 10.10, message: "Refactor OperationCondition types as Condition subclasses.") open func addCondition(_ condition: OperationCondition) { assert(state < .executing, "Cannot modify conditions after operation has begun executing, current state: \(state).") let operation = WrappedOperationCondition(condition) if let dependency = condition.dependencyForOperation(self) { operation.addDependency(dependency) } conditions.insert(operation) } open func addCondition(_ condition: Condition) { assert(state < .executing, "Cannot modify conditions after operation has begun executing, current state: \(state).") conditions.insert(condition) } // MARK: - Add Observer /** Add an observer to the to the operation, can only be done prior to the operation starting. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter observer: type conforming to protocol `OperationObserverType`. */ open func addObserver(_ observer: OperationObserverType) { observers.append(observer) observer.didAttachToOperation(self) } // MARK: - Execution /** Subclasses should override this method to perform their specialized task. They must call a finish methods in order to complete. */ open func execute() { print("\(type(of: self)) must override `execute()`.", terminator: "") finish() } /** Subclasses may override `finished(_:)` if they wish to react to the operation finishing with errors. - parameter errors: an array of `ErrorType`. */ @available(*, unavailable, renamed: "operationDidFinish") open func finished(_ errors: [Error]) { operationDidFinish(errors) } /** Subclasses may override `operationWillFinish(_:)` if they wish to react to the operation finishing with errors. - parameter errors: an array of `ErrorType`. */ open func operationWillFinish(_ errors: [Error]) { /* No op */ } /** Subclasses may override `operationDidFinish(_:)` if they wish to react to the operation finishing with errors. - parameter errors: an array of `ErrorType`. */ open func operationDidFinish(_ errors: [Error]) { /* no op */ } // MARK: - Cancellation /** Cancel the operation with an error. - parameter error: an optional `ErrorType`. */ open func cancelWithError(_ error: Error? = .none) { cancelWithErrors(error.map { [$0] } ?? []) } /** Cancel the operation with multiple errors. - parameter errors: an `[ErrorType]` defaults to empty array. */ open func cancelWithErrors(_ errors: [Error] = []) { stateLock.withCriticalScope { if !errors.isEmpty { log.warning("Did cancel with errors: \(errors).") } _internalErrors += errors } cancel() } /** Subclasses may override `operationWillCancel(_:)` if they wish to react to the operation finishing with errors. - parameter errors: an array of `ErrorType`. */ open func operationWillCancel(_ errors: [Error]) { /* No op */ } /** Subclasses may override `operationDidCancel(_:)` if they wish to react to the operation finishing with errors. - parameter errors: an array of `ErrorType`. */ open func operationDidCancel() { /* No op */ } public final override func cancel() { let willCancel = stateLock.withCriticalScope { () -> Bool in // Do not cancel if already finished or finishing, or cancelled guard state <= .executing && !_cancelled else { return false } // Only a single call to cancel should continue guard !_isHandlingCancel else { return false } _isHandlingCancel = true return true } guard willCancel else { return } operationWillCancel(errors) willChangeValue(forKey: Operation.KeyPath.Cancelled.rawValue) willCancelObservers.forEach { $0.willCancelOperation(self, errors: self.errors) } stateLock.withCriticalScope { _cancelled = true } operationDidCancel() didCancelObservers.forEach { $0.didCancelOperation(self) } log.verbose("Did cancel.") didChangeValue(forKey: Operation.KeyPath.Cancelled.rawValue) // Call super.cancel() to trigger .isReady state change on cancel // as well as isReady KVO notification. super.cancel() let willFinish = stateLock.withCriticalScope { () -> Bool in let willFinish = isExecuting && !disableAutomaticFinishing && !_isHandlingFinish if willFinish { _isHandlingFinish = true } return willFinish } if willFinish { _finish([], fromCancel: true) } } /** This method is used for debugging the current state of an `Operation`. - returns: An `OperationDebugData` object containing debug data for the current `Operation`. */ open func debugData() -> OperationDebugData { return OperationDebugData( description: "Operation: \(self)", properties: [ "cancelled": String(isCancelled), "state": String(describing: state), "errorCount": String(errors.count), "QOS": String(describing: qualityOfService) ], conditions: conditions.map { String(describing: $0) }, dependencies: dependencies.map { ($0 as? OperationDebuggable)?.debugData() ?? $0.debugDataNSOperation() }) } internal func removeDirectDependency(_ directDependency: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") directDependencies.remove(directDependency) super.removeDependency(directDependency) } } // swiftlint:enable type_body_length // MARK: - State public extension AdvancedOperation { fileprivate var state: State { get { return stateLock.withCriticalScope { _state } } set (newState) { stateLock.withCriticalScope { assert(_state.canTransitionToState(newState, whenCancelled: isCancelled), "Attempting to perform illegal cyclic state transition, \(_state) -> \(newState) for operation: \(identity).") log.verbose("\(_state) -> \(newState)") _state = newState } } } /// Boolean indicator for whether the Operation is currently executing or not final override var isExecuting: Bool { return state == .executing } /// Boolean indicator for whether the Operation has finished or not final override var isFinished: Bool { return state == .finished } /// Boolean indicator for whether the Operation has cancelled or not final override var isCancelled: Bool { return stateLock.withCriticalScope { _cancelled } } /// Boolean flag to indicate that the Operation failed due to errors. var failed: Bool { return errors.count > 0 } internal func willEnqueue() { state = .pending } } // MARK: - Dependencies public extension AdvancedOperation { internal func evaluateConditions() -> GroupOperation { func createEvaluateConditionsOperation() -> GroupOperation { // Set the operation on each condition conditions.forEach { $0.operation = self } let evaluator = GroupOperation(operations: Array(conditions)) evaluator.name = "Condition Evaluator for: \(operationName)" super.addDependency(evaluator) return evaluator } assert(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") let evaluator = createEvaluateConditionsOperation() // Add an observer to the evaluator to see if any of the conditions failed. evaluator.addObserver(WillFinishObserver { [unowned self] operation, errors in if errors.count > 0 { // If conditions fail, we should cancel the operation self.cancelWithErrors(errors) } }) directDependencies.forEach { evaluator.addDependency($0) } return evaluator } internal func addDependencyOnPreviousMutuallyExclusiveOperation(_ operation: AdvancedOperation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") super.addDependency(operation) } internal func addDirectDependency(_ directDependency: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") directDependencies.insert(directDependency) super.addDependency(directDependency) } /// Public override to get the dependencies final override var dependencies: [Operation] { return Array(directDependencies.union(indirectDependencies)) } /** Add another `NSOperation` as a dependency. It is a programmatic error to call this method after the receiver has already started executing. Therefore, best practice is to add dependencies before adding them to operation queues. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter operation: a `NSOperation` instance. */ final override func addDependency(_ operation: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") addDirectDependency(operation) } /** Remove another `NSOperation` as a dependency. It is a programmatic error to call this method after the receiver has already started executing. Therefore, best practice is to manage dependencies before adding them to operation queues. - requires: self must not have started yet. i.e. either hasn't been added to a queue, or is waiting on dependencies. - parameter operation: a `NSOperation` instance. */ final override func removeDependency(_ operation: Operation) { precondition(state <= .executing, "Dependencies cannot be modified after execution has begun, current state: \(state).") removeDirectDependency(operation) } } // MARK: - Observers public extension AdvancedOperation { fileprivate(set) var observers: [OperationObserverType] { get { return _observers.read { $0 } } set { _observers.write { (ward: inout [OperationObserverType]) in ward = newValue } } } internal var willExecuteObservers: [OperationWillExecuteObserver] { return observers.compactMap { $0 as? OperationWillExecuteObserver } } internal var willCancelObservers: [OperationWillCancelObserver] { return observers.compactMap { $0 as? OperationWillCancelObserver } } internal var didCancelObservers: [OperationDidCancelObserver] { return observers.compactMap { $0 as? OperationDidCancelObserver } } internal var didProduceOperationObservers: [OperationDidProduceOperationObserver] { return observers.compactMap { $0 as? OperationDidProduceOperationObserver } } internal var willFinishObservers: [OperationWillFinishObserver] { return observers.compactMap { $0 as? OperationWillFinishObserver } } internal var didFinishObservers: [OperationDidFinishObserver] { return observers.compactMap { $0 as? OperationDidFinishObserver } } } // MARK: - Execution public extension AdvancedOperation { /// Starts the operation, correctly managing the cancelled state. Cannot be over-ridden final override func start() { // Don't call super.start guard !isCancelled || disableAutomaticFinishing else { finish() return } main() } /// Triggers execution of the operation's task, correctly managing errors and the cancelled state. Cannot be over-ridden final override func main() { // Inform observers that the operation will execute willExecuteObservers.forEach { $0.willExecuteOperation(self) } let nextState = stateLock.withCriticalScope { () -> (AdvancedOperation.State?) in assert(!isExecuting, "Operation is attempting to execute, but is already executing.") guard !_isTransitioningToExecuting else { assertionFailure("Operation is attempting to execute twice, concurrently.") return nil } // Check to see if the operation has now been finished // by an observer (or anything else) guard state <= .pending else { return nil } // Check to see if the operation has now been cancelled // by an observer guard (_internalErrors.isEmpty && !isCancelled) || disableAutomaticFinishing else { _isHandlingFinish = true return AdvancedOperation.State.finishing } // Transition to the .isExecuting state, and explicitly send the required KVO change notifications _isTransitioningToExecuting = true return AdvancedOperation.State.executing } guard nextState != .finishing else { _finish([], fromCancel: true) return } guard nextState == .executing else { return } willChangeValue(forKey: Operation.KeyPath.Executing.rawValue) let nextState2 = stateLock.withCriticalScope { () -> (AdvancedOperation.State?) in // Re-check state, since it could have changed on another thread (ex. via finish) guard state <= .pending else { return nil } state = .executing _isTransitioningToExecuting = false if isCancelled && !disableAutomaticFinishing && !_isHandlingFinish { // Operation was cancelled, automatic finishing is enabled, // but cancel is not (yet/ever?) handling the finish. // Because cancel could have already passed the check for executing, // handle calling finish here. _isHandlingFinish = true return .finishing } return .executing } // Always send the closing didChangeValueForKey didChangeValue(forKey: Operation.KeyPath.Executing.rawValue) guard nextState2 != .finishing else { _finish([], fromCancel: true) return } guard nextState2 == .executing else { return } log.verbose("Will Execute") execute() } /** Produce another operation on the same queue that this instance is on. - parameter operation: a `NSOperation` instance. */ final func produceOperation(_ operation: Operation) { precondition(state > .initialized, "Cannot produce operation while not being scheduled on a queue.") log.verbose("Did produce \(operation.operationName)") didProduceOperationObservers.forEach { $0.operation(self, didProduceOperation: operation) } } } // MARK: - Finishing public extension AdvancedOperation { /** Finish method which must be called eventually after an operation has begun executing, unless it is cancelled. - parameter errors: an array of `ErrorType`, which defaults to empty. */ final func finish(_ receivedErrors: [Error] = []) { _finish(receivedErrors, fromCancel: false) } fileprivate final func _finish(_ receivedErrors: [Error], fromCancel: Bool = false) { let willFinish = stateLock.withCriticalScope { () -> Bool in // Do not finish if already finished or finishing guard state <= .finishing else { return false } // Only a single call to _finish should continue // (.cancel() sets _isHandlingFinish and fromCancel=true, if appropriate.) guard !_isHandlingFinish || fromCancel else { return false } _isHandlingFinish = true return true } guard willFinish else { return } // NOTE: // - The stateLock should only be held when necessary, and should not // be held when notifying observers (whether via KVO or Operation's // observers) or deadlock can result. let changedExecutingState = isExecuting if changedExecutingState { willChangeValue(forKey: Operation.KeyPath.Executing.rawValue) } stateLock.withCriticalScope { state = .finishing } if changedExecutingState { didChangeValue(forKey: Operation.KeyPath.Executing.rawValue) } let errors = stateLock.withCriticalScope { () -> [Error] in _internalErrors.append(contentsOf: receivedErrors) return _internalErrors } if errors.isEmpty { log.verbose("Will finish with no errors.") } else { log.warning("Will finish with \(errors.count) errors.") } operationWillFinish(errors) willChangeValue(forKey: Operation.KeyPath.Finished.rawValue) willFinishObservers.forEach { $0.willFinishOperation(self, errors: errors) } stateLock.withCriticalScope { state = .finished } operationDidFinish(errors) didFinishObservers.forEach { $0.didFinishOperation(self, errors: errors) } let message = !errors.isEmpty ? "errors: \(errors)" : "no errors" log.verbose("Did finish with \(message)") didChangeValue(forKey: Operation.KeyPath.Finished.rawValue) } /// Convenience method to simplify finishing when there is only one error. @objc(aDifferentFinishWithANameThatDoesntConflictWithSomethingInObjectiveC:) final func finish(_ receivedError: Error?) { finish(receivedError.map { [$0]} ?? []) } /** Public override which deliberately crashes your app, as usage is considered an antipattern To promote best practices, where waiting is never the correct thing to do, we will crash the app if this is called. Instead use discrete operations and dependencies, or groups, or semaphores or even NSLocking. */ final override func waitUntilFinished() { fatalError("Waiting on operations is an anti-pattern. Remove this ONLY if you're absolutely sure there is No Other Way™. Post a question in https://github.com/danthorpe/Operations if you are unsure.") } } private func < (lhs: AdvancedOperation.State, rhs: AdvancedOperation.State) -> Bool { return lhs.rawValue < rhs.rawValue } private func == (lhs: AdvancedOperation.State, rhs: AdvancedOperation.State) -> Bool { return lhs.rawValue == rhs.rawValue } /** A common error type for Operations. Primarily used to indicate error when an Operation's conditions fail. */ public enum OperationError: Error, Equatable { /// Indicates that a condition of the Operation failed. case conditionFailed /// Indicates that the operation timed out. case operationTimedOut(TimeInterval) /// Indicates that a parent operation was cancelled (with errors). case parentOperationCancelledWithErrors([Error]) } /// OperationError is Equatable. public func == (lhs: OperationError, rhs: OperationError) -> Bool { switch (lhs, rhs) { case (.conditionFailed, .conditionFailed): return true case let (.operationTimedOut(aTimeout), .operationTimedOut(bTimeout)): return aTimeout == bTimeout case let (.parentOperationCancelledWithErrors(aErrors), .parentOperationCancelledWithErrors(bErrors)): // Not possible to do a real equality check here. return aErrors.count == bErrors.count default: return false } } extension Operation { /** Chain completion blocks. - parameter block: a Void -> Void block */ public func addCompletionBlock(_ block: @escaping () -> Void) { if let existing = completionBlock { completionBlock = { existing() block() } } else { completionBlock = block } } /** Add multiple depdendencies to the operation. Will add each dependency in turn. - parameter dependencies: and array of `NSOperation` instances. */ public func addDependencies<S>(_ dependencies: S) where S: Sequence, S.Iterator.Element: Operation { precondition(!isExecuting && !isFinished, "Cannot modify the dependencies after the operation has started executing.") dependencies.forEach(addDependency) } /** Remove multiple depdendencies from the operation. Will remove each dependency in turn. - parameter dependencies: and array of `NSOperation` instances. */ public func removeDependencies<S>(_ dependencies: S) where S: Sequence, S.Iterator.Element: Operation { precondition(!isExecuting && !isFinished, "Cannot modify the dependencies after the operation has started executing.") dependencies.forEach(removeDependency) } /// Removes all the depdendencies from the operation. public func removeDependencies() { removeDependencies(dependencies) } internal func setQualityOfServiceFromUserIntent(_ userIntent: AdvancedOperation.UserIntent) { qualityOfService = userIntent.qos } } private extension Operation { enum KeyPath: String { case Cancelled = "isCancelled" case Executing = "isExecuting" case Finished = "isFinished" } } extension NSLock { func withCriticalScope<T>(_ block: () -> T) -> T { lock() let value = block() unlock() return value } } extension NSRecursiveLock { func withCriticalScope<T>(_ block: () -> T) -> T { lock() let value = block() unlock() return value } } extension Array where Element: Operation { internal var splitNSOperationsAndOperations: ([Operation], [AdvancedOperation]) { return reduce(([], [])) { result, element in var (ns, op) = result if let operation = element as? AdvancedOperation { op.append(operation) } else { ns.append(element) } return (ns, op) } } internal var userIntent: AdvancedOperation.UserIntent { get { let (_, ops) = splitNSOperationsAndOperations return ops.map { $0.userIntent }.max { $0.rawValue < $1.rawValue } ?? .none } } internal func forEachOperation(body: (AdvancedOperation) throws -> Void) rethrows { try forEach { if let operation = $0 as? AdvancedOperation { try body(operation) } } } } // swiftlint:enable file_length
mit
3db895cbee6e4cce32fb31f51711cb20
32.832086
208
0.645781
5.151115
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/Omar-Villegas/Ejercicios-Libro/Ejercicio79-5.swift
1
744
/* Created by Omar Villegas on 09/02/17. Copyright © 2017 Omar Villegas. All rights reserved. Materia: Patrones de Diseño Alumno: Villegas Castillo Omar No. de control: 13211106 Ejercicios del PDF "Problemas para Resolver por Computadora 1993" PROBLEMA 79 CAPÍTULO 5 Encontrar el promedio de 1000 números tomados al azar */ import Foundation var suma = Double(0) var numero = 0 //CICLO PARA SUMAR LOS NUMEROS ALEATORIOS for i in 1...1000 { var numeror = Double(arc4random() & 100 + 1) //GENERAR NÚMEROS RANDOM suma = numeror + suma //SUMA DE LOS NÚMEROS } var promedio = Double(0) //DIVISIÓN PARA EL PROMEDIO promedio = (suma / 1000) //IMPRIMIR RESULTADO print("El promedio de 100 números es : \(promedio)")
gpl-3.0
a68ebb238166f5c863a4b137bc44c9e5
21.30303
69
0.725543
2.787879
false
false
false
false
klein-thibault/StarcraftWatch
StarcraftWatch/Models/Video.swift
1
1171
// // Video.swift // StarcraftWatch // // Created by Thibault Klein on 9/14/15. // Copyright © 2015 Prolific Interactive. All rights reserved. // import Foundation import UIKit struct Video { let id: String var URL: NSURL? let name: String let thumbnailURL: NSURL let largeThumbnailURL: NSURL let description: String init(id: String, name: String, description: String, thumbnail: NSURL, largeThumbnailURL: NSURL) { self.id = id self.name = name self.description = description self.thumbnailURL = thumbnail self.largeThumbnailURL = largeThumbnailURL } func videoFormattedDescription() -> String { return self.name + "\n" + self.description } mutating func videoFormattedURL() -> NSURL? { if self.URL == nil { let urlStr = "https://www.youtube.com/watch?v=\(self.id)" self.URL = (NSURL(string: urlStr)) } let videosDict = HCYoutubeParser.h264videosWithYoutubeURL(self.URL) if let video720URL = videosDict["hd720"] as? String { return NSURL(string: video720URL)! } return nil } }
mit
a4a50c511a07caf26336dddef35d047c
23.893617
101
0.626496
4.163701
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/Define/Color.swift
1
891
// // Color.swift // MyApp // // Created by DaoNV on 6/19/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // /** This file defines all colors which are used in this application. Please navigate by the control as prefix. */ import UIKit extension App { struct Color { static let navigationBar = UIColor.black static let navigationBarTextColor = UIColor.white static let tableHeaderView = UIColor.gray static let tableFooterView = UIColor.red static let tableCellTextLabel = UIColor.yellow static let greenTheme = UIColor.RGB(0, 192, 110) static let grayBackground = UIColor.RGB(230, 230, 230) static func button(state: UIControlState) -> UIColor { switch state { case UIControlState.normal: return .blue default: return .gray } } } }
mit
3ce3baf72c314d81fa499edab2bf66b4
25.969697
65
0.639326
4.540816
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift
3
7247
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public final class Rabbit: BlockCipher { public enum Error: Swift.Error { case invalidKeyOrInitializationVector } /// Size of IV in bytes public static let ivSize = 64 / 8 /// Size of key in bytes public static let keySize = 128 / 8 /// Size of block in bytes public static let blockSize = 128 / 8 public var keySize: Int { self.key.count } /// Key private let key: Key /// IV (optional) private let iv: Array<UInt8>? /// State variables private var x = Array<UInt32>(repeating: 0, count: 8) /// Counter variables private var c = Array<UInt32>(repeating: 0, count: 8) /// Counter carry private var p7: UInt32 = 0 /// 'a' constants private var a: Array<UInt32> = [ 0x4d34d34d, 0xd34d34d3, 0x34d34d34, 0x4d34d34d, 0xd34d34d3, 0x34d34d34, 0x4d34d34d, 0xd34d34d3 ] // MARK: - Initializers public convenience init(key: Array<UInt8>) throws { try self.init(key: key, iv: nil) } public init(key: Array<UInt8>, iv: Array<UInt8>?) throws { self.key = Key(bytes: key) self.iv = iv guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { throw Error.invalidKeyOrInitializationVector } } // MARK: - fileprivate func setup() { self.p7 = 0 // Key divided into 8 subkeys let k = Array<UInt32>(unsafeUninitializedCapacity: 8) { buf, count in for j in 0..<8 { buf[j] = UInt32(self.key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(self.key[Rabbit.blockSize - (2 * j + 2)]) << 8) } count = 8 } // Initialize state and counter variables from subkeys for j in 0..<8 { if j % 2 == 0 { self.x[j] = (k[(j + 1) % 8] << 16) | k[j] self.c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8] } else { self.x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8] self.c[j] = (k[j] << 16) | k[(j + 1) % 8] } } // Iterate system four times self.nextState() self.nextState() self.nextState() self.nextState() // Reinitialize counter variables for j in 0..<8 { self.c[j] = self.c[j] ^ self.x[(j + 4) % 8] } if let iv = iv { self.setupIV(iv) } } private func setupIV(_ iv: Array<UInt8>) { // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits // 0 1 2 3 4 5 6 7 IV bytes in array let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]]) let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]]) let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]]) let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]]) // Modify the counter state as function of the IV c[0] = self.c[0] ^ iv0 self.c[1] = self.c[1] ^ iv1 self.c[2] = self.c[2] ^ iv2 self.c[3] = self.c[3] ^ iv3 self.c[4] = self.c[4] ^ iv0 self.c[5] = self.c[5] ^ iv1 self.c[6] = self.c[6] ^ iv2 self.c[7] = self.c[7] ^ iv3 // Iterate system four times self.nextState() self.nextState() self.nextState() self.nextState() } private func nextState() { // Before an iteration the counters are incremented var carry = self.p7 for j in 0..<8 { let prev = self.c[j] self.c[j] = prev &+ self.a[j] &+ carry carry = prev > self.c[j] ? 1 : 0 // detect overflow } self.p7 = carry // save last carry bit // Iteration of the system self.x = Array<UInt32>(unsafeUninitializedCapacity: 8) { newX, count in newX[0] = self.g(0) &+ rotateLeft(self.g(7), by: 16) &+ rotateLeft(self.g(6), by: 16) newX[1] = self.g(1) &+ rotateLeft(self.g(0), by: 8) &+ self.g(7) newX[2] = self.g(2) &+ rotateLeft(self.g(1), by: 16) &+ rotateLeft(self.g(0), by: 16) newX[3] = self.g(3) &+ rotateLeft(self.g(2), by: 8) &+ self.g(1) newX[4] = self.g(4) &+ rotateLeft(self.g(3), by: 16) &+ rotateLeft(self.g(2), by: 16) newX[5] = self.g(5) &+ rotateLeft(self.g(4), by: 8) &+ self.g(3) newX[6] = self.g(6) &+ rotateLeft(self.g(5), by: 16) &+ rotateLeft(self.g(4), by: 16) newX[7] = self.g(7) &+ rotateLeft(self.g(6), by: 8) &+ self.g(5) count = 8 } } private func g(_ j: Int) -> UInt32 { let sum = self.x[j] &+ self.c[j] let square = UInt64(sum) * UInt64(sum) return UInt32(truncatingIfNeeded: square ^ (square >> 32)) } fileprivate func nextOutput() -> Array<UInt8> { self.nextState() var output16 = Array<UInt16>(repeating: 0, count: Rabbit.blockSize / 2) output16[7] = UInt16(truncatingIfNeeded: self.x[0]) ^ UInt16(truncatingIfNeeded: self.x[5] >> 16) output16[6] = UInt16(truncatingIfNeeded: self.x[0] >> 16) ^ UInt16(truncatingIfNeeded: self.x[3]) output16[5] = UInt16(truncatingIfNeeded: self.x[2]) ^ UInt16(truncatingIfNeeded: self.x[7] >> 16) output16[4] = UInt16(truncatingIfNeeded: self.x[2] >> 16) ^ UInt16(truncatingIfNeeded: self.x[5]) output16[3] = UInt16(truncatingIfNeeded: self.x[4]) ^ UInt16(truncatingIfNeeded: self.x[1] >> 16) output16[2] = UInt16(truncatingIfNeeded: self.x[4] >> 16) ^ UInt16(truncatingIfNeeded: self.x[7]) output16[1] = UInt16(truncatingIfNeeded: self.x[6]) ^ UInt16(truncatingIfNeeded: self.x[3] >> 16) output16[0] = UInt16(truncatingIfNeeded: self.x[6] >> 16) ^ UInt16(truncatingIfNeeded: self.x[1]) var output8 = Array<UInt8>(repeating: 0, count: Rabbit.blockSize) for j in 0..<output16.count { output8[j * 2] = UInt8(truncatingIfNeeded: output16[j] >> 8) output8[j * 2 + 1] = UInt8(truncatingIfNeeded: output16[j]) } return output8 } } // MARK: Cipher extension Rabbit: Cipher { public func encrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { self.setup() return Array<UInt8>(unsafeUninitializedCapacity: bytes.count) { result, count in var output = self.nextOutput() var byteIdx = 0 var outputIdx = 0 while byteIdx < bytes.count { if outputIdx == Rabbit.blockSize { output = self.nextOutput() outputIdx = 0 } result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] byteIdx += 1 outputIdx += 1 } count = bytes.count } } public func decrypt(_ bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { try self.encrypt(bytes) } }
gpl-3.0
838b6ee8a9e0b954cc87668ae2f2ff0a
31.78733
217
0.602815
3.151805
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API ClientTests/Tests/Tasks/ScoreTaskCall.swift
1
1962
// // ScoreTaskCall.swift // Habitica API ClientTests // // Created by Phillip Thelen on 12.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Quick import Nimble import ReactiveSwift import Habitica_Models @testable import Habitica_API_Client class ScoreTaskCallSpec: QuickSpec { var stubHolder: StubHolderProtocol? var task: TaskProtocol? override func spec() { HabiticaServerConfig.current = HabiticaServerConfig.stub describe("Score task test") { beforeEach { self.task = APITask() self.stubHolder = StubHolder(stubData: self.dataFor(fileName: "taskResponse", fileExtension: "json")) } context("Success") { it("Should score task up") { // swiftlint:disable:next force_unwrapping let call = ScoreTaskCall(task: self.task!, direction: .up, stubHolder: self.stubHolder) waitUntil(timeout: 0.5) { done in call.objectSignal.observeValues({ (tasks) in expect(tasks).toNot(beNil()) done() }) call.fire() } } } context("Success") { it("Should score task down") { // swiftlint:disable:next force_unwrapping let call = ScoreTaskCall(task: self.task!, direction: .down, stubHolder: self.stubHolder) waitUntil(timeout: 0.5) { done in call.objectSignal.observeValues({ (response) in expect(response).toNot(beNil()) done() }) call.fire() } } } } } }
gpl-3.0
06d0ffab9cc3aa7c3c92b0268d5a9eff
32.810345
117
0.489546
5.357923
false
true
false
false
goblinr/omim
iphone/Maps/Classes/Components/RatingSummaryView/RatingSummaryViewSettings.swift
8
1332
import UIKit struct RatingSummaryViewSettings { enum Default { static let backgroundOpacity: CGFloat = 0.16 static let colors: [MWMRatingSummaryViewValueType: UIColor] = [ .noValue: UIColor.lightGray, .horrible: UIColor.red, .bad: UIColor.orange, .normal: UIColor.yellow, .good: UIColor.green, .excellent: UIColor.blue, ] static let images: [MWMRatingSummaryViewValueType: UIImage] = [:] static let textFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote) static let textSize = textFont.pointSize static let value = "2.2" static let topOffset: CGFloat = 8 static let bottomOffset: CGFloat = 8 static let leadingImageOffset: CGFloat = 12 static let margin: CGFloat = 8 static let trailingTextOffset: CGFloat = 8 static let noValueText = "—" } init() {} var backgroundOpacity = Default.backgroundOpacity var colors = Default.colors var images = Default.images var textFont = Default.textFont var textSize = Default.textSize var value = Default.value var topOffset = Default.topOffset var bottomOffset = Default.bottomOffset var leadingImageOffset = Default.leadingImageOffset var margin = Default.margin var trailingTextOffset = Default.trailingTextOffset var noValueText = Default.noValueText }
apache-2.0
16da0e1f9c969d81293ab8de23fe9dbc
32.25
86
0.725564
4.52381
false
false
false
false
Ybrin/ExponentialBackOff
Example/Tests/Tests.swift
1
2384
// https://github.com/Quick/Quick import Quick import Nimble import ExponentialBackOff import Async class TableOfContentsSpec: QuickSpec { var exponentialBackOff: ExponentialBackOffInstance! var timeOut: TimeInterval! override func spec() { beforeEach { let builder = ExponentialBackOffInstance.Builder() builder.maxElapsedTimeMillis = 1500 builder.maxIntervalMillis = 500 self.exponentialBackOff = ExponentialBackOffInstance(builder: builder) self.timeOut = (TimeInterval(builder.maxIntervalMillis) + TimeInterval(builder.maxIntervalMillis)) * 2 } describe("Testing the exponential backoff algorithm") { it("Should finish with the state failed") { waitUntil(timeout: self.timeOut, action: { (done) in ExponentialBackOff.sharedInstance.runGeneralBackOff(self.exponentialBackOff, codeToRun: { (last, elapsed, completion) in var number: Int = 0 for i in 1 ... 100 { number = number + i } if number != 5051 { _ = completion(false) } else { _ = completion(true) } }, completion: { state in if state == .failed { print("Failed!?") done() } }) }) } it("Should finish with the state succeeded") { waitUntil(timeout: self.timeOut, action: { (done) in ExponentialBackOff.sharedInstance.runGeneralBackOff(self.exponentialBackOff, codeToRun: { (last, elapsed, completion) in var number: Int = 0 for i in 1 ... 100 { number = number + i } if number != 5050 { _ = completion(false) } else { _ = completion(true) } }, completion: { state in if state == .succeeded { done() } }) }) } } } }
mit
cecbca0a8c53cdce8da1339c7fcaf689
33.057143
140
0.460151
5.758454
false
false
false
false
caicai0/ios_demo
load/Carthage/Checkouts/SwiftSoup/Tests/SwiftSoupTests/TextUtil.swift
1
1115
// // TextUtil.swift // SwiftSoup // // Created by Nabil Chatbi on 03/11/16. // Copyright © 2016 Nabil Chatbi. All rights reserved. // import Foundation @testable import SwiftSoup class TextUtil { public static func stripNewlines(_ text: String) -> String { let regex = try! NCRegularExpression(pattern: "\\n\\s*", options: .caseInsensitive) var str = text str = regex.stringByReplacingMatches(in: str, options: [], range: NSRange(0..<str.characters.count), withTemplate: "") return str } } //extension String{ // func replaceAll(of pattern:String,with replacement:String,options: NSRegularExpression.Options = []) -> String{ // do{ // let regex = try NSRegularExpression(pattern: pattern, options: []) // let range = NSRange(0..<self.utf16.count) // return regex.stringByReplacingMatches(in: self, options: [], // range: range, withTemplate: replacement) // }catch{ // NSLog("replaceAll error: \(error)") // return self // } // } // // func trim() -> String { // return trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) // } //}
mit
655ec82be29b37b38f81db40a46f9cac
29.108108
120
0.663375
3.652459
false
false
false
false
heyogrady/SpaceEvaders
SpaceEvaders/OptionsMenu.swift
1
701
import SpriteKit class OptionsMenu { init(menu: SKNode, size: CGSize) { let options = ["sound", "music", "follow", "indicators"] var pos: CGFloat = 51 for option in options { addOption(menu, size: size, option: option, pos: pos) pos -= 5 } } func addOption(menu: SKNode, size: CGSize, option: String, pos: CGFloat) { let height = size.height var isOn = Options.option.get(option) ? "on" : "off" let sprite = Sprite(named: "\(option)\(isOn)", x: size.width * pos / 60, y: 4 * height / 5, size: CGSizeMake(height / 12, height / 12)) sprite.name = "option_\(option)" sprite.addTo(menu) } }
mit
a5985aa87a4f8e662f6ef54e105af18b
34.05
143
0.564907
3.728723
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Platform/BRHTTPIndexMiddleware.swift
1
1094
// // BRHTTPIndexMiddleware.swift // BreadWallet // // Created by Samuel Sutch on 2/19/16. // Copyright (c) 2016-2019 Breadwinner AG. All rights reserved. // import Foundation // BRHTTPIndexMiddleware returns index.html to any GET requests - regardless of the URL being requestd class BRHTTPIndexMiddleware: BRHTTPFileMiddleware { override func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) { if request.method == "GET" { let newRequest = BRHTTPRequestImpl(fromRequest: request) newRequest.path = request.path.rtrim(["/"]) + "/index.html" super.handle(newRequest) { resp in if resp.response == nil { let newRequest = BRHTTPRequestImpl(fromRequest: request) newRequest.path = "/index.html" super.handle(newRequest, next: next) } else { next(resp) } } } else { next(BRHTTPMiddlewareResponse(request: request, response: nil)) } } }
mit
4ecd12999cd8cab75185eec3e5e71b75
35.466667
104
0.597806
4.695279
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineDecorations/Threads/Summary/ThreadSummaryView.swift
1
6055
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Reusable @objc protocol ThreadSummaryViewDelegate: AnyObject { func threadSummaryViewTapped(_ summaryView: ThreadSummaryView) } /// A view to display a summary for an `MXThread` generated by the `MXThreadingService`. @objcMembers class ThreadSummaryView: UIView { private enum Constants { static let viewDefaultWidth: CGFloat = 320 static let cornerRadius: CGFloat = 8 static let lastMessageFont: UIFont = .systemFont(ofSize: 13) } @IBOutlet private weak var iconView: UIImageView! @IBOutlet private weak var numberOfRepliesLabel: UILabel! @IBOutlet private weak var lastMessageAvatarView: UserAvatarView! @IBOutlet private weak var lastMessageContentLabel: UILabel! private var theme: Theme = ThemeService.shared().theme private(set) var thread: MXThreadProtocol? private weak var session: MXSession? private lazy var tapGestureRecognizer: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(tapped(_:))) }() weak var delegate: ThreadSummaryViewDelegate? // MARK: - Setup init(withThread thread: MXThreadProtocol, session: MXSession) { self.thread = thread self.session = session super.init(frame: CGRect(origin: .zero, size: CGSize(width: Constants.viewDefaultWidth, height: PlainRoomCellLayoutConstants.threadSummaryViewHeight))) loadNibContent() update(theme: ThemeService.shared().theme) configure() translatesAutoresizingMaskIntoConstraints = false } static func contentViewHeight(forThread thread: MXThreadProtocol?, fitting maxWidth: CGFloat) -> CGFloat { return PlainRoomCellLayoutConstants.threadSummaryViewHeight } required init?(coder: NSCoder) { super.init(coder: coder) loadNibContent() } @nonobjc func configure(withModel model: ThreadSummaryModel) { numberOfRepliesLabel.text = String(model.numberOfReplies) if let avatar = model.lastMessageSenderAvatar { lastMessageAvatarView.fill(with: avatar) } else { lastMessageAvatarView.avatarImageView.image = nil } if let lastMessage = model.lastMessageText { let mutable = NSMutableAttributedString(attributedString: lastMessage) mutable.setAttributes([ .font: Constants.lastMessageFont ], range: NSRange(location: 0, length: mutable.length)) lastMessageContentLabel.attributedText = mutable } else { lastMessageContentLabel.attributedText = nil } } private func configure() { clipsToBounds = true layer.cornerRadius = Constants.cornerRadius addGestureRecognizer(tapGestureRecognizer) guard let thread = thread, let lastMessage = thread.lastMessage, let session = session, let eventFormatter = session.roomSummaryUpdateDelegate as? MXKEventFormatter, let room = session.room(withRoomId: lastMessage.roomId) else { lastMessageAvatarView.avatarImageView.image = nil lastMessageContentLabel.text = nil return } let lastMessageSender = session.user(withUserId: lastMessage.sender) let fallbackImage = AvatarFallbackImage.matrixItem(lastMessage.sender, lastMessageSender?.displayname) let avatarViewData = AvatarViewData(matrixItemId: lastMessage.sender, displayName: lastMessageSender?.displayname, avatarUrl: lastMessageSender?.avatarUrl, mediaManager: session.mediaManager, fallbackImage: fallbackImage) room.state { [weak self] roomState in guard let self = self else { return } let formatterError = UnsafeMutablePointer<MXKEventFormatterError>.allocate(capacity: 1) let lastMessageText = eventFormatter.attributedString(from: lastMessage.replyStrippedVersion, with: roomState, error: formatterError) let model = ThreadSummaryModel(numberOfReplies: thread.numberOfReplies, lastMessageSenderAvatar: avatarViewData, lastMessageText: lastMessageText) self.configure(withModel: model) } } // MARK: - Action @objc private func tapped(_ sender: UITapGestureRecognizer) { guard thread != nil else { return } delegate?.threadSummaryViewTapped(self) } } extension ThreadSummaryView: NibOwnerLoadable {} extension ThreadSummaryView: Themable { func update(theme: Theme) { self.theme = theme backgroundColor = theme.colors.system iconView.tintColor = theme.colors.secondaryContent numberOfRepliesLabel.textColor = theme.colors.secondaryContent lastMessageContentLabel.textColor = theme.colors.secondaryContent } }
apache-2.0
6d0e9154f5991825bab0a8801abf680b
39.099338
110
0.633196
5.674789
false
false
false
false
jjochen/photostickers
MessagesExtension/Scenes/Messages App/MessagesAppViewController.swift
1
3051
// // MessagesAppViewController.swift // MessageExtension // // Created by Jochen on 28.03.19. // Copyright © 2019 Jochen Pfeiffer. All rights reserved. // import Messages import Reusable import RxCocoa import RxDataSources import RxFlow import RxSwift import UIKit /* TODO: * check https://github.com/sergdort/CleanArchitectureRxSwift * show toolbar with edit/done button only in expanded mode * only in edit mode: edit, sort, delete sticker */ class MessagesAppViewController: MSMessagesAppViewController, StoryboardBased { private lazy var application: Application = { Application() }() private let disposeBag = DisposeBag() private let coordinator = FlowCoordinator() private let requestPresentationStyle = PublishSubject<MSMessagesAppPresentationStyle>() override func viewDidLoad() { super.viewDidLoad() RxImagePickerDelegateProxy.register { RxImagePickerDelegateProxy(imagePicker: $0) } view.tintColor = StyleKit.appColor setupFlow() } private func setupFlow() { coordinator.rx.willNavigate.subscribe(onNext: { flow, step in print("will navigate to flow=\(flow) and step=\(step)") }).disposed(by: disposeBag) coordinator.rx.didNavigate.subscribe(onNext: { flow, step in print("did navigate to flow=\(flow) and step=\(step)") }).disposed(by: disposeBag) requestPresentationStyle.asDriver(onErrorDriveWith: Driver.empty()) .drive(rx.requestPresentationStyle) .disposed(by: disposeBag) let appFlow = StickerBrowserFlow(withServices: application.appServices, requestPresentationStyle: requestPresentationStyle, currentPresentationStyle: rx.willTransitionToPresentationStyle.asDriver()) let appStepper = OneStepper(withSingleStep: PhotoStickerStep.stickerBrowserIsRequired) Flows.whenReady(flow1: appFlow) { [unowned self] root in self.embed(viewController: root) } coordinator.coordinate(flow: appFlow, with: appStepper) } } extension MessagesAppViewController { private func embed(viewController: UIViewController) { for child in children { child.willMove(toParent: nil) child.view.removeFromSuperview() child.removeFromParent() } addChild(viewController) viewController.view.frame = view.bounds viewController.view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(viewController.view) NSLayoutConstraint.activate([ viewController.view.leftAnchor.constraint(equalTo: view.leftAnchor), viewController.view.rightAnchor.constraint(equalTo: view.rightAnchor), viewController.view.topAnchor.constraint(equalTo: view.topAnchor), viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) viewController.didMove(toParent: self) } }
mit
fb3d1728b51ac45e174856ea810680cf
33.269663
115
0.68623
5.178268
false
false
false
false
shuoli84/RxSwift
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaPage.swift
3
844
// // WikipediaPage.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift struct WikipediaPage { let title: String let text: String init(title: String, text: String) { self.title = title self.text = text } // tedious parsing part static func parseJSON(json: NSDictionary) -> RxResult<WikipediaPage> { let title = json.valueForKey("parse")?.valueForKey("title") as? String let text = json.valueForKey("parse")?.valueForKey("text")?.valueForKey("*") as? String if title == nil || text == nil { return failure(apiError("Error parsing page content")) } return success(WikipediaPage(title: title!, text: text!)) } }
mit
ec77a481bde7a91ee47c2d07d5519522
25.40625
94
0.613744
4.350515
false
false
false
false
ospr/UIPlayground
UIPlaygroundUI/SpringBoardAppCollectionViewController.swift
1
5257
// // SpringBoardAppCollectionViewController.swift // UIPlayground // // Created by Kip Nicol on 9/20/16. // Copyright © 2016 Kip Nicol. All rights reserved. // import UIKit protocol SpringBoardAppCollectionViewControllerDelegate: class { func springBoardAppCollectionViewController(_ viewController: SpringBoardAppCollectionViewController, didSelectAppInfo appInfo: SpringBoardAppInfo, selectedAppIconButton: UIButton) func springBoardAppCollectionViewControllerDidUpdateEditMode(_ viewController: SpringBoardAppCollectionViewController) } private let reuseIdentifier = "Cell" struct SpringBoardAppInfo { let appName: String let image: UIImage } class SpringBoardAppCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { let appCollectionLayout: SpringBoardAppCollectionLayout let appInfoItems: [SpringBoardAppInfo] var editModeEnabled: Bool = false { didSet { if editModeEnabled != oldValue { // Reload cells to start/stop animations collectionView!.reloadData() } } } weak var delegate: SpringBoardAppCollectionViewControllerDelegate? fileprivate var appInfoByAppIconButtons = [UIButton : SpringBoardAppInfo]() init(appInfoItems: [SpringBoardAppInfo], appCollectionLayout: SpringBoardAppCollectionLayout) { self.appCollectionLayout = appCollectionLayout self.appInfoItems = appInfoItems let viewLayout = UICollectionViewFlowLayout() viewLayout.minimumInteritemSpacing = appCollectionLayout.minimumInteritemSpacing viewLayout.minimumLineSpacing = appCollectionLayout.minimumLineSpacing viewLayout.itemSize = appCollectionLayout.itemSize viewLayout.sectionInset = appCollectionLayout.sectionInset super.init(collectionViewLayout: viewLayout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() collectionView!.backgroundColor = .clear collectionView!.register(SpringBoardAppIconViewCell.self, forCellWithReuseIdentifier: "AppIconCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // The cells stop animating sometimes when the view disappears // (eg spring board page view transitions) for cell in collectionView!.visibleCells { if let cell = cell as? SpringBoardAppIconViewCell { updateCellAnimations(cell) } } } // MARK: - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return appInfoItems.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let appInfo = appInfoItems[indexPath.row] let appIconCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AppIconCell", for: indexPath) as! SpringBoardAppIconViewCell appIconCell.delegate = self appIconCell.appNameLabel.text = appInfo.appName appIconCell.appIconImage = appInfo.image appIconCell.appIconLength = appCollectionLayout.iconLength appIconCell.appIconButtonView.removeTarget(nil, action: nil, for: .allEvents) appIconCell.appIconButtonView.addTarget(self, action: #selector(appIconButtonWasTapped), for: .touchUpInside) appInfoByAppIconButtons[appIconCell.appIconButtonView] = appInfo updateCellAnimations(appIconCell) return appIconCell } // MARK: - Working with Animations func updateCellAnimations(_ cell: SpringBoardAppIconViewCell) { let jitterAnimationKey = "Jitter" if editModeEnabled { if cell.layer.animation(forKey: jitterAnimationKey) == nil { let jitterAnimation = CAAnimation.jitterAnimation() // Add a offset to the animation time to cause the cells // to jitter at different offsets jitterAnimation.timeOffset = CACurrentMediaTime() + drand48() cell.layer.add(jitterAnimation, forKey: jitterAnimationKey) } } else { cell.layer.removeAnimation(forKey: jitterAnimationKey) } cell.appIconButtonView.isUserInteractionEnabled = !editModeEnabled } // MARK: - Handling touch events func appIconButtonWasTapped(sender: UIButton) { let appInfo = appInfoByAppIconButtons[sender]! delegate?.springBoardAppCollectionViewController(self, didSelectAppInfo: appInfo, selectedAppIconButton: sender) } } extension SpringBoardAppCollectionViewController: SpringBoardAppIconViewCellDelegate { func springBoardAppIconViewCell(didLongPress springBoardAppIconViewCell: SpringBoardAppIconViewCell) { delegate?.springBoardAppCollectionViewControllerDidUpdateEditMode(self) } }
mit
a2eea7c01f3cb5e27cc2d234bb7e658f
37.086957
184
0.703387
5.775824
false
false
false
false
rock-n-code/Kashmir
Kashmir/Shared/Features/Data Source/Protocols/DataSource.swift
1
6835
// // DataSource.swift // Kashmir // // Created by Javier Cicchelli on 09/11/2016. // Copyright © 2016 Rock & Code. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif /** This protocol defines the minimal requirements a compliant data source instance should implement in order to provide data to a view controller. */ public protocol DataSource: class { /// Generic placeholder for the data type instances to use as the source from where the data for the data source is generated. associatedtype SourceData /// Generic placeholder for the section type instances, which must implement the `Sectionable` protocol. associatedtype Section: Sectionable /// Generic placeholder for the item type instances, which must implement the `Itemable` protocol. associatedtype Item: Itemable // MARK: Properties /// The dictionary that persist in memory both section and item type instances obtained from the `source`. var data: [Section: [Item]] { get set } /// The source of data for the `data` dictionary. var sourceData: SourceData? { get set } var numberOfSections: Int { get } // MARK: Initializers /** Default initializer. - returns: A pristine data source with an empty `data` dictionary. */ init() init(data: SourceData) // MARK: Functions func update(data updatedData: SourceData) /** Loads the data from the source into the data dictionary. - important: This function is, in fact, a helper function and as such is executed inside the `init(data: )` and the `update(data: )` functions and it **must not** be called outside that scope at all. - remarks: While implementing this function, the developer has to create the `Section` and the `Items` instances as he/she needs based on his/her data requirements. */ func load() func numberOfItems(at sectionIndex: Int) throws -> Int func items(at sectionIndex: Int) throws -> [Item] func items(at indexPaths: [IndexPath]) throws -> [Item] func section(at sectionIndex: Int) throws -> Section func item(at indexPath: IndexPath) throws -> Item } // MARK: - public extension DataSource { // MARK: Properties /// The number of sections on the dictionary. var numberOfSections: Int { return data.keys.count } // MARK: Initializers /** Recommended initializer. - important: This initializer **must** be used in order to populate the `data` dictionary. - parameter data: An source data instance which is mapped from a JSON response. - returns: A data source with a dictionary filled with sections and theirs respective items. */ init(data: SourceData) { self.init() self.data = [:] self.sourceData = data load() } // MARK: Functions /** Updates the data of the data source. - important: This function **must** be used in order to update the `data` dictionary. - parameter data: An source data instance which is mapped from a JSON response. */ func update(data updatedData: SourceData) { self.data = [:] sourceData = updatedData load() } /** Gets the number of items within a section given its index position. - parameter at: The index position of a `Section` instance. - throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function. - returns: The number of items within the given section. */ func numberOfItems(at sectionIndex: Int) throws -> Int { guard numberOfSections > 0 else { return 0 } let section = try self.section(at: sectionIndex) let items = data[section]! return items.count } /** Creates an array of items within a section given its index position. - parameter at: The index position of a `Section` instance. - throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function. - returns: An array of items within the given section. */ func items(at sectionIndex: Int) throws -> [Item] { guard try numberOfItems(at: sectionIndex) > 0 else { throw DataSourceError.itemsEmpty } let section = try self.section(at: sectionIndex) return data[section]! } /** Creates an array of items with given array of indexPaths. - parameter at: An array of indexPaths. - throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function. - returns: An array of items within the given array of indexPaths. */ func items(at indexPaths: [IndexPath]) throws -> [Item] { var items = [Item]() for indexPath in indexPaths { guard try numberOfItems(at: indexPath.section) > 0 else { throw DataSourceError.itemsEmpty } let item = try self.item(at: indexPath) items.append(item) } return items } /** Gets a section instance given its index position. - parameter at: The index position of a `Section` instance - throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function. - returns: A `Section` instance based on the given index position. */ func section(at sectionIndex: Int) throws -> Section { guard numberOfSections > 0 else { throw DataSourceError.sectionsEmpty } guard sectionIndex <= numberOfSections - 1 else { throw DataSourceError.sectionIndexOutOfBounds } return data.keys.filter({ $0.index == sectionIndex }).first! } /** Gets an item instance given an index path. - parameter at: An index path indicating a both a position in the section and its respective items array. - throws: A `DataSourceError` type error is thrown if any error is catched during the execution of this function. - returns: An `Item` instance based on the given index path. */ func item(at indexPath: IndexPath) throws -> Item { guard try numberOfItems(at: indexPath.section) > 0 else { throw DataSourceError.itemsEmpty } let section = try self.section(at: indexPath.section) let items = data[section]! guard indexPath.item <= items.count - 1 else { throw DataSourceError.itemIndexOutOfBounds } return items[indexPath.item] } }
mit
ac48db9f845c9fcc947f4b7d19fec030
30.786047
203
0.636523
4.80253
false
false
false
false
leyap/VPNOn
VPNOn/LTVPNTableViewController+Geo.swift
1
781
// // LTVPNTableViewController+Geo.swift // VPNOn // // Created by Lex on 3/3/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit import VPNOnKit extension LTVPNTableViewController { func geoDidUpdate(notification: NSNotification) { if let vpn = notification.object as VPN? { VPNManager.sharedManager.geoInfoOfHost(vpn.server) { geoInfo in vpn.countryCode = geoInfo.countryCode vpn.isp = geoInfo.isp vpn.latitude = geoInfo.latitude vpn.longitude = geoInfo.longitude vpn.managedObjectContext!.save(nil) self.tableView.reloadData() } } } }
mit
d1c6aaea57211f66cde13ce54157f52f
23.40625
64
0.558259
4.621302
false
false
false
false
griff/metaz
Plugins/TheMovieDbNG/src/TVSearch.swift
1
8841
// // Search.swift // TheMovieDbNG // // Created by Brian Olsen on 22/02/2020. // import Foundation import MetaZKit @objc public class TVSearch : Search { let tvShow : String let season : Int? let episode : Int? // MARK: - public init(show: String, delegate: SearchProviderDelegate, season: Int? = nil, episode: Int? = nil) { self.tvShow = show self.season = season self.episode = episode super.init(delegate: delegate) } // MARK: - func fetch(series: String) throws -> [Int64] { guard let name = series.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { throw SearchError.PercentEncoding(series) } let url_s = "\(Plugin.BasePath)/search/tv?api_key=\(Plugin.API_KEY)&query=\(name)" guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) } guard let response = try request(url, type: PagedResultsJSON<IdNameJSON>.self) else { throw SearchError.URLSession(url) } return response.results.map { $0.id } } func fetch(seriesInfo id: Int64) throws -> TVShowDetailsJSON { let url_s = "\(Plugin.BasePath)/tv/\(id)?api_key=\(Plugin.API_KEY)&append_to_response=content_ratings,credits,images" guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) } guard let response = try request(url, type: TVShowDetailsJSON.self) else { throw SearchError.URLSession(url) } return response } func fetch(series id: Int64, season: Int) throws -> SeasonDetailsJSON { let url_s = "\(Plugin.BasePath)/tv/\(id)/season/\(season)?api_key=\(Plugin.API_KEY)&append_to_response=credits,images" guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) } guard let response = try request(url, type: SeasonDetailsJSON.self) else { throw SearchError.URLSession(url) } return response } func fetch(series id: Int64, season: Int, episode: Int) throws -> EpisodeJSON { let url_s = "\(Plugin.BasePath)/tv/\(id)/season/\(season)/episode/\(episode)?api_key=\(Plugin.API_KEY)&append_to_response=credits,images" guard let url = URL(string: url_s) else { throw SearchError.URL(url_s) } guard let response = try request(url, type: EpisodeJSON.self) else { throw SearchError.URLSession(url) } return response } // MARK: - func merge(episodes: [EpisodeJSON], with values: [String: Any], posters: [RemoteData], seasonBanners: [RemoteData]) -> [[String: Any]] { return episodes.map {(episode) in var result = values result[MZTVEpisodeTagIdent] = episode.episode_number result.setNormalized(value: episode.name, forKey: MZTitleTagIdent) //result[MZIMDBTagIdent] = episode.imdbId result.setNormalized(value: episode.overview, forKey: MZShortDescriptionTagIdent) result.setNormalized(value: episode.overview, forKey: MZLongDescriptionTagIdent) let director = episode.crew.filter { $0.department == "Directing" }.map{ $0.name }.join() result.setNormalized(value: director, forKey: MZDirectorTagIdent) let screenwriter = episode.crew.filter { $0.department == "Writing" }.map{ $0.name }.join() result.setNormalized(value: screenwriter, forKey: MZScreenwriterTagIdent) let producers = episode.crew.filter { $0.department == "Production" }.map{ $0.name }.join() result.setNormalized(value: producers, forKey: MZProducerTagIdent) result.setNormalized(value: episode.production_code, forKey: MZTVEpisodeIDTagIdent) if let actual = episode.air_date { var firstAired : Date? let f = DateFormatter() f.dateFormat = "yyyy-MM-dd" firstAired = f.date(from: actual) if let date = firstAired { result[MZDateTagIdent] = date } else { NSLog("Unable to parse release date '%@'", actual); } } var images : [RemoteData] = seasonBanners images.append(contentsOf: posters) if !images.isEmpty { result[MZPictureTagIdent] = images } return result } } // MARK: - override public func do_search() throws { let series = try fetch(series: tvShow) for id in series { do { var values = [String: Any]() let info = try fetch(seriesInfo: id) if info.name.normalize().isEmpty { print("TheMovieDB TV Show has \(id) no name") continue } values[MZVideoTypeTagIdent] = NSNumber(value: MZTVShowVideoType.rawValue) values[Plugin.TMDbTVIdTagIdent] = info.id values[MZTVShowTagIdent] = info.name values[MZArtistTagIdent] = info.name //values[MZIMDBTagIdent] = info.imdbId let networks = info.networks.map { $0.name }.join() values.setNormalized(value: networks, forKey: MZTVNetworkTagIdent) values.setNormalized(value: info.overview, forKey: MZShortDescriptionTagIdent) values.setNormalized(value: info.overview, forKey: MZLongDescriptionTagIdent) let genres = info.genres.map { $0.name }.join() values.setNormalized(value: genres, forKey: MZGenreTagIdent) let ratingTag = MZTag.lookup(withIdentifier: MZRatingTagIdent)! if let content_ratings = info.content_ratings { for rating in content_ratings.results { let ratingNr : NSNumber? = ratingTag.object(from: rating.rating) as? NSNumber? ?? nil if let rating = ratingNr { if rating.intValue != MZNoRating.rawValue { values[MZRatingTagIdent] = ratingNr break } } } } if let credits = info.credits { let actors = credits.cast.map { $0.name }.join() values.setNormalized(value: actors, forKey: MZActorsTagIdent) } var posters : [RemoteData] = [] if let images = info.images { posters = try images.posters.map { try Plugin.remote(image: $0, sort: "B") } } var seasons : [Int] = [] if let season = self.season { seasons = [season] } else { seasons = info.seasons.map { $0.season_number } } for season in seasons { let seasonInfo = try fetch(series: id, season: season) var seasonBanners : [RemoteData] = [] if let banners = seasonInfo.images { seasonBanners = try banners.posters.map { try Plugin.remote(image: $0) } } values[MZTVSeasonTagIdent] = season if let credits = seasonInfo.credits { let directors = credits.crew.filter { $0.department == "Directing" }.map{ $0.name }.join() values.setNormalized(value: directors, forKey: MZDirectorTagIdent) let screenwriters = credits.crew.filter { $0.department == "Writing" }.map{ $0.name }.join() values.setNormalized(value: screenwriters, forKey: MZScreenwriterTagIdent) let producers = credits.crew.filter { $0.department == "Production" }.map{ $0.name }.join() values.setNormalized(value: producers, forKey: MZProducerTagIdent) } var episodes = seasonInfo.episodes if let episode = self.episode { episodes = episodes.filter { $0.episode_number == episode } } let results = merge(episodes: episodes, with: values, posters: posters, seasonBanners: seasonBanners) self.delegate.reportSearch(results: results) } } catch SearchError.Canceled { throw SearchError.Canceled } catch { self.delegate.reportSearch(error: error) } } } }
mit
828a558853a05f325af84ac9893e3c80
43.878173
145
0.548807
4.57372
false
false
false
false
github/Nimble
Nimble/Wrappers/ObjCMatcher.swift
77
3344
import Foundation struct ObjCMatcherWrapper : Matcher { let matcher: NMBMatcher let to: String let toNot: String func matches(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { failureMessage.to = to let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) return pass } func doesNotMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool { failureMessage.to = toNot let pass = matcher.matches(({ actualExpression.evaluate() }), failureMessage: failureMessage, location: actualExpression.location) return !pass } } // Equivalent to Expectation, but simplified for ObjC objects only public class NMBExpectation : NSObject { let _actualBlock: () -> NSObject! var _negative: Bool let _file: String let _line: UInt var _timeout: NSTimeInterval = 1.0 public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) { self._actualBlock = actualBlock self._negative = negative self._file = file self._line = line } public var withTimeout: (NSTimeInterval) -> NMBExpectation { return ({ timeout in self._timeout = timeout return self }) } public var to: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.to( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not") ) }) } public var toNot: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toNot( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not") ) }) } public var notTo: (matcher: NMBMatcher) -> Void { return toNot } public var toEventually: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventually( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"), timeout: self._timeout ) }) } public var toEventuallyNot: (matcher: NMBMatcher) -> Void { return ({ matcher in expect(file: self._file, line: self._line){ self._actualBlock() as NSObject? }.toEventuallyNot( ObjCMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"), timeout: self._timeout ) }) } } @objc public class NMBObjCMatcher : NMBMatcher { let _matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool init(matcher: (actualExpression: () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool) { self._matcher = matcher } public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { return _matcher( actualExpression: ({ actualBlock() as NSObject? }), failureMessage: failureMessage, location: location) } }
apache-2.0
6864829055b53a19808e1c935603ef0c
35.347826
138
0.617823
4.917647
false
false
false
false
BanyaKrylov/Learn-Swift
5.1/HW1.playground/Contents.swift
1
280
import UIKit var str = "Homework 1" var numInt: Int8 var numUint: UInt8 numInt = Int8.min numUint = UInt8.max print(numUint, numInt) var num1 = 2 var num2: Int = 100 var numBuffer:Int numBuffer = num1 num1 = num2 num2 = numBuffer print("num1 = \(num1) and num2 = \(num2)")
apache-2.0
71171e8c08c0da300fcdea4d5eb4d01e
12.333333
42
0.692857
2.45614
false
false
false
false
zvonler/PasswordElephant
external/github.com/CryptoSwift/Sources/CryptoSwift/CMAC.swift
2
3775
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // public final class CMAC: Authenticator { public enum Error: Swift.Error { case wrongKeyLength } private let key: SecureBytes private static let BlockSize: Int = 16 private static let Zero: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] private static let Rb: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87] public init(key: Array<UInt8>) throws { if key.count != 16 { throw Error.wrongKeyLength } self.key = SecureBytes(bytes: key) } // MARK: Authenticator public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> { let aes = try AES(key: Array(key), blockMode: CBC(iv: CMAC.Zero), padding: .noPadding) let l = try aes.encrypt(CMAC.Zero) var subKey1 = leftShiftOneBit(l) if (l[0] & 0x80) != 0 { subKey1 = xor(CMAC.Rb, subKey1) } var subKey2 = leftShiftOneBit(subKey1) if (subKey1[0] & 0x80) != 0 { subKey2 = xor(CMAC.Rb, subKey2) } let lastBlockComplete: Bool let blockCount = (bytes.count + CMAC.BlockSize - 1) / CMAC.BlockSize if blockCount == 0 { lastBlockComplete = false } else { lastBlockComplete = bytes.count % CMAC.BlockSize == 0 } var paddedBytes = bytes if !lastBlockComplete { bitPadding(to: &paddedBytes, blockSize: CMAC.BlockSize) } var blocks = Array(paddedBytes.batched(by: CMAC.BlockSize)) var lastBlock = blocks.popLast()! if lastBlockComplete { lastBlock = xor(lastBlock, subKey1) } else { lastBlock = xor(lastBlock, subKey2) } var x = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize) var y = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize) for block in blocks { y = xor(block, x) x = try aes.encrypt(y) } y = xor(lastBlock, x) return try aes.encrypt(y) } // MARK: Helper methods /** Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array - parameters: - bytes: byte array - returns: bit shifted bit string split again in array of bytes */ private func leftShiftOneBit(_ bytes: Array<UInt8>) -> Array<UInt8> { var shifted = Array<UInt8>(repeating: 0x00, count: bytes.count) let last = bytes.count - 1 for index in 0..<last { shifted[index] = bytes[index] << 1 if (bytes[index + 1] & 0x80) != 0 { shifted[index] += 0x01 } } shifted[last] = bytes[last] << 1 return shifted } }
gpl-3.0
c2354393f54dc3024345bc58a4419028
37.121212
217
0.621357
3.664078
false
false
false
false
MukeshKumarS/Swift
test/IRGen/closure.swift
2
3152
// RUN: %target-swift-frontend -primary-file %s -emit-ir | FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* [[DESTROY:@objectdestroy.1]], i8** null, %swift.type { i64 64 }, i32 16 } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define linkonce_odr hidden i64 @[[CLOSURE1:_TFF7closure1aFT1iSi_FSiSiU_FSiSi]](i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal i64 @_TPA_[[CLOSURE1]](i64, %swift.refcounted*) {{.*}} { // CHECK: } // -- Closure entry point // CHECK: define linkonce_odr hidden i64 @[[CLOSURE2:_TFF7closure1buRxS_9OrdinablerFT3seqx_FSiSiU_FSiSi]](i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal i64 @_TPA_[[CLOSURE2]](i64, %swift.refcounted*) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: call void @swift_retain(%swift.refcounted* [[BOX]]) // CHECK: call void @swift_release(%swift.refcounted* %1) // CHECK: [[RES:%.*]] = tail call i64 @[[CLOSURE2]](i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden { i8*, %swift.refcounted* } @_TF7closure14captures_tupleu0_rFT1xTxq___FT_Txq__(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
15486e2bbe08e1b4e94b54c630d5d0ff
53.344828
204
0.620558
3.155155
false
false
false
false
tejen/codepath-instagram
Instagram/Instagram/CommentCell.swift
1
2648
// // CommentCell.swift // Instagram // // Created by Tejen Hasmukh Patel on 3/12/16. // Copyright © 2016 Tejen. All rights reserved. // import UIKit import Parse class CommentCell: UITableViewCell { weak var commentsTableController: CommentsTableViewController?; @IBOutlet weak var profilePicView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var ageLabel: UILabel! var loadingProfile = false; var comment: PFObject? { didSet { let user = comment!["user"] as? User; profilePicView.setImageWithURL(user!.profilePicURL!); usernameLabel.text = user!.username; contentLabel.text = comment!["content"] as? String; ageLabel.text = Post.timeSince(comment!.createdAt!); } } override func awakeFromNib() { super.awakeFromNib() // Initialization code let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("openProfile")); usernameLabel.userInteractionEnabled = true; usernameLabel.addGestureRecognizer(tapGestureRecognizer); let tapGestureRecognizer2 = UITapGestureRecognizer(target:self, action:Selector("openProfile")); profilePicView.userInteractionEnabled = true; profilePicView.addGestureRecognizer(tapGestureRecognizer2); profilePicView.clipsToBounds = true; profilePicView.layer.cornerRadius = 15; } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func openProfile() { if(loadingProfile) { return; } loadingProfile = true; delay(1.0) { () -> () in self.loadingProfile = false; } UIView.animateWithDuration(0.05) { () -> Void in self.usernameLabel.alpha = 0.25; self.profilePicView.alpha = 0.25; } delay(0.2) { () -> () in UIView.animateWithDuration(0.2) { () -> Void in self.usernameLabel.alpha = 1; self.profilePicView.alpha = 1; } let vc = storyboard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController; vc.user = User.getUserByUsername(self.usernameLabel.text!); self.commentsTableController?.navigationController?.pushViewController(vc, animated: true); } } }
apache-2.0
ca820bd96cf9f0aa6de35475ba230611
32.0875
133
0.625236
5.190196
false
false
false
false
loudnate/Loop
Loop/Managers/StatusChartsManager.swift
1
3479
// // StatusChartsManager.swift // Loop // // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation import LoopKit import LoopUI import SwiftCharts class StatusChartsManager: ChartsManager { enum ChartIndex: Int, CaseIterable { case glucose case iob case dose case cob } let glucose: PredictedGlucoseChart let iob: IOBChart let dose: DoseChart let cob: COBChart init(colors: ChartColorPalette, settings: ChartSettings, traitCollection: UITraitCollection) { let glucose = PredictedGlucoseChart() let iob = IOBChart() let dose = DoseChart() let cob = COBChart() self.glucose = glucose self.iob = iob self.dose = dose self.cob = cob super.init(colors: colors, settings: settings, charts: ChartIndex.allCases.map({ (index) -> ChartProviding in switch index { case .glucose: return glucose case .iob: return iob case .dose: return dose case .cob: return cob } }), traitCollection: traitCollection) } } extension StatusChartsManager { func setGlucoseValues(_ glucoseValues: [GlucoseValue]) { glucose.setGlucoseValues(glucoseValues) invalidateChart(atIndex: ChartIndex.glucose.rawValue) } func setPredictedGlucoseValues(_ glucoseValues: [GlucoseValue]) { glucose.setPredictedGlucoseValues(glucoseValues) invalidateChart(atIndex: ChartIndex.glucose.rawValue) } func setAlternatePredictedGlucoseValues(_ glucoseValues: [GlucoseValue]) { glucose.setAlternatePredictedGlucoseValues(glucoseValues) invalidateChart(atIndex: ChartIndex.glucose.rawValue) } func glucoseChart(withFrame frame: CGRect) -> Chart? { return chart(atIndex: ChartIndex.glucose.rawValue, frame: frame) } var targetGlucoseSchedule: GlucoseRangeSchedule? { get { return glucose.targetGlucoseSchedule } set { glucose.targetGlucoseSchedule = newValue invalidateChart(atIndex: ChartIndex.glucose.rawValue) } } var scheduleOverride: TemporaryScheduleOverride? { get { return glucose.scheduleOverride } set { glucose.scheduleOverride = newValue invalidateChart(atIndex: ChartIndex.glucose.rawValue) } } } extension StatusChartsManager { func setIOBValues(_ iobValues: [InsulinValue]) { iob.setIOBValues(iobValues) invalidateChart(atIndex: ChartIndex.iob.rawValue) } func iobChart(withFrame frame: CGRect) -> Chart? { return chart(atIndex: ChartIndex.iob.rawValue, frame: frame) } } extension StatusChartsManager { func setDoseEntries(_ doseEntries: [DoseEntry]) { dose.doseEntries = doseEntries invalidateChart(atIndex: ChartIndex.dose.rawValue) } func doseChart(withFrame frame: CGRect) -> Chart? { return chart(atIndex: ChartIndex.dose.rawValue, frame: frame) } } extension StatusChartsManager { func setCOBValues(_ cobValues: [CarbValue]) { cob.setCOBValues(cobValues) invalidateChart(atIndex: ChartIndex.cob.rawValue) } func cobChart(withFrame frame: CGRect) -> Chart? { return chart(atIndex: ChartIndex.cob.rawValue, frame: frame) } }
apache-2.0
95a2cb28efc81044780fee3160cb9a2f
26.603175
117
0.646924
4.643525
false
false
false
false
benlangmuir/swift
test/SILOptimizer/assemblyvision_remark/basic_yaml.swift
7
5509
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-assembly-vision-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xfrontend -enable-copy-propagation -emit-sil %s -o /dev/null -Xfrontend -verify -Xfrontend -enable-lexical-borrow-scopes=false // RUN: %empty-directory(%t) // RUN: %target-swiftc_driver -wmo -O -Xllvm -sil-disable-pass=FunctionSignatureOpts -Xfrontend -enable-copy-propagation -emit-sil -save-optimization-record=yaml -save-optimization-record-path %t/note.yaml -Xfrontend -enable-lexical-borrow-scopes=false %s -o /dev/null && %FileCheck --input-file=%t/note.yaml %s // REQUIRES: optimized_stdlib,swift_stdlib_no_asserts // This file is testing out the basic YAML functionality to make sure that it // works without burdening basic_yaml.swift with having to update all // of the yaml test cases everytime new code is added. public class Klass {} // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 7 ]], Column: 21 } // CHECK-NEXT: Function: main // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'heap allocated ref of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... public var global = Klass() // expected-remark {{heap allocated ref of type 'Klass'}} // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 42 ]], Column: 12 } // CHECK-NEXT: Function: 'getGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'begin exclusive access to value of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''global''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE - 14 ]], Column: 12 } // CHECK-NEXT: ... // // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 27 ]], Column: 12 } // CHECK-NEXT: Function: 'getGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'end exclusive access to value of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''global''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE - 29 ]], Column: 12 } // CHECK-NEXT: ... // // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 12]], Column: 5 } // CHECK-NEXT: Function: 'getGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'retain of type ''' // CHECK-NEXT: - ValueType: Klass // CHECK-NEXT: - String: '''' // CHECK-NEXT: - InferredValue: 'of ''global''' // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE - 44 ]], Column: 12 } // CHECK-NEXT: ... @inline(never) public func getGlobal() -> Klass { return global // expected-remark @:5 {{retain of type 'Klass'}} // expected-note @-49:12 {{of 'global'}} // expected-remark @-2 {{begin exclusive access to value of type 'Klass'}} // expected-note @-51:12 {{of 'global'}} // NOTE: We really want the end access at :18, not :12. TODO Fix this! // expected-remark @-5 {{end exclusive access to value of type 'Klass'}} // expected-note @-54:12 {{of 'global'}} } // CHECK: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 23]], Column: 11 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'heap allocated ref of type ''' // CHECK-NEXT: - ValueType: // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... // CHECK-NEXT: --- !Missed // CHECK-NEXT: Pass: sil-assembly-vision-remark-gen // CHECK-NEXT: Name: sil.memory // CHECK-NEXT: DebugLoc: { File: '{{.*}}basic_yaml.swift', // CHECK-NEXT: Line: [[# @LINE + 12]], Column: 12 } // CHECK-NEXT: Function: 'useGlobal()' // CHECK-NEXT: Args: // CHECK-NEXT: - String: 'release of type ''' // CHECK-NEXT: - ValueType: // CHECK-NEXT: - String: '''' // CHECK-NEXT: ... public func useGlobal() { let x = getGlobal() // Make sure that the retain msg is at the beginning of the print and the // releases are the end of the print. print(x) // expected-remark @:11 {{heap allocated ref of type}} // We test the type emission above since FileCheck can handle regex. // expected-remark @-2:12 {{release of type}} }
apache-2.0
acb652fb90348600056b2be001f373e2
48.1875
312
0.560174
3.547328
false
false
false
false
MrPudin/Skeem
IOS/Prevoir/ScheduleTaskTBC.swift
1
3140
// // ScheduleTaskTBC.swift // Skeem // // Created by Zhu Zhan Yan on 11/11/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit class ScheduleTaskTBC: UITableViewCell { //UI Element @IBOutlet weak var label_begin: UILabel! @IBOutlet weak var label_subject: UILabel! @IBOutlet weak var label_duration: UILabel! @IBOutlet weak var label_name: UILabel! @IBOutlet weak var label_description: UILabel! @IBOutlet weak var label_status: UILabel! //Data /* * public func updateUI(name:String,subject:String,description:String,duration:Int,begin:Date,completion:Double) * - Updates UI for data specifed * [Argument] * name - name of the task * subject - subject of the task * description - description of the task * duration - duration of the task * begin - begin date/time of the task * completion - Floating point number 0.0<=x<=1.0, DefinesExtent the task is completed * */ public func updateUI(name:String,subject:String,description:String,duration:Int,begin:Date,completion:Double) { //Init Date Data let date = Date() let cal = Calendar.autoupdatingCurrent var begin_dcmp = cal.dateComponents([Calendar.Component.day, Calendar.Component.month,Calendar.Component.year,Calendar.Component.minute,Calendar.Component.hour], from: begin as Date) var diff_dcmp = cal.dateComponents([Calendar.Component.day], from: date, to: begin as Date ) //Name Label self.label_name.text = name //Begin Label //Adjust Label for Readablity switch diff_dcmp.day! { case 0: label_begin.text = "\(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" case 1: label_begin.text = "Tommorow,\(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" default: label_begin.text = "\(begin_dcmp.day!)/\(begin_dcmp.month!)/\(begin_dcmp.year!), \(begin_dcmp.hour!) \((begin_dcmp.minute! < 10) ? "0\(begin_dcmp.minute!)": "\(begin_dcmp.minute!)")" } //Duration Label var drsn_hour = 0 var drsn_min = 0 var drsn_left = duration drsn_hour = drsn_left / (60 * 60) drsn_left -= drsn_hour * (60 * 60) drsn_min = drsn_left / (60) self.label_duration.text = "\(drsn_hour)h \(drsn_min)m" //Status Label self.label_status.text = "\(completion * 100)%" if completion < 0.50 { self.label_status.textColor = UIColor.red } else if completion < 1.00 { self.label_status.textColor = UIColor.yellow } else { self.label_status.textColor = UIColor.green } } //Events override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
39e7d0294dd5375a8a011f2bad991181
32.393617
195
0.608793
3.772837
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project12/Project12/ContentView.swift
1
4845
// // ContentView.swift // Project12 // // Created by Paul Hudson on 17/02/2020. // Copyright © 2020 Paul Hudson. All rights reserved. // import CoreData import SwiftUI struct OneToManyRelationshipsContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Country.entity(), sortDescriptors: []) var countries: FetchedResults<Country> var body: some View { VStack { List { ForEach(countries, id: \.self) { country in Section(header: Text(country.wrappedFullName)) { ForEach(country.candyArray, id: \.self) { candy in Text(candy.wrappedName) } } } } Button("Add") { let candy1 = Candy(context: self.moc) candy1.name = "Mars" candy1.origin = Country(context: self.moc) candy1.origin?.shortName = "UK" candy1.origin?.fullName = "United Kingdom" let candy2 = Candy(context: self.moc) candy2.name = "KitKat" candy2.origin = Country(context: self.moc) candy2.origin?.shortName = "UK" candy2.origin?.fullName = "United Kingdom" let candy3 = Candy(context: self.moc) candy3.name = "Twix" candy3.origin = Country(context: self.moc) candy3.origin?.shortName = "UK" candy3.origin?.fullName = "United Kingdom" let candy4 = Candy(context: self.moc) candy4.name = "Toblerone" candy4.origin = Country(context: self.moc) candy4.origin?.shortName = "CH" candy4.origin?.fullName = "Switzerland" try? self.moc.save() } } } } struct DynamicFilteringContentView: View { @Environment(\.managedObjectContext) var moc @State private var lastNameFilter = "A" var body: some View { VStack { FilteredList(filterKey: "lastName", filterValue: lastNameFilter) { (singer: Singer) in Text("\(singer.wrappedFirstName) \(singer.wrappedLastName)") } Button("Add Examples") { let taylor = Singer(context: self.moc) taylor.firstName = "Taylor" taylor.lastName = "Swift" let ed = Singer(context: self.moc) ed.firstName = "Ed" ed.lastName = "Sheeran" let adele = Singer(context: self.moc) adele.firstName = "Adele" adele.lastName = "Adkins" try? self.moc.save() } Button("Show A") { self.lastNameFilter = "A" } Button("Show S") { self.lastNameFilter = "S" } } } } struct ShipContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Ship.entity(), sortDescriptors: [], predicate: NSPredicate(format: "universe == 'Star Wars'")) var ships: FetchedResults<Ship> var body: some View { VStack { List(ships, id: \.self) { ship in Text(ship.name ?? "Unknown name") } Button("Add Examples") { let ship1 = Ship(context: self.moc) ship1.name = "Enterprise" ship1.universe = "Star Trek" let ship2 = Ship(context: self.moc) ship2.name = "Defiant" ship2.universe = "Star Trek" let ship3 = Ship(context: self.moc) ship3.name = "Millennium Falcon" ship3.universe = "Star Wars" let ship4 = Ship(context: self.moc) ship4.name = "Executor" ship4.universe = "Star Wars" try? self.moc.save() } } } } struct ContentView: View { @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Wizard.entity(), sortDescriptors: []) var wizards: FetchedResults<Wizard> var body: some View { VStack { List(wizards, id: \.self) { wizard in Text(wizard.name ?? "Unknown") } Button("Add") { let wizard = Wizard(context: self.moc) wizard.name = "Harry Potter" } Button("Save") { do { try self.moc.save() } catch { print(error.localizedDescription) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
unlicense
1bdfbe92dc16120ba781c36066326318
28.901235
152
0.502684
4.506047
false
false
false
false
thomasvl/swift-protobuf
Tests/SwiftProtobufTests/Test_Struct.swift
2
18214
// Tests/SwiftProtobufTests/Test_Struct.swift - Verify Struct well-known type // // Copyright (c) 2014 - 2019 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Struct, Value, ListValue are standard PRoto3 message types that support /// general ad hoc JSON parsing and serialization. /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobufCore class Test_Struct: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Struct func testStruct_pbencode() { assertEncode([10, 12, 10, 3, 102, 111, 111, 18, 5, 26, 3, 98, 97, 114]) {(o: inout MessageTestType) in var v = Google_Protobuf_Value() v.stringValue = "bar" o.fields["foo"] = v } } func testStruct_pbdecode() { assertDecodeSucceeds([10, 7, 10, 1, 97, 18, 2, 32, 1, 10, 7, 10, 1, 98, 18, 2, 8, 0]) { (m) in let vTrue = Google_Protobuf_Value(boolValue: true) let vNull: Google_Protobuf_Value = nil var same = Google_Protobuf_Struct() same.fields = ["a": vTrue, "b": vNull] var different = Google_Protobuf_Struct() different.fields = ["a": vTrue, "b": vNull, "c": vNull] return (m.fields.count == 2 && m.fields["a"] == vTrue && m.fields["a"] != vNull && m.fields["b"] == vNull && m.fields["b"] != vTrue && m == same && m != different) } } func test_JSON() { assertJSONDecodeSucceeds("{}") {$0.fields == [:]} assertJSONDecodeFails("null") assertJSONDecodeFails("false") assertJSONDecodeFails("true") assertJSONDecodeFails("[]") assertJSONDecodeFails("{") assertJSONDecodeFails("}") assertJSONDecodeFails("{}}") assertJSONDecodeFails("{]") assertJSONDecodeFails("1") assertJSONDecodeFails("\"1\"") } func test_JSON_field() throws { // "null" as a field value indicates the field is missing // (Except for Value, where "null" indicates NullValue) do { let c1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":null}") // null here decodes to an empty field. // See github.com/protocolbuffers/protobuf Issue #1327 XCTAssertEqual(try c1.jsonString(), "{}") } catch let e { XCTFail("Didn't decode c1: \(e)") } do { let c2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":{}}") XCTAssertNotNil(c2.optionalStruct) XCTAssertEqual(c2.optionalStruct.fields, [:]) } catch let e { XCTFail("Didn't decode c2: \(e)") } } func test_equality() throws { let a1decoded: Google_Protobuf_Struct do { a1decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":1}") } catch { XCTFail("Decode failed for {\"a\":1}") return } let a2decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":2}") var a1literal = Google_Protobuf_Struct() a1literal.fields["a"] = Google_Protobuf_Value(numberValue: 1) XCTAssertEqual(a1literal, a1decoded) XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue) XCTAssertNotEqual(a1decoded, a2decoded) // Hash inequality is not guaranteed, but a collision here would be suspicious let a1literalHash = a1literal.hashValue let a2decodedHash = a2decoded.hashValue XCTAssertNotEqual(a1literalHash, a2decodedHash) } } class Test_JSON_ListValue: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_ListValue // Since ProtobufJSONList is handbuilt rather than generated, // we need to verify all the basic functionality, including // serialization, equality, hash, etc. func testProtobuf() { assertEncode([10, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63, 10, 5, 26, 3, 97, 98, 99, 10, 2, 32, 1]) { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) } } func testJSON() { assertJSONEncode("[1.0,\"abc\",true]") { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) } assertJSONEncode("[1.0,\"abc\",true,[1.0,null],[]]") { (o: inout MessageTestType) in o.values.append(Google_Protobuf_Value(numberValue: 1)) o.values.append(Google_Protobuf_Value(stringValue: "abc")) o.values.append(Google_Protobuf_Value(boolValue: true)) o.values.append(Google_Protobuf_Value(listValue: [1, nil])) o.values.append(Google_Protobuf_Value(listValue: [])) } assertJSONDecodeSucceeds("[]") {$0.values == []} assertJSONDecodeFails("") assertJSONDecodeFails("true") assertJSONDecodeFails("false") assertJSONDecodeFails("{}") assertJSONDecodeFails("1.0") assertJSONDecodeFails("\"a\"") assertJSONDecodeFails("[}") assertJSONDecodeFails("[,]") assertJSONDecodeFails("[true,]") assertJSONDecodeSucceeds("[true]") {$0.values == [Google_Protobuf_Value(boolValue: true)]} } func test_JSON_nested_list() throws { let limit = JSONDecodingOptions().messageDepthLimit let depths = [ // Small lists 1,2,3,4,5, // Little less than default messageDepthLimit, should succeed limit - 3, limit - 2, limit - 1, limit, // Little bigger than default messageDepthLimit, should fail limit + 1, limit + 2, limit + 3, limit + 4, // Really big, should fail cleanly (not crash) 1000,10000,100000,1000000 ] for depth in depths { var s = "" for _ in 0..<(depth / 10) { s.append("[[[[[[[[[[") } for _ in 0..<(depth % 10) { s.append("[") } for _ in 0..<(depth / 10) { s.append("]]]]]]]]]]") } for _ in 0..<(depth % 10) { s.append("]") } // Recursion limits should cause this to // fail cleanly without crashing if depth <= limit { assertJSONDecodeSucceeds(s) {_ in true} } else { assertJSONDecodeFails(s) } } } func test_equality() throws { let a1decoded = try Google_Protobuf_ListValue(jsonString: "[1]") let a2decoded = try Google_Protobuf_ListValue(jsonString: "[2]") var a1literal = Google_Protobuf_ListValue() a1literal.values.append(Google_Protobuf_Value(numberValue: 1)) XCTAssertEqual(a1literal, a1decoded) XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue) XCTAssertNotEqual(a1decoded, a2decoded) // Hash inequality is not guaranteed, but a collision here would be suspicious XCTAssertNotEqual(a1literal.hashValue, a2decoded.hashValue) XCTAssertNotEqual(a1literal, a2decoded) } } class Test_Value: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Value func testValue_empty() throws { let empty = Google_Protobuf_Value() // Serializing an empty value (kind not set) in binary or text is ok; // it is only an error in JSON. XCTAssertEqual(try empty.serializedBytes(), []) XCTAssertEqual(empty.textFormatString(), "") // Make sure an empty value is not equal to a nullValue value. let null: Google_Protobuf_Value = nil XCTAssertNotEqual(empty, null) } } // TODO: Should have convenience initializers on Google_Protobuf_Value class Test_JSON_Value: XCTestCase, PBTestHelpers { typealias MessageTestType = Google_Protobuf_Value func testValue_emptyShouldThrow() throws { let empty = Google_Protobuf_Value() do { _ = try empty.jsonString() XCTFail("Encoding should have thrown .missingValue, but it succeeded") } catch JSONEncodingError.missingValue { // Nothing to do here; this is the expected error. } catch { XCTFail("Encoding should have thrown .missingValue, but instead it threw: \(error)") } } func testValue_null() throws { let nullFromLiteral: Google_Protobuf_Value = nil let null: Google_Protobuf_Value = nil XCTAssertEqual("null", try null.jsonString()) XCTAssertEqual([8, 0], try null.serializedBytes()) XCTAssertEqual(nullFromLiteral, null) XCTAssertNotEqual(nullFromLiteral, Google_Protobuf_Value(numberValue: 1)) assertJSONDecodeSucceeds("null") {$0.nullValue == .nullValue} assertJSONDecodeSucceeds(" null ") {$0.nullValue == .nullValue} assertJSONDecodeFails("numb") do { let m1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalValue\": null}") XCTAssertEqual(try m1.jsonString(), "{\"optionalValue\":null}") XCTAssertEqual(try m1.serializedBytes(), [146, 19, 2, 8, 0]) } catch { XCTFail() } assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nnull_value: NULL_VALUE\n", null) } func testValue_number() throws { let oneFromIntegerLiteral: Google_Protobuf_Value = 1 let oneFromFloatLiteral: Google_Protobuf_Value = 1.0 let twoFromFloatLiteral: Google_Protobuf_Value = 2.0 XCTAssertEqual(oneFromIntegerLiteral, oneFromFloatLiteral) XCTAssertNotEqual(oneFromIntegerLiteral, twoFromFloatLiteral) XCTAssertEqual("1.0", try oneFromIntegerLiteral.jsonString()) XCTAssertEqual([17, 0, 0, 0, 0, 0, 0, 240, 63], try oneFromIntegerLiteral.serializedBytes()) assertJSONEncode("3.25") {(o: inout MessageTestType) in o.numberValue = 3.25 } assertJSONDecodeSucceeds("3.25") {$0.numberValue == 3.25} assertJSONDecodeSucceeds(" 3.25 ") {$0.numberValue == 3.25} assertJSONDecodeFails("3.2.5") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nnumber_value: 1.0\n", oneFromIntegerLiteral) } func testValue_string() throws { // Literals and equality testing let fromStringLiteral: Google_Protobuf_Value = "abcd" XCTAssertEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abcd")) XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abc")) XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value()) // JSON serialization assertJSONEncode("\"abcd\"") {(o: inout MessageTestType) in o.stringValue = "abcd" } assertJSONEncode("\"\"") {(o: inout MessageTestType) in o.stringValue = "" } assertJSONDecodeSucceeds("\"abcd\"") {$0.stringValue == "abcd"} assertJSONDecodeSucceeds(" \"abcd\" ") {$0.stringValue == "abcd"} assertJSONDecodeFails("\"abcd\" XXX") assertJSONDecodeFails("\"abcd") // JSON serializing special characters XCTAssertEqual("\"a\\\"b\"", try Google_Protobuf_Value(stringValue: "a\"b").jsonString()) let valueWithEscapes = Google_Protobuf_Value(stringValue: "a\u{0008}\u{0009}\u{000a}\u{000c}\u{000d}b") let serializedValueWithEscapes = try valueWithEscapes.jsonString() XCTAssertEqual("\"a\\b\\t\\n\\f\\rb\"", serializedValueWithEscapes) do { let parsedValueWithEscapes = try Google_Protobuf_Value(jsonString: serializedValueWithEscapes) XCTAssertEqual(valueWithEscapes.stringValue, parsedValueWithEscapes.stringValue) } catch { XCTFail("Failed to decode \(serializedValueWithEscapes)") } // PB serialization XCTAssertEqual([26, 3, 97, 34, 98], try Google_Protobuf_Value(stringValue: "a\"b").serializedBytes()) assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nstring_value: \"abcd\"\n", fromStringLiteral) } func testValue_bool() { let trueFromLiteral: Google_Protobuf_Value = true let falseFromLiteral: Google_Protobuf_Value = false XCTAssertEqual(trueFromLiteral, Google_Protobuf_Value(boolValue: true)) XCTAssertEqual(falseFromLiteral, Google_Protobuf_Value(boolValue: false)) XCTAssertNotEqual(falseFromLiteral, trueFromLiteral) assertJSONEncode("true") {(o: inout MessageTestType) in o.boolValue = true } assertJSONEncode("false") {(o: inout MessageTestType) in o.boolValue = false } assertJSONDecodeSucceeds("true") {$0.boolValue == true} assertJSONDecodeSucceeds(" false ") {$0.boolValue == false} assertJSONDecodeFails("yes") assertJSONDecodeFails(" true false ") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nbool_value: true\n", trueFromLiteral) } func testValue_struct() throws { assertJSONEncode("{\"a\":1.0}") {(o: inout MessageTestType) in o.structValue = Google_Protobuf_Struct(fields:["a": Google_Protobuf_Value(numberValue: 1)]) } let structValue = try Google_Protobuf_Value(jsonString: "{\"a\":1.0}") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nstruct_value {\n fields {\n key: \"a\"\n value {\n number_value: 1.0\n }\n }\n}\n", structValue) } func testValue_list() throws { let listValue = try Google_Protobuf_Value(jsonString: "[1, true, \"abc\"]") assertDebugDescriptionSuffix(".Google_Protobuf_Value:\nlist_value {\n values {\n number_value: 1.0\n }\n values {\n bool_value: true\n }\n values {\n string_value: \"abc\"\n }\n}\n", listValue) } func testValue_complex() { assertJSONDecodeSucceeds("{\"a\": {\"b\": 1.0}, \"c\": [ 7, true, null, {\"d\": false}]}") { let outer = $0.structValue.fields let a = outer["a"]?.structValue.fields let c = outer["c"]?.listValue.values return (a?["b"]?.numberValue == 1.0 && c?.count == 4 && c?[0].numberValue == 7 && c?[1].boolValue == true && c?[2].nullValue == Google_Protobuf_NullValue() && c?[3].structValue.fields["d"]?.boolValue == false) } } func testStruct_conformance() throws { let json = ("{\n" + " \"optionalStruct\": {\n" + " \"nullValue\": null,\n" + " \"intValue\": 1234,\n" + " \"boolValue\": true,\n" + " \"doubleValue\": 1234.5678,\n" + " \"stringValue\": \"Hello world!\",\n" + " \"listValue\": [1234, \"5678\"],\n" + " \"objectValue\": {\n" + " \"value\": 0\n" + " }\n" + " }\n" + "}\n") let m: ProtobufTestMessages_Proto3_TestAllTypesProto3 do { m = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json) } catch { XCTFail("Decoding failed: \(json)") return } XCTAssertNotNil(m.optionalStruct) let s = m.optionalStruct XCTAssertNotNil(s.fields["nullValue"]) if let nv = s.fields["nullValue"] { XCTAssertEqual(nv.nullValue, Google_Protobuf_NullValue()) } XCTAssertNotNil(s.fields["intValue"]) if let iv = s.fields["intValue"] { XCTAssertEqual(iv, Google_Protobuf_Value(numberValue: 1234)) XCTAssertEqual(iv.numberValue, 1234) } XCTAssertNotNil(s.fields["boolValue"]) if let bv = s.fields["boolValue"] { XCTAssertEqual(bv, Google_Protobuf_Value(boolValue: true)) XCTAssertEqual(bv.boolValue, true) } XCTAssertNotNil(s.fields["doubleValue"]) if let dv = s.fields["doubleValue"] { XCTAssertEqual(dv, Google_Protobuf_Value(numberValue: 1234.5678)) XCTAssertEqual(dv.numberValue, 1234.5678) } XCTAssertNotNil(s.fields["stringValue"]) if let sv = s.fields["stringValue"] { XCTAssertEqual(sv, Google_Protobuf_Value(stringValue: "Hello world!")) XCTAssertEqual(sv.stringValue, "Hello world!") } XCTAssertNotNil(s.fields["listValue"]) if let lv = s.fields["listValue"] { XCTAssertEqual(lv.listValue, [Google_Protobuf_Value(numberValue: 1234), Google_Protobuf_Value(stringValue: "5678")]) } XCTAssertNotNil(s.fields["objectValue"]) if let ov = s.fields["objectValue"] { XCTAssertNotNil(ov.structValue.fields["value"]) if let inner = s.fields["objectValue"]?.structValue.fields["value"] { XCTAssertEqual(inner, Google_Protobuf_Value(numberValue: 0)) XCTAssertEqual(inner.numberValue, 0) } } } func testStruct_null() throws { let json = ("{\n" + " \"optionalStruct\": null\n" + "}\n") do { let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json) let recoded = try decoded.jsonString() XCTAssertEqual(recoded, "{}") } catch { XCTFail("Should have decoded") } } }
apache-2.0
e4ea8cfa2fc29ab0e8a1d8c1c8119d6d
41.259861
216
0.589766
4.559199
false
true
false
false
loudnate/LoopKit
LoopKit/GlucoseEffectVelocity.swift
2
1144
// // GlucoseEffectVelocity.swift // LoopKit // // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation import HealthKit /// The first-derivative of GlucoseEffect, blood glucose over time. public struct GlucoseEffectVelocity: SampleValue { public let startDate: Date public let endDate: Date public let quantity: HKQuantity public init(startDate: Date, endDate: Date, quantity: HKQuantity) { self.startDate = startDate self.endDate = endDate self.quantity = quantity } } extension GlucoseEffectVelocity { static let perSecondUnit = HKUnit.milligramsPerDeciliter.unitDivided(by: .second()) /// The integration of the velocity span public var effect: GlucoseEffect { let duration = endDate.timeIntervalSince(startDate) let velocityPerSecond = quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) return GlucoseEffect( startDate: endDate, quantity: HKQuantity( unit: .milligramsPerDeciliter, doubleValue: velocityPerSecond * duration ) ) } }
mit
a3de2510d9b456690b83bd0c1719a2c2
26.214286
94
0.68154
5.013158
false
false
false
false
charvoa/TimberiOS
TimberiOS/Classes/NetworkManager.swift
1
1514
// // NetworkManager.swift // TimberiOS // // Created by Nicolas on 28/09/2017. // import Foundation import Alamofire extension String: ParameterEncoding { public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var request = try urlRequest.asURLRequest() request.httpBody = data(using: .utf8, allowLossyConversion: false) return request } } open class NetworkManager { public static let shared = NetworkManager() private init() {} open func request(apiToken: String, sourceIdentification: String, endpoint: String, method: HTTPMethod, params: [String: Any], completionHandler: @escaping (DataResponse<String>) -> ()) { let encodedToken = apiToken.toBase64() let headers: HTTPHeaders = [ "authorization": String(format: "Basic %@", encodedToken), "accept": "content/json", "content-type": "application/json" ] Alamofire.request("https://logs.timber.io/sources/\(sourceIdentification)/\(endpoint)", method: method, parameters: params, encoding: JSONEncoding.default, headers: headers) .validate(contentType: ["text/plain"]) .responseString { (response) in completionHandler(response) } } }
mit
6bc9e7a368f52256be2dd85bdb6df506
28.115385
112
0.573316
5.293706
false
false
false
false
tsolomko/SWCompression
Sources/7-Zip/7zFileInfo.swift
1
5471
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import BitByteData class SevenZipFileInfo { struct File { var isEmptyStream = false var isEmptyFile = false var isAntiFile = false var name: String = "" var cTime: Date? var mTime: Date? var aTime: Date? var winAttributes: UInt32? } let numFiles: Int var files = [File]() var unknownProperties = [SevenZipProperty]() init(_ bitReader: MsbBitReader) throws { numFiles = bitReader.szMbd() for _ in 0..<numFiles { files.append(File()) } var isEmptyStream: [UInt8]? var isEmptyFile: [UInt8]? var isAntiFile: [UInt8]? while true { let propertyType = bitReader.byte() if propertyType == 0 { break } let propertySize = bitReader.szMbd() switch propertyType { case 0x0E: // EmptyStream isEmptyStream = bitReader.bits(count: numFiles) bitReader.align() case 0x0F: // EmptyFile guard let emptyStreamCount = isEmptyStream?.filter({ $0 == 1 }).count else { throw SevenZipError.internalStructureError } isEmptyFile = bitReader.bits(count: emptyStreamCount) bitReader.align() case 0x10: // AntiFile (used in backups to indicate that file was removed) guard let emptyStreamCount = isEmptyStream?.filter({ $0 == 1 }).count else { throw SevenZipError.internalStructureError } isAntiFile = bitReader.bits(count: emptyStreamCount) bitReader.align() case 0x11: // File name let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } guard (propertySize - 1) & 1 == 0, let names = String(bytes: bitReader.bytes(count: propertySize - 1), encoding: .utf16LittleEndian) else { throw SevenZipError.internalStructureError } var nextFile = 0 for name in names.split(separator: "\u{0}") { files[nextFile].name = String(name) nextFile += 1 } guard nextFile == numFiles else { throw SevenZipError.internalStructureError } case 0x12: // Creation time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].cTime = Date(bitReader.uint64()) } case 0x13: // Access time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].aTime = Date(bitReader.uint64()) } case 0x14: // Modification time let timesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where timesDefined[i] == 1 { files[i].mTime = Date(bitReader.uint64()) } case 0x15: // WinAttributes let attributesDefined = bitReader.defBits(count: numFiles) bitReader.align() let external = bitReader.byte() guard external == 0 else { throw SevenZipError.externalNotSupported } for i in 0..<numFiles where attributesDefined[i] == 1 { files[i].winAttributes = bitReader.uint32() } case 0x18: // StartPos throw SevenZipError.startPosNotSupported case 0x19: // "Dummy". Used for alignment/padding. guard bitReader.size - bitReader.offset >= propertySize else { throw SevenZipError.internalStructureError } bitReader.offset += propertySize default: // Unknown property guard bitReader.size - bitReader.offset >= propertySize else { throw SevenZipError.internalStructureError } unknownProperties.append(SevenZipProperty(propertyType, propertySize, bitReader.bytes(count: propertySize))) } } var emptyFileIndex = 0 for i in 0..<numFiles { files[i].isEmptyStream = isEmptyStream?[i] == 1 if files[i].isEmptyStream { files[i].isEmptyFile = isEmptyFile?[emptyFileIndex] == 1 files[i].isAntiFile = isAntiFile?[emptyFileIndex] == 1 emptyFileIndex += 1 } } } }
mit
115409ed6dbe0740bd887b58cbbb2cf7
37.801418
117
0.532627
5.20057
false
false
false
false
awkward/Tatsi
Tatsi/Views/Assets Grid/Cells/CameraCollectionViewCell.swift
1
1520
// // CameraCollectionViewCell.swift // Tatsi // // Created by Rens Verhoeven on 30-03-16. // Copyright © 2017 Awkward BV. All rights reserved. // import UIKit final internal class CameraCollectionViewCell: UICollectionViewCell { static var reuseIdentifier: String { return "camera-cell" } lazy private var iconView: CameraIconView = { let iconView = CameraIconView() iconView.translatesAutoresizingMaskIntoConstraints = false return iconView }() override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupView() { self.contentView.addSubview(self.iconView) self.contentView.backgroundColor = UIColor.lightGray self.accessibilityIdentifier = "tatsi.cell.camera" self.accessibilityLabel = LocalizableStrings.cameraButtonTitle self.accessibilityTraits = UIAccessibilityTraits.button self.isAccessibilityElement = true self.setupConstraints() } private func setupConstraints() { let constraints = [ self.iconView.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor), self.iconView.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor) ] NSLayoutConstraint.activate(constraints) } }
mit
0d9a9fe9c93f5819cf15ab08d20b8a65
27.12963
92
0.657011
5.237931
false
false
false
false
CosmicMind/Samples
Projects/Programmatic/ToolbarController/ToolbarController/SearchViewController.swift
1
2309
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class SearchViewController: UIViewController { let v1 = UIView() open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // v1.depthPreset = .depth3 v1.cornerRadiusPreset = .none v1.motionIdentifier = "v1" v1.backgroundColor = Color.green.base view.layout(v1).centerHorizontally().top().horizontally().height(100) prepareToolbar() } } extension SearchViewController { fileprivate func prepareToolbar() { guard let toolbar = toolbarController?.toolbar else { return } toolbar.title = "Search" } }
bsd-3-clause
f5586391324c252089a7bd3c4ca3a472
37.483333
88
0.722824
4.627255
false
false
false
false
AmirDaliri/BaboonProject
Baboon/Baboon/AppDelegate.swift
1
1852
// // AppDelegate.swift // Baboon // // Created by Amir Daliri on 3/21/17. // Copyright © 2017 Baboon. All rights reserved. // import UIKit import XCGLogger import MMDrawerController // TODO: Fix coloring let log: XCGLogger = { let log = XCGLogger.default log.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil, fileLevel: .debug) return log }() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? var drawerController: MMDrawerController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoadingController") as! LoadingController let leftViewController = mainStoryboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController let leftNav = UINavigationController(rootViewController: leftViewController) let centerNav = UINavigationController(rootViewController: centerViewController) drawerController = MMDrawerController(center: centerNav, leftDrawerViewController: leftNav) drawerController?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.all drawerController!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.all; // drawerController!.showsShadow = true drawerController!.setMaximumLeftDrawerWidth(180, animated: true, completion: nil) window!.rootViewController = drawerController window!.makeKeyAndVisible() return true } }
mit
5e5c4411d13663ec9304ccfaca0340e9
32.053571
146
0.772015
5.609091
false
false
false
false
fanyu/EDCCharla
EDCChat/EDCChat/EDCChatMessage.swift
1
2435
// // EDCChatMessage.swift // EDCChat // // Created by FanYu on 11/12/2015. // Copyright © 2015 FanYu. All rights reserved. // import UIKit let EDCChatMessageStatusChangedNotification = "EDCChatMessageStatusChangedNofitication" struct EDCChatMessageOption { // none static var None: Int { return 0x0000 } // 消息静音 static var Mute: Int { return 0x0001 } // 消息隐藏(透明的) static var Hidden: Int { return 0x0010 } // 名片强制显示 static var ContactShow: Int { return 0x0100 } // 名片强制隐藏 static var ContactHidden: Int { return 0x0200 } // 名片根据环境自动显示/隐藏 static var ContactAutomatic: Int { return 0x0400 } } @objc enum EDCChatMessageStatus: Int { case Unknow case Sending case Sent case Unread case Receiving case Received case Read case Played case Destoryed case Error } @objc protocol EDCChatMessageProtocol { var identifier: String { get } var sender: EDCChatUserProtocol? { get } var receiver: EDCChatUserProtocol? { get } var sentTime: NSDate { get } var receiveTime: NSDate { get } var status: EDCChatMessageStatus { get } var content: EDCChatMessageContentProtocol { get } var option: Int { get } var ownership: Bool { get } var height: CGFloat { set get } } class EDCChatMessage: NSObject, EDCChatMessageProtocol { var identifier: String = NSUUID().UUIDString var sender: EDCChatUserProtocol? var receiver: EDCChatUserProtocol? var sentTime: NSDate = .zero var receiveTime: NSDate = .zero var status: EDCChatMessageStatus = .Unknow var content: EDCChatMessageContentProtocol var option: Int = 0 var ownership: Bool = false var height: CGFloat = 0 override init() { self.content = EDCChatMessageContentUnknow() super.init() } init(content: EDCChatMessageContentProtocol) { self.content = content super.init() } } extension EDCChatMessage { func makeDateWithMessage(message: EDCChatMessage) { } } extension EDCChatMessage { func statusChanged() { EDCChatNotificationCenter.postNotificationName(EDCChatMessageStatusChangedNotification, object: self) } } func ==(lhs: EDCChatMessage?, rhs: EDCChatMessage?) -> Bool { return lhs === rhs || lhs?.identifier == rhs?.identifier }
mit
00c6712443c14238c45f43a07b2c41cc
22.64
109
0.67132
4.013582
false
false
false
false
morizotter/MZRSnappySample
MZRSnappySample/MZRSnappySample/ViewController.swift
1
1713
// // ViewController.swift // MZRSnappySample // // Created by MORITA NAOKI on 2014/11/01. // Copyright (c) 2014年 molabo. All rights reserved. // import UIKit import Snappy class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // FULL SCREEN VIEW [BLUE] let blueView = UIView() blueView.backgroundColor = UIColor.blueColor() self.view.addSubview(blueView) blueView.snp_makeConstraints { make in make.edges.equalTo(self.view) return } // PADDING ALL EDGES [ORANGE] let orangeView = UIView() orangeView.backgroundColor = UIColor.orangeColor() self.view.addSubview(orangeView) let orangeViewPadding = UIEdgeInsetsMake(10, 10, 10, 10) orangeView.snp_makeConstraints { make in make.edges.equalTo(self.view).with.insets(orangeViewPadding) return } // VIEW ON PADDING VIEW [GREEN] let greenView = UIView() greenView.backgroundColor = UIColor.greenColor() orangeView.addSubview(greenView) let greenViewPadding = UIEdgeInsetsMake(0.0, 0.0, 150.0, 10.0) greenView.snp_makeConstraints { make in make.top.equalTo(orangeView.snp_top).with.offset(greenViewPadding.top) make.left.equalTo(orangeView.snp_left).with.offset(greenViewPadding.left) make.bottom.equalTo(orangeView.snp_bottom).with.offset(-greenViewPadding.bottom) make.right.equalTo(orangeView.snp_right).with.offset(-greenViewPadding.right) return } } }
mit
ddcee20d4984b7129c0f66cc69e6136f
29.553571
92
0.617183
4.490814
false
false
false
false
youngsoft/TangramKit
TangramKit/TGFlowLayout.swift
1
105640
// // TGFlowLayout.swift // TangramKit // // Created by apple on 16/3/13. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** *流式布局是一种里面的子视图按照添加的顺序依次排列,当遇到某种约束限制后会另起一排再重新排列的多行多列展示的布局视图。这里的约束限制主要有数量约束限制和内容尺寸约束限制两种,排列的方向又分为垂直和水平方向,因此流式布局一共有垂直数量约束流式布局、垂直内容约束流式布局、水平数量约束流式布局、水平内容约束流式布局。流式布局主要应用于那些有规律排列的场景,在某种程度上可以作为UICollectionView的替代品。 1.垂直数量约束流式布局 tg_orientation=.vert,tg_arrangedCount>0 每排数量为3的垂直数量约束流式布局 => +------+---+-----+ | A | B | C | +---+--+-+-+-----+ | D | E | F | | +---+-+--+--+----+ v | G | H | I | +-----+-----+----+ 2.垂直内容约束流式布局. tg_orientation = .vert,tg_arrangedCount = 0 垂直内容约束流式布局 => +-----+-----------+ | A | B | +-----+-----+-----+ | C | D | E | | +-----+-----+-----+ v | F | +-----------------+ 3.水平数量约束流式布局。 tg_orientation = .horz,tg_arrangedCount > 0 每排数量为3的水平数量约束流式布局 => +-----+----+-----+ | A | D | | | |----| G | |-----| | | | | B | E |-----| V |-----| | | | |----| H | | C | |-----| | | F | I | +-----+----+-----+ 4.水平内容约束流式布局 tg_orientation = .horz,arrangedCount = 0 水平内容约束流式布局 => +-----+----+-----+ | A | C | | | |----| | |-----| | | | | | D | | V | | | F | | B |----| | | | | | | | E | | +-----+----+-----+ 流式布局中排的概念是一个通用的称呼,对于垂直方向的流式布局来说一排就是一行,垂直流式布局每排依次从上到下排列,每排内的子视图则是由左往右依次排列;对于水平方向的流式布局来说一排就是一列,水平流式布局每排依次从左到右排列,每排内的子视图则是由上往下依次排列 */ open class TGFlowLayout:TGBaseLayout,TGFlowLayoutViewSizeClass { /** *初始化一个流式布局并指定布局的方向和布局的数量,如果数量为0则表示内容约束流式布局 */ public convenience init(_ orientation:TGOrientation = TGOrientation.vert, arrangedCount:Int = 0) { self.init(frame:CGRect.zero, orientation:orientation, arrangedCount:arrangedCount) } public init(frame: CGRect, orientation:TGOrientation = TGOrientation.vert, arrangedCount:Int = 0) { super.init(frame:frame) let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass lsc.tg_orientation = orientation lsc.tg_arrangedCount = arrangedCount } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** *流式布局的布局方向 *如果是.vert则表示每排先从左到右,再从上到下的垂直布局方式,这个方式是默认方式。 *如果是.horz则表示每排先从上到下,在从左到右的水平布局方式。 */ public var tg_orientation:TGOrientation { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_orientation } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_orientation != newValue) { lsc.tg_orientation = newValue setNeedsLayout() } } } /** *指定方向上的子视图的数量,默认是0表示为内容约束流式布局,当数量不为0时则是数量约束流式布局。当值为0时则表示当子视图在方向上的尺寸超过布局视图时则会新起一排。而如果数量不为0时则: 如果方向为.vert,则表示从左到右的数量,当子视图从左往右满足这个数量后新的子视图将会新起一排 如果方向为.horz,则表示从上到下的数量,当子视图从上往下满足这个数量后新的子视图将会新起一排 */ public var tg_arrangedCount:Int { //get/set方法 get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_arrangedCount } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_arrangedCount != newValue) { lsc.tg_arrangedCount = newValue setNeedsLayout() } } } /** *为流式布局提供分页展示的能力,默认是0表不支持分页展示,当设置为非0时则要求必须是tg_arrangedCount的整数倍数,表示每页的子视图的数量。而tg_arrangedCount则表示每排的子视图的数量。当启用tg_pagedCount时要求将流式布局加入到UIScrollView或者其派生类中才能生效。只有数量约束流式布局才支持分页展示的功能,tg_pagedCount和tg_height.isWrap以及tg_width.isWrap配合使用能实现不同的分页展示能力: 1.垂直数量约束流式布局的tg_height设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的宽度你也可以自定义),整体的分页滚动是从上到下滚动。(每页布局时从左到右再从上到下排列,新页往下滚动继续排列): 1 2 3 4 5 6 ------- ↓ 7 8 9 10 11 12 2.垂直数量约束流式布局的tg_width设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的高度你也可以自定义),整体的分页滚动是从左到右滚动。(每页布局时从左到右再从上到下排列,新页往右滚动继续排列) 1 2 3 | 7 8 9 4 5 6 | 10 11 12 → 1.水平数量约束流式布局的tg_width设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的高度你也可以自定义),整体的分页滚动是从左到右滚动。(每页布局时从上到下再从左到右排列,新页往右滚动继续排列) 1 3 5 | 7 9 11 2 4 6 | 8 10 12 → 2.水平数量约束流式布局的tg_height设置为.wrap时则以UIScrollView的尺寸作为一页展示的大小,因为指定了一页的子视图数量,以及指定了一排的子视图数量,因此默认也会自动计算出子视图的宽度和高度,而不需要单独指出高度和宽度(子视图的宽度你也可以自定义),整体的分页滚动是从上到下滚动。(每页布局时从上到下再从左到右排列,新页往下滚动继续排列) 1 3 5 2 4 6 --------- ↓ 7 9 11 8 10 12 */ public var tg_pagedCount:Int { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_pagedCount } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_pagedCount != newValue) { lsc.tg_pagedCount = newValue setNeedsLayout() } } } /** *子视图自动排列,这个属性只有在内容填充约束流式布局下才有用,默认为false.当设置为YES时则根据子视图的内容自动填充,而不是根据加入的顺序来填充,以便保证不会出现多余空隙的情况。 *请在将所有子视图添加完毕并且初始布局完成后再设置这个属性,否则如果预先设置这个属性则在后续添加子视图时非常耗性能。 */ public var tg_autoArrange:Bool { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_autoArrange } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_autoArrange != newValue) { lsc.tg_autoArrange = newValue setNeedsLayout() } } } /** *设置流式布局中每排子视图的对齐方式。 如果布局的方向是.vert则表示每排子视图的上中下对齐方式,这里的对齐基础是以每排中的最高的子视图为基准。这个属性只支持: TGGravity.vert.top 顶部对齐 TGGravity.vert.center 垂直居中对齐 TGGravity.vert.bottom 底部对齐 TGGravity.vert.fill 两端对齐 如果布局的方向是.horz则表示每排子视图的左中右对齐方式,这里的对齐基础是以每排中的最宽的子视图为基准。这个属性只支持: TGGravity.horz.left 左边对齐 TGGravity.horz.center 水平居中对齐 TGGravity.horz.right 右边对齐 TGGravity.horz.fill 两端对齐 */ public var tg_arrangedGravity:TGGravity { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_arrangedGravity } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_arrangedGravity != newValue) { lsc.tg_arrangedGravity = newValue setNeedsLayout() } } } /** * 指定流式布局最后一行的尺寸或间距的拉伸策略。默认值是TGGravityPolicy.no表示最后一行的尺寸或间接拉伸策略不生效。 在流式布局中我们可以通过tg_gravity属性来对每一行的尺寸或间距进行拉伸处理。但是在实际情况中最后一行的子视图数量可能会小于等于前面行的数量。 在这种情况下如果对最后一行进行相同的尺寸或间距的拉伸处理则有可能会影响整体的布局效果。因此我们可通过这个属性来指定最后一行的尺寸或间距的生效策略。 这个策略在不同的流式布局中效果不一样: 1.在数量约束布局中如果最后一行的子视图数量小于tg_arrangedCount的值时,那么当我们使用tg_gravity来对行内视图进间距拉伸时(between,around,among) 可以指定三种策略:no表示最后一行不进行任何间距拉伸处理,always表示最后一行总是进行间距拉伸处理,auto表示最后一行的每个子视图都和上一行对应位置视图左对齐。 2.在内容约束布局中因为每行的子视图数量不固定,所以只有no和always两种策略有效,并且这两种策略不仅影响子视图的尺寸的拉伸(fill)还影响间距的拉伸效果(between,around,among)。 */ public var tg_lastlineGravityPolicy:TGGravityPolicy { get { return (self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass).tg_lastlineGravityPolicy } set { let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClass if (lsc.tg_lastlineGravityPolicy != newValue) { lsc.tg_lastlineGravityPolicy = newValue setNeedsLayout() } } } /** *在流式布局的一些应用场景中我们有时候希望某些子视图的宽度或者高度是固定的情况下,子视图的间距是浮动的而不是固定的。比如每个子视图的宽度是固定80,那么在小屏幕下每行只能放3个,而我们希望大屏幕每行能放4个或者5个子视图。 因此您可以通过如下方法来设置浮动间距,这个方法会根据您当前布局的orientation方向不同而意义不同: 1.如果您的布局方向是.vert表示设置的是子视图的水平间距,其中的size指定的是子视图的宽度,minSpace指定的是最小的水平间距,maxSpace指定的是最大的水平间距,如果指定的subviewSize计算出的间距大于这个值则会调整subviewSize的宽度。 2.如果您的布局方向是.horz表示设置的是子视图的垂直间距,其中的size指定的是子视图的高度,minSpace指定的是最小的垂直间距,maxSpace指定的是最大的垂直间距,如果指定的subviewSize计算出的间距大于这个值则会调整subviewSize的高度。 3.如果您不想使用浮动间距则请将subviewSize设置为0就可以了。 4.对于数量约束流式布局来说,因为每行和每列的数量的固定的,因此不存在根据屏幕的大小自动换行的能力以及进行最佳数量的排列,但是可以使用这个方法来实现所有子视图尺寸固定但是间距是浮动的功能需求。 5. centered属性指定这个浮动间距是否包括最左边和最右边两个区域,也就是说当设置为true时视图之间以及视图与父视图之间的间距都是相等的,而设置为false时则只有视图之间的间距相等而视图与父视图之间的间距则为0。 */ public func tg_setSubviews(size:CGFloat, minSpace:CGFloat, maxSpace:CGFloat = CGFloat.greatestFiniteMagnitude, centered:Bool = false, inSizeClass type:TGSizeClassType = TGSizeClassType.default) { let lsc = self.tg_fetchSizeClass(with: type) as! TGFlowLayoutViewSizeClassImpl if size == 0.0 { lsc.tgFlexSpace = nil } else { if lsc.tgFlexSpace == nil { lsc.tgFlexSpace = TGSequentLayoutFlexSpace() } lsc.tgFlexSpace.subviewSize = size lsc.tgFlexSpace.minSpace = minSpace lsc.tgFlexSpace.maxSpace = maxSpace lsc.tgFlexSpace.centered = centered } self.setNeedsLayout() } override internal func tgCalcLayoutRect(_ size:CGSize, isEstimate:Bool, hasSubLayout:inout Bool!, sbs:[UIView]!, type :TGSizeClassType) -> CGSize { var selfSize = super.tgCalcLayoutRect(size, isEstimate:isEstimate, hasSubLayout:&hasSubLayout, sbs:sbs, type:type) var sbs:[UIView]! = sbs if sbs == nil { sbs = self.tgGetLayoutSubviews() } let lsc = self.tgCurrentSizeClass as! TGFlowLayoutViewSizeClassImpl for sbv:UIView in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate { sbvtgFrame.frame = sbv.bounds self.tgCalcSizeFromSizeWrapSubview(sbv, sbvsc:sbvsc, sbvtgFrame: sbvtgFrame) } if let sbvl:TGBaseLayout = sbv as? TGBaseLayout { if sbvsc.width.isWrap { if (lsc.tg_pagedCount > 0 || (lsc.tg_orientation == TGOrientation.horz && (lsc.tg_arrangedGravity & TGGravity.vert.mask) == TGGravity.horz.fill) || (lsc.tg_orientation == TGOrientation.vert && ((lsc.tg_gravity & TGGravity.vert.mask) == TGGravity.horz.fill))) { sbvsc.width.resetValue() } } if sbvsc.height.isWrap { if (lsc.tg_pagedCount > 0 || (lsc.tg_orientation == TGOrientation.vert && (lsc.tg_arrangedGravity & TGGravity.horz.mask) == TGGravity.vert.fill) || (lsc.tg_orientation == TGOrientation.horz && ((lsc.tg_gravity & TGGravity.horz.mask) == TGGravity.vert.fill))) { sbvsc.height.resetValue() } } if hasSubLayout != nil && sbvsc.isSomeSizeWrap { hasSubLayout = true } if isEstimate && sbvsc.isSomeSizeWrap { _ = sbvl.tg_sizeThatFits(sbvtgFrame.frame.size,inSizeClass:type) if sbvtgFrame.multiple { sbvtgFrame.sizeClass = sbv.tgMatchBestSizeClass(type) //因为tg_sizeThatFits执行后会还原,所以这里要重新设置 } } } } if lsc.tg_orientation == TGOrientation.vert { if lsc.tg_arrangedCount == 0 { if (lsc.tg_autoArrange) { //计算出每个子视图的宽度。 for sbv in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //暂时把宽度存放sbvtgFrame.trailing上。因为浮动布局来说这个属性无用。 sbvtgFrame.trailing = leadingSpace + rect.size.width + trailingSpace; if _tgCGFloatGreat(sbvtgFrame.trailing , selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) { sbvtgFrame.trailing = selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding; } } let tempSbs:NSMutableArray = NSMutableArray(array: sbs) sbs = self.tgGetAutoArrangeSubviews(tempSbs, selfSize:selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding, space: lsc.tg_hspace) as? [UIView] } selfSize = self.tgLayoutSubviewsForVertContent(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } else { selfSize = self.tgLayoutSubviewsForVert(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } } else { if lsc.tg_arrangedCount == 0 { if (lsc.tg_autoArrange) { //计算出每个子视图的宽度。 for sbv in sbs { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos var rect = sbvtgFrame.frame; rect.size.width = sbvsc.width.numberSize(rect.size.width) rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //如果高度是浮动的则需要调整高度。 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } //暂时把宽度存放sbvtgFrame.trailing上。因为浮动布局来说这个属性无用。 sbvtgFrame.trailing = topSpace + rect.size.height + bottomSpace; if _tgCGFloatGreat(sbvtgFrame.trailing, selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) { sbvtgFrame.trailing = selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding } } let tempSbs:NSMutableArray = NSMutableArray(array: sbs) sbs = self.tgGetAutoArrangeSubviews(tempSbs, selfSize:selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding, space: lsc.tg_vspace) as? [UIView] } selfSize = self.tgLayoutSubviewsForHorzContent(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } else { selfSize = self.tgLayoutSubviewsForHorz(selfSize, sbs: sbs, isEstimate:isEstimate, lsc:lsc) } } tgAdjustLayoutSelfSize(selfSize: &selfSize, lsc: lsc) tgAdjustSubviewsLayoutTransform(sbs: sbs, lsc: lsc, selfSize: selfSize) tgAdjustSubviewsRTLPos(sbs: sbs, selfWidth: selfSize.width) return self.tgAdjustSizeWhenNoSubviews(size: selfSize, sbs: sbs, lsc:lsc) } internal override func tgCreateInstance() -> AnyObject { return TGFlowLayoutViewSizeClassImpl(view:self) } } extension TGFlowLayout { fileprivate func tgCalcSinglelineSize(_ sbs:NSArray, space:CGFloat) ->CGFloat { var size:CGFloat = 0; for i in 0..<sbs.count { let sbv = sbs[i] as! UIView size += sbv.tgFrame.trailing; if (sbv != sbs.lastObject as! UIView) { size += space } } return size; } fileprivate func tgGetAutoArrangeSubviews(_ sbs:NSMutableArray, selfSize:CGFloat, space:CGFloat) ->NSArray { let retArray:NSMutableArray = NSMutableArray(capacity: sbs.count) let bestSinglelineArray:NSMutableArray = NSMutableArray(capacity: sbs.count / 2) while (sbs.count > 0) { self.tgGetAutoArrangeSinglelineSubviews(sbs, index:0, calcArray:NSArray(), selfSize:selfSize, space:space, bestSinglelineArray:bestSinglelineArray) retArray.addObjects(from: bestSinglelineArray as [AnyObject]) bestSinglelineArray.forEach({ (obj) -> () in sbs.remove(obj) }) bestSinglelineArray.removeAllObjects() } return retArray; } fileprivate func tgGetAutoArrangeSinglelineSubviews(_ sbs:NSMutableArray,index:Int,calcArray:NSArray,selfSize:CGFloat,space:CGFloat,bestSinglelineArray:NSMutableArray) { if (index >= sbs.count) { let s1 = self.tgCalcSinglelineSize(calcArray, space:space) let s2 = self.tgCalcSinglelineSize(bestSinglelineArray, space:space) if _tgCGFloatLess(abs(selfSize - s1) , abs(selfSize - s2)) && _tgCGFloatLessOrEqual(s1, selfSize) { bestSinglelineArray.setArray(calcArray as [AnyObject]) } return; } for i in index ..< sbs.count { let calcArray2 = NSMutableArray(array: calcArray) calcArray2.add(sbs[i]) let s1 = self.tgCalcSinglelineSize(calcArray2,space:space) if ( _tgCGFloatLessOrEqual(s1, selfSize)) { let s2 = self.tgCalcSinglelineSize(bestSinglelineArray,space:space) if _tgCGFloatLess(abs(selfSize - s1) , abs(selfSize - s2)) { bestSinglelineArray.setArray(calcArray2 as [AnyObject]) } if ( _tgCGFloatEqual(s1, selfSize)) { break; } self.tgGetAutoArrangeSinglelineSubviews(sbs, index:i + 1, calcArray:calcArray2, selfSize:selfSize, space:space, bestSinglelineArray:bestSinglelineArray) } else { break; } } } //计算Vert下每行的对齐方式 fileprivate func tgCalcVertLayoutSinglelineAlignment(_ selfSize:CGSize, rowMaxHeight:CGFloat, rowMaxWidth:CGFloat, horzGravity:TGGravity, vertAlignment:TGGravity, sbs:[UIView], startIndex:Int, count:Int,vertSpace:CGFloat, horzSpace:CGFloat, horzPadding:CGFloat, isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl) { var addXPos:CGFloat = 0 var addXPosInc:CGFloat = 0 var addXFill:CGFloat = 0 let averageArrange = (horzGravity == TGGravity.horz.fill) //只有最后一行,并且数量小于tg_arrangedCount,并且不是第一行才应用策略。 let applyLastlineGravityPolicy:Bool = (startIndex == sbs.count && count != lsc.tg_arrangedCount && (horzGravity == TGGravity.horz.between || horzGravity == TGGravity.horz.around || horzGravity == TGGravity.horz.among || horzGravity == TGGravity.horz.fill)) //处理 对其方式 if !averageArrange || lsc.tg_arrangedCount == 0 { switch horzGravity { case TGGravity.horz.center: addXPos = (selfSize.width - horzPadding - rowMaxWidth)/2 break case TGGravity.horz.trailing: //不用考虑左边距,而原来的位置增加了左边距 因此不用考虑 addXPos = selfSize.width - horzPadding - rowMaxWidth break case TGGravity.horz.between: if count > 1 && (!applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always) { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/(CGFloat(count) - 1) } break case TGGravity.horz.around: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count) addXPos = addXPosInc / 2.0 } else { addXPos = (selfSize.width - horzPadding - rowMaxWidth) / 2.0 } } break case TGGravity.horz.among: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addXPosInc = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count + 1) addXPos = addXPosInc } else { addXPos = (selfSize.width - horzPadding - rowMaxWidth) / 2.0 } } break default: break } //处理内容拉伸的情况 if lsc.tg_arrangedCount == 0 && averageArrange && count > 0 { if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { addXFill = (selfSize.width - horzPadding - rowMaxWidth)/CGFloat(count) } } } //调整 整行子控件的位置 for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate && self.tg_intelligentBorderline != nil { if let sbvl = sbv as? TGBaseLayout { if !sbvl.tg_notUseIntelligentBorderline { sbvl.tg_leadingBorderline = nil sbvl.tg_topBorderline = nil sbvl.tg_trailingBorderline = nil sbvl.tg_bottomBorderline = nil //如果不是最后一行就画下面, if (startIndex != sbs.count) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果不是最后一列就画右边, if (j < startIndex - 1) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果最后一行的最后一个没有满列数时 if (j == sbs.count - 1 && lsc.tg_arrangedCount != count ) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果有垂直间距则不是第一行就画上 if (vertSpace != 0 && startIndex - count != 0) { sbvl.tg_topBorderline = self.tg_intelligentBorderline; } //如果有水平间距则不是第一列就画左 if (horzSpace != 0 && j != startIndex - count) { sbvl.tg_leadingBorderline = self.tg_intelligentBorderline; } } } } //为子视图设置单独的对齐方式 var sbvVertAlignment = sbvsc.tg_alignment & TGGravity.horz.mask if sbvVertAlignment == TGGravity.none { sbvVertAlignment = vertAlignment } if vertAlignment == TGGravity.vert.between { sbvVertAlignment = vertAlignment } if (sbvVertAlignment != TGGravity.none && sbvVertAlignment != TGGravity.vert.top) || _tgCGFloatNotEqual(addXPos, 0) || _tgCGFloatNotEqual(addXFill, 0) || _tgCGFloatNotEqual(addXPosInc, 0) || applyLastlineGravityPolicy { sbvtgFrame.leading += addXPos if lsc.tg_arrangedCount == 0 && averageArrange { //只拉伸宽度 不拉伸间距 sbvtgFrame.width += addXFill if j != startIndex - count { sbvtgFrame.leading += addXFill * CGFloat(j - (startIndex - count)) } } else { //只拉伸间距 sbvtgFrame.leading += addXPosInc * CGFloat(j - (startIndex - count)) if (startIndex - count) > 0 && applyLastlineGravityPolicy && lsc.tg_lastlineGravityPolicy == TGGravityPolicy.auto { //对齐前一行对应位置的 sbvtgFrame.leading = sbs[j - lsc.tg_arrangedCount].tgFrame.leading } } let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos switch sbvVertAlignment { case TGGravity.vert.center: sbvtgFrame.top += (rowMaxHeight - topSpace - bottomSpace - sbvtgFrame.height) / 2 break case TGGravity.vert.bottom: sbvtgFrame.top += rowMaxHeight - topSpace - bottomSpace - sbvtgFrame.height break case TGGravity.vert.fill: sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rowMaxHeight - topSpace - bottomSpace, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) break default: break } } } } //计算Horz下每行的水平对齐方式。 fileprivate func tgCalcHorzLayoutSinglelineAlignment(_ selfSize:CGSize, colMaxHeight:CGFloat, colMaxWidth:CGFloat, vertGravity:TGGravity, horzAlignment:TGGravity, sbs:[UIView], startIndex:Int, count:Int, vertSpace:CGFloat, horzSpace:CGFloat, vertPadding:CGFloat, isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl) { var addYPos:CGFloat = 0 var addYPosInc:CGFloat = 0 var addYFill:CGFloat = 0 let averageArrange = (vertGravity == TGGravity.vert.fill) //只有最后一行,并且数量小于tg_arrangedCount,并且不是第一行才应用策略。 let applyLastlineGravityPolicy:Bool = (startIndex == sbs.count && count != lsc.tg_arrangedCount && (vertGravity == TGGravity.vert.between || vertGravity == TGGravity.vert.around || vertGravity == TGGravity.vert.among || vertGravity == TGGravity.vert.fill)) if !averageArrange || lsc.tg_arrangedCount == 0 { switch vertGravity { case TGGravity.vert.center: addYPos = (selfSize.height - vertPadding - colMaxHeight)/2 break case TGGravity.vert.bottom: addYPos = selfSize.height - vertPadding - colMaxHeight break case TGGravity.vert.between: if count > 1 && (!applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always) { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/(CGFloat(count) - 1) } break case TGGravity.vert.around: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count) addYPos = addYPosInc / 2.0 } else { addYPos = (selfSize.height - vertPadding - colMaxHeight) / 2.0 } } break case TGGravity.vert.among: if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { if count > 1 { addYPosInc = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count + 1) addYPos = addYPosInc } else { addYPos = (selfSize.height - vertPadding - colMaxHeight) / 2.0 } } break default: break } //处理内容拉伸的情况 if lsc.tg_arrangedCount == 0 && averageArrange && count > 0 { if !applyLastlineGravityPolicy || lsc.tg_lastlineGravityPolicy == TGGravityPolicy.always { addYFill = (selfSize.height - vertPadding - colMaxHeight)/CGFloat(count) } } } //调整位置 for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if !isEstimate && self.tg_intelligentBorderline != nil { if let sbvl = sbv as? TGBaseLayout { if !sbvl.tg_notUseIntelligentBorderline { sbvl.tg_leadingBorderline = nil sbvl.tg_topBorderline = nil sbvl.tg_trailingBorderline = nil sbvl.tg_bottomBorderline = nil //如果不是最后一行就画下面, if (j < startIndex - 1) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果不是最后一列就画右边, if (startIndex != sbs.count ) { sbvl.tg_trailingBorderline = self.tg_intelligentBorderline; } //如果最后一行的最后一个没有满列数时 if (j == sbs.count - 1 && lsc.tg_arrangedCount != count ) { sbvl.tg_bottomBorderline = self.tg_intelligentBorderline; } //如果有垂直间距则不是第一行就画上 if (vertSpace != 0 && j != startIndex - count) { sbvl.tg_topBorderline = self.tg_intelligentBorderline } //如果有水平间距则不是第一列就画左 if (horzSpace != 0 && startIndex - count != 0 ) { sbvl.tg_leadingBorderline = self.tg_intelligentBorderline; } } } } //为子视图设置单独的对齐方式 var sbvHorzAlignment = self.tgConvertLeftRightGravityToLeadingTrailing(sbvsc.tg_alignment & TGGravity.vert.mask) if sbvHorzAlignment == TGGravity.none { sbvHorzAlignment = horzAlignment } if horzAlignment == TGGravity.vert.between { sbvHorzAlignment = horzAlignment } if (sbvHorzAlignment != TGGravity.none && sbvHorzAlignment != TGGravity.horz.leading) || _tgCGFloatNotEqual(addYPos, 0) || _tgCGFloatNotEqual(addYFill, 0) || _tgCGFloatNotEqual(addYPosInc, 0) || applyLastlineGravityPolicy { sbvtgFrame.top += addYPos if lsc.tg_arrangedCount == 0 && averageArrange { //只拉伸宽度不拉伸间距 sbvtgFrame.height += addYFill if j != startIndex - count { sbvtgFrame.top += addYFill * CGFloat(j - (startIndex - count)) } } else { //只拉伸间距 sbvtgFrame.top += addYPosInc * CGFloat(j - (startIndex - count)) if (startIndex - count) > 0 && applyLastlineGravityPolicy && lsc.tg_lastlineGravityPolicy == TGGravityPolicy.auto { //对齐前一行对应位置的 sbvtgFrame.top = sbs[j - lsc.tg_arrangedCount].tgFrame.top } } let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos switch sbvHorzAlignment { case TGGravity.horz.center: sbvtgFrame.leading += (colMaxWidth - leadingSpace - trailingSpace - sbvtgFrame.width)/2 break case TGGravity.horz.trailing: sbvtgFrame.leading += colMaxWidth - leadingSpace - trailingSpace - sbvtgFrame.width break case TGGravity.horz.fill: sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: colMaxWidth - leadingSpace - trailingSpace, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) break default: break } } } } fileprivate func tgCalcVertLayoutSinglelineWeight(selfSize:CGSize, totalFloatWidth:CGFloat, totalWeight:CGFloat,sbs:[UIView],startIndex:NSInteger, count:NSInteger) { var totalFloatWidth = totalFloatWidth var totalWeight = totalWeight for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue/100 } let tempWidth = sbvsc.width.measure(_tgRoundNumber(totalFloatWidth * ( widthWeight / totalWeight))) totalFloatWidth -= tempWidth totalWeight -= widthWeight sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv:sbv,calcSize:tempWidth,sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width; } } } fileprivate func tgCalcHorzLayoutSinglelineWeight(selfSize:CGSize, totalFloatHeight:CGFloat, totalWeight:CGFloat,sbs:[UIView],startIndex:NSInteger, count:NSInteger) { var totalFloatHeight = totalFloatHeight var totalWeight = totalWeight for j in startIndex - count ..< startIndex { let sbv:UIView = sbs[j] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue / 100 } let tempHeight = sbvsc.height.measure(_tgRoundNumber(totalFloatHeight * ( heightWeight / totalWeight))) totalFloatHeight -= tempHeight totalWeight -= heightWeight sbvtgFrame.height = self.tgValidMeasure(sbvsc.height,sbv:sbv,calcSize:tempHeight,sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height; if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { sbvtgFrame.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:sbvsc.width.measure(sbvtgFrame.height),sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) } } } } fileprivate func tgLayoutSubviewsForVert(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let autoArrange:Bool = lsc.tg_autoArrange let arrangedCount:Int = lsc.tg_arrangedCount var leadingPadding:CGFloat = lsc.tgLeadingPadding var trailingPadding:CGFloat = lsc.tgTrailingPadding let topPadding:CGFloat = lsc.tgTopPadding let bottomPadding:CGFloat = lsc.tgBottomPadding var vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask let horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let vertAlignment:TGGravity = lsc.tg_arrangedGravity & TGGravity.horz.mask var horzSpace = lsc.tg_hspace let vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,leadingPadding,trailingPadding,horzSpace) = t.calcMaxMinSubviewSize(selfSize.width, arrangedCount: arrangedCount, startPadding: leadingPadding, endPadding: trailingPadding, space: horzSpace) } var rowMaxHeight:CGFloat = 0 var rowMaxWidth:CGFloat = 0 var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var maxWidth = leadingPadding var maxHeight = topPadding //判断父滚动视图是否分页滚动 var isPagingScroll = false if let scrolv = self.superview as? UIScrollView, scrolv.isPagingEnabled { isPagingScroll = true } var pagingItemHeight:CGFloat = 0 var pagingItemWidth:CGFloat = 0 var isVertPaging = false var isHorzPaging = false if lsc.tg_pagedCount > 0 && self.superview != nil { let rows = CGFloat(lsc.tg_pagedCount / arrangedCount) //每页的行数。 //对于垂直流式布局来说,要求要有明确的宽度。因此如果我们启用了分页又设置了宽度包裹时则我们的分页是从左到右的排列。否则分页是从上到下的排列。 if lsc.width.isWrap { isHorzPaging = true if isPagingScroll { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - trailingPadding - CGFloat(arrangedCount - 1) * horzSpace ) / CGFloat(arrangedCount) } else { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - CGFloat(arrangedCount) * horzSpace ) / CGFloat(arrangedCount) } pagingItemHeight = (selfSize.height - topPadding - bottomPadding - (rows - 1) * vertSpace) / rows } else { isVertPaging = true pagingItemWidth = (selfSize.width - leadingPadding - trailingPadding - CGFloat(arrangedCount - 1) * horzSpace) / CGFloat(arrangedCount) //分页滚动时和非分页滚动时的高度计算是不一样的。 if (isPagingScroll) { pagingItemHeight = (self.superview!.bounds.height - topPadding - bottomPadding - (rows - 1) * vertSpace) / CGFloat(rows) } else { pagingItemHeight = (self.superview!.bounds.height - topPadding - rows * vertSpace) / rows } } } let averageArrange = (horzGravity == TGGravity.horz.fill) var arrangedIndex:Int = 0 var rowTotalWeight:CGFloat = 0 var rowTotalFixedWidth:CGFloat = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if (arrangedIndex >= arrangedCount) { arrangedIndex = 0; if (rowTotalWeight != 0 && !averageArrange) { self.tgCalcVertLayoutSinglelineWeight(selfSize:selfSize,totalFloatWidth:selfSize.width - leadingPadding - trailingPadding - rowTotalFixedWidth,totalWeight:rowTotalWeight,sbs:sbs,startIndex:i,count:arrangedCount) } rowTotalWeight = 0; rowTotalFixedWidth = 0; } let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if sbvsc.width.weightVal != nil || sbvsc.width.isFill { if sbvsc.width.isFill { rowTotalWeight += 1.0 } else { rowTotalWeight += sbvsc.width.weightVal.rawValue / 100 } } else { if subviewSize != 0 { rect.size.width = subviewSize - leadingSpace - trailingSpace } if pagingItemWidth != 0 { rect.size.width = pagingItemWidth - leadingSpace - trailingSpace } if sbvsc.width.numberVal != nil && !averageArrange { rect.size.width = sbvsc.width.measure; } rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc,rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:rect.size.width,sbvSize:rect.size,selfLayoutSize:selfSize) rowTotalFixedWidth += rect.size.width; } rowTotalFixedWidth += leadingSpace + trailingSpace; if (arrangedIndex != (arrangedCount - 1)) { rowTotalFixedWidth += horzSpace } sbvtgFrame.frame = rect; arrangedIndex += 1 } //最后一行。 if (rowTotalWeight != 0 && !averageArrange) { //如果最后一行没有填满则应该减去一个间距的值。 if arrangedIndex < arrangedCount { rowTotalFixedWidth -= horzSpace } self.tgCalcVertLayoutSinglelineWeight(selfSize:selfSize,totalFloatWidth:selfSize.width - leadingPadding - trailingPadding - rowTotalFixedWidth,totalWeight:rowTotalWeight,sbs:sbs,startIndex:sbs.count, count:arrangedIndex) } var nextPointOfRows:[CGPoint]! = nil if autoArrange { nextPointOfRows = [CGPoint]() for _ in 0 ..< arrangedCount { nextPointOfRows.append(CGPoint(x:leadingPadding, y: topPadding)) } } var pageWidth:CGFloat = 0; //页宽 let averageWidth:CGFloat = (selfSize.width - leadingPadding - trailingPadding - (CGFloat(arrangedCount) - 1) * horzSpace) / CGFloat(arrangedCount) arrangedIndex = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) //换行 if arrangedIndex >= arrangedCount { arrangedIndex = 0 yPos += rowMaxHeight yPos += vertSpace //分别处理水平分页和垂直分页。 if (isHorzPaging) { if (i % lsc.tg_pagedCount == 0) { pageWidth += self.superview!.bounds.width if (!isPagingScroll) { pageWidth -= leadingPadding } yPos = topPadding } } if (isVertPaging) { //如果是分页滚动则要多添加垂直间距。 if (i % lsc.tg_pagedCount == 0) { if (isPagingScroll) { yPos -= vertSpace yPos += bottomPadding yPos += topPadding } } } xPos = leadingPadding + pageWidth //计算每行的gravity情况 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: i, count: arrangedCount, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) rowMaxHeight = 0 rowMaxWidth = 0 } let topSpace = sbvsc.top.absPos let leadingSpace = sbvsc.leading.absPos let bottomSpace = sbvsc.bottom.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if (pagingItemHeight != 0) { rect.size.height = pagingItemHeight - topSpace - bottomSpace } rect.size.height = sbvsc.height.numberSize(rect.size.height) if averageArrange { rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: averageWidth - leadingSpace - trailingSpace, sbvSize: rect.size, selfLayoutSize:selfSize) } rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) //如果高度是浮动的 则需要调整陶都 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue/100 } rect.size.height = sbvsc.height.measure((selfSize.height - yPos - bottomPadding)*heightWeight - topSpace - bottomSpace) } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) if _tgCGFloatLess(rowMaxHeight , topSpace + bottomSpace + rect.size.height) { rowMaxHeight = topSpace + bottomSpace + rect.size.height } if autoArrange { var minPt:CGPoint = CGPoint(x:CGFloat.greatestFiniteMagnitude, y:CGFloat.greatestFiniteMagnitude) var minNextPointIndex:Int = 0 for idx in 0 ..< arrangedCount { let pt = nextPointOfRows[idx] if minPt.y > pt.y { minPt = pt minNextPointIndex = idx } } xPos = minPt.x yPos = minPt.y minPt.y = minPt.y + topSpace + rect.size.height + bottomSpace + vertSpace nextPointOfRows[minNextPointIndex] = minPt if minNextPointIndex + 1 <= arrangedCount - 1 { minPt = nextPointOfRows[minNextPointIndex + 1] minPt.x = xPos + leadingSpace + rect.size.width + trailingSpace + horzSpace nextPointOfRows[minNextPointIndex + 1] = minPt } if _tgCGFloatLess(maxHeight, yPos + topSpace + rect.size.height + bottomSpace) { maxHeight = yPos + topSpace + rect.size.height + bottomSpace } } else if vertAlignment == TGGravity.vert.between { //当行是紧凑排行时需要特殊处理当前的垂直位置。 //第0行特殊处理。 if (i - arrangedCount < 0) { yPos = topPadding } else { //取前一行的对应的列的子视图。 let (prevSbvtgFrame, prevSbvsc) = self.tgGetSubviewFrameAndSizeClass(sbs[i - arrangedCount]) //当前子视图的位置等于前一行对应列的最大y的值 + 前面对应列的尾部间距 + 子视图之间的行间距。 yPos = prevSbvtgFrame.frame.maxY + prevSbvsc.bottom.absPos + vertSpace } if _tgCGFloatLess(maxHeight, yPos + topSpace + rect.size.height + bottomSpace) { maxHeight = yPos + topSpace + rect.size.height + bottomSpace } } else { maxHeight = yPos + rowMaxHeight } rect.origin.x = (xPos + leadingSpace) rect.origin.y = (yPos + topSpace) xPos += (leadingSpace + rect.size.width + trailingSpace) if _tgCGFloatLess(rowMaxWidth , xPos - leadingPadding) { rowMaxWidth = xPos - leadingPadding } if _tgCGFloatLess(maxWidth , xPos) { maxWidth = xPos } if arrangedIndex != (arrangedCount - 1) && !autoArrange { xPos += horzSpace } sbvtgFrame.frame = rect arrangedIndex += 1 } //最后一行 布局 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) maxHeight = maxHeight + bottomPadding if lsc.height.isWrap { selfSize.height = maxHeight //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isVertPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.height , totalPages * self.superview!.bounds.height) { selfSize.height = totalPages * self.superview!.bounds.height } } } else { var addYPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 let arranges = floor(CGFloat(sbs.count + arrangedCount - 1) / CGFloat(arrangedCount)) if arranges <= 1 && vertGravity == TGGravity.vert.around { vertGravity = TGGravity.vert.center } if vertGravity == TGGravity.vert.center { addYPos = (selfSize.height - maxHeight)/2 } else if vertGravity == TGGravity.vert.bottom { addYPos = selfSize.height - maxHeight } else if (vertGravity == TGGravity.vert.fill) { if (arranges > 0) { fill = (selfSize.height - maxHeight) / arranges } } else if (vertGravity == TGGravity.vert.between) { if (arranges > 1) { between = (selfSize.height - maxHeight) / (arranges - 1) } } else if (vertGravity == TGGravity.vert.around) { between = (selfSize.height - maxHeight) / arranges } else if (vertGravity == TGGravity.vert.among) { between = (selfSize.height - maxHeight) / (arranges + 1) } if addYPos != 0 || between != 0 || fill != 0 { for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame let line = i / arrangedCount sbvtgFrame.height += fill sbvtgFrame.top += fill * CGFloat(line) sbvtgFrame.top += addYPos sbvtgFrame.top += between * CGFloat(line) //如果是vert_around那么所有行都应该添加一半的between值。 if (vertGravity == TGGravity.vert.around) { sbvtgFrame.top += (between / 2.0) } if (vertGravity == TGGravity.vert.among) { sbvtgFrame.top += between } } } } if lsc.width.isWrap && !averageArrange { selfSize.width = maxWidth + trailingPadding //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isHorzPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.width , totalPages * self.superview!.bounds.width) { selfSize.width = totalPages * self.superview!.bounds.width } } } return selfSize } fileprivate func tgLayoutSubviewsForVertContent(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize var leadingPadding:CGFloat = lsc.tgLeadingPadding var trailingPadding:CGFloat = lsc.tgTrailingPadding let topPadding:CGFloat = lsc.tgTopPadding let bottomPadding:CGFloat = lsc.tgBottomPadding var vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask let horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let vertAlignment:TGGravity = lsc.tg_arrangedGravity & TGGravity.horz.mask var horzSpace = lsc.tg_hspace let vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,leadingPadding,trailingPadding,horzSpace) = t.calcMaxMinSubviewSizeForContent(selfSize.width, startPadding: leadingPadding, endPadding: trailingPadding, space: horzSpace) } var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var rowMaxHeight:CGFloat = 0 var rowMaxWidth:CGFloat = 0 var arrangeIndexSet = IndexSet() var arrangeIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame if subviewSize != 0 { rect.size.width = subviewSize - leadingSpace - trailingSpace } rect.size.width = sbvsc.width.numberSize(rect.size.width) rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal { heightWeight = t.rawValue/100 } rect.size.height = sbv.tg_height.measure((selfSize.height - yPos - bottomPadding)*heightWeight - topSpace - bottomSpace) } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { //如果过了,则表示当前的剩余空间为0了,所以就按新的一行来算。。 var floatWidth = selfSize.width - trailingPadding - xPos - leadingSpace - trailingSpace; if arrangeIndex != 0 { floatWidth -= horzSpace } if _tgCGFloatLessOrEqual(floatWidth, 0){ floatWidth = selfSize.width - leadingPadding - trailingPadding } var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal{ widthWeight = t.rawValue/100 } rect.size.width = (floatWidth + sbvsc.width.increment) * widthWeight - leadingSpace - trailingSpace; } rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.height.isRelaSizeEqualTo(sbvsc.width) { rect.size.height = sbvsc.height.measure(rect.size.width) } //如果高度是浮动则需要调整 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) //计算xPos的值加上leadingSpace + rect.size.width + trailingSpace + lsc.tg_hspace 的值要小于整体的宽度。 var place:CGFloat = xPos + leadingSpace + rect.size.width + trailingSpace if arrangeIndex != 0 { place += horzSpace } place += trailingPadding //sbv所占据的宽度要超过了视图的整体宽度,因此需要换行。但是如果arrangedIndex为0的话表示这个控件的整行的宽度和布局视图保持一致。 if place - selfSize.width > 0.0001 { xPos = leadingPadding yPos += vertSpace yPos += rowMaxHeight arrangeIndexSet.insert(i - arrangeIndex) //计算每行Gravity情况 self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex: i, count: arrangeIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding: leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) //计算单独的sbv的宽度是否大于整体的宽度。如果大于则缩小宽度。 if _tgCGFloatGreat(leadingSpace + trailingSpace + rect.size.width , selfSize.width - leadingPadding - trailingPadding) { rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: selfSize.width - leadingPadding - trailingPadding - leadingSpace - trailingSpace, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } } rowMaxHeight = 0 rowMaxWidth = 0 arrangeIndex = 0 } if arrangeIndex != 0 { xPos += horzSpace } rect.origin.x = xPos + leadingSpace rect.origin.y = yPos + topSpace xPos += leadingSpace + rect.size.width + trailingSpace if _tgCGFloatLess(rowMaxHeight , topSpace + bottomSpace + rect.size.height) { rowMaxHeight = topSpace + bottomSpace + rect.size.height; } if _tgCGFloatLess(rowMaxWidth , xPos - leadingPadding) { rowMaxWidth = xPos - leadingPadding } sbvtgFrame.frame = rect; arrangeIndex += 1 } //设置最后一行 arrangeIndexSet.insert(sbs.count - arrangeIndex) self .tgCalcVertLayoutSinglelineAlignment(selfSize, rowMaxHeight: rowMaxHeight, rowMaxWidth: rowMaxWidth, horzGravity: horzGravity, vertAlignment: vertAlignment, sbs: sbs, startIndex:sbs.count, count: arrangeIndex, vertSpace: vertSpace, horzSpace: horzSpace, horzPadding:leadingPadding + trailingPadding, isEstimate: isEstimate, lsc:lsc) if lsc.height.isWrap { selfSize.height = yPos + bottomPadding + rowMaxHeight; } else { var addYPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 if arrangeIndexSet.count <= 1 && vertGravity == TGGravity.vert.around { vertGravity = TGGravity.vert.center } if vertGravity == TGGravity.vert.center { addYPos = (selfSize.height - bottomPadding - rowMaxHeight - yPos)/2 } else if vertGravity == TGGravity.vert.bottom { addYPos = selfSize.height - bottomPadding - rowMaxHeight - yPos } else if vertGravity == TGGravity.vert.fill { if arrangeIndexSet.count > 0 { fill = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count) } } else if (vertGravity == TGGravity.vert.between) { if arrangeIndexSet.count > 1 { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count - 1) } } else if (vertGravity == TGGravity.vert.around) { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count) } else if (vertGravity == TGGravity.vert.among) { between = (selfSize.height - bottomPadding - rowMaxHeight - yPos) / CGFloat(arrangeIndexSet.count + 1) } if addYPos != 0 || between != 0 || fill != 0 { var line:CGFloat = 0 var lastIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame sbvtgFrame.top += addYPos let index = arrangeIndexSet.integerLessThanOrEqualTo(i) if lastIndex != index { lastIndex = index! line += 1 } sbvtgFrame.height += fill sbvtgFrame.top += fill * line sbvtgFrame.top += between * line //如果是vert_around那么所有行都应该添加一半的between值。 if (vertGravity == TGGravity.vert.around) { sbvtgFrame.top += (between / 2.0) } if (vertGravity == TGGravity.vert.among) { sbvtgFrame.top += between } } } } return selfSize } fileprivate func tgLayoutSubviewsForHorz(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let autoArrange:Bool = lsc.tg_autoArrange let arrangedCount:Int = lsc.tg_arrangedCount let leadingPadding:CGFloat = lsc.tgLeadingPadding let trailingPadding:CGFloat = lsc.tgTrailingPadding var topPadding:CGFloat = lsc.tgTopPadding var bottomPadding:CGFloat = lsc.tgBottomPadding let vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask var horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let horzAlignment:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_arrangedGravity & TGGravity.vert.mask) let horzSpace = lsc.tg_hspace var vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,topPadding,bottomPadding,vertSpace) = t.calcMaxMinSubviewSize(selfSize.height, arrangedCount: arrangedCount, startPadding: topPadding, endPadding: bottomPadding, space: vertSpace) } var colMaxWidth:CGFloat = 0 var colMaxHeight:CGFloat = 0 var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var maxHeight:CGFloat = topPadding var maxWidth:CGFloat = leadingPadding //判断父滚动视图是否分页滚动 var isPagingScroll = false if let scrolv = self.superview as? UIScrollView, scrolv.isPagingEnabled { isPagingScroll = true } var pagingItemHeight:CGFloat = 0 var pagingItemWidth:CGFloat = 0 var isVertPaging = false var isHorzPaging = false if lsc.tg_pagedCount > 0 && self.superview != nil { let cols = CGFloat(lsc.tg_pagedCount / arrangedCount) //每页的列数。 //对于水平流式布局来说,要求要有明确的高度。因此如果我们启用了分页又设置了高度包裹时则我们的分页是从上到下的排列。否则分页是从左到右的排列。 if lsc.height.isWrap { isVertPaging = true if isPagingScroll { pagingItemHeight = (self.superview!.bounds.height - topPadding - bottomPadding - CGFloat(arrangedCount - 1) * vertSpace ) / CGFloat(arrangedCount) } else { pagingItemHeight = (self.superview!.bounds.height - topPadding - CGFloat(arrangedCount) * vertSpace ) / CGFloat(arrangedCount) } pagingItemWidth = (selfSize.width - leadingPadding - trailingPadding - (cols - 1) * horzSpace) / cols } else { isHorzPaging = true pagingItemHeight = (selfSize.height - topPadding - bottomPadding - CGFloat(arrangedCount - 1) * vertSpace) / CGFloat(arrangedCount) //分页滚动时和非分页滚动时的高度计算是不一样的。 if (isPagingScroll) { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - trailingPadding - (cols - 1) * horzSpace) / cols } else { pagingItemWidth = (self.superview!.bounds.width - leadingPadding - cols * horzSpace) / cols } } } let averageArrange = (vertGravity == TGGravity.vert.fill) var arrangedIndex:Int = 0 var rowTotalWeight:CGFloat = 0 var rowTotalFixedHeight:CGFloat = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if (arrangedIndex >= arrangedCount) { arrangedIndex = 0; if (rowTotalWeight != 0 && !averageArrange) { self.tgCalcHorzLayoutSinglelineWeight(selfSize:selfSize,totalFloatHeight:selfSize.height - topPadding - bottomPadding - rowTotalFixedHeight,totalWeight:rowTotalWeight,sbs:sbs,startIndex:i,count:arrangedCount) } rowTotalWeight = 0; rowTotalFixedHeight = 0; } let topSpace = sbvsc.top.absPos let bottomSpace = sbvsc.bottom.absPos let leadingSpace = sbvsc.leading.absPos let trailingSpace = sbvsc.trailing.absPos var rect = sbvtgFrame.frame if (pagingItemWidth != 0) { rect.size.width = pagingItemWidth - leadingSpace - trailingSpace } rect.size.width = sbvsc.width.numberSize(rect.size.width) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize,sbvsc:sbvsc,lsc:lsc, rect: rect) rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:rect.size.width,sbvSize:rect.size,selfLayoutSize:selfSize) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { if sbvsc.height.isFill { rowTotalWeight += 1.0 } else { rowTotalWeight += sbvsc.height.weightVal.rawValue/100 } } else { if subviewSize != 0 { rect.size.height = subviewSize - topSpace - bottomSpace } if (pagingItemHeight != 0) { rect.size.height = pagingItemHeight - topSpace - bottomSpace } if (sbvsc.height.numberVal != nil && !averageArrange) { rect.size.height = sbvsc.height.measure; } rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) //如果高度是浮动的则需要调整高度。 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) } rect.size.height = self.tgValidMeasure(sbvsc.height,sbv:sbv,calcSize:rect.size.height,sbvSize:rect.size,selfLayoutSize:selfSize) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = self.tgValidMeasure(sbvsc.width,sbv:sbv,calcSize:sbvsc.width.measure(rect.size.height),sbvSize:rect.size,selfLayoutSize:selfSize) } rowTotalFixedHeight += rect.size.height; } rowTotalFixedHeight += topSpace + bottomSpace if (arrangedIndex != (arrangedCount - 1)) { rowTotalFixedHeight += vertSpace } sbvtgFrame.frame = rect; arrangedIndex += 1 } //最后一行。 if (rowTotalWeight != 0 && !averageArrange) { if arrangedIndex < arrangedCount { rowTotalFixedHeight -= vertSpace } self.tgCalcHorzLayoutSinglelineWeight(selfSize:selfSize,totalFloatHeight:selfSize.height - topPadding - bottomPadding - rowTotalFixedHeight,totalWeight:rowTotalWeight,sbs:sbs,startIndex:sbs.count,count:arrangedIndex) } var nextPointOfRows:[CGPoint]! = nil if autoArrange { nextPointOfRows = [CGPoint]() for _ in 0 ..< arrangedCount { nextPointOfRows.append(CGPoint(x:leadingPadding, y: topPadding)) } } var pageHeight:CGFloat = 0 let averageHeight:CGFloat = (selfSize.height - topPadding - bottomPadding - (CGFloat(arrangedCount) - 1) * vertSpace) / CGFloat(arrangedCount) arrangedIndex = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if arrangedIndex >= arrangedCount { arrangedIndex = 0 xPos += colMaxWidth xPos += horzSpace //分别处理水平分页和垂直分页。 if (isVertPaging) { if (i % lsc.tg_pagedCount == 0) { pageHeight += self.superview!.bounds.height if (!isPagingScroll) { pageHeight -= topPadding } xPos = leadingPadding; } } if (isHorzPaging) { //如果是分页滚动则要多添加垂直间距。 if (i % lsc.tg_pagedCount == 0) { if (isPagingScroll) { xPos -= horzSpace xPos += trailingPadding xPos += leadingPadding } } } yPos = topPadding + pageHeight; //计算每行Gravity情况 self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: i, count: arrangedCount, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) colMaxWidth = 0 colMaxHeight = 0 } let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame if averageArrange { rect.size.height = (averageHeight - topSpace - bottomSpace) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = sbvsc.width.measure(rect.size.height) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) } } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue/100 } rect.size.width = sbvsc.width.measure((selfSize.width - xPos - trailingPadding)*widthWeight - leadingSpace - trailingSpace) rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) } if _tgCGFloatLess(colMaxWidth , leadingSpace + trailingSpace + rect.size.width) { colMaxWidth = leadingSpace + trailingSpace + rect.size.width } if autoArrange { var minPt:CGPoint = CGPoint(x:CGFloat.greatestFiniteMagnitude, y:CGFloat.greatestFiniteMagnitude) var minNextPointIndex:Int = 0 for idx in 0 ..< arrangedCount { let pt = nextPointOfRows[idx] if minPt.x > pt.x { minPt = pt minNextPointIndex = idx } } xPos = minPt.x yPos = minPt.y minPt.x = minPt.x + leadingSpace + rect.size.width + trailingSpace + horzSpace; nextPointOfRows[minNextPointIndex] = minPt if minNextPointIndex + 1 <= arrangedCount - 1 { minPt = nextPointOfRows[minNextPointIndex + 1] minPt.y = yPos + topSpace + rect.size.height + bottomSpace + vertSpace nextPointOfRows[minNextPointIndex + 1] = minPt } if _tgCGFloatLess(maxWidth, xPos + leadingSpace + rect.size.width + trailingSpace) { maxWidth = xPos + leadingSpace + rect.size.width + trailingSpace } } else if horzAlignment == TGGravity.horz.between { //当列是紧凑排列时需要特殊处理当前的水平位置。 //第0列特殊处理。 if (i - arrangedCount < 0) { xPos = leadingPadding } else { //取前一列的对应的行的子视图。 let (prevSbvtgFrame, prevSbvsc) = self.tgGetSubviewFrameAndSizeClass(sbs[i - arrangedCount]) //当前子视图的位置等于前一列对应行的最大x的值 + 前面对应行的尾部间距 + 子视图之间的列间距。 xPos = prevSbvtgFrame.frame.maxX + prevSbvsc.trailing.absPos + horzSpace } if _tgCGFloatLess(maxWidth, xPos + leadingSpace + rect.size.width + trailingSpace) { maxWidth = xPos + leadingSpace + rect.size.width + trailingSpace } } else { maxWidth = xPos + colMaxWidth } rect.origin.y = yPos + topSpace rect.origin.x = xPos + leadingSpace yPos += topSpace + rect.size.height + bottomSpace if _tgCGFloatLess(colMaxHeight , (yPos - topPadding)) { colMaxHeight = yPos - topPadding } if _tgCGFloatLess(maxHeight , yPos) { maxHeight = yPos } if arrangedIndex != (arrangedCount - 1) && !autoArrange { yPos += vertSpace } sbvtgFrame.frame = rect arrangedIndex += 1 } //最后一列 self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) if lsc.height.isWrap && !averageArrange { selfSize.height = maxHeight + bottomPadding //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isVertPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.height , totalPages * self.superview!.bounds.height) { selfSize.height = totalPages * self.superview!.bounds.height } } } maxWidth = maxWidth + trailingPadding if lsc.width.isWrap { selfSize.width = maxWidth //只有在父视图为滚动视图,且开启了分页滚动时才会扩充具有包裹设置的布局视图的宽度。 if (isHorzPaging && isPagingScroll) { //算出页数来。如果包裹计算出来的宽度小于指定页数的宽度,因为要分页滚动所以这里会扩充布局的宽度。 let totalPages:CGFloat = floor(CGFloat(sbs.count + lsc.tg_pagedCount - 1 ) / CGFloat(lsc.tg_pagedCount)) if _tgCGFloatLess(selfSize.width , totalPages * self.superview!.bounds.width) { selfSize.width = totalPages * self.superview!.bounds.width } } } else { var addXPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 let arranges = floor(CGFloat(sbs.count + arrangedCount - 1) / CGFloat(arrangedCount)) if arranges <= 1 && horzGravity == TGGravity.horz.around { horzGravity = TGGravity.horz.center } if horzGravity == TGGravity.horz.center { addXPos = (selfSize.width - maxWidth) / 2 } else if horzGravity == TGGravity.horz.trailing { addXPos = selfSize.width - maxWidth } else if (horzGravity == TGGravity.horz.fill) { if (arranges > 0) { fill = (selfSize.width - maxWidth) / arranges } } else if (horzGravity == TGGravity.horz.between) { if (arranges > 1) { between = (selfSize.width - maxWidth) / (arranges - 1) } } else if (horzGravity == TGGravity.horz.around) { between = (selfSize.width - maxWidth) / arranges } else if (horzGravity == TGGravity.horz.among) { between = (selfSize.width - maxWidth) / (arranges + 1) } if addXPos != 0 || between != 0 || fill != 0 { for i:Int in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame let line = i / arrangedCount sbvtgFrame.width += fill sbvtgFrame.leading += fill * CGFloat(line) sbvtgFrame.leading += addXPos sbvtgFrame.leading += between * CGFloat(line) //如果是vert_around那么所有行都应该添加一半的between值。 if (horzGravity == TGGravity.horz.around) { sbvtgFrame.leading += (between / 2.0) } if (horzGravity == TGGravity.horz.among) { sbvtgFrame.leading += between } } } } return selfSize } fileprivate func tgLayoutSubviewsForHorzContent(_ selfSize:CGSize, sbs:[UIView], isEstimate:Bool, lsc:TGFlowLayoutViewSizeClassImpl)->CGSize { var selfSize = selfSize let leadingPadding:CGFloat = lsc.tgLeadingPadding let trailingPadding:CGFloat = lsc.tgTrailingPadding var topPadding:CGFloat = lsc.tgTopPadding var bottomPadding:CGFloat = lsc.tgBottomPadding let vertGravity:TGGravity = lsc.tg_gravity & TGGravity.horz.mask var horzGravity:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_gravity & TGGravity.vert.mask) let horzAlignment:TGGravity = self.tgConvertLeftRightGravityToLeadingTrailing(lsc.tg_arrangedGravity & TGGravity.vert.mask) //支持浮动垂直间距。 let horzSpace = lsc.tg_hspace var vertSpace = lsc.tg_vspace var subviewSize:CGFloat = 0.0 if let t = lsc.tgFlexSpace, sbs.count > 0 { (subviewSize,topPadding,bottomPadding,vertSpace) = t.calcMaxMinSubviewSizeForContent(selfSize.height, startPadding: topPadding, endPadding: bottomPadding, space: vertSpace) } var xPos:CGFloat = leadingPadding var yPos:CGFloat = topPadding var colMaxWidth:CGFloat = 0 var colMaxHeight:CGFloat = 0 var arrangeIndexSet = IndexSet() var arrangedIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) let topSpace:CGFloat = sbvsc.top.absPos let leadingSpace:CGFloat = sbvsc.leading.absPos let bottomSpace:CGFloat = sbvsc.bottom.absPos let trailingSpace:CGFloat = sbvsc.trailing.absPos var rect:CGRect = sbvtgFrame.frame rect.size.width = sbvsc.width.numberSize(rect.size.width) if subviewSize != 0 { rect.size.height = subviewSize - topSpace - bottomSpace } rect.size.height = sbvsc.height.numberSize(rect.size.height) rect = tgSetSubviewRelativeSize(sbvsc.height, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) rect = tgSetSubviewRelativeSize(sbvsc.width, selfSize: selfSize, sbvsc:sbvsc, lsc:lsc, rect: rect) if sbvsc.height.weightVal != nil || sbvsc.height.isFill { //如果过了,则表示当前的剩余空间为0了,所以就按新的一行来算。。 var floatHeight = selfSize.height - bottomPadding - yPos - topSpace - bottomSpace if arrangedIndex != 0 { floatHeight -= vertSpace } if (_tgCGFloatLessOrEqual(floatHeight, 0)){ floatHeight = selfSize.height - topPadding - bottomPadding } var heightWeight:CGFloat = 1.0 if let t = sbvsc.height.weightVal{ heightWeight = t.rawValue/100 } rect.size.height = (floatHeight + sbvsc.height.increment) * heightWeight - topSpace - bottomSpace; } rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) if sbvsc.width.isRelaSizeEqualTo(sbvsc.height) { rect.size.width = sbvsc.width.measure(rect.size.height) } if sbvsc.width.weightVal != nil || sbvsc.width.isFill { var widthWeight:CGFloat = 1.0 if let t = sbvsc.width.weightVal { widthWeight = t.rawValue / 100 } rect.size.width = sbvsc.width.measure((selfSize.width - xPos - trailingPadding)*widthWeight - leadingSpace - trailingSpace) } rect.size.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: rect.size.width, sbvSize: rect.size, selfLayoutSize: selfSize) //如果高度是浮动则调整 if sbvsc.height.isFlexHeight { rect.size.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: rect.size.width) rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } //计算yPos的值加上topSpace + rect.size.height + bottomSpace + lsc.tg_vspace 的值要小于整体的宽度。 var place:CGFloat = yPos + topSpace + rect.size.height + bottomSpace if arrangedIndex != 0 { place += vertSpace } place += bottomPadding //sbv所占据的宽度要超过了视图的整体宽度,因此需要换行。但是如果arrangedIndex为0的话表示这个控件的整行的宽度和布局视图保持一致。 if place - selfSize.height > 0.0001 { yPos = topPadding xPos += horzSpace xPos += colMaxWidth //计算每行Gravity情况 arrangeIndexSet.insert(i - arrangedIndex) self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: i, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding+bottomPadding, isEstimate: isEstimate, lsc:lsc) //计算单独的sbv的高度是否大于整体的高度。如果大于则缩小高度。 if _tgCGFloatGreat(topSpace + bottomSpace + rect.size.height , selfSize.height - topPadding - bottomPadding) { rect.size.height = selfSize.height - topPadding - bottomPadding - topSpace - bottomSpace rect.size.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: rect.size.height, sbvSize: rect.size, selfLayoutSize: selfSize) } colMaxWidth = 0; colMaxHeight = 0; arrangedIndex = 0; } if arrangedIndex != 0 { yPos += vertSpace } rect.origin.x = xPos + leadingSpace rect.origin.y = yPos + topSpace yPos += topSpace + rect.size.height + bottomSpace if _tgCGFloatLess(colMaxWidth , leadingSpace + trailingSpace + rect.size.width) { colMaxWidth = leadingSpace + trailingSpace + rect.size.width } if _tgCGFloatLess(colMaxHeight , (yPos - topPadding)) { colMaxHeight = (yPos - topPadding); } sbvtgFrame.frame = rect; arrangedIndex += 1; } //最后一行 arrangeIndexSet.insert(sbs.count - arrangedIndex) self.tgCalcHorzLayoutSinglelineAlignment(selfSize, colMaxHeight: colMaxHeight, colMaxWidth: colMaxWidth, vertGravity: vertGravity, horzAlignment: horzAlignment, sbs: sbs, startIndex: sbs.count, count: arrangedIndex, vertSpace: vertSpace, horzSpace: horzSpace, vertPadding:topPadding + bottomPadding, isEstimate: isEstimate, lsc:lsc) if lsc.width.isWrap { selfSize.width = xPos + trailingPadding + colMaxWidth } else { var addXPos:CGFloat = 0 var between:CGFloat = 0 var fill:CGFloat = 0 if arrangeIndexSet.count <= 1 && horzGravity == TGGravity.horz.around { horzGravity = TGGravity.horz.center } if (horzGravity == TGGravity.horz.center) { addXPos = (selfSize.width - trailingPadding - colMaxWidth - xPos) / 2; } else if (horzGravity == TGGravity.horz.trailing) { addXPos = selfSize.width - trailingPadding - colMaxWidth - xPos; } else if (horzGravity == TGGravity.horz.fill) { if (arrangeIndexSet.count > 0) { fill = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count) } } else if (horzGravity == TGGravity.horz.between) { if (arrangeIndexSet.count > 1) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count - 1) } } else if (horzGravity == TGGravity.horz.around) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count) } else if (horzGravity == TGGravity.horz.among) { between = (selfSize.width - trailingPadding - colMaxWidth - xPos) / CGFloat(arrangeIndexSet.count + 1) } if (addXPos != 0 || between != 0 || fill != 0) { var line:CGFloat = 0 var lastIndex:Int = 0 for i in 0..<sbs.count { let sbv:UIView = sbs[i] let sbvtgFrame = sbv.tgFrame sbvtgFrame.leading += addXPos let index = arrangeIndexSet.integerLessThanOrEqualTo(i) if lastIndex != index { lastIndex = index! line += 1 } sbvtgFrame.width += fill sbvtgFrame.leading += fill * line sbvtgFrame.leading += between * line if (horzGravity == TGGravity.horz.around) { sbvtgFrame.leading += (between / 2.0) } if (horzGravity == TGGravity.horz.among) { sbvtgFrame.leading += between } } } } return selfSize } }
mit
cb5791cd1c46d683f3e8f67441e9c452
39.37875
348
0.513936
4.670538
false
false
false
false
Luavis/Kasa
Kasa.swift/ShadowLabel.swift
1
1497
// // ShadowLabel.swift // Kasa.swift // // Created by Luavis Kang on 12/2/15. // Copyright © 2015 Luavis. All rights reserved. // import Cocoa class VerticallyCenteredTextFieldCell:NSTextFieldCell { override func titleRectForBounds(theRect: NSRect) -> NSRect { let stringHeight = self.attributedStringValue.size().height var titleRect = super.titleRectForBounds(theRect) let oldOriginY = theRect.origin.y titleRect.origin.y = theRect.origin.y + (theRect.size.height - stringHeight) / 2.0 titleRect.size.height = titleRect.size.height - (titleRect.origin.y - oldOriginY) return titleRect } override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) { super.drawInteriorWithFrame(self.titleRectForBounds(cellFrame), inView: controlView) } } class ShadowLabel: NSTextField { var shadowColor = NSColor.blackColor(); var shadowOffset = CGSize(width: 1.0, height: 1.0) var shadowRadius:Float = 2.0 var shadowOpacity:Float = 1.0 override func awakeFromNib() { self.drawShadow() } func drawShadow() { self.wantsLayer = true; let layer:CALayer! = self.layer!; layer.backgroundColor = NSColor.clearColor().CGColor; layer.shadowColor = self.shadowColor.CGColor; layer.shadowOffset = self.shadowOffset layer.shadowOpacity = self.shadowOpacity layer.shadowRadius = CGFloat(self.shadowRadius) } }
mit
dc9ef6d5d3972b4fd19f2a37c6fc09f4
26.2
92
0.68516
4.286533
false
false
false
false
clooth/HanekeSwift
Haneke/Data.swift
1
3235
// // Data.swift // Haneke // // Created by Hermes Pique on 9/19/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit // See: http://stackoverflow.com/questions/25922152/not-identical-to-self public protocol DataConvertible { typealias Result static func convertFromData(data:NSData) -> Result? } public protocol DataRepresentable { func asData() -> NSData! } private let imageSync = NSLock() extension UIImage : DataConvertible, DataRepresentable { public typealias Result = UIImage static func safeImageWithData(data:NSData) -> Result? { imageSync.lock() let image = UIImage(data:data) imageSync.unlock() return image } public class func convertFromData(data:NSData) -> Result? { let image = UIImage.safeImageWithData(data) return image } public func asData() -> NSData! { return self.hnk_data() } } extension String : DataConvertible, DataRepresentable { public typealias Result = String public static func convertFromData(data:NSData) -> Result? { var string = NSString(data: data, encoding: NSUTF8StringEncoding) return string as? Result } public func asData() -> NSData! { return self.dataUsingEncoding(NSUTF8StringEncoding) } } extension NSData : DataConvertible, DataRepresentable { public typealias Result = NSData public class func convertFromData(data:NSData) -> Result? { return data } public func asData() -> NSData! { return self } } public enum JSON : DataConvertible, DataRepresentable { public typealias Result = JSON case Dictionary([String:AnyObject]) case Array([AnyObject]) public static func convertFromData(data:NSData) -> Result? { var error : NSError? if let object : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) { switch (object) { case let dictionary as [String:AnyObject]: return JSON.Dictionary(dictionary) case let array as [AnyObject]: return JSON.Array(array) default: return nil } } else { Log.error("Invalid JSON data", error) return nil } } public func asData() -> NSData! { switch (self) { case .Dictionary(let dictionary): return NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.allZeros, error: nil) case .Array(let array): return NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions.allZeros, error: nil) } } public var array : [AnyObject]! { switch (self) { case .Dictionary(let _): return nil case .Array(let array): return array } } public var dictionary : [String:AnyObject]! { switch (self) { case .Dictionary(let dictionary): return dictionary case .Array(let _): return nil } } }
apache-2.0
87d2b222740f506074b5da79034ae07f
24.674603
137
0.606801
4.850075
false
false
false
false
frodoking/GithubIOSClient
Github/Core/Module/Users/UserDetailViewController.swift
1
9167
// // UserDetailViewController.swift // Github // // Created by frodo on 15/10/25. // Copyright © 2015年 frodo. All rights reserved. // import UIKit import Alamofire class UserDetailViewController: UIViewController, ViewPagerIndicatorDelegate, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var titleImageView: UIImageView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var emaiButton: UIButton! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var blogButton: UIButton! @IBOutlet weak var companyLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var createLabel: UILabel! @IBOutlet weak var viewPagerIndicator: ViewPagerIndicator! @IBOutlet weak var tableView: UITableView! private lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshAction:", forControlEvents: UIControlEvents.ValueChanged) return refreshControl }() var viewModule: UserDetailViewModule? var tabIndex: Int = 0 var array: NSArray? { didSet { self.tableView.reloadData() } } var user: User? { didSet { self.title = user?.login } } private func updateUserInfo () { if let _ = user { if let avatar_url = user!.avatar_url { Alamofire.request(.GET, avatar_url) .responseData { response in NSLog("Fetch: Image: \(avatar_url)") let imageData = UIImage(data: response.data!) self.titleImageView?.image = imageData } } if let login = user!.login { loginButton.setTitle(login, forState:UIControlState.Normal) } if let email = user!.email { emaiButton.setTitle(email, forState:UIControlState.Normal) } if let name = user!.name { nameLabel.text = name } if let blog = user!.blog { blogButton.setTitle(blog, forState:UIControlState.Normal) } if let company = user!.company { companyLabel.text = company } if let location = user!.location { locationLabel.text = location } if let created_at = user!.created_at { createLabel.text = created_at } } } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge.None self.automaticallyAdjustsScrollViewInsets=false self.view.backgroundColor = Theme.WhiteColor self.navigationController?.navigationBar.backgroundColor = Theme.Color titleImageView.layer.cornerRadius = 10 titleImageView.layer.borderColor = Theme.GrayColor.CGColor titleImageView.layer.borderWidth = 0.3 titleImageView.layer.masksToBounds=true viewModule = UserDetailViewModule() if self.user != nil { viewModule?.loadUserFromApi((self.user!.login)!, handler: { user in if user != nil { self.user = user self.updateUserInfo() } }) } updateUserInfo() viewPagerIndicator.titles = UserDetailViewModule.Indicator //监听ViewPagerIndicator选中项变化 viewPagerIndicator.delegate = self viewPagerIndicator.setTitleColorForState(Theme.Color, state: UIControlState.Selected) //选中文字的颜色 viewPagerIndicator.setTitleColorForState(UIColor.blackColor(), state: UIControlState.Normal) //正常文字颜色 viewPagerIndicator.tintColor = Theme.Color //指示器和基线的颜色 viewPagerIndicator.showBottomLine = true //基线是否显示 viewPagerIndicator.autoAdjustSelectionIndicatorWidth = true//指示器宽度是按照文字内容大小还是按照count数量平分屏幕 viewPagerIndicator.indicatorDirection = .Bottom//指示器位置 viewPagerIndicator.titleFont = UIFont.systemFontOfSize(14) self.tableView.addSubview(self.refreshControl) self.tableView.estimatedRowHeight = tableView.rowHeight self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.dataSource = self self.tableView.delegate = self viewPagerIndicator.setSelectedIndex(tabIndex) refreshAction(refreshControl) } func refreshAction(sender: UIRefreshControl) { self.refreshControl.beginRefreshing() if let _ = user { viewModule?.loadDataFromApiWithIsFirst(true, currentIndex: tabIndex, userName: (user?.login)!, handler: { array in self.refreshControl.endRefreshing() if array.count > 0 { self.array = array } }) } } @IBAction func backAction(sender: UIBarButtonItem) { if let prevViewController = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 2] { self.navigationController?.popToViewController(prevViewController, animated: true) } else { self.navigationController?.popToRootViewControllerAnimated(true) } } } // MARK: - ViewPagerIndicator extension UserDetailViewController { // 点击顶部选中后回调 func indicatorChange(indicatorIndex: Int) { self.tabIndex = indicatorIndex switch indicatorIndex { case 0: self.array = viewModule!.userRepositoriesDataSource.dsArray break case 1: self.array = viewModule!.userFollowingDataSource.dsArray break case 2: self.array = viewModule!.userFollowersDataSource.dsArray break default:break } self.refreshAction(self.refreshControl) } } // MARK: - UITableViewDataSource extension UserDetailViewController { func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections if array == nil { return 0 } return self.array!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tabIndex == 0 { let cell = tableView.dequeueReusableCellWithIdentifier(Key.CellReuseIdentifier.RepositoryCell, forIndexPath: indexPath) as! RepositoryTableViewCell cell.repository = self.array![indexPath.section] as? Repository return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier(Key.CellReuseIdentifier.UserCell, forIndexPath: indexPath) as! UserTableViewCell cell.user = self.array![indexPath.section] as? User return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if tabIndex == 0 { return Theme.RepositoryTableViewCellheight } return Theme.UserTableViewCellHeight } } // MARK: - Navigation extension UserDetailViewController { // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let viewController = segue.destinationViewController if let userDetailViewController = viewController as? UserDetailViewController { if let cell = sender as? UserTableViewCell { let selectedIndex = tableView.indexPathForCell(cell)?.section if let index = selectedIndex { userDetailViewController.user = self.array![index] as? User } } } else if let repositoryDetailViewController = viewController as? RepositoryDetailViewController { if let cell = sender as? RepositoryTableViewCell { let selectedIndex = tableView.indexPathForCell(cell)?.section if let index = selectedIndex { repositoryDetailViewController.repository = self.array![index] as? Repository } } } } }
apache-2.0
5d6a0e8883e8043dfae280019b5c8177
35.658537
159
0.616212
5.751276
false
false
false
false
ios-ximen/DYZB
斗鱼直播/斗鱼直播/Classes/Home/Controllers/AmuseController.swift
1
1411
// // AmuseController.swift // 斗鱼直播 // // Created by niujinfeng on 2017/7/10. // Copyright © 2017年 niujinfeng. All rights reserved. // import UIKit fileprivate let KmenuViewH : CGFloat = 200 class AmuseController: BaseAnchorController { //mark: -模型数据 fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() //mark: -懒加载 fileprivate lazy var amuseMenuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMendView() menuView.frame = CGRect(x: 0, y: -KmenuViewH, width: KscreenWidth, height: KmenuViewH) return menuView }() } //设置ui extension AmuseController{ override func setUpUI() { //调用父类 super.setUpUI() //添加menuview collectionView.addSubview(amuseMenuView) //设置内边距 collectionView.contentInset = UIEdgeInsetsMake(KmenuViewH, 0, 0, 0) } } //mark: -加载数据 extension AmuseController{ override func loadData(){ //传递模型数据 baseVM = amuseVM amuseVM.loadAmuseData{ self.collectionView.reloadData() var tempGroups = self.amuseVM.anchorsGroup tempGroups.removeFirst() //传递数据 self.amuseMenuView.anchorGroup = tempGroups; //加载数据完成 self.loadDataFinished() } } }
mit
bac43dedcf5170b2831db7d55d1c85f8
24.882353
94
0.621212
4.385382
false
false
false
false
2794129697/-----mx
CoolXuePlayer/NetWorkHelper.swift
1
6432
// // NetWorkHelper.swift // CoolXuePlayer // // Created by lion-mac on 15/7/24. // Copyright (c) 2015年 lion-mac. All rights reserved. // import Foundation public class NetWorkHelper:NSObject{ //网络状态 public static var networkStatus:Int = 0 //网络是否正常 public static var is_network_ok:Bool = false //是否已经注册网络监测 private static var is_register_network_monitor:Bool = false private static var hostReachability:Reachability! private static var internetReachability:Reachability! private static var wifiReachability:Reachability! private static var observer:NetWorkHelper = NetWorkHelper() private override init(){ println("init") } //监测设备网络 public class func registerNetWorkMonitor(){ if !self.is_register_network_monitor { self.is_register_network_monitor = true NSNotificationCenter.defaultCenter().addObserver(observer, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil) self.hostReachability = Reachability(hostName: "www.apple.com") self.hostReachability.startNotifier() self.internetReachability = Reachability.reachabilityForInternetConnection() self.internetReachability.startNotifier() self.wifiReachability = Reachability.reachabilityForLocalWiFi() self.wifiReachability.startNotifier() println(self.hostReachability.currentReachabilityStatus().value) println(self.internetReachability.currentReachabilityStatus().value) println(self.wifiReachability.currentReachabilityStatus().value) if self.hostReachability.currentReachabilityStatus().value != 0 || self.internetReachability.currentReachabilityStatus().value != 0 || self.wifiReachability.currentReachabilityStatus().value != 0{ NetWorkHelper.is_network_ok = true } } } //设备网络环境发生变化时通知(不能写成私有方法) func reachabilityChanged(note:NSNotification){ println("reachabilityChanged") var curReach:Reachability = note.object as! Reachability var netStatus:NetworkStatus = curReach.currentReachabilityStatus() var connectionRequired = curReach.connectionRequired() var statusString = ""; println(netStatus.value) if netStatus.value == 0 { NetWorkHelper.is_network_ok = false println("没有可用网络!\(netStatus.value)") D3Notice.showText("没有可用网络!",time:D3Notice.longTime,autoClear:true) }else{ NetWorkHelper.is_network_ok = true println("网络已连接!\(netStatus.value)") //D3Notice.showText("网络已连接!\(netStatus.value)",time:D3Notice.longTime,autoClear:true) } switch netStatus.value { case 0: break; case 1: break; case 2: break; default: break; } if (connectionRequired){ println("%@, Connection Required"+"Concatenation of status string with connection requirement") } } } public enum IJReachabilityType { case WWAN, WiFi, NotConnected } public class IJReachability { /** :see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/ */ public class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } public class func isConnectedToNetworkOfType() -> IJReachabilityType { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return .NotConnected } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) != 0 //let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0 if(isReachable && isWWAN){ return .WWAN } if(isReachable && !isWWAN){ return .WiFi } return .NotConnected //let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 //return (isReachable && !needsConnection) ? true : false } public class func test(){ if IJReachability.isConnectedToNetwork() { println("Network Connection: Available") } else { println("Network Connection: Unavailable") } let statusType = IJReachability.isConnectedToNetworkOfType() switch statusType { case .WWAN: println("Connection Type: Mobile\n") case .WiFi: println("Connection Type: WiFi\n") case .NotConnected: println("Connection Type: Not connected to the Internet\n") } } }
lgpl-3.0
b41f431553651acaefa9d180a0a30e25
36.404762
208
0.625875
4.913213
false
false
false
false
CoderJackyHuang/SwiftExtensionCodes
SwiftExtensionCollection/ViewController.swift
1
2244
// // ViewController.swift // SwiftExtensionCollection // // Created by huangyibiao on 15/9/22. // Copyright © 2015年 huangyibiao. All rights reserved. // import UIKit class ViewController: UIViewController { var timer: NSTimer? override func viewDidLoad() { super.viewDidLoad() let string = " 就要去" print(string.hyb_length() == 5) print(string.hyb_trimLeft() == "就要去") let str = " \n 测试" print(str.hyb_trimLeft()) print(str.hyb_trimLeft(true)) print(" ".hyb_trim().hyb_length() == 0) print(" \n ".hyb_trimLeft(true).hyb_length() == 0) print("right ----------") print(" 去掉右边的空格 ".hyb_trimRight().hyb_length() == " 去掉右边的空格 ".hyb_length() - 4) print(" ".hyb_trimRight().hyb_length() == 0) print(" \n ".hyb_trimRight().hasSuffix("\n")) print(" \n ".hyb_trimRight(true).hyb_length() == 0) print("".hyb_trimRight().hyb_length() == 0) // print("after delay 4") // NSObject.hyb_delay(4) { () -> Void in //NSTimer.hyb_schedule(NSTimeInterval(0.1), repeats: true) { () -> Void in // print("111") // print("hyb_schdule(1, count: 2)") // } // // NSTimer.hyb_schdule(count: nil) { () -> Void in // print("nil count") // } // // // 可以省略 // NSTimer.hyb_schdule(count: 2) { // print("hehe") // } // self.hyb_showAlert("Thanks") // self.hyb_showOkAlert("Thanks") { () -> Void in // print("hehe") // } // self.hyb_showOkAlert("Thanks") { () -> Void in // print("hehe") // } // self.hyb_showAlert("Thanks", message: "hehe", buttonTitles: ["Left", "Right"]) { (index) -> Void in // print("\(index)") // } // self.hyb_okCancelDirection = .CancelOk // self.hyb_showAlert("cancel, ok") // self.hyb_showActionSheet("Thanks", message: "How to call with hyb_showActionSheet", cancel: "Cancel", destructive: "Destructive", otherTitles: "Beijing", "ShenZhen") { (index) -> Void in // print(index) // } self.hyb_showActionSheet("Thanks", message: "How to use", cancel: "Cancel", otherTitles: "First", "Second") { (index) -> Void in print(index) } } }
mit
39d17a4e3c3312638f23cf87197ba76d
28.186667
191
0.559159
3.040278
false
false
false
false
2794129697/-----mx
CoolXuePlayer/HTTPRequestSerializer.swift
1
11868
////////////////////////////////////////////////////////////////////////////////////////////////// // // HTTPRequestSerializer.swift // // Created by Dalton Cherry on 6/3/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation extension String { /** A simple extension to the String object to encode it for web request. :returns: Encoded version of of string it was called as. */ var escaped: String { return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,self,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as! String } } /// Default Serializer for serializing an object to an HTTP request. This applies to form serialization, parameter encoding, etc. public class HTTPRequestSerializer: NSObject { let contentTypeKey = "Content-Type" /// headers for the request. public var headers = Dictionary<String,String>() /// encoding for the request. public var stringEncoding: UInt = NSUTF8StringEncoding /// Send request if using cellular network or not. Defaults to true. public var allowsCellularAccess = true /// If the request should handle cookies of not. Defaults to true. public var HTTPShouldHandleCookies = true /// If the request should use piplining or not. Defaults to false. public var HTTPShouldUsePipelining = false /// How long the timeout interval is. Defaults to 60 seconds. public var timeoutInterval: NSTimeInterval = 60 /// Set the request cache policy. Defaults to UseProtocolCachePolicy. public var cachePolicy: NSURLRequestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy /// Set the network service. Defaults to NetworkServiceTypeDefault. public var networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeDefault /// Initializes a new HTTPRequestSerializer Object. public override init() { super.init() } /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :returns: A new NSMutableURLRequest with said options. */ public func newRequest(url: NSURL, method: HTTPMethod) -> NSMutableURLRequest { var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval) request.HTTPMethod = method.rawValue request.cachePolicy = self.cachePolicy request.timeoutInterval = self.timeoutInterval request.allowsCellularAccess = self.allowsCellularAccess request.HTTPShouldHandleCookies = self.HTTPShouldHandleCookies request.HTTPShouldUsePipelining = self.HTTPShouldUsePipelining request.networkServiceType = self.networkServiceType for (key,val) in self.headers { request.addValue(val, forHTTPHeaderField: key) } return request } /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A new NSMutableURLRequest with said options or an error. */ public func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) { var request = newRequest(url, method: method) var isMulti = false //do a check for upload objects to see if we are multi form if let params = parameters { isMulti = isMultiForm(params) } // if isMulti { // if(method != .POST && method != .PUT && method != .PATCH) { // request.HTTPMethod = HTTPMethod.POST.rawValue // you probably wanted a post // } // var boundary = "Boundary+\(arc4random())\(arc4random())" // if parameters != nil { // request.HTTPBody = dataFromParameters(parameters!,boundary: boundary) // } // if request.valueForHTTPHeaderField(contentTypeKey) == nil { // request.setValue("multipart/form-data; boundary=\(boundary)", // forHTTPHeaderField:contentTypeKey) // } // return (request,nil) // } var queryString = "" if parameters != nil { queryString = self.stringFromParameters(parameters!) } println("queryString=\(queryString)") if isURIParam(method) { var para = (request.URL!.query != nil) ? "&" : "?" var newUrl = "\(request.URL!.absoluteString!)" if count(queryString) > 0 { newUrl += "\(para)\(queryString)" } request.URL = NSURL(string: newUrl) } else { var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); if request.valueForHTTPHeaderField(contentTypeKey) == nil { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField:contentTypeKey) } request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding) } return (request,nil) } ///check for multi form objects public func isMultiForm(params: Dictionary<String,AnyObject>) -> Bool { for (name,object: AnyObject) in params { if object is HTTPUpload { return true } else if let subParams = object as? Dictionary<String,AnyObject> { if isMultiForm(subParams) { return true } } } return false } ///check if enum is a HTTPMethod that requires the params in the URL public func isURIParam(method: HTTPMethod) -> Bool { if(method == .GET || method == .HEAD || method == .DELETE) { return true } return false } ///convert the parameter dict to its HTTP string representation func stringFromParameters(parameters: Dictionary<String,AnyObject>) -> String { return join("&", map(serializeObject(parameters, key: nil), {(pair) in return pair.stringValue() })) } ///the method to serialized all the objects func serializeObject(object: AnyObject,key: String?) -> Array<HTTPPair> { var collect = Array<HTTPPair>() if let array = object as? Array<AnyObject> { for nestedValue : AnyObject in array { collect.extend(self.serializeObject(nestedValue,key: "\(key!)[]")) } } else if let dict = object as? Dictionary<String,AnyObject> { for (nestedKey, nestedObject: AnyObject) in dict { var newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey collect.extend(self.serializeObject(nestedObject,key: newKey)) } } else { collect.append(HTTPPair(value: object, key: key)) } return collect } //create a multi form data object of the parameters func dataFromParameters(parameters: Dictionary<String,AnyObject>,boundary: String) -> NSData { var mutData = NSMutableData() var multiCRLF = "\r\n" var boundSplit = "\(multiCRLF)--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)! var lastBound = "\(multiCRLF)--\(boundary)--\(multiCRLF)".dataUsingEncoding(self.stringEncoding)! mutData.appendData("--\(boundary)\(multiCRLF)".dataUsingEncoding(self.stringEncoding)!) let pairs = serializeObject(parameters, key: nil) let count = pairs.count-1 var i = 0 for pair in pairs { var append = true if let upload = pair.getUpload() { if let data = upload.data { mutData.appendData(multiFormHeader(pair.k, fileName: upload.fileName, type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(self.stringEncoding)!) mutData.appendData(data) } else { append = false } } else { let str = "\(multiFormHeader(pair.k, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.getValue())" mutData.appendData(str.dataUsingEncoding(self.stringEncoding)!) } if append { if i == count { mutData.appendData(lastBound) } else { mutData.appendData(boundSplit) } } i++ } return mutData } ///helper method to create the multi form headers func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String { var str = "Content-Disposition: form-data; name=\"\(name.escaped)\"" if fileName != nil { str += "; filename=\"\(fileName!)\"" } str += multiCRLF if type != nil { str += "Content-Type: \(type!)\(multiCRLF)" } str += multiCRLF return str } /// Creates key/pair of the parameters. class HTTPPair: NSObject { var val: AnyObject var k: String! init(value: AnyObject, key: String?) { self.val = value self.k = key } func getUpload() -> HTTPUpload? { return self.val as? HTTPUpload } func getValue() -> String { var val = "" if let str = self.val as? String { val = str } else if self.val.description != nil { val = self.val.description } return val } func stringValue() -> String { var v = getValue() if self.k == nil { return v.escaped } return "\(self.k.escaped)=\(v.escaped)" } } } /// JSON Serializer for serializing an object to an HTTP request. Same as HTTPRequestSerializer, expect instead of HTTP form encoding it does JSON. public class JSONRequestSerializer: HTTPRequestSerializer { /** Creates a new NSMutableURLRequest object with configured options. :param: url The url you would like to make a request to. :param: method The HTTP method/verb for the request. :param: parameters The parameters are HTTP parameters you would like to send. :returns: A new NSMutableURLRequest with said options or an error. */ public override func createRequest(url: NSURL, method: HTTPMethod, parameters: Dictionary<String,AnyObject>?) -> (request: NSURLRequest, error: NSError?) { if self.isURIParam(method) { return super.createRequest(url, method: method, parameters: parameters) } var request = newRequest(url, method: method) var error: NSError? if parameters != nil { var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: self.contentTypeKey) request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions(), error:&error) } return (request, error) } }
lgpl-3.0
8fdfcc87045891a7e7046649c31d9c12
40.351916
180
0.596225
5.221293
false
false
false
false
romankisil/eqMac2
native/app/Source/UI/UI.swift
1
11772
// // UI.swift // eqMac // // Created by Roman Kisil on 24/12/2018. // Copyright © 2018 Roman Kisil. All rights reserved. // import Foundation import ReSwift import Cocoa import EmitterKit import SwiftyUserDefaults import WebKit import Zip import SwiftHTTP import Shared enum UIMode: String, Codable { case window = "window" case popover = "popover" } extension UIMode { static let allValues = [ window.rawValue, popover.rawValue ] } class UI: StoreSubscriber { static var state: UIState { return Application.store.state.ui } static var minHeight: Double { return state.minHeight * scale } static var minWidth: Double { return state.minWidth * scale } static var maxHeight: Double { var maxHeight = (state.maxHeight ?? 4000) * scale if (maxHeight < minHeight) { maxHeight = minHeight } return maxHeight } static var maxWidth: Double { var maxWidth = (state.maxWidth ?? 4000) * scale if (maxWidth < minWidth) { maxWidth = minWidth } return maxWidth } static var height: Double { get { return window.height } set { window.height = newValue } } static var width: Double { get { return window.width } set { window.width = newValue } } static var scale: Double { return state.scale } static var minSize: NSSize { return NSSize( width: minWidth, height: minHeight ) } static var maxSize: NSSize { if isResizable { return NSSize( width: maxWidth, height: maxHeight ) } else { return minSize } } static var isResizable: Bool { return state.resizable } static var domain = Constants.UI_ENDPOINT_URL.host! static func unarchiveZip () { // Unpack Archive let fs = FileManager.default if fs.fileExists(atPath: remoteZipPath.path) { try! Zip.unzipFile(remoteZipPath, destination: localPath, overwrite: true, password: nil) // Unzip } else { if !fs.fileExists(atPath: localZipPath.path) { Console.log("\(localZipPath.path) doesnt exist") let bundleUIZipPath = Bundle.main.url(forResource: "ui", withExtension: "zip", subdirectory: "Embedded")! try! fs.copyItem(at: bundleUIZipPath, to: localZipPath) } try! Zip.unzipFile(localZipPath, destination: localPath, overwrite: true, password: nil) // Unzip } } static var localZipPath: URL { return Application.supportPath.appendingPathComponent( "ui-\(Application.version) (Local).zip", isDirectory: false ) } static var remoteZipPath: URL { return Application.supportPath.appendingPathComponent( "ui-\(Application.version) (Remote).zip", isDirectory: false ) } static var localPath: URL { return Application.supportPath.appendingPathComponent("ui") } static let statusItem = StatusItem() static let storyboard = NSStoryboard(name: "Main", bundle: Bundle.main) static var windowController: NSWindowController = ( storyboard.instantiateController( withIdentifier: "EQMWindowController" ) as! NSWindowController) static var window: Window = (windowController.window! as! Window) static var viewController = ( storyboard.instantiateController( withIdentifier: "EQMViewController" ) as! ViewController) static var cachedIsShown: Bool = false static var isShownChanged = Event<Bool>() static var isShown: Bool { return window.isShown } static var mode: UIMode = .window { willSet { DispatchQueue.main.async { window.becomeFirstResponder() if (!duringInit) { show() } } } } static var alwaysOnTop = false { didSet { DispatchQueue.main.async { if alwaysOnTop { window.level = .floating } else { window.level = .normal } } } } static var canHide: Bool { get { return window.canHide } set { window.canHide = newValue } } static func toggle () { DispatchQueue.main.async { if isShown { close() } else { show() } } } static func show () { DispatchQueue.main.async { if mode == .popover { // If mode is Popover move the window to where the Popover would be if let frame = statusItem.item.button?.window?.frame { var point = frame.origin point.x = point.x - window.frame.width / 2 + frame.width / 2 point.y -= 10 window.setFrameOrigin(point) } } window.show() NSApp.activate(ignoringOtherApps: true) } } static func close () { DispatchQueue.main.async { window.close() NSApp.hide(self) } } static func hide () { DispatchQueue.main.async { if mode == .popover { close() } else { window.performMiniaturize(nil) } } } // Instance static var statusItemClickedListener: EventListener<Void>! static var bridge: Bridge! static var duringInit = true init (_ completion: @escaping () -> Void) { DispatchQueue.main.async { func setup () { ({ UI.mode = Application.store.state.ui.mode UI.alwaysOnTop = Application.store.state.ui.alwaysOnTop UI.width = Application.store.state.ui.width UI.height = Application.store.state.ui.height UI.statusItem.iconType = Application.store.state.ui.statusItemIconType })() UI.window.contentViewController = UI.viewController // Set window position to where it was last time, in case that position is not available anymore - reset. if var windowPosition = Application.store.state.ui.windowPosition { var withinBounds = false for screen in NSScreen.screens { if NSPointInRect(windowPosition, screen.frame) { withinBounds = true break } } if (!withinBounds) { if let mainScreen = NSScreen.screens.first { let screenSize = mainScreen.frame.size windowPosition.x = screenSize.width / 2 - CGFloat(UI.width / 2) windowPosition.y = screenSize.height / 2 - CGFloat(UI.height / 2) } else { windowPosition.x = 0 windowPosition.y = 0 } } UI.window.position = windowPosition Application.dispatchAction(UIAction.setWindowPosition(windowPosition)) } UI.close() self.setupStateListener() UI.setupBridge() UI.setupListeners() UI.load() func checkIfVisible () { let shown = UI.isShown if (UI.cachedIsShown != shown) { UI.cachedIsShown = shown UI.isShownChanged.emit(shown) } Async.delay(1000) { checkIfVisible() } } checkIfVisible() completion() Async.delay(1000) { UI.duringInit = false } } if (!UI.viewController.isViewLoaded) { UI.viewController.loaded.once { setup() } let _ = UI.viewController.view } else { setup() } } } static func reload () { viewController.webView.reload() } static func setupBridge () { bridge = Bridge(webView: viewController.webView) } // MARK: - State public typealias StoreSubscriberStateType = UIState private func setupStateListener () { Application.store.subscribe(self) { subscription in subscription.select { state in state.ui } } } func newState(state: UIState) { DispatchQueue.main.async { if (state.mode != UI.mode) { UI.mode = state.mode } if (state.alwaysOnTop != UI.alwaysOnTop) { UI.alwaysOnTop = state.alwaysOnTop } if (state.statusItemIconType != UI.statusItem.iconType) { UI.statusItem.iconType = state.statusItemIconType } if (state.height != UI.height && state.fromUI) { UI.height = state.height } if (state.width != UI.width && state.fromUI) { UI.width = state.width } UI.checkFixWindowSize() } } private static func checkFixWindowSize () { if (UI.height < Double(UI.minSize.height)) { UI.height = Double(UI.minSize.height) } if (UI.height > Double(UI.maxSize.height)) { UI.height = Double(UI.maxSize.height) } if (UI.width < Double(UI.minSize.width)) { UI.width = Double(UI.minSize.width) } if (UI.width > Double(UI.maxSize.width)) { UI.width = Double(UI.maxSize.width) } } private static func setupListeners () { statusItemClickedListener = statusItem.clicked.on {_ in toggle() } } static var hasLoaded = false static var loaded = Event<Void>() static func whenLoaded (_ completion: @escaping () -> Void) { if hasLoaded { return completion() } loaded.once { completion() } } private static func load () { hasLoaded = false func startUILoad (_ url: URL) { DispatchQueue.main.async { viewController.load(url) } } func loadRemote () { Console.log("Loading Remote UI") startUILoad(Constants.UI_ENDPOINT_URL) self.getRemoteVersion { remoteVersion in if remoteVersion != nil { let fs = FileManager.default if fs.fileExists(atPath: remoteZipPath.path) { unarchiveZip() let currentVersion = try? String(contentsOf: localPath.appendingPathComponent("version.txt")) if (currentVersion?.trim() != remoteVersion?.trim()) { self.cacheRemote() } } else { self.cacheRemote() } } } } func loadLocal () { Console.log("Loading Local UI") unarchiveZip() let url = URL(string: "\(localPath)/index.html")! startUILoad(url) } if (Application.store.state.settings.doOTAUpdates) { remoteIsReachable() { reachable in if reachable { loadRemote() } else { loadLocal() } } } else { loadLocal() } } private static func getRemoteVersion (_ completion: @escaping (String?) -> Void) { HTTP.GET("\(Constants.UI_ENDPOINT_URL)/version.txt") { resp in completion(resp.error != nil ? nil : resp.text?.trim()) } } private static func remoteIsReachable (_ completion: @escaping (Bool) -> Void) { var returned = false Networking.checkConnected { reachable in if (!reachable) { returned = true return completion(false) } HTTP.GET(Constants.UI_ENDPOINT_URL.absoluteString) { response in returned = true completion(response.error == nil) } } Async.delay(1000) { if (!returned) { returned = true completion(false) } } } private static func cacheRemote () { // Only download ui.zip when UI endpoint is remote if Constants.UI_ENDPOINT_URL.absoluteString.contains(Constants.DOMAIN) { let remoteZipUrl = "\(Constants.UI_ENDPOINT_URL)/ui.zip" Console.log("Caching Remote UI from \(remoteZipUrl)") let download = HTTP(URLRequest(urlString: remoteZipUrl)!) download.run() { resp in Console.log("Finished caching Remote UI") if resp.error == nil { do { try resp.data.write(to: remoteZipPath, options: .atomic) } catch { print(error) } } } } } deinit { Application.store.unsubscribe(self) } }
mit
8418b18049f710edd464843000bb6fbf
22.876268
113
0.595531
4.343542
false
false
false
false
adamkaplan/swifter
SwifterTests/LinkedListTests.swift
1
2301
// // LinkedListTests.swift // Swifter // // Created by Daniel Hanggi on 6/26/14. // Copyright (c) 2014 Yahoo!. All rights reserved. // import XCTest class LinkedListTests: XCTestCase { func testInit() { let l1 = LinkedList(this: 10) XCTAssertEqual(l1.this!, 10) XCTAssertNil(l1.next) XCTAssertNil(l1.prev) } func testPush() { let l1 = LinkedList(this: "Cat") l1.push("Kitten") XCTAssertEqual(l1.this!, "Kitten") XCTAssertEqual(l1.next!.this!, "Cat") XCTAssertEqual(l1.next!.prev!.this!, "Kitten") XCTAssertNil(l1.next!.next) XCTAssertNil(l1.prev) } func testPop() { let l1 = LinkedList(this: "Cat") l1.push("Kitten") l1.push("Kitty") XCTAssertEqual(l1.pop()!, "Kitty") XCTAssertEqual(l1.next!.prev!.this!, "Kitten") XCTAssertEqual(l1.this!, "Kitten") XCTAssertEqual(l1.next!.this!, "Cat") XCTAssertNil(l1.next!.next) XCTAssertNil(l1.prev) } func testAppend1() -> () { let l1 = LinkedList(this: "Cat") let l2 = LinkedList(this: "Kitty") l2.append("Kitten") XCTAssertEqual(l2.this!, "Kitty") XCTAssertEqual(l2.next!.this!, "Kitten") XCTAssertEqual(l2.next!.prev!.this!, "Kitty") l1.append(l2) XCTAssertEqual(l1.this!, "Cat") XCTAssertEqual(l1.next!.this!, "Kitty") XCTAssertEqual(l1.next!.prev!.this!, "Cat") XCTAssertEqual(l1.next!.next!.this!, "Kitten") XCTAssertNil(l1.next!.next!.next) } func testIsEmpty() { let l1 = LinkedList<Int>() XCTAssertTrue(l1.isEmpty()) let l2 = LinkedList(this: 10) XCTAssertFalse(l2.isEmpty()) l2.pop() XCTAssertTrue(l2.isEmpty()) } func testSequence() { let l1 = LinkedList<Int>() l1.push(3) l1.push(2) l1.push(1) l1.push(0) var counter = 0 // for i in l1 { // XCTAssertEqual(i, counter++) // } XCTAssertEqual(l1.pop()!, 0) XCTAssertEqual(l1.pop()!, 1) XCTAssertEqual(l1.pop()!, 2) XCTAssertEqual(l1.pop()!, 3) XCTAssertTrue(l1.isEmpty()) } }
apache-2.0
00b2e86d754712abef22e5cf4e1ef365
25.755814
54
0.543677
3.658188
false
true
false
false
AaronMT/firefox-ios
Client/Frontend/Widgets/OneLineCell.swift
8
2163
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit struct OneLineCellUX { static let ImageSize: CGFloat = 29 static let ImageCornerRadius: CGFloat = 6 static let HorizontalMargin: CGFloat = 16 } class OneLineTableViewCell: UITableViewCell, Themeable { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.separatorInset = .zero self.applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let indentation = CGFloat(indentationLevel) * indentationWidth imageView?.translatesAutoresizingMaskIntoConstraints = true imageView?.contentMode = .scaleAspectFill imageView?.layer.cornerRadius = OneLineCellUX.ImageCornerRadius imageView?.layer.masksToBounds = true imageView?.snp.remakeConstraints { make in guard let _ = imageView?.superview else { return } make.width.height.equalTo(OneLineCellUX.ImageSize) make.leading.equalTo(indentation + OneLineCellUX.HorizontalMargin) make.centerY.equalToSuperview() } textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel textLabel?.snp.remakeConstraints { make in guard let _ = textLabel?.superview else { return } make.leading.equalTo(indentation + OneLineCellUX.ImageSize + OneLineCellUX.HorizontalMargin*2) make.trailing.equalTo(isEditing ? 0 : -OneLineCellUX.HorizontalMargin) make.centerY.equalToSuperview() } } override func prepareForReuse() { super.prepareForReuse() self.applyTheme() } func applyTheme() { backgroundColor = UIColor.theme.tableView.rowBackground textLabel?.textColor = UIColor.theme.tableView.rowText } }
mpl-2.0
92447c4dc63e095c6925561f7f65b472
33.887097
106
0.686084
5.125592
false
false
false
false