repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
DanielAsher/VIPER-SWIFT
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift
2
8916
// // GitHubSearchRepositoriesAPI.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /** Parsed GitHub respository. */ struct Repository: CustomDebugStringConvertible { var name: String var url: String init(name: String, url: String) { self.name = name self.url = url } } extension Repository { var debugDescription: String { return "\(name) | \(url)" } } /** ServiceState state. */ enum ServiceState { case Online case Offline } /** Raw response from GitHub API */ enum SearchRepositoryResponse { /** New repositories just fetched */ case Repositories(repositories: [Repository], nextURL: NSURL?) /** In case there was some problem fetching data from service, this will be returned. It really doesn't matter if that is a failure in network layer, parsing error or something else. In case data can't be read and parsed properly, something is wrong with server response. */ case ServiceOffline /** This example uses unauthenticated GitHub API. That API does have throttling policy and you won't be able to make more then 10 requests per minute. That is actually an awesome scenario to demonstrate complex retries using alert views and combination of timers. Just search like mad, and everything will be handled right. */ case LimitExceeded } /** This is the final result of loading. Crème de la crème. */ struct RepositoriesState { /** List of parsed repositories ready to be shown in the UI. */ let repositories: [Repository] /** Current network state. */ let serviceState: ServiceState? /** Limit exceeded */ let limitExceeded: Bool static let empty = RepositoriesState(repositories: [], serviceState: nil, limitExceeded: false) } class GitHubSearchRepositoriesAPI { static let sharedAPI = GitHubSearchRepositoriesAPI(wireframe: DefaultWireframe()) let activityIndicator = ActivityIndicator() // Why would network service have wireframe service? It's here to abstract promting user // Do we really want to make this example project factory/fascade/service competition? :) private let _wireframe: Wireframe private init(wireframe: Wireframe) { _wireframe = wireframe } } // MARK: Pagination extension GitHubSearchRepositoriesAPI { /** Public fascade for search. */ func search(query: String, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> { let escapedQuery = query.URLEscaped let url = NSURL(string: "https://api.github.com/search/repositories?q=\(escapedQuery)")! return recursivelySearch([], loadNextURL: url, loadNextPageTrigger: loadNextPageTrigger) // Here we go again .startWith(RepositoriesState.empty) } private func recursivelySearch(loadedSoFar: [Repository], loadNextURL: NSURL, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> { return loadSearchURL(loadNextURL).flatMap { searchResponse -> Observable<RepositoriesState> in switch searchResponse { /** If service is offline, that's ok, that means that this isn't the last thing we've heard from that API. It will retry until either battery drains, you become angry and close the app or evil machine comes back from the future, steals your device and Googles Sarah Connor's address. */ case .ServiceOffline: return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .Offline, limitExceeded: false)) case .LimitExceeded: return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .Online, limitExceeded: true)) case let .Repositories(newPageRepositories, maybeNextURL): var loadedRepositories = loadedSoFar loadedRepositories.appendContentsOf(newPageRepositories) let appenedRepositories = RepositoriesState(repositories: loadedRepositories, serviceState: .Online, limitExceeded: false) // if next page can't be loaded, just return what was loaded, and stop guard let nextURL = maybeNextURL else { return Observable.just(appenedRepositories) } return [ // return loaded immediately Observable.just(appenedRepositories), // wait until next page can be loaded Observable.never().takeUntil(loadNextPageTrigger), // load next page self.recursivelySearch(loadedRepositories, loadNextURL: nextURL, loadNextPageTrigger: loadNextPageTrigger) ].concat() } } } private func loadSearchURL(searchURL: NSURL) -> Observable<SearchRepositoryResponse> { return NSURLSession.sharedSession() .rx_response(NSURLRequest(URL: searchURL)) .retry(3) .trackActivity(self.activityIndicator) .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { data, httpResponse -> SearchRepositoryResponse in if httpResponse.statusCode == 403 { return .LimitExceeded } let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data) guard let json = jsonRoot as? [String: AnyObject] else { throw exampleError("Casting to dictionary failed") } let repositories = try GitHubSearchRepositoriesAPI.parseRepositories(json) let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse) return .Repositories(repositories: repositories, nextURL: nextURL) } .retryOnBecomesReachable(.ServiceOffline, reachabilityService: ReachabilityService.sharedReachabilityService) } } // MARK: Parsing the response extension GitHubSearchRepositoriesAPI { private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\"" private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.AllowCommentsAndWhitespace]) private static func parseLinks(links: String) throws -> [String: String] { let length = (links as NSString).length let matches = GitHubSearchRepositoriesAPI.linksRegex.matchesInString(links, options: NSMatchingOptions(), range: NSRange(location: 0, length: length)) var result: [String: String] = [:] for m in matches { let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in let range = m.rangeAtIndex(rangeIndex) let startIndex = links.startIndex.advancedBy(range.location) let endIndex = startIndex.advancedBy(range.length) let stringRange = startIndex ..< endIndex return links.substringWithRange(stringRange) } if matches.count != 2 { throw exampleError("Error parsing links") } result[matches[1]] = matches[0] } return result } private static func parseNextURL(httpResponse: NSHTTPURLResponse) throws -> NSURL? { guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else { return nil } let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks) guard let nextPageURL = links["next"] else { return nil } guard let nextUrl = NSURL(string: nextPageURL) else { throw exampleError("Error parsing next url `\(nextPageURL)`") } return nextUrl } private static func parseJSON(httpResponse: NSHTTPURLResponse, data: NSData) throws -> AnyObject { if !(200 ..< 300 ~= httpResponse.statusCode) { throw exampleError("Call failed") } return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: []) } private static func parseRepositories(json: [String: AnyObject]) throws -> [Repository] { guard let items = json["items"] as? [[String: AnyObject]] else { throw exampleError("Can't find items") } return try items.map { item in guard let name = item["name"] as? String, url = item["url"] as? String else { throw exampleError("Can't parse repository") } return Repository(name: name, url: url) } } }
mit
95ca50e84b158745f472e19db223aba7
33.680934
158
0.641198
5.163963
false
false
false
false
GabrielMassana/ButtonBackgroundColor-iOS
ButtonBackgroundColor-iOS/UIButton+ButtonBackgroundColor.swift
1
3338
// // UIButton+ButtonBackgroundColor.swift // ButtonBackgroundColor // // Created by GabrielMassana on 12/04/2016. // Copyright © 2016 GabrielMassana. All rights reserved. // import UIKit import ObjectiveC /// Key for a normal backgroundColor. var BackgroundColorNormal = "BackgroundColorNormal" /// Key for a highlighted backgroundColor. var BackgroundColorHighlighted = "BackgroundColorHighlighted" /// Extension to handle the background color of a UIButton in normal and highlighted state. public extension UIButton { //MARK: ButtonBackgroundColor /** Sets the background colors to use in normal and highlighted button state. - parameter normal: the color for a normal state. - parameter highlighted: the color for a highlighted state. */ @objc(bbc_backgroundColorNormal:backgroundColorHighlighted:) public func backgroundColorForStates(normal: UIColor, highlighted: UIColor) { //set normal background color backgroundColor = normal //handle states addTarget(self, action:#selector(UIButton.buttonTouchUpInside(_:)), for:.touchUpInside) addTarget(self, action:#selector(UIButton.buttonTouchUpOutside(_:)), for:.touchUpOutside) addTarget(self, action:#selector(UIButton.buttonTouchDown(_:)), for:.touchDown) addTarget(self, action:#selector(UIButton.buttonTouchCancel(_:)), for:.touchCancel) //store colors objc_setAssociatedObject(self, &BackgroundColorNormal, normal, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) objc_setAssociatedObject(self, &BackgroundColorHighlighted, highlighted, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } //MARK: Getters /** The color for a normal state. returns: The normal background color */ public func normalBackgroundColor() -> UIColor? { return objc_getAssociatedObject(self, &BackgroundColorNormal) as? UIColor } /** The color for a highlighted state. returns: The highlighted background color. */ public func highlightedBackgroundColor() -> UIColor? { return objc_getAssociatedObject(self, &BackgroundColorHighlighted) as? UIColor } //MARK: ButtonActions /** The button updates the background color after a Control Event TouchUpInside. - parameter sender: the button. */ func buttonTouchUpInside(_ sender: UIButton) { sender.backgroundColor = normalBackgroundColor() } /** The button updates the background color after a Control Event TouchUpOutside. - parameter sender: the button. */ func buttonTouchUpOutside(_ sender: UIButton) { sender.backgroundColor = normalBackgroundColor() } /** The button updates the background color after a Control Event TouchDown. - parameter sender: the button. */ func buttonTouchDown(_ sender: UIButton) { sender.backgroundColor = highlightedBackgroundColor() } /** The button updates the background color after a Control Event TouchCancel. - parameter sender: the button. */ func buttonTouchCancel(_ sender: UIButton) { sender.backgroundColor = normalBackgroundColor() } }
mit
3aab6801d6cabfc32221702c986cb401
29.614679
138
0.686245
5.296825
false
false
false
false
reterVision/TinderSwipeCardsSwift
TinderSwipeCardsSwift/DraggableView.swift
1
6251
// // DraggableView.swift // TinderSwipeCardsSwift // // Created by Gao Chao on 4/30/15. // Copyright (c) 2015 gcweb. All rights reserved. // import Foundation import UIKit let ACTION_MARGIN: Float = 120 //%%% distance from center where the action applies. Higher = swipe further in order for the action to be called let SCALE_STRENGTH: Float = 4 //%%% how quickly the card shrinks. Higher = slower shrinking let SCALE_MAX:Float = 0.93 //%%% upper bar for how much the card shrinks. Higher = shrinks less let ROTATION_MAX: Float = 1 //%%% the maximum rotation allowed in radians. Higher = card can keep rotating longer let ROTATION_STRENGTH: Float = 320 //%%% strength of rotation. Higher = weaker rotation let ROTATION_ANGLE: Float = 3.14/8 //%%% Higher = stronger rotation angle protocol DraggableViewDelegate { func cardSwipedLeft(card: UIView) -> Void func cardSwipedRight(card: UIView) -> Void } class DraggableView: UIView { var delegate: DraggableViewDelegate! var panGestureRecognizer: UIPanGestureRecognizer! var originPoint: CGPoint! var overlayView: OverlayView! var information: UILabel! var xFromCenter: Float! var yFromCenter: Float! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.setupView() information = UILabel(frame: CGRectMake(0, 50, self.frame.size.width, 100)) information.text = "no info given" information.textAlignment = NSTextAlignment.Center information.textColor = UIColor.blackColor() self.backgroundColor = UIColor.whiteColor() panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "beingDragged:") self.addGestureRecognizer(panGestureRecognizer) self.addSubview(information) overlayView = OverlayView(frame: CGRectMake(self.frame.size.width/2-100, 0, 100, 100)) overlayView.alpha = 0 self.addSubview(overlayView) xFromCenter = 0 yFromCenter = 0 } func setupView() -> Void { self.layer.cornerRadius = 4; self.layer.shadowRadius = 3; self.layer.shadowOpacity = 0.2; self.layer.shadowOffset = CGSizeMake(1, 1); } func beingDragged(gestureRecognizer: UIPanGestureRecognizer) -> Void { xFromCenter = Float(gestureRecognizer.translationInView(self).x) yFromCenter = Float(gestureRecognizer.translationInView(self).y) switch gestureRecognizer.state { case UIGestureRecognizerState.Began: self.originPoint = self.center case UIGestureRecognizerState.Changed: let rotationStrength: Float = min(xFromCenter/ROTATION_STRENGTH, ROTATION_MAX) let rotationAngle = ROTATION_ANGLE * rotationStrength let scale = max(1 - fabsf(rotationStrength) / SCALE_STRENGTH, SCALE_MAX) self.center = CGPointMake(self.originPoint.x + CGFloat(xFromCenter), self.originPoint.y + CGFloat(yFromCenter)) let transform = CGAffineTransformMakeRotation(CGFloat(rotationAngle)) let scaleTransform = CGAffineTransformScale(transform, CGFloat(scale), CGFloat(scale)) self.transform = scaleTransform self.updateOverlay(CGFloat(xFromCenter)) case UIGestureRecognizerState.Ended: self.afterSwipeAction() case UIGestureRecognizerState.Possible: fallthrough case UIGestureRecognizerState.Cancelled: fallthrough case UIGestureRecognizerState.Failed: fallthrough default: break } } func updateOverlay(distance: CGFloat) -> Void { if distance > 0 { overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeRight) } else { overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeLeft) } overlayView.alpha = CGFloat(min(fabsf(Float(distance))/100, 0.4)) } func afterSwipeAction() -> Void { let floatXFromCenter = Float(xFromCenter) if floatXFromCenter > ACTION_MARGIN { self.rightAction() } else if floatXFromCenter < -ACTION_MARGIN { self.leftAction() } else { UIView.animateWithDuration(0.3, animations: {() -> Void in self.center = self.originPoint self.transform = CGAffineTransformMakeRotation(0) self.overlayView.alpha = 0 }) } } func rightAction() -> Void { let finishPoint: CGPoint = CGPointMake(500, 2 * CGFloat(yFromCenter) + self.originPoint.y) UIView.animateWithDuration(0.3, animations: { self.center = finishPoint }, completion: { (value: Bool) in self.removeFromSuperview() }) delegate.cardSwipedRight(self) } func leftAction() -> Void { let finishPoint: CGPoint = CGPointMake(-500, 2 * CGFloat(yFromCenter) + self.originPoint.y) UIView.animateWithDuration(0.3, animations: { self.center = finishPoint }, completion: { (value: Bool) in self.removeFromSuperview() }) delegate.cardSwipedLeft(self) } func rightClickAction() -> Void { let finishPoint = CGPointMake(600, self.center.y) UIView.animateWithDuration(0.3, animations: { self.center = finishPoint self.transform = CGAffineTransformMakeRotation(1) }, completion: { (value: Bool) in self.removeFromSuperview() }) delegate.cardSwipedRight(self) } func leftClickAction() -> Void { let finishPoint: CGPoint = CGPointMake(-600, self.center.y) UIView.animateWithDuration(0.3, animations: { self.center = finishPoint self.transform = CGAffineTransformMakeRotation(1) }, completion: { (value: Bool) in self.removeFromSuperview() }) delegate.cardSwipedLeft(self) } }
mit
249654e95bc5aaf7cef391863e2f434e
35.138728
148
0.62758
4.918175
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Home/UpcomingItemsCollectionViewCell.swift
1
4320
// // Copyright (c) 2019 Google Inc. // // 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 public class UpcomingItemsCollectionViewCell: UICollectionViewCell { static var cellHeight: CGFloat { return UpcomingItemCollectionViewCell.cellSize.height + 16 } public lazy private(set) var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = UpcomingItemCollectionViewCell.cellSize layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) let collectionView = UICollectionView(frame: contentView.frame, collectionViewLayout: layout) collectionView.contentInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8) collectionView.backgroundColor = .clear collectionView.register( UpcomingItemCollectionViewCell.self, forCellWithReuseIdentifier: UpcomingItemCollectionViewCell.reuseIdentifier() ) return collectionView }() public override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(collectionView) setupConstraints() } private var upcomingItemsDataSource: UpcomingItemsDataSource? private lazy var emptyItemsView = EmptyItemsBackgroundView(frame: contentView.bounds) public func populate(upcomingItems: UpcomingItemsDataSource) { upcomingItems.reloadData() upcomingItemsDataSource = upcomingItems collectionView.dataSource = upcomingItems collectionView.delegate = upcomingItems collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.reloadData() upcomingItems.updateHandler = { dataSource in if dataSource.isEmpty { self.showEmptyItemsView(dataSource: dataSource) } else { self.hideEmptyItemsView() } self.collectionView.reloadData() } } func showEmptyItemsView(dataSource: UpcomingItemsDataSource) { emptyItemsView.navigator = dataSource.rootNavigator collectionView.backgroundView = emptyItemsView } func hideEmptyItemsView() { collectionView.backgroundView = nil emptyItemsView.removeFromSuperview() } public override func prepareForReuse() { collectionView.dataSource = nil upcomingItemsDataSource?.updateHandler = nil upcomingItemsDataSource = nil } private func setupConstraints() { let constraints: [NSLayoutConstraint] = [ NSLayoutConstraint(item: collectionView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: collectionView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: collectionView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: 0), NSLayoutConstraint(item: collectionView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0) ] contentView.addConstraints(constraints) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f8cfa3348ebf7f2ef6fc0abe9ecf5c35
34.121951
97
0.643981
5.517241
false
false
false
false
couchbase/couchbase-lite-ios
Swift/Ordering.swift
1
3412
// // Ordering.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc 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 /// Ordering represents a single ordering component in the query ORDER BY clause. public protocol OrderingProtocol { } @available(*, deprecated, message: "Please use QuerySortOrder") typealias SortOrder = QuerySortOrder /// SortOrder allows to specify the ordering direction which is ascending or /// descending order. The default ordering is the ascending order. public protocol QuerySortOrder: OrderingProtocol { /// Specifies ascending order. /// /// - Returns: The ascending Ordering object. func ascending() -> OrderingProtocol /// Specifies descending order. /// /// - Returns: The descending Ordering object. func descending() -> OrderingProtocol } /// Ordering factory. public final class Ordering { /// Create an Ordering instance with the given property name. /// /// - Parameter property: The property name. /// - Returns: The SortOrder object used for specifying the sort order, /// ascending or descending order. public static func property(_ property: String) -> QuerySortOrder { return expression(Expression.property(property)) } /// Create an Ordering instance with the given expression. /// /// - Parameter expression: The Expression object. /// - Returns: The SortOrder object used for specifying the sort order, /// ascending or descending order. public static func expression(_ expression: ExpressionProtocol) -> QuerySortOrder { let sortOrder = CBLQueryOrdering.expression(expression.toImpl()) return _QuerySortOrder(impl: sortOrder) } } /* internal */ class QueryOrdering : OrderingProtocol { let impl: CBLQueryOrdering init(impl: CBLQueryOrdering) { self.impl = impl } func toImpl() -> CBLQueryOrdering { return self.impl } static func toImpl(orderings: [OrderingProtocol]) -> [CBLQueryOrdering] { var impls: [CBLQueryOrdering] = [] for o in orderings { impls.append(o.toImpl()) } return impls; } } /* internal */ class _QuerySortOrder: QueryOrdering, QuerySortOrder { public func ascending() -> OrderingProtocol { let o = self.impl as! CBLQuerySortOrder return QueryOrdering(impl: o.ascending()) } public func descending() -> OrderingProtocol { let o = self.impl as! CBLQuerySortOrder return QueryOrdering(impl: o.descending()) } } extension OrderingProtocol { func toImpl() -> CBLQueryOrdering { if let o = self as? QueryOrdering { return o.toImpl() } fatalError("Unsupported ordering.") } }
apache-2.0
cdfb81e8080256687ee74d5f0d41c812
28.413793
87
0.661782
4.667579
false
false
false
false
jsilverMDX/GlobalChat2
GlobalChat Swift OS X/GlobalChat/PrivateMessageController.swift
1
2291
// // PrivateMessageController.swift // GlobalChat // // Created by Jonathan Silverman on 7/5/20. // Copyright © 2020 Jonathan Silverman. All rights reserved. // import Cocoa class PrivateMessageController: NSViewController, NSTextFieldDelegate { @IBOutlet weak var scroll_view: NSScrollView! @IBOutlet weak var pm_window_text: NSTextView! @IBOutlet weak var chat_message: NSTextField! var handle : String = "" // their handle var gcc: GlobalChatController? var pm_buffer : String = "" override func viewDidLoad() { super.viewDidLoad() // Do view setup here. print("pm window loaded \(gcc!.handle) and \(handle)") chat_message.delegate = self } @IBAction func sendMessage(_ sender: NSTextField) { print("sendMessage:") let message = sender.stringValue if message == "" { return } if message.components(separatedBy: " ").first?.prefix(1) != "/" { gcc!.priv_msg(handle, message: message) } else { gcc!.run_command(message) } chat_message.stringValue = "" } func output_to_chat_window(_ str: String) { self.pm_buffer = self.pm_buffer + str update_and_scroll() } func update_and_scroll() { parse_links() update_chat_views() } func parse_links() { self.pm_window_text.isEditable = true self.pm_window_text.isAutomaticLinkDetectionEnabled = true self.pm_window_text.textStorage!.setAttributedString(NSAttributedString.init(string: self.pm_buffer)) if self.gcc!.osxMode == "Dark" { self.pm_window_text.textColor = NSColor.white } self.pm_window_text.checkTextInDocument(nil) self.pm_window_text.isEditable = false } func update_chat_views() { //let frame_height = self.scroll_view.documentView!.frame.size.height //let content_size = self.scroll_view.contentSize.height let y = self.pm_window_text.string.count self.scroll_view.drawsBackground = false self.pm_window_text.scrollRangeToVisible(NSRange.init(location: y, length: 0)) self.scroll_view.reflectScrolledClipView(self.scroll_view.contentView) } }
gpl-3.0
b6b19998b3da885bb3974b6319b10e4b
30.805556
109
0.627074
4.103943
false
false
false
false
Zewo/System
Sources/POSIX/Thread.swift
6
4135
#if os(Linux) import Glibc #else import Darwin.C #endif public enum ThreadError: Error { case notEnoughResources case invalidReturnValue } /// A wrapper for the POSIX pthread_t type. public final class PThread<T> { internal let thread: pthread_t private let context: ThreadContext private let keepAlive: Bool public var done: Bool { return context.done } /** Creates a new thread which immediately begins executing the passed routine. - parameter keepAlive: A boolean determining whether the thread execution should be canceled upon deinitialization of the created instance. Defaults to true. - parameter routine: A closure which is executed on a new thread. Errors thrown in the routine are thrown in the `join` method. - remarks: The routine can return `Void`, which is useful when there is need for a result. */ public init(keepAlive: Bool = true, routine: @escaping () throws -> (T)) throws { let context = ThreadContext(routine: routine) #if os(Linux) let pthreadPointer = UnsafeMutablePointer<pthread_t>.allocate(capacity: 1) defer { pthreadPointer.deallocate(capacity: 1) } #else let pthreadPointer = UnsafeMutablePointer<pthread_t?>.allocate(capacity: 1) defer { pthreadPointer.deallocate(capacity: 1) } #endif let result = pthread_create( pthreadPointer, nil, // default attributes pthreadRunner, encode(context) ) if result == EAGAIN { throw ThreadError.notEnoughResources } #if os(Linux) self.thread = pthreadPointer.pointee #else self.thread = pthreadPointer.pointee! #endif self.context = context self.keepAlive = keepAlive } deinit { pthread_detach(thread) if !keepAlive { abort() } } /** Suspends execution until the thread's routine has finished executing. - returns: Returns the result of the routine. */ public func wait() throws -> T { var _out: UnsafeMutableRawPointer? pthread_join(thread, &_out) guard let out = _out else { throw ThreadError.invalidReturnValue } let result: Result<T> = decode(out) switch result { case .success(let t): return t case .failure(let e): throw e } } /** Stops the execution of the thread. - note: Cancelling only takes place after the cleanup (asynchronous) has finished. */ public func abort() { pthread_cancel(thread) } } private enum Result<T> { case success(T) case failure(Error) init(of routine: () throws -> T) { do { self = try .success(routine()) } catch { self = .failure(error) } } } private final class ThreadContext { var done = false let routine: () -> UnsafeMutableRawPointer? init<T>(routine: @escaping () throws -> T) { self.routine = { return encode(Result(of: routine)) } } } private final class Box<T> { let value: T init(_ value: T) { self.value = value } } private func decode<T>(_ memory: UnsafeMutableRawPointer) -> T { // TODO: find a way to handle errors here let unmanaged = Unmanaged<Box<T>>.fromOpaque(memory) defer { unmanaged.release() } return unmanaged.takeUnretainedValue().value } private func encode<T>(_ t: T) -> UnsafeMutableRawPointer { return Unmanaged.passRetained(Box(t)).toOpaque() } // Two variations for portability, let compiler decide which one to use private func pthreadRunner(context: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? { // TODO: don't force unwrap let context = decode(context!) as ThreadContext let result = context.routine() context.done = true return result } private func pthreadRunner(context: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer? { return pthreadRunner(context: .some(context)) }
mit
d63125fb8f4136e7fc31fee4a2e37088
25.170886
132
0.625635
4.558986
false
false
false
false
ghuitster/FoodPhoto
FoodPhoto/SyncController.swift
1
14774
import UIKit import BoxContentSDK import ReachabilitySwift enum SyncError: ErrorType { case folderCreationError } class SyncController: UIViewController { @IBOutlet var progressBar: UIProgressView! @IBOutlet var progressText: UILabel! var backgroundTask : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid override func viewDidLoad() -> Void { super.viewDidLoad() self.updateProgress(0, total: 0) } override func didReceiveMemoryWarning() -> Void { super.didReceiveMemoryWarning() } @IBAction func beginSync(sender: AnyObject) -> Void { var reachability: Reachability do { reachability = try Reachability.reachabilityForInternetConnection() } catch { self.displayAlert("Internet Connection Error", message: "You don't have an Internet connection. Connect to the Internet and try again.", error: error) return } if reachability.isReachable() { if reachability.isReachableViaWiFi() { self.loginBox() } else { let connectionAlert = UIAlertController(title: "Cellular Data Connection", message: "You're not connected to WiFi. Syncing may use lots of your data. Are you sure you want to continue?", preferredStyle: UIAlertControllerStyle.Alert) connectionAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in self.loginBox() })) connectionAlert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: { (action: UIAlertAction!) in return })) presentViewController(connectionAlert, animated: true, completion: nil) } } else { self.displayAlert("Internet Connection Error", message: "You don't have an Internet connection. Connect to the Internet and try again.", error: nil) } } func loginBox() -> Void { BOXContentClient.defaultClient().authenticateWithCompletionBlock({(user: BOXUser!, error: NSError!) -> Void in if error == nil { self.syncImages() } else { self.displayAlert("Login Error", message: "There was a problem logging in. The error was: " + error.box_localizedFailureReasonString(), error: error) } }) } func syncImages() -> Void { let rootFolderItemsRequest = BOXContentClient.defaultClient().folderItemsRequestWithID("0") rootFolderItemsRequest.performRequestWithCompletion({(items: [AnyObject]!, error: NSError!) -> Void in if error == nil { var foodPhotoFolderExists = false for item in items as! [BOXItem] { if item.isFolder && item.name == "FoodPhoto" { foodPhotoFolderExists = true self.uploadImages(item.modelID) } } if !foodPhotoFolderExists { let foodPhotoFolderCreateRequest = BOXContentClient.defaultClient().folderCreateRequestWithName("FoodPhoto", parentFolderID: "0") foodPhotoFolderCreateRequest.performRequestWithCompletion({(folder: BOXFolder!, error: NSError!) -> Void in if error == nil { self.uploadImages(folder.modelID) } else { self.displayAlert("Sync Error", message: "There was a problem syncing. Something bad happened when trying to create the FoodPhoto folder. The error was: " + error.box_localizedFailureReasonString(), error: error) } }) } } else { self.displayAlert("Sync Error", message: "There was a problem syncing. An issue arose when trying to get the FoodPhoto folder ID from Box. The error was: " + error.box_localizedFailureReasonString(), error: error) } }) } func getJpgFilesInDocumentsDirectory() -> [NSURL] { let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! var directoryContents: [NSURL] do { directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: []) } catch { self.displayAlert("Sync Error", message: "There was a problem syncing. Something bad happened when getting the images stored on this device.", error: error) return [NSURL]() } return directoryContents.filter{$0.pathExtension == "jpg"} } func uploadImages(foodPhotoFolderId: String) -> Void { let jpgFiles = self.getJpgFilesInDocumentsDirectory() let totalImages = jpgFiles.count var imagesUploaded = 0 self.updateProgress(imagesUploaded, total: totalImages) let mySerialQueue = dispatch_queue_create("edu.usu.ndfs", DISPATCH_QUEUE_SERIAL) var imageFolderIds = [String: String]() do { imageFolderIds = try self.createImageFolderMapping(jpgFiles, foodPhotoFolderId: foodPhotoFolderId) } catch { return } for jpgFile in jpgFiles { dispatch_async(mySerialQueue) { self.backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ self.endBackgroundTask() }) let semaphore = dispatch_semaphore_create(0) let imageName = jpgFile.lastPathComponent! let data = NSFileManager.defaultManager().contentsAtPath(jpgFile.path!)! let folderName = self.getFolderName(imageName) let uploadRequest = BOXContentClient.defaultClient().fileUploadRequestToFolderWithID(imageFolderIds[folderName], fromData: data, fileName: imageName) uploadRequest.performRequestWithProgress({(totalBytesTransferred: Int64, totalBytesExpectedToTransfer: Int64) -> Void in }, completion: {(file: BOXFile!, error: NSError!) -> Void in if error == nil { do { try NSFileManager.defaultManager().removeItemAtURL(jpgFile) } catch { dispatch_sync(dispatch_get_main_queue()) { self.displayAlert("Sync Error", message: "There was an error when uploading " + imageName + ". The image was unable to be deleted from this device.", error: error) } return } print("successfully uploaded " + imageName) imagesUploaded += 1 dispatch_sync(dispatch_get_main_queue()) { self.updateProgress(imagesUploaded, total: totalImages) } } else { dispatch_sync(dispatch_get_main_queue()) { self.displayAlert("Sync Error", message: "There was an error when uploading " + imageName + ". The error was: " + error.box_localizedFailureReasonString(), error: error) } } self.endBackgroundTask() dispatch_semaphore_signal(semaphore) }) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } } } func createImageFolderMapping(jpgFiles: [NSURL], foodPhotoFolderId: String) throws -> [String: String] { var imageFolderIds = [String: String]() for jpgFile in jpgFiles { let imageName = jpgFile.lastPathComponent! let folderName = self.getFolderName(imageName) if(imageFolderIds[folderName] == nil) { let imageFolderId = self.getImageFolderId(folderName, foodPhotoFolderId: foodPhotoFolderId) if(imageFolderId == nil) { throw SyncError.folderCreationError } imageFolderIds[folderName] = imageFolderId } } return imageFolderIds } func getFolderName(imageName: String) -> String { let imageNameArray = imageName.characters.split{$0 == "-"}.map(String.init) return imageNameArray[1] + "-" + imageNameArray[2] } func getImageFolderId(folderName: String, foodPhotoFolderId: String) -> String? { let mySerialQueue = dispatch_queue_create("edu.usu.ndfs.folderGetting", DISPATCH_QUEUE_SERIAL) var imageFolderId: String? let outerSemaphore = dispatch_semaphore_create(0) dispatch_async(mySerialQueue) { self.backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ self.endBackgroundTask() }) let semaphore = dispatch_semaphore_create(0) let foodPhotoItemsRequest = BOXContentClient.defaultClient().folderItemsRequestWithID(foodPhotoFolderId) foodPhotoItemsRequest.performRequestWithCompletion({(items: [AnyObject]!, error: NSError!) -> Void in if error == nil { for item in items as! [BOXItem] { if item.isFolder && (item.name.caseInsensitiveCompare(folderName) == NSComparisonResult.OrderedSame) { imageFolderId = item.modelID break } } } else { dispatch_async(dispatch_get_main_queue()) { self.displayAlert("Sync Error", message: "There was a problem syncing. Something bad happened when trying to get the folder " + folderName + " ID from Box. The error was: " + error.box_localizedFailureReasonString(), error: error) } } self.endBackgroundTask() dispatch_semaphore_signal(semaphore) dispatch_semaphore_signal(outerSemaphore) }) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } dispatch_semaphore_wait(outerSemaphore, DISPATCH_TIME_FOREVER) if(imageFolderId == nil) { imageFolderId = self.createImageFolder(folderName, foodPhotoFolderId: foodPhotoFolderId) } return imageFolderId } func createImageFolder(folderName: String, foodPhotoFolderId: String) -> String? { var imageFolderId: String? let mySerialQueue = dispatch_queue_create("edu.usu.ndfs.folderCreation", DISPATCH_QUEUE_SERIAL) let outerSemaphore = dispatch_semaphore_create(0) dispatch_async(mySerialQueue) { self.backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ self.endBackgroundTask() }) let semaphore = dispatch_semaphore_create(0) let foodPhotoFolderCreateRequest = BOXContentClient.defaultClient().folderCreateRequestWithName(folderName, parentFolderID: foodPhotoFolderId) foodPhotoFolderCreateRequest.performRequestWithCompletion({(folder: BOXFolder!, error: NSError!) -> Void in if error == nil { imageFolderId = folder.modelID } else { dispatch_async(dispatch_get_main_queue()) { self.displayAlert("Sync Error", message: "There was a problem syncing. An error occurred when trying to create the folder " + folderName + ". The error was: " + error.box_localizedFailureReasonString(), error: error) } } self.endBackgroundTask() dispatch_semaphore_signal(semaphore) dispatch_semaphore_signal(outerSemaphore) }) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } dispatch_semaphore_wait(outerSemaphore, DISPATCH_TIME_FOREVER) return imageFolderId } func endBackgroundTask() -> Void { UIApplication.sharedApplication().endBackgroundTask(self.backgroundTask) self.backgroundTask = UIBackgroundTaskInvalid } func updateProgress(imagesUploaded: Int, total: Int) -> Void { let progress = Float(imagesUploaded) / Float(total) self.progressText.text! = String(imagesUploaded) + " / " + String(total) self.progressBar.setProgress(progress, animated: true) if imagesUploaded == total && total != 0 { self.displayAlert("Sync Success", message: "All images successfully synced", error: nil) } } func displayAlert(title: String, message: String, error: ErrorType?) -> Void { print(error) let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func logout(sender: AnyObject) -> Void { let logoutAlert = UIAlertController(title: "Logout", message: "Are you really sure you want to log out of your Box account?", preferredStyle: UIAlertControllerStyle.Alert) logoutAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: {(action: UIAlertAction!) in BOXContentClient.defaultClient().logOut() self.displayAlert("Logout Success", message: "Successfully logged out", error: nil) })) logoutAlert.addAction(UIAlertAction(title: "No", style: .Cancel, handler: {(action: UIAlertAction!) in })) self.presentViewController(logoutAlert, animated: true, completion: nil) } }
mit
32b80738dcaf6568d07fbb7ff51532b1
45.753165
254
0.579938
5.686682
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/StaticLength.swift
1
918
// // StaticLength.swift // ReformCore // // Created by Laszlo Korte on 13.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // struct StaticLength : WriteableRuntimeLength { fileprivate let formId : FormIdentifier fileprivate let offset : Int init(formId: FormIdentifier, offset: Int) { self.formId = formId self.offset = offset } func getLengthFor<R:Runtime>(_ runtime: R) -> Double? { guard let l = runtime.read(formId, offset: offset) else { return nil } return Double(bitPattern: l) } func setLengthFor<R:Runtime>(_ runtime: R, length: Double) { runtime.write(formId, offset: offset, value: length.bitPattern) } } extension StaticLength : Equatable { } func ==(lhs: StaticLength, rhs: StaticLength) -> Bool { return lhs.formId == rhs.formId && lhs.offset == rhs.offset }
mit
2260d92bcd8d2030c11c9728884e3cd5
23.131579
71
0.627045
4.039648
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_10/BookReader/BookReader/BookmarkViewController.swift
1
3974
// // BookmarkViewController.swift // BookReader // // Created by Kishikawa Katsumi on 2017/07/03. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import UIKit import PDFKit class BookmarkViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var pdfDocument: PDFDocument? var bookmarks = [Int]() weak var delegate: BookmarkViewControllerDelegate? let thumbnailCache = NSCache<NSNumber, UIImage>() private let downloadQueue = DispatchQueue(label: "com.kishikawakatsumi.pdfviewer.thumbnail") var cellSize: CGSize { if let collectionView = collectionView { var width = collectionView.frame.width var height = collectionView.frame.height if width > height { swap(&width, &height) } width = (width - 20 * 4) / 3 height = width * 1.5 return CGSize(width: width, height: height) } return CGSize(width: 100, height: 150) } override func viewDidLoad() { super.viewDidLoad() let backgroundView = UIView() backgroundView.backgroundColor = .gray collectionView?.backgroundView = backgroundView collectionView?.register(UINib(nibName: String(describing: ThumbnailGridCell.self), bundle: nil), forCellWithReuseIdentifier: "Cell") NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil) refreshData() } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return bookmarks.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ThumbnailGridCell let pageNumber = bookmarks[indexPath.item] if let page = pdfDocument?.page(at: pageNumber) { cell.pageNumber = pageNumber let key = NSNumber(value: pageNumber) if let thumbnail = thumbnailCache.object(forKey: key) { cell.image = thumbnail } else { let size = cellSize downloadQueue.async { let thumbnail = page.thumbnail(of: size, for: .cropBox) self.thumbnailCache.setObject(thumbnail, forKey: key) if cell.pageNumber == pageNumber { DispatchQueue.main.async { cell.image = thumbnail } } } } } return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let page = pdfDocument?.page(at: bookmarks[indexPath.item]) { delegate?.bookmarkViewController(self, didSelectPage: page) } collectionView.deselectItem(at: indexPath, animated: true) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return cellSize } private func refreshData() { if let documentURL = pdfDocument?.documentURL?.absoluteString, let bookmarks = UserDefaults.standard.array(forKey: documentURL) as? [Int] { self.bookmarks = bookmarks collectionView?.reloadData() } } @objc func userDefaultsDidChange(_ notification: Notification) { refreshData() } } protocol BookmarkViewControllerDelegate: class { func bookmarkViewController(_ bookmarkViewController: BookmarkViewController, didSelectPage page: PDFPage) }
mit
f347a4899c087b949b19f9badaefef56
35.449541
160
0.648125
5.587904
false
false
false
false
kidaa/codecombat-ios
CodeCombat/RootViewController.swift
2
1660
// // RootViewController.swift // CodeCombat // // Created by Sam Soffes on 10/7/15. // Copyright © 2015 CodeCombat. All rights reserved. // import UIKit /// Root view controller of the window that manages transitioning between sign in and the game class RootViewController: UIViewController { // MARK: - Properties private var viewController: UIViewController? { willSet { guard let viewController = viewController else { return } viewController.willMoveToParentViewController(nil) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() } didSet { guard let viewController = viewController else { return } viewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] addChildViewController(viewController) view.addSubview(viewController.view) viewController.didMoveToParentViewController(self) setNeedsStatusBarAppearanceUpdate() } } // MARK: - Initializers deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "update", name: User.currentUserDidChangeNotificationName, object: nil) update() } // MARK: - Private @objc private func update() { guard let user = User.currentUser else { viewController = SignInViewController() return } // TODO: WebManager.sharedInstance.loginToGetAuthCookie() if let viewController = viewController as? GameViewController { viewController.user = user } else { viewController = GameViewController(user: user) } } }
mit
ee7193c04d8523b274e12c58c179cc29
22.366197
138
0.749247
4.582873
false
false
false
false
Error-freeIT/Dock-Master
Dock Master/Dock.swift
1
30575
// // Dock.swift // Dock Master // // Created by Michael Page on 27/05/2016. // Copyright © 2016 Error-free IT. All rights reserved. // import Foundation class DockItem { // tile-type will either be directory-tile: local directory, file-tile: application/webloc, url-tile: URL or network share. var tileType: String? { get { func returnTileType(target: String) -> String { // If the path contains "://" (CFURL). if target.rangeOfString("://") != nil { return "url-tile" // If the target has a file extension. } else if NSURL(fileURLWithPath: target).pathExtension != "" { return "file-tile" } else { return "directory-tile" } } if let unwrappedCfurlString = cfurlString { return returnTileType(unwrappedCfurlString) } else if let unwrappedHomeDirectoryRelative = homeDirectoryRelative { return returnTileType(unwrappedHomeDirectoryRelative) } else { return nil } } } // If the dock items cfurlString starts with ~ this key will be set to the value of cfurlString, private var _homeDirectoryRelative: String = "" var homeDirectoryRelative: String? { get { if _homeDirectoryRelative != "" { return _homeDirectoryRelative } else { return nil } } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _displayAs. _homeDirectoryRelative = unwrappedNewValue } else { // Set _homeDirectoryRelative to "" to reflect no preference. _homeDirectoryRelative = "" } } } // Path to resource (e.g. /Applications/App Store.app, smb://server/staffresources, http://www.google.com), private var _cfurlString: String = "" var cfurlString: String? { get { if _cfurlString.hasPrefix("~") { // Dock item is home directory relative. self.homeDirectoryRelative = _cfurlString return nil // If _cfurlString is no longer it's inital value (""). } else if _cfurlString != "" { // Return the value it has been set to. return _cfurlString } else { return nil } } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _displayAs. _cfurlString = unwrappedNewValue } else { // Set _cfurlString to "" to reflect no preference. _cfurlString = "" } } } // cfurlStringType depends on the path style: 0: /Applications/Safari.app, 15: file:///Applications/Safari.app/. var cfurlStringType: Int? { get { if let unwrappedCfurlString = cfurlString { // If dock item is not home directory relative, as they do not have a _CFURLStringType key. if !unwrappedCfurlString.hasPrefix("~") { // If the path contains :// it's a CFURL string type 15. if unwrappedCfurlString.rangeOfString("://") != nil { return 15 } else { return 0 } } } return nil } } // arrangement (sort by) will be 1: name, 2: date added, 3: date modified, 4: date created or 5: kind. // _arrangement is used to backup the computed property. private var _arrangement: Int = 0 var arrangement: Int? { get { // If _arrangement is no longer it's inital value (0). if _arrangement != 0 { // Return the value it has been set to. return _arrangement } else if tileType == "directory-tile" && _arrangement == 0 { // It hasn't been set, but is a directory, return the default value (sort by name). return 1 } else { return nil } } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _arrangement. _arrangement = unwrappedNewValue } else { // Set _arrangement to 0 to reflect no preference. _arrangement = 0 } } } // showAs (view content as) will be 1: fan, 2: grid, 3: list or 4: automatic. // _showAs is used to backup the computed property. private var _showAs: Int = 0 var showAs: Int? { get { // If _showAs is no longer it's inital value (0). if _showAs != 0 { // Return the value it has been set to. return _showAs } else if tileType == "directory-tile" && _showAs == 0 { // It hasn't been set, but is a directory, return the default value (view content as automatic). return 4 } else { return nil } } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _showAs. _showAs = unwrappedNewValue } else { // Set _showAs to 0 to reflect no preference. _showAs = 0 } } } // displayAs will either be 1: folder or 2: stack. // _displayAs is used to backup the computed property. private var _displayAs: Int = 0 var displayAs: Int? { get { // If _displayAs is no longer it's inital value (0). if _displayAs != 0 { // Return the value it has been set to. return _displayAs } else if tileType == "directory-tile" && _displayAs == 0 { // It hasn't been set, but is a directory, return the default value (display as a stack). return 2 } else { return nil } } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _displayAs. _displayAs = unwrappedNewValue } else { // Set _displayAs to 0 to reflect no preference. _displayAs = 0 } } } // Optional dock item label applied to URLs, shares and home directory relative paths. // _label is used to backup the computed property. private var _label: String = "" var label: String? { get { // If _label is no longer it's inital value (""). if _label != "" { // Return the value it has been set to. return _label } else if tileType == "url-tile" && _label == "" { // It hasn't been set. A url-tile (share path) MUST include a label, otherwise it will not be displayed. if let unwrappedCfurlString = cfurlString { let path = NSString(string: unwrappedCfurlString) // Remove any extension and extract the last part of the path (e.g. Shared). let extractedLabel = path.lastPathComponent return extractedLabel } } // It's not a url/share. return nil } set { // If newValue is not nil. if let unwrappedNewValue = newValue { // Store the new value in _displayAs. _label = unwrappedNewValue } else { // Set _label to "" to reflect no preference. _label = "" } } } // If removable is set in make the dock item removable. Note: this only applies to plist output, profiles do not support opt. var removable: Bool = false // Note: making an argument optional will allow input to be nil. init(cfurlString: String, arrangement: Int? = nil, showAs: Int? = nil, displayAs: Int? = nil, label: String? = nil, removable: Bool? = false) { self.cfurlString = cfurlString } func generateDockItemXML() -> [String: AnyObject] { /* let appStructure = ["tile-type":tileType!, "tile-data": "file-data": ["_CFURLString":cfurlString!, "_CFURLStringType":cfurlStringType! ] ] ] let shareStructure = ["tile-type":tileType!, "tile-data": ["label":label!, "url": ["_CFURLString":cfurlString!, "_CFURLStringType":cfurlStringType! ] ] ] let directoryStructure = ["tile-type":tileType!, "tile-data": ["label":label!, "home directory relative":homeDirectoryRelative!, "arrangement":arrangement!, "displayas":displayAs!, "showas":showAs! ] ] */ var dockItemXML = [String: AnyObject]() var tileData = [String: AnyObject]() var fileData = [String: AnyObject]() dockItemXML["tile-type"] = tileType // ["tile-data"] if let unwrappedhomeDirectoryRelative = homeDirectoryRelative { tileData["home directory relative"] = unwrappedhomeDirectoryRelative } if let unwrappedArrangement = arrangement { tileData["arrangement"] = unwrappedArrangement } if let unwrappedDisplayAs = displayAs { tileData["displayas"] = unwrappedDisplayAs } if let unwrappedShowAs = showAs { tileData["showas"] = unwrappedShowAs } if let unwrappedLabel = label { tileData["label"] = unwrappedLabel } // ["file-data"]/["url"] if let unwrappedCFURLString = cfurlString { fileData["_CFURLString"] = unwrappedCFURLString } if let unwrappedCFURLStringType = cfurlStringType { fileData["_CFURLStringType"] = unwrappedCFURLStringType } // If fileData is not empty insert ["file-data"]/["url"] into ["tile-data"]. if !fileData.isEmpty { if let tileType = dockItemXML["tile-type"] as? String { // If dock item is a URL use "url" as key instead of "file-data" if tileType == "url-tile" { tileData["url"] = fileData } else { tileData["file-data"] = fileData } } } dockItemXML["tile-data"] = tileData return dockItemXML } func convertAppCFURLStringType15ToCFURLStringType0(cfurlStringType15: String) -> String? { // Convert file:///Applications/Safari.app/ to /Applications/Safari.app/. let pathWithoutScheme = cfurlStringType15.stringByReplacingOccurrencesOfString("file://", withString: "") // Convert /Applications/Safari.app/ to /Applications/Safari.app. let cfurlStringType0 = NSURL(fileURLWithPath: pathWithoutScheme).path return cfurlStringType0 } } class Dock { // Becomes dockmaster.lowercaseSpacelessDisplayName. Profiles with the same identifier are overwritten. var payloadIdentifier: String { get { let lowercaseSpacelessDisplayName = payloadDisplayName.lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "") return lowercaseSpacelessDisplayName } } // Defines whether the profile can be removed. // With PayloadRemovalDisallowed set to true, profiles installed manually can only be removed using administrative authority. However if the profile is installed by an MDM, only the MDM can remove the profile (applies to 10.10 and later). var payloadRemovalDisallowed: Bool = true // Determines if this profile be applied to all users (System) or just the current user (User)? var payloadScope: String // Currently, a profile payload type can only be Configuration. let payloadType = "Configuration" // Generates a random Universal Unique Identifier. let payloadUUID = NSUUID().UUIDString // The version number of the profile format. Currently, this should be 1. let payloadVersion = 1 // Pretty name displayed to users (e.g. Student Dock). var payloadDisplayName: String // Organization name display to users (e.g. Error-free IT). var payloadOrganization: String? // Description of the profile (e.g. "Music Lab dock profile"). var payloadDescription: String? let dockPayloadType = "com.apple.dock" // Currently, all dock payloads are version 1, but Apple may release a new payload version to support additional features. let dockPayloadVersion = 1 // Becomes lowercaseSpacelessDisplayName. var dockPayloadIdentifier: String { get { return "dockmaster.\(payloadIdentifier)" } } // Whether payload should be acted upon. let dockPayloadEnabled = true // Generates a random Universal Unique Identifier. let dockPayloadUUID = NSUUID().UUIDString // Payload display name presented to the user during profile install. let dockPayloadDisplayName = "Dock" // Prevents the dock from being modified. var dockContentsImmutable: Bool // Removes any existing dock items before adding the dock items in the profile. var dockStaticOnly: Bool // Arrays of dock applications. var dockStaticApps = [DockItem]() var dockPersistentApps = [DockItem]() // Arrays of dock others (directories, shares and bookmarks). var dockStaticOthers = [DockItem]() var dockPersistentOthers = [DockItem]() // Adds the user's network home folder to the dock. Note: This will add a duplicate if the directory services plugin is also set to add the network home folder to the dock. var dockAddNetworkHome: Bool? // Sets the tile size (maximum icon size). The value can be anywhere between 1 and 256, (larger number = larger tiles). 68 is OS X's default value. var dockTileSize: Int? var dockTileSizeImmutable: Bool? // Enable magnification when hovering over dock items. OS X disables this feature by default. var dockMagnification: Bool? var dockMagnificationImmutable: Bool? // Sets the level of magnification when hovering over dock items. The value can be anywhere between 1 and 256, (larger number = larger magnification). var dockMagnificationSize: Int? var dockMagnificationSizeImmutable: Bool? // Sets the position of the dock. It can either be left, bottom (default) or right. var dockPosition: String? var dockPositionImmutable: Bool? // Sets the dock minimize effect, it can either be genie (default) or scale. var dockMinimizeEffect: String? var dockMinimizeEffectImmutable: Bool? // Whether applications animate (bounce) on open. var dockAnimateAppLaunch: Bool? var dockAnimateAppLaunchImmutable: Bool? // Whether the dock hides and only appears on hover. var dockAutoHide: Bool? // Displays a light or black dot (depending on OS X version) to indicate the application is running. OS X enables this feature by default. var dockShowProcessIndicators: Bool? var dockShowProcessIndicatorsImmutable: Bool? // Sets application windows to minimize into their respective application icon. OS X disables this feature by default. var dockMinimizeIntoApp: Bool? var dockMinimizeIntoAppImmutable: Bool? // Packages generated apply to existing user accounts (true) or only new user accounts (false). var packageAppliesToExistingUsers = true // Version number of package. var packageVersion = "1.0" init(payloadScope: String = "System", payloadDisplayName: String = "Custom Dock", dockContentsImmutable: Bool = false, dockStaticOnly: Bool = false) { self.payloadScope = payloadScope self.payloadDisplayName = payloadDisplayName self.dockContentsImmutable = dockContentsImmutable self.dockStaticOnly = dockStaticOnly } // Add a new dock item to dock array. func addNewDockItem(dockItem: DockItem) { if dockItem.tileType == "file-tile" && !dockItem._cfurlString.hasSuffix(".webloc") { if dockItem.removable { self.dockPersistentApps.append(dockItem) } else { self.dockStaticApps.append(dockItem) } } else { if dockItem.removable { self.dockPersistentOthers.append(dockItem) } else { self.dockStaticOthers.append(dockItem) } } } func generateUniversalXML() -> [String: AnyObject] { var universalXML = [String: AnyObject]() universalXML["contents-immutable"] = dockContentsImmutable if let unwrappedDockAddNetworkHome = dockAddNetworkHome { if unwrappedDockAddNetworkHome { universalXML["MCXDockSpecialFolders"] = ["AddDockMCXOriginalNetworkHomeFolder"] } } if let unwrappedDockTileSize = dockTileSize { universalXML["tilesize"] = unwrappedDockTileSize } if let unwrappedDockTileSizeImmutable = dockTileSizeImmutable { universalXML["size-immutable"] = unwrappedDockTileSizeImmutable } if let unwrappedDockMagnification = dockMagnification { universalXML["magnification"] = unwrappedDockMagnification } if let unwrappedDockMagnificationImmutable = dockMagnificationImmutable { universalXML["magnify-immutable"] = unwrappedDockMagnificationImmutable } if let unwrappedDockMagnificationSize = dockMagnificationSize { universalXML["largesize"] = unwrappedDockMagnificationSize } if let unwrappedDockMagnificationSizeImmutable = dockMagnificationSizeImmutable { universalXML["magsize-immutable"] = unwrappedDockMagnificationSizeImmutable } if let unwrappedDockPosition = dockPosition { universalXML["orientation"] = unwrappedDockPosition } if let unwrappedDockPositionImmutable = dockPositionImmutable { universalXML["position-immutable"] = unwrappedDockPositionImmutable } if let unwrappedDockMinimizeEffect = dockMinimizeEffect { universalXML["mineffect"] = unwrappedDockMinimizeEffect } if let unwrappedDockMinimizeEffectImmutable = dockMinimizeEffectImmutable { universalXML["mineffect-immutable"] = unwrappedDockMinimizeEffectImmutable } if let unwrappedDockAnimateAppLaunch = dockAnimateAppLaunch { universalXML["launchanim"] = unwrappedDockAnimateAppLaunch } if let unwrappedDockAnimateAppLaunchImmutable = dockAnimateAppLaunchImmutable { universalXML["launchanim-immutable"] = unwrappedDockAnimateAppLaunchImmutable } if let unwrappedDockAutoHide = dockAutoHide { universalXML["autohide"] = unwrappedDockAutoHide } if let unwrappedDockShowProcessIndicators = dockShowProcessIndicators { universalXML["show-process-indicators"] = unwrappedDockShowProcessIndicators } if let unwrappedDockShowProcessIndicatorsImmutable = dockShowProcessIndicatorsImmutable { universalXML["show-process-indicators-immutable"] = unwrappedDockShowProcessIndicatorsImmutable } if let unwrappedDockMinimizeIntoApp = dockMinimizeIntoApp { universalXML["minimize-to-application"] = unwrappedDockMinimizeIntoApp } if let unwrappedDockMinimizeIntoAppImmutable = dockMinimizeIntoAppImmutable { universalXML["minimize-to-application-immutable"] = unwrappedDockMinimizeIntoAppImmutable } // If dockStaticApps is not empty. if !dockStaticApps.isEmpty { universalXML["static-apps"] = generateCombinedDockItemXML(dockStaticApps) } // If dockStaticOthers is not empty. if !dockStaticOthers.isEmpty { universalXML["static-others"] = generateCombinedDockItemXML(dockStaticOthers) } return universalXML } func generateProfileXML() -> [String: AnyObject] { var profileXML = [String: AnyObject]() var dockPayloadContent = generateUniversalXML() profileXML["PayloadIdentifier"] = payloadIdentifier profileXML["PayloadRemovalDisallowed"] = payloadRemovalDisallowed profileXML["PayloadScope"] = payloadScope profileXML["PayloadType"] = payloadType profileXML["PayloadUUID"] = payloadUUID profileXML["PayloadVersion"] = payloadVersion profileXML["PayloadDisplayName"] = payloadDisplayName if let unwrappedPayloadDescription = payloadDescription { profileXML["PayloadDescription"] = unwrappedPayloadDescription } if let unwrappedPayloadOrganization = payloadOrganization { profileXML["PayloadOrganization"] = unwrappedPayloadOrganization } dockPayloadContent["PayloadType"] = dockPayloadType dockPayloadContent["PayloadVersion"] = dockPayloadVersion dockPayloadContent["PayloadIdentifier"] = dockPayloadIdentifier dockPayloadContent["PayloadEnabled"] = dockPayloadEnabled dockPayloadContent["PayloadUUID"] = dockPayloadUUID dockPayloadContent["PayloadDisplayName"] = dockPayloadDisplayName dockPayloadContent["static-only"] = dockStaticOnly let dockPayloadContentArray: Array<AnyObject> = [dockPayloadContent] profileXML["PayloadContent"] = dockPayloadContentArray return profileXML } func generatePlistXML() -> [String: AnyObject] { var plistXML = generateUniversalXML() // If dockPersistentApps is not empty. if !dockPersistentApps.isEmpty { plistXML["persistent-apps"] = generateCombinedDockItemXML(dockPersistentApps) } // If dockPersistentOthers is not empty. if !dockPersistentOthers.isEmpty { plistXML["persistent-others"] = generateCombinedDockItemXML(dockPersistentOthers) } plistXML["version"] = 1 return plistXML } private func generateCombinedDockItemXML(dockItems: [DockItem]) -> [[String: AnyObject]] { var combinedDockItemsXML = [[String: AnyObject]]() for dockItem in dockItems { combinedDockItemsXML.append(dockItem.generateDockItemXML()) } return combinedDockItemsXML } // Function to load a dock template from file, into a Dock object. func loadDockTemplate(templateDockFile: String) -> Dock { let templateDock = Dock() if let loadedPlist = FileOperation().readDictionaryFromFile(templateDockFile) { if let displayName = loadedPlist["display_name"] as? String { templateDock.payloadDisplayName = displayName } if let organization = loadedPlist["organization"] as? String { templateDock.payloadOrganization = organization } if let description = loadedPlist["description"] as? String { templateDock.payloadDescription = description } if let scope = loadedPlist["scope"] as? String { templateDock.payloadScope = scope } if let contentsImmutable = loadedPlist["contents_immutable"] as? Bool { templateDock.dockContentsImmutable = contentsImmutable } if let mergeWithExistingDock = loadedPlist["merge_with_existing_dock"] as? Bool { let staticOnly = !mergeWithExistingDock templateDock.dockStaticOnly = staticOnly } if let addNetworkHome = loadedPlist["add_network_home"] as? Bool { templateDock.dockAddNetworkHome = addNetworkHome } if let tileSize = loadedPlist["tile_size"] as? Int { templateDock.dockTileSize = tileSize } if let tileSizeImmutable = loadedPlist["tile_size_immutable"] as? Bool { templateDock.dockTileSizeImmutable = tileSizeImmutable } if let magnification = loadedPlist["magnification"] as? Bool { templateDock.dockMagnification = magnification } if let magnificationImmutable = loadedPlist["magnification_immutable"] as? Bool { templateDock.dockMagnificationImmutable = magnificationImmutable } if let magnificationSize = loadedPlist["magnification_size"] as? Int { templateDock.dockMagnificationSize = magnificationSize } if let magnificationSizeImmutable = loadedPlist["magnification_size_immutable"] as? Bool { templateDock.dockMagnificationSizeImmutable = magnificationSizeImmutable } if let position = loadedPlist["position"] as? String { templateDock.dockPosition = position } if let positionImmutable = loadedPlist["position_immutable"] as? Bool { templateDock.dockPositionImmutable = positionImmutable } if let minimizeEffect = loadedPlist["minimize_effect"] as? String { templateDock.dockMinimizeEffect = minimizeEffect } if let minimizeEffectImmutable = loadedPlist["minimize_effect_immutable"] as? Bool { templateDock.dockMinimizeEffectImmutable = minimizeEffectImmutable } if let animateAppLaunch = loadedPlist["animate_app_launch"] as? Bool { templateDock.dockAnimateAppLaunch = animateAppLaunch } if let animateAppLaunchImmutable = loadedPlist["animate_app_launch_immutable"] as? Bool { templateDock.dockAnimateAppLaunchImmutable = animateAppLaunchImmutable } if let autoHide = loadedPlist["auto_hide"] as? Bool { templateDock.dockAutoHide = autoHide } if let showProcessIndicators = loadedPlist["show_process_indicators"] as? Bool { templateDock.dockShowProcessIndicators = showProcessIndicators } if let showProcessIndicatorsImmutable = loadedPlist["show_process_indicators_immutable"] as? Bool { templateDock.dockShowProcessIndicatorsImmutable = showProcessIndicatorsImmutable } if let minimizeIntoApp = loadedPlist["minimize_into_app"] as? Bool { templateDock.dockMinimizeIntoApp = minimizeIntoApp } if let minimizeIntoAppImmutable = loadedPlist["minimize_into_app_immutable"] as? Bool { templateDock.dockMinimizeIntoAppImmutable = minimizeIntoAppImmutable } if let applications = loadedPlist["applications"] { for application in applications as! NSArray { if let cfurlString = application["cfurl_string"] as? String { let dockItem = DockItem(cfurlString: cfurlString) dockItem.removable = application["removable"] as? Bool ?? false templateDock.addNewDockItem(dockItem) } } } if let others = loadedPlist["others"] { for other in others as! NSArray { if let cfurlString = other["cfurl_string"] as? String { let dockItem = DockItem(cfurlString: cfurlString) dockItem.arrangement = other["arrangement"] as? Int ?? nil dockItem.showAs = other["show_as"] as? Int ?? nil dockItem.displayAs = other["display_as"] as? Int ?? nil dockItem.label = other["label"] as? String ?? nil dockItem.removable = other["removable"] as? Bool ?? false templateDock.addNewDockItem(dockItem) } } } if let packageAppliesToExistingUsers = loadedPlist["package_applies_to_existing_users"] as? Bool { templateDock.packageAppliesToExistingUsers = packageAppliesToExistingUsers } if let packageVersion = loadedPlist["package_version"] as? String { templateDock.packageVersion = packageVersion } } return templateDock } }
apache-2.0
941f580c44fa27718e7307dffe1776d0
40.655313
242
0.576863
5.244254
false
false
false
false
kaideyi/KDYSample
KYWebo/KYWebo/Bizs/Home/View/WbStatusView.swift
1
11437
// // WbStatusView.swift // KYWebo // // Created by kaideyi on 2017/8/13. // Copyright © 2017年 mac. All rights reserved. // import UIKit import YYKit class WbStatusView: UIView { // MARK: - Properites var contentBgView: UIView! // 内容视图 var profileView: WbProfileView! // 个人资料 var textLabel: YYLabel! // 正文文本 var picsView: UIView! // 图片视图 var retweetBgView: UIView! // 转发视图 var retweetTextLabel: YYLabel! // 转发文本 var retweetPicsView: UIView! // 转发图片视图 var toolbarView: WbToolbarView! // 工具栏视图 var isTouchRetweetView: Bool = false // MARK: - Life Cycle override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { // 内容视图 contentBgView = UIView() contentBgView.isExclusiveTouch = true contentBgView.backgroundColor = .white contentBgView.size = CGSize(width: kScreenWidth, height: 1) self.addSubview(contentBgView) // 个人资料 profileView = WbProfileView() profileView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kCellProfileHeight) contentBgView.addSubview(profileView) // 正文 textLabel = YYLabel() textLabel.left = kCellContentLeft textLabel.width = kCellContentWidth textLabel.textVerticalAlignment = .top textLabel.displaysAsynchronously = true textLabel.ignoreCommonProperties = true textLabel.fadeOnAsynchronouslyDisplay = false textLabel.fadeOnHighlight = false textLabel.highlightTapAction = { (containerView, text, range, rect) in // 点击事件处理,代理到控制器中 // ... } contentBgView.addSubview(textLabel) picsView = UIView() picsView.backgroundColor = .clear picsView.left = kCellContentLeft picsView.width = kCellContentWidth contentBgView.addSubview(picsView) // 转发视图 retweetBgView = UIView() retweetBgView.isExclusiveTouch = true retweetBgView.left = kCellContentLeft retweetBgView.width = kCellContentWidth retweetBgView.backgroundColor = UIColor(hexString: "#f7f7f7") contentBgView.addSubview(retweetBgView) // 转发文本 retweetTextLabel = YYLabel() retweetTextLabel.left = kCellReteetLeft retweetTextLabel.width = kCellReteetWidth retweetTextLabel.textVerticalAlignment = .top retweetTextLabel.displaysAsynchronously = true retweetTextLabel.ignoreCommonProperties = true retweetTextLabel.fadeOnAsynchronouslyDisplay = false retweetTextLabel.fadeOnHighlight = false retweetTextLabel.highlightTapAction = { (containerView, text, range, rect) in // 点击事件处理,代理到控制器中 // ... } contentBgView.addSubview(retweetTextLabel) retweetPicsView = UIView() retweetPicsView.backgroundColor = .clear retweetPicsView.left = kCellReteetLeft retweetPicsView.width = kCellReteetWidth contentBgView.addSubview(retweetPicsView) // 工具栏 toolbarView = WbToolbarView(frame: CGRect(x: 0, y: 0, width: kCellContentWidth, height: kCellToolbarHeight)) toolbarView.left = kCellContentLeft contentBgView.addSubview(toolbarView) } // MARK: - Layout func setupStatus(withViewmodel viewModel: HomeItemViewModel) { self.height = viewModel.totalHeight contentBgView.top = viewModel.topMargin contentBgView.height = viewModel.totalHeight - viewModel.topMargin - viewModel.bottomMargin // Cell里的元素布局 var top: CGFloat = 0 // y轴的坐标 // 个人资料 let avatarUrl = URL(string: (viewModel.wbstatus?.user.avatarLarge)!) profileView.avatarIamge.setImageWith(avatarUrl, placeholder: nil) profileView.nameLabel.textLayout = viewModel.nameTextLayout profileView.sourceLabel.textLayout = viewModel.sourceTextLayout profileView.top = top top += viewModel.profileHeight // 正文文本 textLabel.textLayout = viewModel.textLayout textLabel.height = viewModel.textHeight textLabel.top = top top += viewModel.textHeight retweetBgView.isHidden = true retweetTextLabel.isHidden = true retweetPicsView.isHidden = true picsView.isHidden = true // 转发视图,展示的优先级:转发->图片 if viewModel.retweetHeight > 0 { retweetBgView.isHidden = false retweetBgView.height = viewModel.retweetHeight retweetBgView.top = top + kCellPaddingText if let textlayout = viewModel.retweetTextLayout { retweetTextLabel.isHidden = false retweetTextLabel.textLayout = textlayout retweetTextLabel.height = viewModel.retweetTextHeight retweetTextLabel.top = top + kCellPaddingText } // 有转发的图片或视频 if viewModel.retweetPicsHeight > 0 { retweetPicsView.isHidden = false retweetPicsView.height = viewModel.retweetPicsHeight retweetPicsView.top = retweetTextLabel.bottom + kCellPaddingText setPicsImage(withViewModel: viewModel, isRetweet: true) } } else if viewModel.picsHeight > 0 { picsView.isHidden = false picsView.height = viewModel.picsHeight picsView.top = textLabel.bottom + kCellPaddingText setPicsImage(withViewModel: viewModel, isRetweet: false) } // 工具栏 toolbarView.bottom = contentBgView.height if viewModel.wbstatus?.repostsCount != 0 { toolbarView.repostButton.setTitle(String.init(format: "转发 %d", (viewModel.wbstatus?.repostsCount)!), for: .normal) } else { toolbarView.repostButton.setTitle("转发", for: .normal) } if viewModel.wbstatus?.commentsCount != 0 { toolbarView.commentButton.setTitle(String.init(format: "评论 %d", (viewModel.wbstatus?.commentsCount)!), for: .normal) } else { toolbarView.commentButton.setTitle("评论", for: .normal) } if viewModel.wbstatus?.attitudesCount != 0 { toolbarView.likeButton.setTitle(String.init(format: "点赞 %d", (viewModel.wbstatus?.attitudesCount)!), for: .normal) } else { toolbarView.likeButton.setTitle("点赞", for: .normal) } } func setPicsImage(withViewModel viewModel: HomeItemViewModel, isRetweet: Bool) { guard let model = viewModel.wbstatus else { return } var picArray: [WbPicture] = [] var width: CGFloat = 0 var height: CGFloat = 0 if isRetweet { guard let array = model.retweetedStatus?.picUrls else { return } picArray = array width = viewModel.retweetPicSize.width height = viewModel.retweetPicSize.height retweetPicsView.removeAllSubviews() } else { picArray = model.picUrls width = viewModel.picSize.width height = viewModel.picSize.height picsView.removeAllSubviews() } var i = 0 for pic in picArray { // 创建九宫格(暂为对gif、长图的处理) let imageView = YYControl() imageView.clipsToBounds = true imageView.backgroundColor = UIColor(hexString: "#f0f0f0") imageView.isExclusiveTouch = true imageView.layer.borderWidth = 0.5 imageView.layer.borderColor = UIColor(hexString: "#f0f0f0")?.cgColor imageView.touchBlock = { (view, state, touches, evnet) in // 点击了图片的事件 } pic.bmiddle = pic.thumbnail.replacingOccurrences(of: "thumbnail", with: "bmiddle") imageView.layer.setImageWith(URL(string: pic.bmiddle), placeholder: nil, options: .avoidSetImage, completion: { (image, url, from, stage, error) in // 需要处理图片(横图、竖图、小图,长图等) imageView.contentMode = .scaleAspectFill; imageView.image = image }) if isRetweet { retweetPicsView.addSubview(imageView) } else { picsView.addSubview(imageView) } let row = i / 3 // 3 为列数 let col = i % 3 let margin: CGFloat = kCellPaddingPic let xPos = CGFloat(col) * CGFloat(height + margin) let yPos = CGFloat(row) * CGFloat(height + margin) if picArray.count == 1 { imageView.frame = CGRect(x: xPos, y: yPos, width: width, height: height) } else { imageView.frame = CGRect(x: xPos, y: yPos, width: height, height: height) } i += 1 } } // MARK: - Touchs override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: UITouch = touches.first! let point: CGPoint = touch.location(in: retweetBgView) let insideRetweet = retweetBgView.bounds.contains(point) if insideRetweet && !retweetBgView.isHidden { isTouchRetweetView = true retweetBgView.perform(#selector(setter: UIView.backgroundColor), with: UIColor(hexString: "#f0f0f0"), afterDelay: 0.15) } else { isTouchRetweetView = false contentBgView.perform(#selector(setter: UIView.backgroundColor), with: UIColor(hexString: "#f0f0f0"), afterDelay: 0.15) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { setupBgviewColor() if isTouchRetweetView { } else { } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { setupBgviewColor() } func setupBgviewColor() { // 取消上次的延迟 NSObject.cancelPreviousPerformRequests(withTarget: retweetBgView, selector: #selector(setter: UIView.backgroundColor), object: UIColor(hexString: "#f0f0f0")) NSObject.cancelPreviousPerformRequests(withTarget: contentBgView, selector: #selector(setter: UIView.backgroundColor), object: UIColor(hexString: "#f0f0f0")) // 设置背景颜色 contentBgView.backgroundColor = .white retweetBgView.backgroundColor = UIColor(hexString: "#f7f7f7") } }
mit
9aba52bd535885cb70630575d5f99e1a
35.177049
165
0.593348
4.908363
false
false
false
false
martyav/iRockPaperScissors
iRockPaperScissors/Pickers.swift
1
736
// // GameLogic.swift // iRockPaperScissors // // Created by Marty Avedon on 12/3/16. // Copyright © 2016 Marty Hernandez Avedon. All rights reserved. // import Foundation func chosenByPlayer(_ num: Int) -> (weapon: Weapon, emoji: String) { let playersChoice = Weapon.convertInt(toWeapon: num) let playersPickEmoji = Weapon.convertWeapon(toEmoji: playersChoice) return (playersChoice, playersPickEmoji) } func chooseForComputer() -> (weapon: Weapon, emoji: String) { let randomChoice = Int(arc4random_uniform(2)) let computersPick = Weapon.convertInt(toWeapon: randomChoice) let computersPickEmoji = Weapon.convertWeapon(toEmoji: computersPick) return (computersPick, computersPickEmoji) }
mit
4c000e5d2ae10821125952e495c70631
29.625
73
0.730612
3.602941
false
false
false
false
avaidyam/Parrot
Mocha/Promise.swift
1
7202
import Foundation /// TODO: Convert blocks to @escaping @throws... with (T) -> (U), () -> (T), (T) -> () forms. public final class Promise<T> { public private(set) var name: String? public private(set) var index: Int fileprivate var delay: DispatchTimeInterval = .seconds(0) fileprivate var onQueue: DispatchQueue = .main fileprivate var promise: (Promise) -> () public fileprivate(set) var error: Error? public fileprivate(set) var previousResult: T? fileprivate var next: Promise? fileprivate var catchThis: ((Promise) -> ())? fileprivate var finallyThis: ((Promise) -> ())? fileprivate init(name: String? = nil, on queue: DispatchQueue = .main, after delay: DispatchTimeInterval = .seconds(0), index: Int, do this: @escaping (Promise<T>) -> ()) { self.name = name self.index = index self.onQueue = queue self.delay = delay self.promise = this } public init(name: String? = nil, on queue: DispatchQueue = .main, after delay: DispatchTimeInterval = .seconds(0), do this: @escaping (Promise<T>) -> ()) { self.name = name self.index = 0 self.onQueue = queue self.delay = delay self.promise = this let action = { self.promise(self) } if delay.toSeconds() > 0 { queue.asyncAfter(deadline: .now() + delay, execute: action) } else { queue.async(execute: action) } } /// Done Callback, should be called within every this and then closures /// /// - Parameters: /// - error: error if any, will continue to the catch and finally closures /// - result: result (optional) passed to the next then or finally closures public func done(result: T? = nil, error: Error? = nil) { if let error = error { self.error = error lastDo.catchThis?(self) lastDo.previousResult = result lastDo.finallyThis?(lastDo) } else if let next = self.next { if next.delay.toSeconds() > 0 { next.onQueue.asyncAfter(deadline: .now() + next.delay, execute: { next.previousResult = result next.promise(next) }) } else { next.onQueue.async { next.previousResult = result next.promise(next) } } } else { lastDo.previousResult = result lastDo.finallyThis?(lastDo) } } public func then(name: String? = nil, on queue: DispatchQueue? = nil, after delay: DispatchTimeInterval = .seconds(0), do this: @escaping (Promise) -> ()) -> Promise { guard self.catchThis == nil else { fatalError("Can't call next() after catch()") } let queue = queue ?? self.onQueue let next = Promise(name: name, on: queue, after: delay, index: self.index + 1, do: this) self.next = next return next } @discardableResult public func `catch`(_ this: @escaping (Promise) -> ()) -> Promise { self.catchThis = this return self } public func `finally`(_ this: @escaping (Promise) -> ()) { self.finallyThis = this } private var lastDo: Promise { var last = self while let next = last.next { last = next } return last } } /// An asynchronous do-catch-finally block. /// (It's something like a Promise, but not chainable or "evaluatable.") /// /// sync: `do { ... } catch(...) { ... } finally { ... }` /// /// async: `myFunc().do { value in ... }.catch { error in ... }.finally { ... }` /// public final class Callback<T> { public enum Result { case result(T) case error(Error) } public private(set) var completed = false private var do_handler: (T) -> () = {_ in} private var catch_handler: (Error) -> () = {_ in} private var finally_handler: () -> () = {} private var do_queue: DispatchQueue? = nil private var catch_queue: DispatchQueue? = nil private var finally_queue: DispatchQueue? = nil /// do { ... } /// - Note: if `queue` is nil, the `do { .... }` handler will be executed on the /// same queue as the callee's current queue when completing the `Callback`. public func `do`(on queue: DispatchQueue? = nil, _ handler: @escaping (T) -> ()) -> Callback<T> { self.do_queue = queue self.do_handler = handler return self } /// catch(let error) { ... } /// - Note: if `queue` is nil, the `catch { .... }` handler will be executed on the /// same queue as the callee's current queue when completing the `Callback`. public func `catch`(on queue: DispatchQueue? = nil, _ handler: @escaping (Error) -> ()) -> Callback<T> { self.catch_queue = queue self.catch_handler = handler return self } /// finally { ... } /// - Note: if `queue` is `nil`, the `finally { ... }` handler will be executed on the /// same queue as either the `do` or `catch` handlers, whichever occurs. public func `finally`(on queue: DispatchQueue? = nil, _ handler: @escaping () -> ()) -> Callback<T> { self.finally_queue = queue self.finally_handler = handler return self } /// Server-side completion. At the time of completion, whichever handlers are registered /// will be invoked on their respective queues (if applicable). public func complete(with result: Result) { guard !self.completed else { return } self.completed = true switch result { case .result(let value): self.perform(on: self.do_queue) { self.do_handler(value) self.perform(on: self.finally_queue, self.finally_handler) } case .error(let error): self.perform(on: self.catch_queue) { self.catch_handler(error) self.perform(on: self.finally_queue, self.finally_handler) } } } /// Server-side completion via throwing handler block. /// - Note: not providing a `queue` may cause completion before a handler can /// be registed on the "client-side" or caller-side. public func complete(on queue: DispatchQueue? = nil, with handler: @escaping () throws -> (T)) { guard !self.completed else { return } self.completed = true self.perform(on: queue) { do { let result = try handler() self.complete(with: .result(result)) } catch(let error) { self.complete(with: .error(error)) } } } // Optional<DispatchQueue> support. private func perform(on queue: DispatchQueue?, _ handler: @escaping () -> ()) { if let q = queue { q.async(execute: handler) } else { handler() } } }
mpl-2.0
5a477ec112941b839a6ab1e35181a0cf
34.303922
108
0.548042
4.346409
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/SchemaGeneration.swift
1
6168
// // SchemaGeneration.swift // ZeeQL3 // // Created by Helge Hess on 08.06.17. // Copyright © 2017-2021 ZeeZide GmbH. All rights reserved. // public protocol SchemaGeneration: AnyObject { var adaptor : Adaptor { get } var log : ZeeQLLogger { get } var createdTables : Set<String> { get set } var extraTableJoins : [ SQLExpression ] { get set } func reset() func appendExpression(_ expr: SQLExpression, toScript sb: inout String) func schemaCreationStatementsForEntities(_ entities: [ Entity ], options: SchemaGenerationOptions) -> [ SQLExpression ] func createTableStatementsForEntityGroup(_ entities: [ Entity ], options: SchemaGenerationOptions) -> [ SQLExpression ] func dropTableStatementsForEntityGroup(_ entities: [ Entity ]) -> [ SQLExpression ] /** * Supports: * ALTER TABLE table ADD CONSTRAINT table2target * FOREIGN KEY ( target_id ) REFERENCES target( target_id ); * ALTER TABLE table DROP CONSTRAINT table2target; * - Note: constraint name must be known! */ var supportsDirectForeignKeyModification : Bool { get } } public class SchemaGenerationOptions { var dropTables = true var createTables = true var embedConstraintsInTable = true } public extension SchemaGeneration { func reset() { createdTables.removeAll() extraTableJoins.removeAll() } func appendExpression(_ expr: SQLExpression, toScript sb: inout String) { sb += expr.statement } func schemaCreationStatementsForEntities(_ entities: [ Entity ], options: SchemaGenerationOptions) -> [ SQLExpression ] { reset() var statements = [ SQLExpression ]() statements.reserveCapacity(entities.count * 2) var entityGroups = entities.extractEntityGroups() if options.dropTables { for group in entityGroups { statements.append(contentsOf: dropTableStatementsForEntityGroup(group)) } } if options.createTables { if !supportsDirectForeignKeyModification || options.embedConstraintsInTable // not strictly necessary but nicer { entityGroups.sort { lhs, rhs in // areInIncreasingOrder let lhsr = lhs.countReferencesToEntityGroup(rhs) let rhsr = rhs.countReferencesToEntityGroup(lhs) if lhsr < rhsr { return true } if lhsr > rhsr { return false } // sort by name return lhs[0].name < rhs[0].name } } for group in entityGroups { let sa = createTableStatementsForEntityGroup(group, options: options) statements.append(contentsOf: sa) } statements.append(contentsOf: extraTableJoins) } return statements } func createTableStatementsForEntityGroup(_ entities: [ Entity ], options: SchemaGenerationOptions) -> [ SQLExpression ] { guard !entities.isEmpty else { return [] } // collect attributes, unique columns and relationships we want to create let attributes = entities.groupAttributes let relships = entities.groupRelationships // build statement let rootEntity = entities[0] // we may or may not want to find the actual let table = rootEntity.externalName ?? rootEntity.name let expr = adaptor.expressionFactory.createExpression(rootEntity) assert(!createdTables.contains(table)) createdTables.insert(table) for attr in attributes { // TBD: is the pkey handling right for groups? expr.addCreateClauseForAttribute(attr, in: rootEntity) } var sql = "CREATE TABLE " sql += expr.sqlStringFor(schemaObjectName: table) sql += " ( " sql += expr.listString var constraintNames = Set<String>() for rs in relships { guard rs.isForeignKeyRelationship else { continue } let fkexpr = adaptor.expressionFactory.createExpression(rootEntity) guard let fkSQL = fkexpr.sqlForForeignKeyConstraint(rs) else { log.warn("Could not create constraint statement for relationship:", rs) continue } var needsAlter = true if options.embedConstraintsInTable && rs.constraintName == nil { // if the constraint has an explicit name, keep it! if let dest = rs.destinationEntity?.externalName ?? rs.destinationEntity?.name, createdTables.contains(dest) { sql += ",\n" sql += fkSQL needsAlter = false } } if needsAlter { var constraintName : String = rs.constraintName ?? rs.name if constraintNames.contains(constraintName) { constraintName = rs.name + String(describing: constraintNames.count) if constraintNames.contains(constraintName) { log.error("Failed to generate unique name for constraint:", rs) continue } } constraintNames.insert(constraintName) var sql = "ALTER TABLE " sql += expr.sqlStringFor(schemaObjectName: table) sql += " ADD CONSTRAINT " sql += expr.sqlStringFor(schemaObjectName: constraintName) sql += " " sql += fkSQL fkexpr.statement = sql extraTableJoins.append(fkexpr) } } sql += " )" expr.statement = sql return [ expr ] } func dropTableStatementsForEntityGroup(_ entities: [ Entity ]) -> [ SQLExpression ] { // we just drop the single table shared by all, right? guard !entities.isEmpty else { return [] } let rootEntity = entities[0] // we may or may not want to find the actual let table = rootEntity.externalName ?? rootEntity.name let expr = adaptor.expressionFactory.createExpression(rootEntity) expr.statement = "DROP TABLE " + expr.sqlStringFor(schemaObjectName: table) return [ expr ] } }
apache-2.0
f33924434913f2ac5794ebbfbee4bb0d
29.529703
79
0.61894
4.754819
false
false
false
false
andrealufino/Luminous
Sources/Luminous/Luminous+Disk.swift
1
5896
// // Luminous+Disk.swift // Luminous // // Created by Andrea Mario Lufino on 10/11/2019. // import Foundation extension Luminous { // MARK: Disk /// Disk information. public struct Disk { // The credits for these functions are to Cuong Lam for this SO answer : http://stackoverflow.com/a/29417855/588967 private static func MBFormatter(_ bytes: Int64) -> String { let formatter = ByteCountFormatter() formatter.allowedUnits = ByteCountFormatter.Units.useMB formatter.countStyle = ByteCountFormatter.CountStyle.decimal formatter.includesUnit = false return formatter.string(fromByteCount: bytes) as String } /// The total disk space in string format (megabytes). @available(*, deprecated, message: "Use totalSpace(measureUnit:) instead.") public static var totalSpace: String { return ByteCountFormatter.string(fromByteCount: totalSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary) } /// The free disk space in string format (megabytes). @available(*, deprecated, message: "Use freeSpace(measureUnit:) instead.") public static var freeSpace: String { return ByteCountFormatter.string(fromByteCount: freeSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary) } /// The used disk space in string format (megabytes). @available(*, deprecated, message: "Use usedSpace(measureUnit:) instead.") public static var usedSpace: String { return ByteCountFormatter.string(fromByteCount: usedSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary) } /// The total disk space in bytes. 0 if something went wrong. public static var totalSpaceInBytes: Int64 { do { let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String) let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value return space! } catch { return 0 } } /// The free disk space in bytes. 0 if something went wrong. public static var freeSpaceInBytes: Int64 { do { let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String) let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value return freeSpace! } catch { return 0 } } /// The used disk space in bytes. 0 if something went wrong. @available(*, deprecated, message: "Use usedSpace(measureUnit:) instead.") public static var usedSpaceInBytes: Int64 { let usedSpace = totalSpaceInBytes - freeSpaceInBytes return usedSpace } /// The free disk space in percentage. @available(*, deprecated, message: "Use freeSpace(measureUnit:) instead.") public static var freeSpaceInPercentage: Float { let freeSpace = Float(freeSpaceInBytes) let totalSpace = Float(totalSpaceInBytes) return (freeSpace * 100) / totalSpace } /// The used disk space in percentage. public static var usedSpaceInPercentage: Float { let usedSpace = Float(usedSpaceInBytes) let totalSpace = Float(totalSpaceInBytes) return (usedSpace * 100) / totalSpace } /// The total space of the internal disk. /// - Parameter measureUnit: The measure unit. If `percentage` the return value will be `100.0`. public static func totalSpace(measureUnit: MeasureUnit = .bytes) -> Double { switch measureUnit { case .bytes: return Double(totalSpaceInBytes) case .kilobytes: return Double(totalSpaceInBytes / 1024) case .megabytes: return Double(totalSpaceInBytes / 1024 / 1024) case .gigabytes: return Double(totalSpaceInBytes / 1024 / 1024 / 1024) case .percentage: return 100.0 } } /// The used space of the internal disk. /// - Parameter measureUnit: The measure unit. public static func usedSpace(measureUnit: MeasureUnit = .bytes) -> Double { switch measureUnit { case .bytes: return Double(usedSpaceInBytes) case .kilobytes: return Double(usedSpaceInBytes / 1024) case .megabytes: return Double(usedSpaceInBytes / 1024 / 1024) case .gigabytes: return Double(usedSpaceInBytes / 1024 / 1024 / 1024) case .percentage: return Double(((usedSpaceInBytes * 100) / totalSpaceInBytes)) } } /// The free space of the internal disk. /// - Parameter measureUnit: The measure unit. public static func freeSpace(measureUnit: MeasureUnit = .bytes) -> Double { switch measureUnit { case .bytes: return Double(freeSpaceInBytes) case .kilobytes: return Double(freeSpaceInBytes / 1024) case .megabytes: return Double(freeSpaceInBytes / 1024 / 1024) case .gigabytes: return Double(freeSpaceInBytes / 1024 / 1024 / 1024) case .percentage: return Double(((freeSpaceInBytes * 100) / totalSpaceInBytes)) } } } }
mit
1728da22a437c417f9e20a14b947771e
39.108844
128
0.584634
5.34058
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift
15
4475
// // UISearchBar+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) #if !RX_NO_MODULE import RxSwift #endif import UIKit extension Reactive where Base: UISearchBar { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> { return RxSearchBarDelegateProxy.proxy(for: base) } /// Reactive wrapper for `text` property. public var text: ControlProperty<String?> { return value } /// Reactive wrapper for `text` property. public var value: ControlProperty<String?> { let source: Observable<String?> = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable<String?> in let text = searchBar?.text return (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) .map { a in return a[1] as? String } .startWith(text) } let bindingObserver = Binder(self.base) { (searchBar, text: String?) in searchBar.text = text } return ControlProperty(values: source, valueSink: bindingObserver) } /// Reactive wrapper for `selectedScopeButtonIndex` property. public var selectedScopeButtonIndex: ControlProperty<Int> { let source: Observable<Int> = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable<Int> in let index = source?.selectedScopeButtonIndex ?? 0 return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) .map { a in return try castOrThrow(Int.self, a[1]) } .startWith(index) } let bindingObserver = Binder(self.base) { (searchBar, index: Int) in searchBar.selectedScopeButtonIndex = index } return ControlProperty(values: source, valueSink: bindingObserver) } #if os(iOS) /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. public var cancelButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. public var bookmarkButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. public var resultsListButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } #endif /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. public var searchButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. public var textDidBeginEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. public var textDidEndEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } } #endif
mit
c006e547d59924c067813b7bcacda7b2
34.507937
156
0.662494
4.916484
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/LoginEpilogueViewController.swift
1
6228
import UIKit import WordPressShared import WordPressAuthenticator // MARK: - LoginEpilogueViewController // class LoginEpilogueViewController: UIViewController { /// Button Container View. /// @IBOutlet var buttonPanel: UIView! @IBOutlet var blurEffectView: UIVisualEffectView! /// Line displayed atop the buttonPanel when the table is scrollable. /// @IBOutlet var topLine: UIView! @IBOutlet var topLineHeightConstraint: NSLayoutConstraint! /// Done Button. /// @IBOutlet var doneButton: UIButton! /// Constraints on the table view container. /// Used to adjust the width on iPad. @IBOutlet var tableViewLeadingConstraint: NSLayoutConstraint! @IBOutlet var tableViewTrailingConstraint: NSLayoutConstraint! private var defaultTableViewMargin: CGFloat = 0 /// Blur effect on button panel /// private var blurEffect: UIBlurEffect.Style { return .systemChromeMaterial } /// Links to the Epilogue TableViewController /// private var tableViewController: LoginEpilogueTableViewController? /// Analytics Tracker /// private let tracker = AuthenticatorAnalyticsTracker.shared /// Closure to be executed upon dismissal. /// var onDismiss: (() -> Void)? /// Site that was just connected to our awesome app. /// var credentials: AuthenticatorCredentials? { didSet { guard isViewLoaded, let credentials = credentials else { return } refreshInterface(with: credentials) } } // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() guard let credentials = credentials else { fatalError() } view.backgroundColor = .basicBackground topLine.backgroundColor = .divider defaultTableViewMargin = tableViewLeadingConstraint.constant setTableViewMargins(forWidth: view.frame.width) refreshInterface(with: credentials) WordPressAuthenticator.track(.loginEpilogueViewed) // If the user just signed in, refresh the A/B assignments ABTest.start() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard let epilogueTableViewController = segue.destination as? LoginEpilogueTableViewController else { return } guard let credentials = credentials else { fatalError() } epilogueTableViewController.setup(with: credentials, onConnectSite: { [weak self] in self?.handleConnectAnotherButton() }) tableViewController = epilogueTableViewController } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIDevice.isPad() ? .all : .portrait } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() configurePanelBasedOnTableViewContents() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) setTableViewMargins(forWidth: size.width) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setTableViewMargins(forWidth: view.frame.width) } } // MARK: - Private Extension // private extension LoginEpilogueViewController { /// Refreshes the UI so that the specified WordPressSite is displayed. /// func refreshInterface(with credentials: AuthenticatorCredentials) { configureDoneButton() } /// Setup: Buttons /// func configureDoneButton() { doneButton.setTitle(NSLocalizedString("Done", comment: "A button title"), for: .normal) doneButton.accessibilityIdentifier = "Done" } /// Setup: Button Panel /// func configurePanelBasedOnTableViewContents() { guard let tableView = tableViewController?.tableView else { return } topLineHeightConstraint.constant = .hairlineBorderWidth let contentSize = tableView.contentSize let screenHeight = UIScreen.main.bounds.height let panelHeight = buttonPanel.frame.height if contentSize.height >= (screenHeight - panelHeight) { topLine.isHidden = false blurEffectView.effect = UIBlurEffect(style: blurEffect) blurEffectView.isHidden = false } else { buttonPanel.backgroundColor = .basicBackground topLine.isHidden = true blurEffectView.isHidden = true } } func setTableViewMargins(forWidth viewWidth: CGFloat) { guard traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular else { tableViewLeadingConstraint.constant = defaultTableViewMargin tableViewTrailingConstraint.constant = defaultTableViewMargin return } let marginMultiplier = UIDevice.current.orientation.isLandscape ? TableViewMarginMultipliers.ipadLandscape : TableViewMarginMultipliers.ipadPortrait let margin = viewWidth * marginMultiplier tableViewLeadingConstraint.constant = margin tableViewTrailingConstraint.constant = margin } enum TableViewMarginMultipliers { static let ipadPortrait: CGFloat = 0.1667 static let ipadLandscape: CGFloat = 0.25 } // MARK: - Actions @IBAction func dismissEpilogue() { tracker.track(click: .continue) onDismiss?() navigationController?.dismiss(animated: true) } func handleConnectAnotherButton() { guard let controller = WordPressAuthenticator.signinForWPOrg() else { return } navigationController?.setViewControllers([controller], animated: true) } }
gpl-2.0
b118e7b16f5cc990c2fc650afa9368b9
29.529412
112
0.674213
5.750693
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/UIActivityIndicator.swift
1
5122
// // UIActivityIndicator.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 26.03.17. // Copyright © 2017 Modum. All rights reserved. // import UIKit /* Custom UI activity indicator component */ class UIActivityIndicator : UIView { // MARK: Constants fileprivate let minStrokeLength: CGFloat = 0.05 fileprivate let maxStrokeLength: CGFloat = 0.7 // MARK: Properties fileprivate let circleShapeLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear initShapeLayer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func startAnimating() { if layer.animation(forKey: "rotation") == nil { startStrokeAnimation() startRotatingAnimation() } } func stopAnimating() { circleShapeLayer.removeAllAnimations() layer.removeAllAnimations() circleShapeLayer.transform = CATransform3DIdentity layer.transform = CATransform3DIdentity } fileprivate func initShapeLayer() { circleShapeLayer.actions = ["strokeEnd" : NSNull(), "strokeStart" : NSNull(), "transform" : NSNull(), "strokeColor" : NSNull()] circleShapeLayer.backgroundColor = UIColor.clear.cgColor circleShapeLayer.strokeColor = IOS7_BLUE_COLOR.cgColor circleShapeLayer.fillColor = UIColor.clear.cgColor circleShapeLayer.lineWidth = 5 circleShapeLayer.lineCap = kCALineCapRound circleShapeLayer.strokeStart = 0 circleShapeLayer.strokeEnd = minStrokeLength let center = CGPoint(x: bounds.width*0.5, y: bounds.height*0.5) circleShapeLayer.frame = bounds circleShapeLayer.path = UIBezierPath(arcCenter: center, radius: center.x, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true).cgPath layer.addSublayer(circleShapeLayer) } fileprivate func startRotatingAnimation() { let rotation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.toValue = Double.pi*2 rotation.duration = 2.2 rotation.isCumulative = true rotation.isAdditive = true rotation.repeatCount = Float.infinity layer.add(rotation, forKey: "rotation") } fileprivate func startStrokeAnimation() { let easeInOutSineTimingFunc = CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1.0) let progress: CGFloat = maxStrokeLength let endFromValue: CGFloat = circleShapeLayer.strokeEnd let endToValue: CGFloat = endFromValue + progress let strokeEnd = CABasicAnimation(keyPath: "strokeEnd") strokeEnd.fromValue = endFromValue strokeEnd.toValue = endToValue strokeEnd.duration = 0.5 strokeEnd.fillMode = kCAFillModeForwards strokeEnd.timingFunction = easeInOutSineTimingFunc strokeEnd.beginTime = 0.1 strokeEnd.isRemovedOnCompletion = false let startFromValue: CGFloat = circleShapeLayer.strokeStart let startToValue: CGFloat = fabs(endToValue - minStrokeLength) let strokeStart = CABasicAnimation(keyPath: "strokeStart") strokeStart.fromValue = startFromValue strokeStart.toValue = startToValue strokeStart.duration = 0.4 strokeStart.fillMode = kCAFillModeForwards strokeStart.timingFunction = easeInOutSineTimingFunc strokeStart.beginTime = strokeEnd.beginTime + strokeEnd.duration + 0.2 strokeStart.isRemovedOnCompletion = false let pathAnim = CAAnimationGroup() pathAnim.animations = [strokeEnd, strokeStart] pathAnim.duration = strokeStart.beginTime + strokeStart.duration pathAnim.fillMode = kCAFillModeForwards pathAnim.isRemovedOnCompletion = false CATransaction.begin() CATransaction.setCompletionBlock { if self.circleShapeLayer.animation(forKey: "stroke") != nil { self.circleShapeLayer.transform = CATransform3DRotate(self.circleShapeLayer.transform, CGFloat(Double.pi*2) * progress, 0, 0, 1) self.circleShapeLayer.removeAnimation(forKey: "stroke") self.startStrokeAnimation() } } circleShapeLayer.add(pathAnim, forKey: "stroke") CATransaction.commit() } }
apache-2.0
872aa92820ccdd41680076c821b43da7
41.322314
144
0.584651
5.590611
false
false
false
false
oceanfive/swift
swift_two/swift_two/Classes/View(controller)/Home/HYRetweetedStatusView.swift
1
1357
// // HYRetweetedStatusView.swift // swift_two // // Created by ocean on 16/6/21. // Copyright © 2016年 ocean. All rights reserved. // import UIKit class HYRetweetedStatusView: UIView { let nameLabel = UILabel() let textLabel = UILabel() var retweetedStatusFrame = HYRetweetedStatusFrame(){ willSet(newValue){ let status = newValue.status //MARK: - 不要忘记设置本身的frame self.frame = newValue.frame! nameLabel.frame = newValue.nameLabelFrame! nameLabel.text = "@\((status.retweeted_status?.user?.name)!)" textLabel.frame = newValue.textLabelFrame! textLabel.text = status.retweeted_status?.text } } override init(frame: CGRect) { super.init(frame: frame) addSubview(nameLabel) nameLabel.font = kHomeCellRetweetedNameLabelFont nameLabel.textColor = kHomeCellRetweetedNameLabelColor addSubview(textLabel) textLabel.font = kHomeCellRetweetedTextLabelFont textLabel.textColor = kHomeCellRetweetedTextLabelColor textLabel.numberOfLines = 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b7e1105535e6e27fe1d834e0263817d6
21.644068
73
0.606287
4.875912
false
false
false
false
alblue/swift-corelibs-foundation
TestFoundation/TestProcess.swift
1
23381
// This source file is part of the Swift.org open source project // // Copyright (c) 2015 - 2016, 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // class TestProcess : XCTestCase { static var allTests: [(String, (TestProcess) -> () throws -> Void)] { #if os(Android) return [] #else return [ ("test_exit0" , test_exit0), ("test_exit1" , test_exit1), ("test_exit100" , test_exit100), ("test_sleep2", test_sleep2), ("test_sleep2_exit1", test_sleep2_exit1), ("test_terminationReason_uncaughtSignal", test_terminationReason_uncaughtSignal), ("test_pipe_stdin", test_pipe_stdin), ("test_pipe_stdout", test_pipe_stdout), ("test_pipe_stderr", test_pipe_stderr), ("test_current_working_directory", test_current_working_directory), ("test_pipe_stdout_and_stderr_same_pipe", test_pipe_stdout_and_stderr_same_pipe), ("test_file_stdout", test_file_stdout), ("test_passthrough_environment", test_passthrough_environment), ("test_no_environment", test_no_environment), ("test_custom_environment", test_custom_environment), ("test_run", test_run), ("test_preStartEndState", test_preStartEndState), ("test_interrupt", test_interrupt), ("test_terminate", test_terminate), ("test_suspend_resume", test_suspend_resume), ] #endif } #if !os(Android) func test_exit0() { let process = Process() let executablePath = "/bin/bash" if #available(OSX 10.13, *) { process.executableURL = URL(fileURLWithPath: executablePath) } else { // Fallback on earlier versions process.launchPath = executablePath } XCTAssertEqual(executablePath, process.launchPath) process.arguments = ["-c", "exit 0"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 0) XCTAssertEqual(process.terminationReason, .exit) } func test_exit1() { let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "exit 1"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 1) XCTAssertEqual(process.terminationReason, .exit) } func test_exit100() { let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "exit 100"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 100) XCTAssertEqual(process.terminationReason, .exit) } func test_sleep2() { let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "sleep 2"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 0) XCTAssertEqual(process.terminationReason, .exit) } func test_sleep2_exit1() { let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "sleep 2; exit 1"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 1) XCTAssertEqual(process.terminationReason, .exit) } func test_terminationReason_uncaughtSignal() { let process = Process() process.launchPath = "/bin/bash" process.arguments = ["-c", "kill -TERM $$"] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 15) XCTAssertEqual(process.terminationReason, .uncaughtSignal) } func test_pipe_stdin() { let process = Process() process.launchPath = "/bin/cat" let outputPipe = Pipe() process.standardOutput = outputPipe let inputPipe = Pipe() process.standardInput = inputPipe process.launch() inputPipe.fileHandleForWriting.write("Hello, 🐶.\n".data(using: .utf8)!) // Close the input pipe to send EOF to cat. inputPipe.fileHandleForWriting.closeFile() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 0) let data = outputPipe.fileHandleForReading.availableData guard let string = String(data: data, encoding: .utf8) else { XCTFail("Could not read stdout") return } XCTAssertEqual(string, "Hello, 🐶.\n") } func test_pipe_stdout() { let process = Process() process.launchPath = "/usr/bin/which" process.arguments = ["which"] let pipe = Pipe() process.standardOutput = pipe process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 0) let data = pipe.fileHandleForReading.availableData guard let string = String(data: data, encoding: .ascii) else { XCTFail("Could not read stdout") return } XCTAssertTrue(string.hasSuffix("/which\n")) } func test_pipe_stderr() { let process = Process() process.launchPath = "/bin/cat" process.arguments = ["invalid_file_name"] let errorPipe = Pipe() process.standardError = errorPipe process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 1) let data = errorPipe.fileHandleForReading.availableData guard let _ = String(data: data, encoding: .ascii) else { XCTFail("Could not read stdout") return } // testing the return value of an external process does not port well, and may change. // XCTAssertEqual(string, "/bin/cat: invalid_file_name: No such file or directory\n") } func test_pipe_stdout_and_stderr_same_pipe() { let process = Process() process.launchPath = "/bin/cat" process.arguments = ["invalid_file_name"] let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe // Clear the environment to stop the malloc debug flags used in Xcode debug being // set in the subprocess. process.environment = [:] process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 1) let data = pipe.fileHandleForReading.availableData guard let string = String(data: data, encoding: .ascii) else { XCTFail("Could not read stdout") return } // Remove the leading '/bin/' since on macOS '/bin/cat' just outputs 'cat:' let searchStr = "/bin/" let errMsg = string.replacingOccurrences(of: searchStr, with: "", options: [.literal, .anchored], range: searchStr.startIndex..<searchStr.endIndex) XCTAssertEqual(errMsg, "cat: invalid_file_name: No such file or directory\n") } func test_file_stdout() { let process = Process() process.launchPath = "/usr/bin/which" process.arguments = ["which"] mkstemp(template: "TestProcess.XXXXXX") { handle in process.standardOutput = handle process.launch() process.waitUntilExit() XCTAssertEqual(process.terminationStatus, 0) handle.seek(toFileOffset: 0) let data = handle.readDataToEndOfFile() guard let string = String(data: data, encoding: .ascii) else { XCTFail("Could not read stdout") return } XCTAssertTrue(string.hasSuffix("/which\n")) } } func test_passthrough_environment() { do { let (output, _) = try runTask(["/usr/bin/env"], environment: nil) let env = try parseEnv(output) XCTAssertGreaterThan(env.count, 0) } catch let error { XCTFail("Test failed: \(error)") } } func test_no_environment() { do { let (output, _) = try runTask(["/usr/bin/env"], environment: [:]) let env = try parseEnv(output) XCTAssertEqual(env.count, 0) } catch let error { XCTFail("Test failed: \(error)") } } func test_custom_environment() { do { let input = ["HELLO": "WORLD", "HOME": "CUPERTINO"] let (output, _) = try runTask(["/usr/bin/env"], environment: input) let env = try parseEnv(output) XCTAssertEqual(env, input) } catch let error { XCTFail("Test failed: \(error)") } } private func realpathOf(path: String) -> String? { let fm = FileManager.default let length = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: length) let fsRep = fm.fileSystemRepresentation(withPath: path) #if !DARWIN_COMPATIBILITY_TESTS defer { fsRep.deallocate() } #endif guard let result = realpath(fsRep, &buf) else { return nil } return fm.string(withFileSystemRepresentation: result, length: strlen(result)) } func test_current_working_directory() { let tmpDir = "/tmp" guard let resolvedTmpDir = realpathOf(path: tmpDir) else { XCTFail("Cant find realpath of /tmp") return } let fm = FileManager.default let previousWorkingDirectory = fm.currentDirectoryPath // Test that getcwd() returns the currentDirectoryPath do { let (pwd, _) = try runTask([xdgTestHelperURL().path, "--getcwd"], currentDirectoryPath: tmpDir) // Check the sub-process used the correct directory XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), resolvedTmpDir) } catch let error { XCTFail("Test failed: \(error)") } // Test that $PWD by default is set to currentDirectoryPath do { let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], currentDirectoryPath: tmpDir) // Check the sub-process used the correct directory XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), tmpDir) } catch let error { XCTFail("Test failed: \(error)") } // Test that $PWD can be over-ridden do { var env = ProcessInfo.processInfo.environment env["PWD"] = "/bin" let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], environment: env, currentDirectoryPath: tmpDir) // Check the sub-process used the correct directory XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), "/bin") } catch let error { XCTFail("Test failed: \(error)") } // Test that $PWD can be set to empty do { var env = ProcessInfo.processInfo.environment env["PWD"] = "" let (pwd, _) = try runTask([xdgTestHelperURL().path, "--echo-PWD"], environment: env, currentDirectoryPath: tmpDir) // Check the sub-process used the correct directory XCTAssertEqual(pwd.trimmingCharacters(in: .newlines), "") } catch let error { XCTFail("Test failed: \(error)") } XCTAssertEqual(previousWorkingDirectory, fm.currentDirectoryPath) } func test_run() { let fm = FileManager.default let cwd = fm.currentDirectoryPath do { let process = try Process.run(URL(fileURLWithPath: "/bin/sh", isDirectory: false), arguments: ["-c", "exit 123"], terminationHandler: nil) process.waitUntilExit() XCTAssertEqual(process.terminationReason, .exit) XCTAssertEqual(process.terminationStatus, 123) } catch { XCTFail("Cant execute /bin/sh: \(error)") } XCTAssertEqual(fm.currentDirectoryPath, cwd) do { let process = Process() process.executableURL = URL(fileURLWithPath: "/bin/sh", isDirectory: false) process.arguments = ["-c", "exit 0"] process.currentDirectoryURL = URL(fileURLWithPath: "/.../_no_such_directory", isDirectory: true) try process.run() XCTFail("Executed /bin/sh with invalid currentDirectoryURL") process.terminate() process.waitUntilExit() } catch { } XCTAssertEqual(fm.currentDirectoryPath, cwd) do { let process = Process() process.executableURL = URL(fileURLWithPath: "/..", isDirectory: false) process.arguments = [] process.currentDirectoryURL = URL(fileURLWithPath: "/tmp") try process.run() XCTFail("Somehow executed a directory!") process.terminate() process.waitUntilExit() } catch { } XCTAssertEqual(fm.currentDirectoryPath, cwd) fm.changeCurrentDirectoryPath(cwd) } func test_preStartEndState() { let process = Process() XCTAssertNil(process.executableURL) XCTAssertNotNil(process.currentDirectoryURL) XCTAssertNil(process.arguments) XCTAssertNil(process.environment) XCTAssertFalse(process.isRunning) XCTAssertEqual(process.processIdentifier, 0) XCTAssertEqual(process.qualityOfService, .default) process.executableURL = URL(fileURLWithPath: "/bin/cat", isDirectory: false) _ = try? process.run() XCTAssertTrue(process.isRunning) XCTAssertTrue(process.processIdentifier > 0) process.terminate() process.waitUntilExit() XCTAssertFalse(process.isRunning) XCTAssertTrue(process.processIdentifier > 0) XCTAssertEqual(process.terminationReason, .uncaughtSignal) XCTAssertEqual(process.terminationStatus, SIGTERM) } func test_interrupt() { let helper = _SignalHelperRunner() do { try helper.start() } catch { XCTFail("Cant run xdgTestHelper: \(error)") return } if !helper.waitForReady() { XCTFail("Didnt receive Ready from sub-process") return } let now = DispatchTime.now().uptimeNanoseconds let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000) var count = 3 while count > 0 { helper.process.interrupt() guard helper.semaphore.wait(timeout: timeout) == .success else { helper.process.terminate() XCTFail("Timedout waiting for signal") return } if helper.sigIntCount == 3 { break } count -= 1 } helper.process.terminate() XCTAssertEqual(helper.sigIntCount, 3) helper.process.waitUntilExit() let terminationReason = helper.process.terminationReason XCTAssertEqual(terminationReason, Process.TerminationReason.exit) let status = helper.process.terminationStatus XCTAssertEqual(status, 99) } func test_terminate() { let cat = URL(fileURLWithPath: "/bin/cat", isDirectory: false) guard let process = try? Process.run(cat, arguments: []) else { XCTFail("Cant run /bin/cat") return } process.terminate() process.waitUntilExit() let terminationReason = process.terminationReason XCTAssertEqual(terminationReason, Process.TerminationReason.uncaughtSignal) XCTAssertEqual(process.terminationStatus, SIGTERM) } func test_suspend_resume() { let helper = _SignalHelperRunner() do { try helper.start() } catch { XCTFail("Cant run xdgTestHelper: \(error)") return } if !helper.waitForReady() { XCTFail("Didnt receive Ready from sub-process") return } let now = DispatchTime.now().uptimeNanoseconds let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000) func waitForSemaphore() -> Bool { guard helper.semaphore.wait(timeout: timeout) == .success else { helper.process.terminate() XCTFail("Timedout waiting for signal") return false } return true } XCTAssertTrue(helper.process.isRunning) XCTAssertTrue(helper.process.suspend()) XCTAssertTrue(helper.process.isRunning) XCTAssertTrue(helper.process.resume()) if waitForSemaphore() == false { return } XCTAssertEqual(helper.sigContCount, 1) XCTAssertTrue(helper.process.resume()) XCTAssertTrue(helper.process.suspend()) XCTAssertTrue(helper.process.resume()) XCTAssertEqual(helper.sigContCount, 1) XCTAssertTrue(helper.process.suspend()) XCTAssertTrue(helper.process.suspend()) XCTAssertTrue(helper.process.resume()) if waitForSemaphore() == false { return } helper.process.suspend() helper.process.resume() if waitForSemaphore() == false { return } XCTAssertEqual(helper.sigContCount, 3) helper.process.terminate() helper.process.waitUntilExit() XCTAssertFalse(helper.process.isRunning) XCTAssertFalse(helper.process.suspend()) XCTAssertTrue(helper.process.resume()) XCTAssertTrue(helper.process.resume()) } #endif } private enum Error: Swift.Error { case TerminationStatus(Int32) case UnicodeDecodingError(Data) case InvalidEnvironmentVariable(String) } // Run xdgTestHelper, wait for 'Ready' from the sub-process, then signal a semaphore. // Read lines from a pipe and store in a queue. class _SignalHelperRunner { let process = Process() let semaphore = DispatchSemaphore(value: 0) private let outputPipe = Pipe() private let sQueue = DispatchQueue(label: "io queue") private let source: DispatchSourceRead private var gotReady = false private var bytesIn = Data() private var _sigIntCount = 0 private var _sigContCount = 0 var sigIntCount: Int { return sQueue.sync { return _sigIntCount } } var sigContCount: Int { return sQueue.sync { return _sigContCount } } init() { process.executableURL = xdgTestHelperURL() process.environment = ProcessInfo.processInfo.environment process.arguments = ["--signal-test"] process.standardOutput = outputPipe.fileHandleForWriting source = DispatchSource.makeReadSource(fileDescriptor: outputPipe.fileHandleForReading.fileDescriptor, queue: sQueue) let workItem = DispatchWorkItem(block: { [weak self] in if let strongSelf = self { let newLine = UInt8(ascii: "\n") strongSelf.bytesIn.append(strongSelf.outputPipe.fileHandleForReading.availableData) if strongSelf.bytesIn.isEmpty { return } // Split the incoming data into lines. while let index = strongSelf.bytesIn.index(of: newLine) { if index >= strongSelf.bytesIn.startIndex { // dont include the newline when converting to string let line = String(data: strongSelf.bytesIn[strongSelf.bytesIn.startIndex..<index], encoding: String.Encoding.utf8) ?? "" strongSelf.bytesIn.removeSubrange(strongSelf.bytesIn.startIndex...index) if strongSelf.gotReady == false && line == "Ready" { strongSelf.semaphore.signal() strongSelf.gotReady = true; } else if strongSelf.gotReady == true { if line == "Signal: SIGINT" { strongSelf._sigIntCount += 1 strongSelf.semaphore.signal() } else if line == "Signal: SIGCONT" { strongSelf._sigContCount += 1 strongSelf.semaphore.signal() } } } } } }) source.setEventHandler(handler: workItem) } deinit { source.cancel() process.terminate() process.waitUntilExit() } func start() throws { source.resume() try process.run() } func waitForReady() -> Bool { let now = DispatchTime.now().uptimeNanoseconds let timeout = DispatchTime(uptimeNanoseconds: now + 2_000_000_000) guard semaphore.wait(timeout: timeout) == .success else { process.terminate() return false } return true } } #if !os(Android) private func runTask(_ arguments: [String], environment: [String: String]? = nil, currentDirectoryPath: String? = nil) throws -> (String, String) { let process = Process() var arguments = arguments process.launchPath = arguments.removeFirst() process.arguments = arguments // Darwin Foundation doesnt allow .environment to be set to nil although the documentation // says it is an optional. https://developer.apple.com/documentation/foundation/process/1409412-environment if let e = environment { process.environment = e } if let directoryPath = currentDirectoryPath { process.currentDirectoryPath = directoryPath } let stdoutPipe = Pipe() let stderrPipe = Pipe() process.standardOutput = stdoutPipe process.standardError = stderrPipe try process.run() process.waitUntilExit() guard process.terminationStatus == 0 else { throw Error.TerminationStatus(process.terminationStatus) } let stdoutData = stdoutPipe.fileHandleForReading.availableData guard let stdout = String(data: stdoutData, encoding: .utf8) else { throw Error.UnicodeDecodingError(stdoutData) } let stderrData = stderrPipe.fileHandleForReading.availableData guard let stderr = String(data: stderrData, encoding: .utf8) else { throw Error.UnicodeDecodingError(stderrData) } return (stdout, stderr) } private func parseEnv(_ env: String) throws -> [String: String] { var result = [String: String]() for line in env.components(separatedBy: "\n") where line != "" { guard let range = line.range(of: "=") else { throw Error.InvalidEnvironmentVariable(line) } result[String(line[..<range.lowerBound])] = String(line[range.upperBound...]) } return result } #endif
apache-2.0
217e3d6f7630adacb4f0fb21516a94b9
34.150376
150
0.592043
5.017171
false
true
false
false
smartystreets/smartystreets-ios-sdk
Sources/SmartyStreets/USExtract/USExtractResult.swift
1
1300
import Foundation @objcMembers public class USExtractResult: NSObject, Codable { // See "https://smartystreets.com/docs/cloud/us-extract-api#http-response-status" public var metadata:USExtractMetadata? public var addresses:[USExtractAddress]? init(dictionary: NSDictionary) { super.init() if let metadata = dictionary["meta"] { self.metadata = USExtractMetadata(dictionary: metadata as! NSDictionary) } else { self.metadata = USExtractMetadata(dictionary: NSDictionary()) } if let addresses = dictionary["addresses"] { self.addresses = convertToAddressObjects(addresses as! [[String:Any]]) } else { self.addresses = [USExtractAddress]() } } func convertToAddressObjects(_ object:[[String:Any]]) -> [USExtractAddress] { var mutable = [USExtractAddress]() for city in object { mutable.append(USExtractAddress(dictionary: city as NSDictionary)) } return mutable } func getAddressAtIndex(index:Int) -> USExtractAddress { if let addresses = self.addresses { return addresses[index] } else { return USExtractAddress(dictionary: NSDictionary()) } } }
apache-2.0
2f7718dd4736b55df0c8bc1a8891f60d
33.210526
88
0.621538
4.779412
false
false
false
false
jflinter/Dwifft
Dwifft/AbstractDiffCalculator.swift
1
4201
// // AbstractDiffCalculator.swift // Dwifft // // Created by Jack Flintermann on 12/11/17. // Copyright © 2017 jflinter. All rights reserved. // import Foundation /// A parent class for all diff calculators. Don't use it directly. public class AbstractDiffCalculator<Section: Equatable, Value: Equatable> { internal init(initialSectionedValues: SectionedValues<Section, Value>) { self._sectionedValues = initialSectionedValues } /// The number of sections in the diff calculator. Return this inside /// `numberOfSections(in: tableView)` or `numberOfSections(in: collectionView)`. /// Don't implement that method any other way (see the docs for `numberOfObjects(inSection:)` /// for more context). public final func numberOfSections() -> Int { return self.sectionedValues.sections.count } /// The section at a given index. If you implement `tableView:titleForHeaderInSection` or /// `collectionView:viewForSupplementaryElementOfKind:atIndexPath`, you can use this /// method to get information about that section out of Dwifft. /// /// - Parameter forSection: the index of the section you care about. /// - Returns: the Section at that index. public final func value(forSection: Int) -> Section { return self.sectionedValues[forSection].0 } /// The, uh, number of objects in a given section. Use this to implement /// `UITableViewDataSource.numberOfRowsInSection:` or `UICollectionViewDataSource.numberOfItemsInSection:`. /// Seriously, don't implement that method any other way - there is some subtle timing stuff /// around when this value should change in order to satisfy `UITableView`/`UICollectionView`'s internal /// assertions, that Dwifft knows how to handle correctly. Read the source for /// Dwifft+UIKit.swift if you don't believe me/want to learn more. /// /// - Parameter section: a section of your table/collection view /// - Returns: the number of objects in that section. public final func numberOfObjects(inSection section: Int) -> Int { return self.sectionedValues[section].1.count } /// The value at a given index path. Use this to implement /// `UITableViewDataSource.cellForRowAtIndexPath` or `UICollectionViewDataSource.cellForItemAtIndexPath`. /// /// - Parameter indexPath: the index path you are interested in /// - Returns: the thing at that index path public final func value(atIndexPath indexPath: IndexPath) -> Value { #if os(iOS) || os(tvOS) let row = indexPath.row #endif #if os(macOS) let row = indexPath.item #endif return self.sectionedValues[indexPath.section].1[row] } /// Set this variable to automatically trigger the correct section/row/item insertion/deletions /// on your table/collection view. public final var sectionedValues: SectionedValues<Section, Value> { get { return _sectionedValues } set { let oldSectionedValues = sectionedValues let newSectionedValues = newValue let diff = Dwifft.diff(lhs: oldSectionedValues, rhs: newSectionedValues) if (diff.count > 0) { self.processChanges(newState: newSectionedValues, diff: diff) } } } internal static func buildSectionedValues(values: [Value], sectionIndex: Int) -> SectionedValues<Int, Value> { let firstRows = (0..<sectionIndex).map { ($0, [Value]()) } return SectionedValues(firstRows + [(sectionIndex, values)]) } // UITableView and UICollectionView both perform assertions on the *current* number of rows/items before performing any updates. As such, the `sectionedValues` property must be backed by an internal value that does not change until *after* `beginUpdates`/`performBatchUpdates` has been called. internal final var _sectionedValues: SectionedValues<Section, Value> internal func processChanges(newState: SectionedValues<Section, Value>, diff: [SectionedDiffStep<Section, Value>]){ fatalError("override me") } }
mit
2ad0111c31195a1ffd01aff3d424c014
44.16129
297
0.684048
4.8
false
false
false
false
Eonil/Editor
Editor4/WorkspaceSerializationUtility.swift
1
6202
// // WorkspaceFileList.swift // Editor4 // // Created by Hoon H. on 2016/05/27. // Copyright © 2016 Eonil. All rights reserved. // /// Provides serialization of workspace path items. /// /// This serializes a path item into a custom schemed URL. /// Each path items will be stored in this form. /// /// editor://workspace/folder1/folder2?group /// editor://workspace/folder1/folder2/file3?comment=extra%20info /// /// Rules /// ----- /// 1. Conforms RFC URL standards. (done by Cocoa classes) /// 2. Slashes(`/`) cannot be a part of node name. Even with escapes. /// This equally applied to all of Unix file systems and URL standards. /// You must use slashes as a directory separator to conform URL standard /// even if you're using this data on Windows. /// 3. All files are stored in sorted flat list. Yes, base paths are /// duplicated redundant data, but this provides far more DVCS-friendly /// (diff/merge) data form, and I believe that is far more important /// then micro spatial efficiency. Also, in most cases, you will be /// using at least a kind of compression, and this kind of redundancy /// is very compression friendly. /// /// Workspace is defined by a sorted list of paths to files in the workspace. /// All items are full paths to workspace root. /// Container directories must have an explicit entry. Missing container /// is an error. /// /// Strict reader requires all intermediate folders comes up before any /// descendant nodes. Anyway error-tolerant reader will be provided later /// for practical use with DVCS systems by inferring missing containers. /// /// **WARNING:** /// In early development stage, all items must be sorted in TOPOLOGICAL ORDER. /// In later version we will ship an error-tolerant version that performs; /// - Filling missing group items automatically. /// - Re-sorting items in topologic order. /// - Removing duplicated group entries. /// - Removing duplicated non-group entries. /// struct WorkspaceSerializationUtility { static func deserialize(s: String) throws -> WorkspaceState { var workspaceState = WorkspaceState() try workspaceState.files.deserializeAndReset(s) return workspaceState } static func serialize(workspaceState: WorkspaceState) throws -> AnySequence<String> { let fileLines = try workspaceState.files.serialize() var fileLineGenerator = fileLines.generate() var isSeparator = true return AnySequence { return AnyGenerator { () -> String? in isSeparator.flip() if isSeparator { return "\n" } return fileLineGenerator.next() } } } } private extension Bool { mutating func flip() { self = !self } } struct SerializationError: ErrorType { var message: String init(_ message: String) { self.message = message } } import Foundation.NSURL private extension FileTree2 { private mutating func deserializeAndReset(s: String) throws { let lines = s.componentsSeparatedByString("\n") var newTree = FileTree2(rootState: FileState2(form: .Container, phase: .Normal, name: "")) try lines.filter({ $0.isEmpty == false }).forEach({ try newTree.deserializeAndAppendFile($0) }) // Atomic transaction. self = newTree } private mutating func deserializeAndAppendFile(s: String) throws { guard let u = NSURLComponents(string: s) else { throw SerializationError("Ill-formed code `\(s)`. Not a proper URL.") } guard u.scheme == "editor" else { throw SerializationError("Bad scheme `\(u.scheme ?? "nil")`.") } guard u.host == "workspace" else { throw SerializationError("Bad host `\(u.host ?? "nil")`.") } guard let p = u.path else { throw SerializationError("Missing path from url `\(s)`.") } let qs = u.queryItems ?? [] let path = FileNodePath(p.componentsSeparatedByString("/").filter({ $0.isEmpty == false })) guard let (superfilePath, fileName) = path.splitLast() else { return () /* Root path. Already exists. */ } var fileState = FileState2(form: (qs.contains({ $0.name == "group" }) ? .Container : .Data), phase: .Normal, name: fileName) fileState.comment = qs.filter({ $0.name == "comment" }).first?.value guard let superfileID = self.searchFileIDForPath(superfilePath) else { throw SerializationError("Missing super-file ID for path `\(superfilePath)`.") } try append(fileState, asSubnodeOf: superfileID) } } private extension FileTree2 { private func collectAllFileIDsInDFS() -> [FileID2] { var buffer = [FileID2]() buffer.reserveCapacity(count) func collectIn(fileID: FileID2) { buffer.append(fileID) for subfileID in self[fileID].subfileIDs { collectIn(subfileID) } } collectIn(rootID) return buffer } /// Performs serialization for all files in DFS order. private func serialize() throws -> [String] { return try collectAllFileIDsInDFS().map(serializeFile) } private func serializeFile(fileID: FileID2) throws -> String { assert(contains(fileID)) let fileState = self[fileID] let filePath = self.resolvePathFor(fileID) let u = NSURLComponents() u.scheme = "editor" u.host = "workspace" u.path = "/" + filePath.keys.joinWithSeparator("/") u.queryItems = [ fileState.serializeGrouping(), fileState.serializeComment(), ].flatMap({ $0 }) guard let s = u.string else { throw SerializationError("Cannot get `string` from `\(u)`.") } return s } } private extension FileState2 { private func serializeGrouping() -> NSURLQueryItem? { guard form == .Container else { return nil } return NSURLQueryItem(name: "group", value: nil) } private func serializeComment() -> NSURLQueryItem? { guard let comment = comment else { return nil } return NSURLQueryItem(name: "comment", value: comment) } }
mit
b1df12fc310f5e0eadf9618e56ffca00
35.263158
159
0.645864
4.366901
false
false
false
false
hardikamal/actor-platform
actor-apps/app-ios/Actor/Controllers/Settings/SettingsPrivacyViewController.swift
24
4949
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class SettingsPrivacyViewController: AATableViewController { // MARK: - // MARK: Private vars private let CellIdentifier = "CellIdentifier" private var authSessions: [APAuthSession]? // MARK: - // MARK: Constructors init() { super.init(style: UITableViewStyle.Grouped) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title") tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier) tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.separatorStyle = UITableViewCellSeparatorStyle.None execute(MSG.loadSessionsCommand(), successBlock: { (val) -> Void in var list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! APAuthSession) } self.tableView.reloadData() }, failureBlock: nil) } // MARK: - // MARK: Getters private func terminateSessionsCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("PrivacyTerminate", comment: "Terminate action")) cell.style = .Normal // cell.showTopSeparator() // cell.showBottomSeparator() return cell } private func sessionsCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell var session = authSessions![indexPath.row] cell.setContent(session.getDeviceTitle()) cell.style = .Normal // if (indexPath.row == 0) { // cell.showTopSeparator() // } else { // cell.hideTopSeparator() // } // cell.showBottomSeparator() return cell } // MARK: - // MARK: UITableView Data Source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if authSessions != nil { if count(authSessions!) > 0 { return 2 } } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return count(authSessions!) } return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 && indexPath.row == 0 { return terminateSessionsCell(indexPath) } else if (indexPath.section == 1) { return sessionsCell(indexPath) } return UITableViewCell() } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section > 0 { return nil } return NSLocalizedString("PrivacyTerminateHint", comment: "Terminate hint") } // MARK: - // MARK: UITableView Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 0 { execute(MSG.terminateAllSessionsCommand()) } else if (indexPath.section == 1) { execute(MSG.terminateSessionCommandWithId(authSessions![indexPath.row].getId()), successBlock: { (val) -> Void in self.execute(MSG.loadSessionsCommand(), successBlock: { (val) -> Void in var list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! APAuthSession) } self.tableView.reloadData() }, failureBlock: nil) }, failureBlock: nil) } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.sectionColor } func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.hintColor } }
mit
1cd6a27d17a35cdc211d3d93fb05c05b
34.35
125
0.615882
5.338727
false
false
false
false
lanjing99/RxSwiftDemo
24-building-complete-rxswift-app/starter/QuickTodo/QuickTodo/Extensions/UINavigationController+Rx.swift
3
2235
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import RxCocoa class RxNavigationControllerDelegateProxy: DelegateProxy, DelegateProxyType, UINavigationControllerDelegate { static func currentDelegateFor(_ object: AnyObject) -> AnyObject? { guard let navigationController = object as? UINavigationController else { fatalError() } return navigationController.delegate } static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { guard let navigationController = object as? UINavigationController else { fatalError() } if delegate == nil { navigationController.delegate = nil } else { guard let delegate = delegate as? UINavigationControllerDelegate else { fatalError() } navigationController.delegate = delegate } } } extension Reactive where Base: UINavigationController { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var delegate: DelegateProxy { return RxNavigationControllerDelegateProxy.proxyForObject(base) } }
mit
27c4a470233969acd8c6dd291c47fa2e
36.881356
109
0.747204
5.185615
false
false
false
false
wangyuanou/Coastline
Coastline/UI/View+Animation.swift
1
5698
// // View+Animation.swift // Coastline // // Created by 王渊鸥 on 2017/1/20. // Copyright © 2017年 王渊鸥. All rights reserved. // import UIKit public extension UIView { public func shake(_ duration:TimeInterval, times:Int, offset:CGFloat, completion: ((Bool) -> Swift.Void)? = nil) { UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(), animations: { [weak self] in guard let view = self else { return } let perTime = 1.0 / Double(times) let basePos = view.frameLeft for n in 0..<times { let start = Double(n) * perTime if n == times - 1 { UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: perTime, animations: { [weak view, basePos] in view?.frameLeft = basePos }) } else if n % 2 == 0 { UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: perTime, animations: { [weak view, basePos, offset] in view?.frameLeft = basePos - offset }) } else { UIView.addKeyframe(withRelativeStartTime: start, relativeDuration: perTime, animations: { [weak view, basePos, offset] in view?.frameLeft = basePos + offset }) } } }, completion: completion) } public func popOut(_ duration:TimeInterval, completion:((Bool)-> Swift.Void)? = nil) { guard let sv = self.superview else { completion?(false) return } self.frameTop = sv.bounds.height self.frameCenterH = sv.bounds.width / 2.0 UIView.animateKeyframes(withDuration: duration+0.3, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { [weak self, weak sv, duration] in guard let view = self, let sv = sv else { return } let p0 = duration / (duration + 0.3) let pL = (1.0 - p0) / 3.0 UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: p0, animations: { [weak view, weak sv] in guard let sv = sv else { return } view?.frameTop = sv.bounds.height * 2.0 / 3.0 }) UIView.addKeyframe(withRelativeStartTime: p0, relativeDuration: pL, animations: { [weak view, weak sv] in guard let sv = sv else { return } view?.frameTop = sv.bounds.height * 2.0 / 3.0 - 5.0 }) UIView.addKeyframe(withRelativeStartTime: p0+pL, relativeDuration: pL, animations: { [weak view, weak sv] in guard let sv = sv else { return } view?.frameTop = sv.bounds.height * 2.0 / 3.0 + 5.0 }) UIView.addKeyframe(withRelativeStartTime: p0+2*pL, relativeDuration: pL, animations: { [weak view, weak sv] in guard let sv = sv else { return } view?.frameTop = sv.bounds.height * 2.0 / 3.0 }) }, completion: completion) } public func unPopOut(_ duration:TimeInterval, completion:((Bool)-> Swift.Void)? = nil) { UIView.animate(withDuration: duration, animations: { [weak self] in guard let sv = self?.superview else { return } self?.frameTop = sv.bounds.height }, completion: completion) } public func startWaiting(title:String, timeout:TimeInterval = 5.0) { endWaiting() let backView = UIView(frame: self.bounds) backView.tag = 12301 backView.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.4) self.addSubview(backView) let barView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 120)) barView.backgroundColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.9) barView.frameCetner = backView.boundsCenter barView.layer.masksToBounds = true barView.layer.cornerRadius = 8.0 backView.addSubview(barView) let pgLayer = CAShapeLayer() let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 40, height: 40)) path.lineWidth = 20 pgLayer.fillColor = nil pgLayer.strokeColor = UIColor.white.cgColor pgLayer.path = path.cgPath pgLayer.strokeStart = 0.0 pgLayer.strokeEnd = 0.8 pgLayer.lineWidth = 5 pgLayer.lineCap = kCALineCapRound pgLayer.frame = CGRect(center:barView.bounds.center, size:CGSize(width:40, height:40)).offsetBy(dx: 0, dy: -5) barView.layer.addSublayer(pgLayer) pgLayer.addCycleAnimation() let label = UILabel(frame: CGRect(x: 0, y: 0, width: 120, height: 20)) label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.white label.text = title label.frameCetner = barView.boundsCenter label.textAlignment = .center label.frameTop += 40 barView.addSubview(label) if timeout > 0.0 { Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(endWaiting), userInfo: nil, repeats: false) } } public func endWaiting() { let view = self.viewWithTag(12301) view?.removeFromSuperview() } public func startHud(title:String, timeout:TimeInterval = 0.0) { killHud() let textSize = title.textSize(UIFont.systemFont(ofSize: 14)) let barView = UIView(frame: CGRect(x: 0, y: 0, width: textSize.width + 20, height: textSize.height + 10)) barView.tag = 12302 barView.backgroundColor = UIColor.black barView.layer.masksToBounds = true barView.layer.cornerRadius = 8.0 self.addSubview(barView) let label = UILabel(frame: barView.bounds) label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.white label.text = title label.textAlignment = .center barView.addSubview(label) barView.popOut(0.1) { [weak self, timeout] (r) in guard let s = self else { return } if r && timeout > 0.0 { Timer.scheduledTimer(timeInterval: timeout, target: s, selector: #selector(s.killHud), userInfo: nil, repeats: false) } } } public func endHud() { let view = self.viewWithTag(12302) view?.unPopOut(0.2, completion: { [weak self] (r) in self?.killHud() }) } public func killHud() { let view = self.viewWithTag(12302) view?.removeFromSuperview() } }
mit
53e0f4ef69965e6bf375e6c4654016e0
33.442424
154
0.685201
3.30215
false
false
false
false
jdbateman/Lendivine
OAuthSwift-master/OAuthSwiftDemo/KivaCart.swift
1
2046
// // KivaCart.swift // OAuthSwift // // Created by john bateman on 11/8/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import Foundation class KivaCart { // make the cart a Singleton static let sharedInstance = KivaCart() // usage: KivaCart.sharedInstance // items in the cart var items = [KivaCartItem]() // return number of items in the cart var count: Int { return items.count } // designated initializer init() { } // designated initializer init(item: KivaCartItem) { } // designated initializer init(items: [KivaCartItem]) { } // add an item to the cart func add(item: KivaCartItem) { items.append(item) } // remove all items from the cart func empty() { items.removeAll() } // get JSON representation of the cart. func getJSONData() -> NSData? { do { let serializableItems: [[String : AnyObject]] = convertCartItemsToSerializableItems() let json = try NSJSONSerialization.dataWithJSONObject(serializableItems, options: NSJSONWritingOptions.PrettyPrinted) return json } catch let error as NSError { print(error) return nil } } /*! @brief Convert the cart item to a Dictionary that is serializable by NSJSONSerialization. @discussion In order for NSJSONSerialization to convert an object to JSON the top level object must be an Array or Dictionary and all sub-objects must be one of the following types: NSString, NSNumber, NSArray, NSDictionary, or NSNull, or the Swift equivalents. */ func convertCartItemsToSerializableItems() -> [[String : AnyObject]] { var itemsArray = [[String: AnyObject]]() for item in items { let dictionary: [String: AnyObject] = item.getDictionaryRespresentation() itemsArray.append(dictionary) } return itemsArray } }
mit
7bd0f486a72fb24c15ae92b63e81894b
26.28
265
0.616626
4.7669
false
false
false
false
JulianNicholls/Uber-Clone-2
ParseStarterProject/DriverViewController.swift
1
7048
// // DriverViewController.swift // Schnell // // Created by Julian Nicholls on 26/01/2016. // Copyright © 2016 Parse. All rights reserved. // import UIKit import Parse class DriverViewController: UITableViewController, CLLocationManagerDelegate { var usernames = [String]() var locations = [CLLocationCoordinate2D]() var distances = [CLLocationDistance]() var driverLocation = CLLocationCoordinate2D() var locationManager = CLLocationManager() var refresher = UIRefreshControl() var adding = false override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() loadRequests() NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("loadRequests"), userInfo: nil, repeats: true) // Add a pull to refresh refresher.attributedTitle = NSAttributedString(string: "Pull to see new ride requests") refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refresher) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return locations.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("requestCell", forIndexPath: indexPath) let distance = renderDistance(distances[indexPath.row]) cell.textLabel!.text = "\(usernames[indexPath.row]) \(distance)" // (\(place)) return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "logoutDriver" { PFUser.logOut() navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: false) } else { if segue.identifier == "showRequest" { if let destCtrl = segue.destinationViewController as? RequestViewController { let row = tableView.indexPathForSelectedRow!.row destCtrl.reqLocation = locations[row] destCtrl.reqRider = usernames[row] destCtrl.reqDistance = distances[row] } } else { print("Asked for odd segue") } } } func refresh() { loadRequests() refresher.endRefreshing() } func renderDistance(dist: CLLocationDistance) -> String { let d = Double(dist) if d < 600.0 { return String(format: "%.0f m", arguments: [d]) } else if d < 20000.0 { return String(format: "%.1f km", arguments: [d / 1000.0]) } return String(format: "%.0f km", arguments: [d / 1000.0]) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let driver = locations[0] if PFUser.currentUser()?.objectId == nil { locationManager.stopUpdatingLocation() } // print(driver) let query = PFQuery(className: "DriverLocation") query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!) query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in if error == nil { let objects = objects! if objects.count > 0 { self.adding = false // print("Updating location") for request in objects { request["location"] = PFGeoPoint(latitude: driver.coordinate.latitude, longitude: driver.coordinate.longitude) request.saveInBackground() } } else if !self.adding { self.adding = true // print("New record") let locRecord = PFObject(className: "DriverLocation") locRecord["username"] = PFUser.currentUser()?.username locRecord["location"] = PFGeoPoint(latitude: driver.coordinate.latitude, longitude: driver.coordinate.longitude) locRecord.saveInBackground() } } else { print(error?.localizedDescription) } } } func loadRequests() { PFGeoPoint.geoPointForCurrentLocationInBackground { (dloc, error) -> Void in if error == nil { self.driverLocation = CLLocationCoordinate2DMake((dloc?.latitude)!, (dloc?.longitude)!) self.usernames.removeAll(keepCapacity: true) self.locations.removeAll(keepCapacity: true) self.distances.removeAll(keepCapacity: true) let reqQuery = PFQuery(className: "RideRequest") reqQuery.whereKey("location", nearGeoPoint: dloc!) reqQuery.limit = 10 reqQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in if error == nil { if let objects = objects as [PFObject]! { for request in objects { if request["driverResponded"] == nil { if let username = request["username"] as? String { self.usernames.append(username) } if let loc = request["location"] as? PFGeoPoint { let cloc = CLLocationCoordinate2DMake(loc.latitude, loc.longitude) self.locations.append(cloc) let reqLoc = CLLocation(latitude: cloc.latitude, longitude: cloc.longitude) let drvLoc = CLLocation(latitude: (dloc?.latitude)!, longitude: (dloc?.longitude)!) self.distances.append(drvLoc.distanceFromLocation(reqLoc)) } } } } self.tableView.reloadData() } else { print(error?.localizedDescription) } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
0dcd60856f99acdff416f0db85808507
32.557143
134
0.549454
5.766776
false
false
false
false
nathawes/swift
test/IDE/complete_expr_postfix_begin.swift
1
31628
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_3 | %FileCheck %s -check-prefix=COMMON // RUN-FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_4 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_5 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_6 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IGNORED_3 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_1 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_2 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_2 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_3 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_4 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_5 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_6 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_7 | %FileCheck %s -check-prefix=FIND_FUNC_PARAM_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_FUNC_PARAM_SELECTOR_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=COMMON < %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_FUNC_PARAM_SELECTOR_1 < %t.param.txt // RUN: %FileCheck %s -check-prefix=NO_SELF < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_1 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_2 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_3 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_4 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_5 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_CONSTRUCTOR_PARAM_SELECTOR_1 | %FileCheck %s -check-prefix=FIND_CONSTRUCTOR_PARAM_SELECTOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_1 > %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_1 < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FIND_DESTRUCTOR_PARAM_2 > %t.param.txt // RUN: %FileCheck %s -check-prefix=FIND_DESTRUCTOR_PARAM_2 < %t.param.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NO_PLACEHOLDER_NAMES_1 | %FileCheck %s -check-prefix=NO_PLACEHOLDER_NAMES_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_1 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_2 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_3 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_5 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_6 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_7 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_INVALID_8 | %FileCheck %s -check-prefix=COMMON // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | %FileCheck %s -check-prefix=MY_ALIAS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | %FileCheck %s -check-prefix=MY_ALIAS_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_1 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_2 | %FileCheck %s -check-prefix=IN_FOR_EACH_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_3 | %FileCheck %s -check-prefix=IN_FOR_EACH_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_4 | %FileCheck %s -check-prefix=IN_FOR_EACH_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_5 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_6 | %FileCheck %s -check-prefix=IN_FOR_EACH_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_7 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_8 | %FileCheck %s -check-prefix=IN_FOR_EACH_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_9 | %FileCheck %s -check-prefix=IN_FOR_EACH_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_10 | %FileCheck %s -check-prefix=IN_FOR_EACH_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_11 | %FileCheck %s -check-prefix=IN_FOR_EACH_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_FOR_EACH_12 | %FileCheck %s -check-prefix=IN_FOR_EACH_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DEPRECATED_1 | %FileCheck %s -check-prefix=DEPRECATED_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_TUPLE_1 | %FileCheck %s -check-prefix=IN_TUPLE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_TUPLE_2 | %FileCheck %s -check-prefix=IN_TUPLE_2 // RUN-FIXME(rdar56755598): %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_1 | %FileCheck %s -check-prefix=OWN_INIT_1 // RUN-FIXME(rdar56755598): %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_2 | %FileCheck %s -check-prefix=OWN_INIT_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_3 | %FileCheck %s -check-prefix=OWN_INIT_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_4 | %FileCheck %s -check-prefix=OWN_INIT_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_5 | %FileCheck %s -check-prefix=OWN_INIT_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_6 | %FileCheck %s -check-prefix=OWN_INIT_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_INIT_7 | %FileCheck %s -check-prefix=OWN_INIT_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_1 | %FileCheck %s -check-prefix=OWN_ACCESSOR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_2 | %FileCheck %s -check-prefix=OWN_ACCESSOR_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_3 | %FileCheck %s -check-prefix=OWN_ACCESSOR_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_4 | %FileCheck %s -check-prefix=OWN_ACCESSOR_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_5 | %FileCheck %s -check-prefix=OWN_ACCESSOR_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_6 | %FileCheck %s -check-prefix=OWN_ACCESSOR_6 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_7 | %FileCheck %s -check-prefix=OWN_ACCESSOR_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_8 | %FileCheck %s -check-prefix=OWN_ACCESSOR_7 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_9 | %FileCheck %s -check-prefix=OWN_ACCESSOR_9 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_10 | %FileCheck %s -check-prefix=OWN_ACCESSOR_10 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_11 | %FileCheck %s -check-prefix=OWN_ACCESSOR_11 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_12 | %FileCheck %s -check-prefix=OWN_ACCESSOR_11 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_13 | %FileCheck %s -check-prefix=OWN_ACCESSOR_13 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_14 | %FileCheck %s -check-prefix=OWN_ACCESSOR_13 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_15 | %FileCheck %s -check-prefix=OWN_ACCESSOR_13 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OWN_ACCESSOR_16 | %FileCheck %s -check-prefix=OWN_ACCESSOR_13 // // Test code completion at the beginning of expr-postfix. // //===--- Helper types that are used in this test struct FooStruct { } var fooObject : FooStruct func fooFunc() -> FooStruct { return fooObject } enum FooEnum { } class FooClass { } protocol FooProtocol { } typealias FooTypealias = Int // COMMON: Begin completions // Function parameter // COMMON-DAG: Decl[LocalVar]/Local: fooParam[#FooStruct#]{{; name=.+$}} // Global completions // COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // COMMON-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}} // COMMON-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}} // COMMON-DAG: Decl[Protocol]/CurrModule: FooProtocol[#FooProtocol#]{{; name=.+$}} // COMMON-DAG: Decl[TypeAlias]/CurrModule{{(/TypeRelation\[Identical\])?}}: FooTypealias[#Int#]{{; name=.+$}} // COMMON-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}} // COMMON-DAG: Keyword[try]/None: try{{; name=.+$}} // COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}} // COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}} // COMMON-DAG: Literal[Nil]/None: nil{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int8[#Int8#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int16[#Int16#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int32[#Int32#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int64[#Int64#]{{; name=.+$}} // COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Bool[#Bool#]{{; name=.+$}} // COMMON-DAG: Keyword[#function]/None{{(/TypeRelation\[Identical\])?}}: #function[#String#]{{; name=.+$}} // COMMON-DAG: Keyword[#file]/None{{(/TypeRelation\[Identical\])?}}: #file[#String#]{{; name=.+$}} // COMMON-DAG: Keyword[#line]/None{{(/TypeRelation\[Identical\])?}}: #line[#Int#]{{; name=.+$}} // COMMON-DAG: Keyword[#column]/None{{(/TypeRelation\[Identical\])?}}: #column[#Int#]{{; name=.+$}} // COMMON: End completions // NO_SELF-NOT: {{[[:<:]][Ss]elf[[:>:]]}} //===--- Test that we can code complete at the beginning of expr-postfix. func testExprPostfixBegin1(fooParam: FooStruct) { #^EXPR_POSTFIX_BEGIN_1^# } func testExprPostfixBegin2(fooParam: FooStruct) { 1 + #^EXPR_POSTFIX_BEGIN_2^# } func testExprPostfixBegin3(fooParam: FooStruct) { fooFunc() 1 + #^EXPR_POSTFIX_BEGIN_3^# } func testExprPostfixBegin4(fooParam: FooStruct) { "\(#^EXPR_POSTFIX_BEGIN_4^#)" } func testExprPostfixBegin3(fooParam: FooStruct) { 1+#^EXPR_POSTFIX_BEGIN_5^# } func testExprPostfixBegin3(fooParam: FooStruct) { for i in 1...#^EXPR_POSTFIX_BEGIN_6^# } //===--- Test that we sometimes ignore the expr-postfix. // In these cases, displaying '.instance*' completion results is technically // valid, but would be extremely surprising. func testExprPostfixBeginIgnored1(fooParam: FooStruct) { fooFunc() #^EXPR_POSTFIX_BEGIN_IGNORED_1^# } func testExprPostfixBeginIgnored2(fooParam: FooStruct) { 123456789 #^EXPR_POSTFIX_BEGIN_IGNORED_2^# } func testExprPostfixBeginIgnored3(fooParam: FooStruct) { 123456789 + fooFunc() #^EXPR_POSTFIX_BEGIN_IGNORED_3^# } //===--- Test that we include function parameters in completion results. func testFindFuncParam1(fooParam: FooStruct, a: Int, b: Float, c: inout Double, d: inout Double) { #^FIND_FUNC_PARAM_1^# // FIND_FUNC_PARAM_1: Begin completions // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: c[#inout Double#]{{; name=.+$}} // FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: d[#inout Double#]{{; name=.+$}} // FIND_FUNC_PARAM_1: End completions } func testFindFuncParam2<Foo : FooProtocol>(fooParam: FooStruct, foo: Foo) { #^FIND_FUNC_PARAM_2^# // FIND_FUNC_PARAM_2: Begin completions // FIND_FUNC_PARAM_2-DAG: Decl[GenericTypeParam]/Local: Foo[#Foo#]{{; name=.+$}} // FIND_FUNC_PARAM_2-DAG: Decl[LocalVar]/Local: foo[#FooProtocol#]{{; name=.+$}} // FIND_FUNC_PARAM_2: End completions } struct TestFindFuncParam3_4 { func testFindFuncParam3(a: Int, b: Float, c: Double) { #^FIND_FUNC_PARAM_3^# // FIND_FUNC_PARAM_3: Begin completions // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}} // FIND_FUNC_PARAM_3: End completions } func testFindFuncParam4<U>(a: Int, b: U) { #^FIND_FUNC_PARAM_4^# // FIND_FUNC_PARAM_4: Begin completions // FIND_FUNC_PARAM_4-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_4: End completions } } struct TestFindFuncParam5_6<T> { func testFindFuncParam5(a: Int, b: T) { #^FIND_FUNC_PARAM_5^# // FIND_FUNC_PARAM_5: Begin completions // FIND_FUNC_PARAM_5-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_5: End completions } func testFindFuncParam6<U>(a: Int, b: T, c: U) { #^FIND_FUNC_PARAM_6^# // FIND_FUNC_PARAM_6: Begin completions // FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}} // FIND_FUNC_PARAM_6: End completions } } class TestFindFuncParam7 { func testFindFuncParam7(a: Int, b: Float, c: Double) { #^FIND_FUNC_PARAM_7^# // FIND_FUNC_PARAM_7: Begin completions // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam7#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}} // FIND_FUNC_PARAM_7: End completions } } func testFindFuncParamSelector1(a: Int, b x: Float, foo fooParam: FooStruct, bar barParam: inout FooStruct) { #^FIND_FUNC_PARAM_SELECTOR_1^# // FIND_FUNC_PARAM_SELECTOR_1: Begin completions // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Float#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: barParam[#inout FooStruct#]{{; name=.+$}} // FIND_FUNC_PARAM_SELECTOR_1: End completions } //===--- Test that we include constructor parameters in completion results. class TestFindConstructorParam1 { init(a: Int, b: Float) { #^FIND_CONSTRUCTOR_PARAM_1^# // FIND_CONSTRUCTOR_PARAM_1: Begin completions // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam1#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_1: End completions } } struct TestFindConstructorParam2 { init(a: Int, b: Float) { #^FIND_CONSTRUCTOR_PARAM_2^# // FIND_CONSTRUCTOR_PARAM_2: Begin completions // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam2#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_2: End completions } } class TestFindConstructorParam3 { init<U>(a: Int, b: U) { #^FIND_CONSTRUCTOR_PARAM_3^# // FIND_CONSTRUCTOR_PARAM_3: Begin completions // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam3#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_3: End completions } } class TestFindConstructorParam4<T> { init(a: Int, b: T) { #^FIND_CONSTRUCTOR_PARAM_4^# // FIND_CONSTRUCTOR_PARAM_4: Begin completions // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam4<T>#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_4: End completions } } class TestFindConstructorParam5<T> { init<U>(a: Int, b: T, c: U) { #^FIND_CONSTRUCTOR_PARAM_5^# // FIND_CONSTRUCTOR_PARAM_5: Begin completions // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam5<T>#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_5: End completions } } class TestFindConstructorParamSelector1 { init(a x: Int, b y: Float) { #^FIND_CONSTRUCTOR_PARAM_SELECTOR_1^# // FIND_CONSTRUCTOR_PARAM_SELECTOR_1: Begin completions // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParamSelector1#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: y[#Float#]{{; name=.+$}} // FIND_CONSTRUCTOR_PARAM_SELECTOR_1: End completions } } //===--- Test that we include destructor's 'self' in completion results. class TestFindDestructorParam1 { deinit { #^FIND_DESTRUCTOR_PARAM_1^# // FIND_DESTRUCTOR_PARAM_1: Begin completions // FIND_DESTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam1#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_1: End completions } } class TestFindDestructorParam2<T> { deinit { #^FIND_DESTRUCTOR_PARAM_2^# // FIND_DESTRUCTOR_PARAM_2: Begin completions // FIND_DESTRUCTOR_PARAM_2-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam2<T>#]{{; name=.+$}} // FIND_DESTRUCTOR_PARAM_2: End completions } } struct TestPlaceholdersInNames { var <#placeholder_in_name1#>: FooStruct func test() { var <#placeholder_in_name2#>: FooStruct #^NO_PLACEHOLDER_NAMES_1^# } // NO_PLACEHOLDER_NAMES_1-NOT: placeholder_in_name } //===--- Test that we don't crash in constructors and destructors in contexts //===--- where they are not allowed. init() { var fooParam = FooStruct() #^IN_INVALID_1^# } init { // Missing parameters var fooParam = FooStruct() #^IN_INVALID_2^# } deinit { var fooParam = FooStruct() #^IN_INVALID_3^# } func testInInvalid5() { var fooParam = FooStruct() init() { #^IN_INVALID_5^# } } func testInInvalid6() { deinit { var fooParam = FooStruct() #^IN_INVALID_6^# } } struct TestInInvalid7 { deinit { var fooParam = FooStruct() #^IN_INVALID_7^# } } func foo() -> Undeclared { var fooParam = FooStruct() #^IN_INVALID_8^# } // MY_ALIAS_1: Decl[TypeAlias]/Local: MyAlias[#(T, T)#]; // MY_ALIAS_1: Decl[LocalVar]/Local/TypeRelation[Identical]: x[#MyAlias<Int>#]; name=x // MY_ALIAS_1: Decl[LocalVar]/Local/TypeRelation[Identical]: y[#(Int, Int)#]; name=y func testGenericTypealias1() { typealias MyAlias<T> = (T, T) let x: MyAlias<Int> = (1, 2) var y: (Int, Int) y = #^GENERIC_TYPEALIAS_1^# } // MY_ALIAS_2: Decl[TypeAlias]/Local: MyAlias[#(T, T)#]; // MY_ALIAS_2: Decl[LocalVar]/Local/TypeRelation[Identical]: x[#(Int, Int)#]; name=x // MY_ALIAS_2: Decl[LocalVar]/Local/TypeRelation[Identical]: y[#MyAlias<Int>#]; name=y func testGenericTypealias2() { typealias MyAlias<T> = (T, T) let x: (Int, Int) = (1, 2) var y: MyAlias<Int> y = #^GENERIC_TYPEALIAS_2^# } func testInForEach1(arg: Int) { let local = 2 for index in #^IN_FOR_EACH_1^# { let inBody = 3 } let after = 4 // IN_FOR_EACH_1-NOT: Decl[LocalVar] // IN_FOR_EACH_1: Decl[LocalVar]/Local: local[#Int#]; // IN_FOR_EACH_1-NOT: after // IN_FOR_EACH_1: Decl[LocalVar]/Local: arg[#Int#]; // IN_FOR_EACH_1-NOT: Decl[LocalVar] } func testInForEach2(arg: Int) { let local = 2 for index in 1 ... #^IN_FOR_EACH_2^# { let inBody = 3 } let after = 4 // IN_FOR_EACH_2-NOT: Decl[LocalVar] // IN_FOR_EACH_2: Decl[LocalVar]/Local/TypeRelation[Identical]: local[#Int#]; // IN_FOR_EACH_2-NOT: after // IN_FOR_EACH_2: Decl[LocalVar]/Local/TypeRelation[Identical]: arg[#Int#]; // IN_FOR_EACH_2-NOT: Decl[LocalVar] } func testInForEach3(arg: Int) { let local = 2 for index: Int in 1 ... 2 where #^IN_FOR_EACH_3^# { let inBody = 3 } let after = 4 // IN_FOR_EACH_3-NOT: Decl[LocalVar] // IN_FOR_EACH_3: Decl[LocalVar]/Local: index[#Int#]; // IN_FOR_EACH_3-NOT: Decl[LocalVar] // IN_FOR_EACH_3: Decl[LocalVar]/Local: local[#Int#]; // IN_FOR_EACH_3-NOT: after // IN_FOR_EACH_3: Decl[LocalVar]/Local: arg[#Int#]; // IN_FOR_EACH_3-NOT: Decl[LocalVar] } func testInForEach4(arg: Int) { let local = 2 for index in 1 ... 2 { #^IN_FOR_EACH_4^# } let after = 4 } func testInForEach5(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_5^#] {} let after = 4 } func testInForEach6(arg: Int) { let local = 2 for index in [1,#^IN_FOR_EACH_6^#] {} let after = 4 } func testInForEach7(arg: Int) { let local = 2 for index in [1:#^IN_FOR_EACH_7^#] {} let after = 4 } func testInForEach8(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_8^#:] {} let after = 4 } func testInForEach9(arg: Int) { let local = 2 for index in [#^IN_FOR_EACH_9^#:2] {} let after = 4 // NOTE: [Convertible] to AnyHashable. // IN_FOR_EACH_4-NOT: Decl[LocalVar] // IN_FOR_EACH_4: Decl[LocalVar]/Local/TypeRelation[Convertible]: local[#Int#]; // IN_FOR_EACH_4-NOT: after // IN_FOR_EACH_4: Decl[LocalVar]/Local/TypeRelation[Convertible]: arg[#Int#]; // IN_FOR_EACH_4-NOT: Decl[LocalVar] } func testInForEach10(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_10^#] {} let after = 4 } func testInForEach11(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_11^#:] {} let after = 4 } func testInForEach12(arg: Int) { let local = 2 for index in [1:2, #^IN_FOR_EACH_12^#:2] {} let after = 4 } @available(*, deprecated) struct Deprecated { @available(*, deprecated) func testDeprecated() { @available(*, deprecated) let local = 1 @available(*, deprecated) func f() {} #^DEPRECATED_1^# } } // DEPRECATED_1: Begin completions // DEPRECATED_1-DAG: Decl[LocalVar]/Local/NotRecommended: local[#Int#]; // DEPRECATED_1-DAG: Decl[FreeFunction]/Local/NotRecommended: f()[#Void#]; // DEPRECATED_1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: testDeprecated()[#Void#]; // DEPRECATED_1-DAG: Decl[Struct]/CurrModule/NotRecommended: Deprecated[#Deprecated#]; // DEPRECATED_1: End completions func testTuple(localInt: Int) { let localStr: String = "foo" let _: (Int, String) = (1, #^IN_TUPLE_1^#) let _: (Int, String) = (#^IN_TUPLE_2^#, "foo") } // IN_TUPLE_1: Begin completions // IN_TUPLE_1: Decl[LocalVar]/Local/TypeRelation[Identical]: localStr[#String#]; name=localStr // IN_TUPLE_1: Decl[LocalVar]/Local: localInt[#Int#]; name=localInt // IN_TUPLE_1: End completions // IN_TUPLE_2: Begin completions // IN_TUPLE_2: Decl[LocalVar]/Local: localStr[#String#]; name=localStr // IN_TUPLE_2: Decl[LocalVar]/Local/TypeRelation[Identical]: localInt[#Int#]; name=localInt // IN_TUPLE_2: End completions var ownInit1: Int = #^OWN_INIT_1^# // OWN_INIT_1: Begin completions // OWN_INIT_1-NOT: ownInit1 func sync() {} var ownInit2: () -> Void = { #^OWN_INIT_2^# } // OWN_INIT_2: Begin completions // OWN_INIT_2-NOT: ownInit2 struct OwnInitTester { var ownInit3: Int = #^OWN_INIT_3^# // OWN_INIT_3: Begin completions // OWN_INIT_3-NOT: ownInit3 var ownInit4: () -> Void = { #^OWN_INIT_4^# } // OWN_INIT_4: Begin completions // OWN_INIT_4-NOT: ownInit4 } func ownInitTesting() { var ownInit5: Int = #^OWN_INIT_5^# // OWN_INIT_5: Begin completions // OWN_INIT_5-NOT: ownInit5 var ownInit6: () -> Void = { #^OWN_INIT_6^# } // OWN_INIT_6: Begin completions // OWN_INIT_6-NOT: ownInit6 } func ownInitTestingShadow(ownInit7: Int) { var ownInit7: Int = #^OWN_INIT_7^# // OWN_INIT_7: Begin completions // OWN_INIT_7: Decl[LocalVar]/Local/TypeRelation[Identical]: ownInit7[#Int#]; } var inAccessor1: Int { get { #^OWN_ACCESSOR_1^# } // OWN_ACCESSOR_1: Begin completions // OWN_ACCESSOR_1: Decl[GlobalVar]/CurrModule/NotRecommended/TypeRelation[Identical]: inAccessor1[#Int#]; set { #^OWN_ACCESSOR_2^# } // OWN_ACCESSOR_2: Begin completions // OWN_ACCESSOR_2: Decl[GlobalVar]/CurrModule: inAccessor1[#Int#]; } var inAccessor2: Int = 1 { didSet { #^OWN_ACCESSOR_3^# } // OWN_ACCESSOR_3: Begin completions // OWN_ACCESSOR_3: Decl[GlobalVar]/CurrModule: inAccessor2[#Int#]; willSet { #^OWN_ACCESSOR_4^# } } class InAccessorTest { var inAccessor3: Int { get { #^OWN_ACCESSOR_5^# } // OWN_ACCESSOR_5: Begin completions // OWN_ACCESSOR_5: Decl[InstanceVar]/CurrNominal/NotRecommended/TypeRelation[Identical]: inAccessor3[#Int#]; set { #^OWN_ACCESSOR_6^# } // OWN_ACCESSOR_6: Begin completions // OWN_ACCESSOR_6: Decl[InstanceVar]/CurrNominal: inAccessor3[#Int#]; } var inAccessor4: Int = 1 { didSet { #^OWN_ACCESSOR_7^# } // OWN_ACCESSOR_7: Begin completions // OWN_ACCESSOR_7: Decl[InstanceVar]/CurrNominal: inAccessor4[#Int#]; willSet { #^OWN_ACCESSOR_8^# } } } func inAccessorTest() { var inAccessor5: Int { get { #^OWN_ACCESSOR_9^# } // OWN_ACCESSOR_9: Begin completions // OWN_ACCESSOR_9: Decl[LocalVar]/Local/NotRecommended/TypeRelation[Identical]: inAccessor5[#Int#]; set { #^OWN_ACCESSOR_10^# } // OWN_ACCESSOR_10: Begin completions // OWN_ACCESSOR_10: Decl[LocalVar]/Local: inAccessor5[#Int#]; } var inAccessor6: Int = 1 { didSet { #^OWN_ACCESSOR_11^# } // OWN_ACCESSOR_11: Begin completions // OWN_ACCESSOR_11: Decl[LocalVar]/Local: inAccessor6[#Int#]; willSet { #^OWN_ACCESSOR_12^# } } } class InAccessorTestQualified { var inAccessorProp: Int { get { let _ = self.#^OWN_ACCESSOR_13^# // OWN_ACCESSOR_13: Begin completions // OWN_ACCESSOR_13-DAG: Decl[InstanceVar]/CurrNominal: inAccessorProp[#Int#]; // OWN_ACCESSOR_13: End completions let _ = \InAccessorTestQualified.#^OWN_ACCESSOR_14^# } set { let _ = self.#^OWN_ACCESSOR_15^# let _ = \InAccessorTestQualified.#^OWN_ACCESSOR_16^# } } }
apache-2.0
472f166c05605ad84ec71ba28754ff22
46.276532
188
0.686449
3.098051
false
true
false
false
SoufianeLasri/Sisley
Sisley/DotView.swift
1
1070
// // DotView.swift // Sisley // // Created by Soufiane Lasri on 29/12/2015. // Copyright © 2015 Soufiane Lasri. All rights reserved. // import UIKit class DotView: UIView { override init( frame: CGRect ) { super.init( frame: frame ) self.backgroundColor = UIColor.whiteColor() self.layer.cornerRadius = self.frame.width / 2 self.layer.borderWidth = 1.5 self.layer.borderColor = UIColor( red: 0.5, green: 0.55, blue: 0.68, alpha: 1.0 ).CGColor } func toggleDot( state: Bool ) { if state == true { UIView.animateWithDuration( 0.3, animations: { self.backgroundColor = UIColor( red: 0.5, green: 0.55, blue: 0.68, alpha: 1.0 ) }, completion: nil ) } else { UIView.animateWithDuration( 0.3, animations: { self.backgroundColor = UIColor.whiteColor() }, completion: nil ) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
47685f465a92b0a1585923cc38fcdd03
28.694444
97
0.577175
3.831541
false
false
false
false
tlax/GaussSquad
GaussSquad/View/LinearEquations/Project/Main/VLinearEquationsProject.swift
1
5278
import UIKit class VLinearEquationsProject:VView, UICollectionViewDelegate, UICollectionViewDataSource { private weak var controller:CLinearEquationsProject! private weak var viewBar:VLinearEquationsProjectBar! private weak var collectionView:VCollection! private weak var spinner:VSpinner! private weak var layoutBarTop:NSLayoutConstraint! private let kBarHeight:CGFloat = 210 private let kDeselectTime:TimeInterval = 0.2 override init(controller:CController) { super.init(controller:controller) self.controller = controller as? CLinearEquationsProject let viewBar:VLinearEquationsProjectBar = VLinearEquationsProjectBar( controller:self.controller) viewBar.isHidden = true self.viewBar = viewBar let spinner:VSpinner = VSpinner() self.spinner = spinner let flow:VLinearEquationsProjectFlow = VLinearEquationsProjectFlow( model:self.controller.model, barHeight:kBarHeight) let collectionView:VCollection = VCollection(flow:flow) collectionView.backgroundColor = UIColor.white collectionView.alwaysBounceVertical = true collectionView.alwaysBounceHorizontal = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell( cell:VLinearEquationsProjectCellIndex.self) collectionView.registerCell( cell:VLinearEquationsProjectCellPolynomialDecimal.self) collectionView.registerCell( cell:VLinearEquationsProjectCellPolynomialDivision.self) collectionView.registerCell( cell:VLinearEquationsProjectCellEquals.self) collectionView.registerCell( cell:VLinearEquationsProjectCellNewPolynomial.self) collectionView.registerCell( cell:VLinearEquationsProjectCellNewRow.self) self.collectionView = collectionView addSubview(collectionView) addSubview(viewBar) addSubview(spinner) layoutBarTop = NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.equalsHorizontal( view:viewBar, toView:self) NSLayoutConstraint.equals( view:spinner, toView:self) NSLayoutConstraint.equals( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } deinit { spinner.stopAnimating() } //MARK: private private func modelAtIndex(index:IndexPath) -> MLinearEquationsProjectRowItem { let item:MLinearEquationsProjectRowItem = controller.model.rows[index.section].items[index.item] return item } //MARK: public func refresh() { spinner.stopAnimating() collectionView.isHidden = false collectionView.reloadData() viewBar.isHidden = false viewBar.viewIndeterminates.refresh() } func startLoading() { spinner.startAnimating() collectionView.isHidden = true viewBar.isHidden = true } //MARK: collectionView delegate func scrollViewDidScroll(_ scrollView:UIScrollView) { var offsetY:CGFloat = -scrollView.contentOffset.y if offsetY > 0 { offsetY = 0 } layoutBarTop.constant = offsetY } func numberOfSections(in collectionView:UICollectionView) -> Int { let count:Int = controller.model.rows.count return count } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = controller.model.rows[section].items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MLinearEquationsProjectRowItem = modelAtIndex(index:indexPath) let cell:VLinearEquationsProjectCell = collectionView.dequeueReusableCell( withReuseIdentifier: item.reusableIdentifier, for:indexPath) as! VLinearEquationsProjectCell cell.config(model:item, indexPath:indexPath) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.isUserInteractionEnabled = false let item:MLinearEquationsProjectRowItem = modelAtIndex(index:indexPath) item.selected( controller:controller, index:indexPath) DispatchQueue.main.asyncAfter( deadline:DispatchTime.now() + kDeselectTime) { [weak collectionView] in collectionView?.isUserInteractionEnabled = true collectionView?.selectItem( at:nil, animated:true, scrollPosition:UICollectionViewScrollPosition()) } } }
mit
921e1d94f73ea02b2b3f573c149f6469
30.416667
117
0.645889
5.923681
false
false
false
false
fireunit/login
Pods/Material/Sources/iOS/ImageCardView.swift
2
16023
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * 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 Material 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 public class ImageCardView : MaterialPulseView { /** :name: dividerLayer */ private var dividerLayer: CAShapeLayer? /** :name: dividerColor */ @IBInspectable public var dividerColor: UIColor? { didSet { dividerLayer?.backgroundColor = dividerColor?.CGColor } } /** :name: divider */ @IBInspectable public var divider: Bool = true { didSet { reloadView() } } /** :name: dividerInsets */ public var dividerInsetPreset: MaterialEdgeInset = .None { didSet { dividerInset = MaterialEdgeInsetToValue(dividerInsetPreset) } } /** :name: dividerInset */ @IBInspectable public var dividerInset: UIEdgeInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0) { didSet { reloadView() } } /** :name: imageLayer */ public private(set) var imageLayer: CAShapeLayer? /** :name: image */ @IBInspectable public override var image: UIImage? { get { return nil == imageLayer?.contents ? nil : UIImage(CGImage: imageLayer?.contents as! CGImage) } set(value) { if let v = value { prepareImageLayer() imageLayer?.contents = v.CGImage if 0 == maxImageHeight { imageLayer?.frame.size.height = image!.size.height / contentsScale } else { let h: CGFloat = image!.size.height / contentsScale imageLayer?.frame.size.height = maxImageHeight < h ? maxImageHeight : h } imageLayer?.hidden = false } else { imageLayer?.contents = nil imageLayer?.frame = CGRectZero imageLayer?.hidden = true imageLayer?.removeFromSuperlayer() } reloadView() } } /** :name: maxImageHeight */ @IBInspectable public var maxImageHeight: CGFloat = 0 { didSet { if let v: UIImage = image { if 0 < maxImageHeight { prepareImageLayer() let h: CGFloat = v.size.height / contentsScale imageLayer?.frame.size.height = maxImageHeight < h ? maxImageHeight : h } else { maxImageHeight = 0 imageLayer?.frame.size.height = nil == image ? 0 : v.size.height / contentsScale } reloadView() } } } /** :name: contentsRect */ @IBInspectable public override var contentsRect: CGRect { didSet { prepareImageLayer() imageLayer?.contentsRect = contentsRect } } /** :name: contentsCenter */ @IBInspectable public override var contentsCenter: CGRect { didSet { prepareImageLayer() imageLayer?.contentsCenter = contentsCenter } } /** :name: contentsScale */ @IBInspectable public override var contentsScale: CGFloat { didSet { prepareImageLayer() imageLayer?.contentsScale = contentsScale } } /// Determines how content should be aligned within the visualLayer's bounds. @IBInspectable public override var contentsGravity: String { get { return nil == imageLayer ? "" : imageLayer!.contentsGravity } set(value) { prepareImageLayer() imageLayer?.contentsGravity = value } } /** :name: contentInsets */ public var contentInsetPreset: MaterialEdgeInset = .Square2 { didSet { contentInset = MaterialEdgeInsetToValue(contentInsetPreset) } } /** :name: contentInset */ @IBInspectable public var contentInset: UIEdgeInsets = MaterialEdgeInsetToValue(.Square2) { didSet { reloadView() } } /** :name: titleLabelInsets */ public var titleLabelInsetPreset: MaterialEdgeInset = .Square2 { didSet { titleLabelInset = MaterialEdgeInsetToValue(titleLabelInsetPreset) } } /** :name: titleLabelInset */ @IBInspectable public var titleLabelInset: UIEdgeInsets = MaterialEdgeInsetToValue(.Square2) { didSet { reloadView() } } /** :name: titleLabel */ @IBInspectable public var titleLabel: UILabel? { didSet { reloadView() } } /** :name: contentViewInsets */ public var contentViewInsetPreset: MaterialEdgeInset = .Square2 { didSet { contentViewInset = MaterialEdgeInsetToValue(contentViewInsetPreset) } } /** :name: contentViewInset */ @IBInspectable public var contentViewInset: UIEdgeInsets = MaterialEdgeInsetToValue(.Square2) { didSet { reloadView() } } /** :name: contentView */ @IBInspectable public var contentView: UIView? { didSet { reloadView() } } /** :name: leftButtonsInsets */ public var leftButtonsInsetPreset: MaterialEdgeInset = .None { didSet { leftButtonsInset = MaterialEdgeInsetToValue(leftButtonsInsetPreset) } } /** :name: leftButtonsInset */ @IBInspectable public var leftButtonsInset: UIEdgeInsets = MaterialEdgeInsetToValue(.None) { didSet { reloadView() } } /** :name: leftButtons */ public var leftButtons: Array<UIButton>? { didSet { reloadView() } } /** :name: rightButtonsInsets */ public var rightButtonsInsetPreset: MaterialEdgeInset = .None { didSet { rightButtonsInset = MaterialEdgeInsetToValue(rightButtonsInsetPreset) } } /** :name: rightButtonsInset */ @IBInspectable public var rightButtonsInset: UIEdgeInsets = MaterialEdgeInsetToValue(.None) { didSet { reloadView() } } /** :name: rightButtons */ public var rightButtons: Array<UIButton>? { didSet { reloadView() } } /** :name: init */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** :name: init */ public override init(frame: CGRect) { super.init(frame: frame) } /** :name: init */ public convenience init() { self.init(frame: CGRectZero) } /** :name: init */ public convenience init?(image: UIImage? = nil, titleLabel: UILabel? = nil, contentView: UIView? = nil, leftButtons: Array<UIButton>? = nil, rightButtons: Array<UIButton>? = nil) { self.init(frame: CGRectZero) prepareProperties(image, titleLabel: titleLabel, contentView: contentView, leftButtons: leftButtons, rightButtons: rightButtons) } /** :name: layoutSublayersOfLayer */ public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) if self.layer == layer { // image imageLayer?.frame.size.width = bounds.width // divider if divider { var y: CGFloat = contentInset.bottom + dividerInset.bottom if 0 < leftButtons?.count { y += leftButtonsInset.top + leftButtonsInset.bottom + leftButtons![0].frame.height } else if 0 < rightButtons?.count { y += rightButtonsInset.top + rightButtonsInset.bottom + rightButtons![0].frame.height } if 0 < y { prepareDivider(bounds.height - y - 0.5, width: bounds.width) } } else { dividerLayer?.removeFromSuperlayer() dividerLayer = nil } } } /** :name: reloadView */ public func reloadView() { // clear constraints so new ones do not conflict removeConstraints(constraints) for v in subviews { v.removeFromSuperview() } var verticalFormat: String = "V:|" var views: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() var metrics: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() if nil != imageLayer?.contents { verticalFormat += "-(insetTop)" metrics["insetTop"] = imageLayer!.frame.height } else if nil != titleLabel { verticalFormat += "-(insetTop)" metrics["insetTop"] = contentInset.top + titleLabelInset.top } else if nil != contentView { verticalFormat += "-(insetTop)" metrics["insetTop"] = contentInset.top + contentViewInset.top } // title if let v: UILabel = titleLabel { addSubview(v) if nil == imageLayer?.contents { verticalFormat += "-[titleLabel]" views["titleLabel"] = v } else { MaterialLayout.alignFromTop(self, child: v, top: contentInset.top + titleLabelInset.top) } MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + titleLabelInset.left, right: contentInset.right + titleLabelInset.right) } // detail if let v: UIView = contentView { addSubview(v) if nil == imageLayer?.contents && nil != titleLabel { verticalFormat += "-(insetB)" metrics["insetB"] = titleLabelInset.bottom + contentViewInset.top } else { metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + contentViewInset.top } verticalFormat += "-[contentView]" views["contentView"] = v MaterialLayout.alignToParentHorizontally(self, child: v, left: contentInset.left + contentViewInset.left, right: contentInset.right + contentViewInset.right) } // leftButtons if let v: Array<UIButton> = leftButtons { if 0 < v.count { var h: String = "H:|" var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() var i: Int = 0 for b in v { let k: String = "b\(i)" d[k] = b if 0 == i { h += "-(left)-" } else { h += "-(left_right)-" } h += "[\(k)]" addSubview(b) MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + leftButtonsInset.bottom) i += 1 } addConstraints(MaterialLayout.constraint(h, options: [], metrics: ["left" : contentInset.left + leftButtonsInset.left, "left_right" : leftButtonsInset.left + leftButtonsInset.right], views: d)) } } // rightButtons if let v: Array<UIButton> = rightButtons { if 0 < v.count { var h: String = "H:" var d: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() var i: Int = v.count - 1 for b in v { let k: String = "b\(i)" d[k] = b h += "[\(k)]" if 0 == i { h += "-(right)-" } else { h += "-(right_left)-" } addSubview(b) MaterialLayout.alignFromBottom(self, child: b, bottom: contentInset.bottom + rightButtonsInset.bottom) i -= 1 } addConstraints(MaterialLayout.constraint(h + "|", options: [], metrics: ["right" : contentInset.right + rightButtonsInset.right, "right_left" : rightButtonsInset.right + rightButtonsInset.left], views: d)) } } if nil == imageLayer?.contents { if 0 < leftButtons?.count { verticalFormat += "-(insetC)-[button]" views["button"] = leftButtons![0] metrics["insetC"] = leftButtonsInset.top metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom } else if 0 < rightButtons?.count { verticalFormat += "-(insetC)-[button]" views["button"] = rightButtons![0] metrics["insetC"] = rightButtonsInset.top metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom } if nil != contentView { if nil == metrics["insetC"] { metrics["insetBottom"] = contentInset.bottom + contentViewInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } else { metrics["insetC"] = (metrics["insetC"] as! CGFloat) + contentViewInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } } else if nil != titleLabel { if nil == metrics["insetC"] { metrics["insetBottom"] = contentInset.bottom + titleLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } else { metrics["insetC"] = (metrics["insetC"] as! CGFloat) + titleLabelInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } } else if nil != metrics["insetC"] { metrics["insetC"] = (metrics["insetC"] as! CGFloat) + contentInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0) } } else if nil != contentView { if 0 < leftButtons?.count { verticalFormat += "-(insetC)-[button]" views["button"] = leftButtons![0] metrics["insetC"] = leftButtonsInset.top metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom } else if 0 < rightButtons?.count { verticalFormat += "-(insetC)-[button]" views["button"] = rightButtons![0] metrics["insetC"] = rightButtonsInset.top metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom } if nil == metrics["insetC"] { metrics["insetBottom"] = contentInset.bottom + contentViewInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } else { metrics["insetC"] = (metrics["insetC"] as! CGFloat) + contentViewInset.bottom + (divider ? dividerInset.top + dividerInset.bottom : 0) } } else { if 0 < leftButtons?.count { verticalFormat += "-[button]" views["button"] = leftButtons![0] metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + contentInset.top + leftButtonsInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0) metrics["insetBottom"] = contentInset.bottom + leftButtonsInset.bottom } else if 0 < rightButtons?.count { verticalFormat += "-[button]" views["button"] = rightButtons![0] metrics["insetTop"] = (metrics["insetTop"] as! CGFloat) + contentInset.top + rightButtonsInset.top + (divider ? dividerInset.top + dividerInset.bottom : 0) metrics["insetBottom"] = contentInset.bottom + rightButtonsInset.bottom } else { if translatesAutoresizingMaskIntoConstraints { addConstraints(MaterialLayout.constraint("V:[view(height)]", options: [], metrics: ["height": imageLayer!.frame.height], views: ["view": self])) } else { height = imageLayer!.frame.height } } } if 0 < views.count { verticalFormat += "-(insetBottom)-|" addConstraints(MaterialLayout.constraint(verticalFormat, options: [], metrics: metrics, views: views)) } } /** :name: prepareView */ public override func prepareView() { super.prepareView() depth = .Depth1 dividerColor = MaterialColor.grey.lighten3 cornerRadiusPreset = .Radius1 } /** :name: prepareImageLayer */ internal func prepareImageLayer() { if nil == imageLayer { imageLayer = CAShapeLayer() imageLayer!.masksToBounds = true imageLayer!.zPosition = 0 visualLayer.addSublayer(imageLayer!) } } /** :name: prepareDivider */ internal func prepareDivider(y: CGFloat, width: CGFloat) { if nil == dividerLayer { dividerLayer = CAShapeLayer() dividerLayer!.zPosition = 0 layer.addSublayer(dividerLayer!) } dividerLayer?.backgroundColor = dividerColor?.CGColor dividerLayer?.frame = CGRectMake(dividerInset.left, y, width - dividerInset.left - dividerInset.right, 1) } /** :name: prepareProperties */ internal func prepareProperties(image: UIImage?, titleLabel: UILabel?, contentView: UIView?, leftButtons: Array<UIButton>?, rightButtons: Array<UIButton>?) { self.image = image self.titleLabel = titleLabel self.contentView = contentView self.leftButtons = leftButtons self.rightButtons = rightButtons } }
mit
6751bda47e8824cd81bde272e89b5e89
26.580034
209
0.678337
3.711605
false
false
false
false
superk589/DereGuide
DereGuide/LiveSimulator/LSRange.swift
2
2633
// // LSRange.swift // DereGuide // // Created by zzk on 2017/3/31. // Copyright © 2017 zzk. All rights reserved. // import Foundation struct LSRange<Bound: Comparable & Numeric>: Equatable { var begin: Bound var end: Bound init(begin: Bound, length: Bound) { assert(length >= 0) self.init(begin: begin, end: begin + length) } init(begin: Bound, end: Bound) { assert(end >= begin) self.begin = begin self.end = end } var length: Bound { return end - begin } func contains(_ value: Bound) -> Bool { return value >= begin && value < end } func contains(_ otherRange: LSRange<Bound>) -> Bool { return begin <= otherRange.begin && end >= otherRange.end } func intersects(_ otherRange: LSRange<Bound>) -> Bool { return contains(otherRange.begin) || contains(otherRange.end) || otherRange.contains(self) } func intersection(_ otherRange: LSRange<Bound>) -> LSRange<Bound>? { guard intersects(otherRange) else { return nil } var begin = self.begin var end = self.end if contains(otherRange.begin) { begin = otherRange.begin } if contains(otherRange.end) { end = otherRange.end } // notice that length may be zero, due to float accuracy problem, even though end != begin return LSRange(begin: begin, end: end) } func subtract(_ otherRange: LSRange<Bound>) -> [LSRange<Bound>] { if !intersects(otherRange) || otherRange.contains(self) { return [self] } var ranges = [LSRange<Bound>]() if begin < otherRange.begin { ranges.append(LSRange(begin: begin, end: otherRange.begin)) } if end > otherRange.end { ranges.append(LSRange(begin: otherRange.end, end: end)) } return ranges } } extension CGSSRankedSkill { func getUpRanges(lastNoteSec sec: Float) -> [LSRange<Float>] { let condition: Int = skill.condition // 最后一个note的前三秒不再触发新的技能 let count = Int(ceil((sec - 3) / Float(condition))) var ranges = [LSRange<Float>]() for i in 0..<count { // 第一个触发区间内不触发技能 if i == 0 { continue } let range = LSRange(begin: Float(i * condition), length: Float(length) / 100) ranges.append(range) } return ranges } }
mit
f4c2a48b1ea4e025b90d14562cf7779c
25.8125
98
0.549728
4.185366
false
false
false
false
russbishop/swift
test/ClangModules/sdk.swift
1
1045
// RUN: %target-swift-frontend -parse -verify %s // XFAIL: linux import Foundation // Swift and Foundation types should work. func available_Int(_ a: Int) {} func available_DateFormatter(_ a: DateFormatter) {} // Some traditional Objective-C types should fail with fixits. func unavailable_id(_ a: id) {} // expected-error {{use of undeclared type 'id'; did you mean to use 'AnyObject'?}} {{26-28=AnyObject}} func unavailable_Class(_ a: Class) {} // expected-error {{use of undeclared type 'Class'; did you mean to use 'AnyClass'?}} {{29-34=AnyClass}} func unavailable_BOOL(_ a: BOOL) {} // expected-error {{use of undeclared type 'BOOL'; did you mean to use 'ObjCBool'?}} {{28-32=ObjCBool}} func unavailable_SEL(_ a: SEL) {} // expected-error {{use of undeclared type 'SEL'; did you mean to use 'Selector'?}} {{27-30=Selector}} func unavailable_NSUInteger(_ a: NSUInteger) {} // expected-error {{use of undeclared type 'NSUInteger'; did you mean to use 'Int'?}} {{34-44=Int}} expected-note {{did you mean to use 'UInt'?}} {{34-44=UInt}}
apache-2.0
e2c82b79e3843c6d04c22ed2e5e7b022
54
208
0.689952
3.679577
false
false
false
false
MaddTheSane/WWDC
WWDC/AboutWindowController.swift
1
3014
// // AboutWindowController.swift // About // // Created by Guilherme Rambo on 20/12/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import Cocoa class AboutWindowController: NSWindowController { @IBOutlet weak private var applicationNameLabel: NSTextField! @IBOutlet weak private var versionLabel: NSTextField! @IBOutlet weak var contributorsLabel: NSTextField! @IBOutlet weak private var creatorLabel: NSTextField! @IBOutlet weak private var licenseLabel: NSTextField! var infoText: String? { didSet { guard let infoText = infoText else { return } contributorsLabel.stringValue = infoText } } convenience init(infoText: String?) { self.init(windowNibName: "AboutWindowController") self.infoText = infoText } override func windowDidLoad() { super.windowDidLoad() // close the window when the escape key is pressed NSEvent.addLocalMonitorForEventsMatchingMask(.KeyDownMask) { event in guard event.keyCode == 53 else { return event } self.closeAnimated() return nil } window?.collectionBehavior = [.Transient, .IgnoresCycle] window?.movable = false window?.titlebarAppearsTransparent = true window?.titleVisibility = .Hidden let info = NSBundle.mainBundle().infoDictionary! if let appName = info["CFBundleName"] as? String { applicationNameLabel.stringValue = appName } else { applicationNameLabel.stringValue = "" } if let version = info["CFBundleShortVersionString"] as? String { versionLabel.stringValue = "Version \(version)" } else { versionLabel.stringValue = "" } if let infoText = infoText { contributorsLabel.stringValue = infoText } else { contributorsLabel.stringValue = "" } if let license = info["GRBundleLicenseName"] as? String { licenseLabel.stringValue = "License: \(license)" } else { licenseLabel.stringValue = "" } if let creator = info["GRBundleMainDeveloperName"] as? String { creatorLabel.stringValue = "Created by \(creator)" } else { creatorLabel.stringValue = "" } } override func showWindow(sender: AnyObject?) { window?.center() window?.alphaValue = 0.0 super.showWindow(sender) window?.animator().alphaValue = 1.0 } func closeAnimated() { NSAnimationContext.beginGrouping() NSAnimationContext.currentContext().duration = 0.4 NSAnimationContext.currentContext().completionHandler = { self.close() } window?.animator().alphaValue = 0.0 NSAnimationContext.endGrouping() } }
bsd-2-clause
ee7f101c89bddfca3d195c479777b900
29.13
77
0.595752
5.518315
false
false
false
false
yuwang17/JokeBox
JokeBox/MainViewController.swift
1
13834
// // ViewController.swift // JokeBox // // Created by Wang Yu on 5/24/15. // Copyright (c) 2015 Yu Wang. All rights reserved. // import UIKit import Spring import Social import MessageUI class MainViewController: UIViewController, JokeManagerDelegate, ImageGetterDelegate, MFMailComposeViewControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var backgroundMaskView: UIView! @IBOutlet weak var dialogView: UIView! @IBOutlet weak var shareView: UIView! @IBOutlet weak var headerView: UIView! @IBOutlet weak var jokeLabel: SpringLabel! @IBOutlet weak var maskButton: UIButton! @IBOutlet weak var emailButton: UIButton! @IBOutlet weak var twitterButton: UIButton! @IBOutlet weak var facebookButton: UIButton! @IBOutlet weak var shareLabelsView: UIView! @IBOutlet weak var shareButton: DesignableButton! @IBOutlet weak var favoriteButton: DesignableButton! @IBOutlet weak var jokeLabelActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var shareButtonWidthConstraint: NSLayoutConstraint! var placeHolderImageIndex: Int { get { let random: Int = Int(rand() % 11) return random } } var imageGetter: ImageGetter = ImageGetter() var jokeMgr: JokeManager = JokeManager() var imageUrls = [String]() { didSet { dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { for var index = 0; index < self.imageUrls.count-1; index++ { let imageData = NSData(contentsOfURL: NSURL(string: self.imageUrls[index])!) dispatch_async(dispatch_get_main_queue()) { if imageData != nil { let curImage: UIImage = UIImage(data: imageData!)! self.images.append(curImage) } } } } } } var images = [UIImage]() var jokes = [Joke]() var currentNumber: Int = 0 { didSet { if currentNumber >= 25 { jokeMgr.getManyRandomJoke() imageGetter.getFlickrInterestingnessPhotos() currentNumber = 0 images.removeAll(keepCapacity: true) jokeLabelActivityIndicator.startAnimating() } } } var favoriteButtonIsClicked: Bool = false { didSet { if favoriteButtonIsClicked == true { favoriteButton.setImage(UIImage(named: "leftButton-selected"), forState: UIControlState.Normal) } else { favoriteButton.setImage(UIImage(named: "leftButton"), forState: UIControlState.Normal) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. jokeMgr.delegate = self imageGetter.delegate = self imageGetter.getFlickrInterestingnessPhotos() animator = UIDynamicAnimator(referenceView: view) shareButtonWidthConstraint.constant = self.view.frame.width / 3 dialogView.alpha = 0 imageView.contentMode = UIViewContentMode.ScaleAspectFill jokeLabel.numberOfLines = 0 jokeLabel.text = "" jokeLabel.adjustsFontSizeToFitWidth = true jokeLabelActivityIndicator.hidesWhenStopped = true jokeLabelActivityIndicator.startAnimating() jokeMgr.getManyRandomJoke() facebookButton.addTarget(self, action: "faceBookButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) twitterButton.addTarget(self, action: "twitterButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) emailButton.addTarget(self, action: "emailButtonDidPressed:", forControlEvents: UIControlEvents.TouchUpInside) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(Bool()) insertBlurView(backgroundMaskView, UIBlurEffectStyle.Dark) insertBlurView(headerView, UIBlurEffectStyle.Dark) jokeLabel.text = "" if !jokes.isEmpty { jokeLabel.text = jokes[currentNumber].content } if jokeLabel.text == "" { jokeMgr.getOneRandomJoke() } favoriteButtonIsClicked = false let scale = CGAffineTransformMakeScale(0.5, 0.5) let translate = CGAffineTransformMakeTranslation(0, -200) dialogView.transform = CGAffineTransformConcat(scale, translate) spring(0.5) { let scale = CGAffineTransformMakeScale(1, 1) let translate = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformConcat(scale, translate) } dialogView.alpha = 1 if !images.isEmpty { var oldImageSize = CGSize() let currentImage = images.removeAtIndex(0) fadeChangeBackgroundImage(currentImage) imageView.image = currentImage } else { setCurrentImageAsRandomImageInPlaceHolder() } favoriteButton.animation = "pop" shareButton.animation = "pop" shareButton.delay = 0.1 favoriteButton.animate() shareButton.animate() } func setCurrentImageAsRandomImageInPlaceHolder() { let currentImage: UIImage? = UIImage(named: "placeHoldImage\(placeHolderImageIndex)") fadeChangeBackgroundImage(currentImage!) imageView.image = currentImage } func gotOneRandomJoke(joke: Joke) { if jokeLabel.text == "" { self.jokeLabel.text = joke.content jokeLabel.animation = "fadeIn" jokeLabel.animate() jokeLabelActivityIndicator.stopAnimating() } } func gotManyRandomJokes(jokes: [Joke]) { self.jokes = jokes jokeLabelActivityIndicator.stopAnimating() } func gotFlickrInterestingnessPhotoUrls(urlList: [String]) { imageUrls = urlList } @IBAction func maskButtonDidPress(sender: AnyObject) { spring(0.5) { self.maskButton.alpha = 0 } hideShareView() } func showMask() { self.maskButton.hidden = false self.maskButton.alpha = 0 spring(0.5) { self.maskButton.alpha = 1 } } @IBAction func favoriteButtonDidPress(sender: UIButton) { favoriteButtonIsClicked = !favoriteButtonIsClicked } @IBAction func shareButtonDidPress(sender: AnyObject) { shareView.hidden = false showMask() shareView.transform = CGAffineTransformMakeTranslation(0, 200) emailButton.transform = CGAffineTransformMakeTranslation(0, 200) twitterButton.transform = CGAffineTransformMakeTranslation(0, 200) facebookButton.transform = CGAffineTransformMakeTranslation(0, 200) shareLabelsView.alpha = 0 spring(0.5) { self.shareView.transform = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformMakeScale(0.8, 0.8) } springWithDelay(0.5, 0.05, { self.emailButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.10, { self.twitterButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.15, { self.facebookButton.transform = CGAffineTransformMakeTranslation(0, 0) }) springWithDelay(0.5, 0.2, { self.shareLabelsView.alpha = 1 }) } func hideShareView() { spring(0.5) { self.shareView.transform = CGAffineTransformMakeTranslation(0, 0) self.dialogView.transform = CGAffineTransformMakeScale(1, 1) self.shareView.hidden = true } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } var animator : UIDynamicAnimator! var attachmentBehavior : UIAttachmentBehavior! var gravityBehaviour : UIGravityBehavior! var snapBehavior : UISnapBehavior! @IBOutlet var panRecognizer: UIPanGestureRecognizer! @IBAction func handleGesture(sender: AnyObject) { let myView = dialogView let location = sender.locationInView(view) let boxLocation = sender.locationInView(dialogView) if sender.state == UIGestureRecognizerState.Began { animator.removeBehavior(snapBehavior) let centerOffset = UIOffsetMake(boxLocation.x - CGRectGetMidX(myView.bounds), boxLocation.y - CGRectGetMidY(myView.bounds)); attachmentBehavior = UIAttachmentBehavior(item: myView, offsetFromCenter: centerOffset, attachedToAnchor: location) attachmentBehavior.frequency = 0 animator.addBehavior(attachmentBehavior) } else if sender.state == UIGestureRecognizerState.Changed { attachmentBehavior.anchorPoint = location } else if sender.state == UIGestureRecognizerState.Ended { animator.removeBehavior(attachmentBehavior) snapBehavior = UISnapBehavior(item: myView, snapToPoint: CGPoint(x: view.center.x, y: view.center.y - 45)) animator.addBehavior(snapBehavior) let translation = sender.translationInView(view) if translation.y > 100 { animator.removeAllBehaviors() var gravity = UIGravityBehavior(items: [dialogView]) gravity.gravityDirection = CGVectorMake(0, 10) animator.addBehavior(gravity) delay(0.3) { self.refreshView() } } } } func refreshView() { currentNumber++ animator.removeAllBehaviors() snapBehavior = UISnapBehavior(item: dialogView, snapToPoint: CGPoint(x: view.center.x, y: view.center.y - 45)) attachmentBehavior.anchorPoint = CGPoint(x: view.center.x, y: view.center.y - 45) dialogView.center = CGPoint(x: view.center.x, y: view.center.y - 45) viewDidAppear(true) } func fadeChangeBackgroundImage(toImage: UIImage) { UIView.transitionWithView(self.backgroundImageView, duration: 1.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in self.backgroundImageView.image = toImage }, completion: nil) } func faceBookButtonDidPressed(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) { var fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook) fbShare.setInitialText("\(jokeLabel.text!)") self.presentViewController(fbShare, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } func twitterButtonDidPressed(sender: UIButton) { if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter){ var twitterSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) twitterSheet.setInitialText("\(jokeLabel.text!)") self.presentViewController(twitterSheet, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Accounts", message: "Please login to a Twitter account to share.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } func emailButtonDidPressed(sender: UIButton) { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property mailComposerVC.setSubject("Check this out. Such funny joke!") mailComposerVC.setMessageBody("\(jokeLabel.text!)", isHTML: false) return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { controller.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
09bb46f046070ddb3dd4aef50c9dd9c4
39.215116
213
0.645077
5.416601
false
false
false
false
sarvex/SwiftRecepies
Networking/Sending HTTP Requests with NSURLConnection/Sending HTTP Requests with NSURLConnection/ViewController.swift
1
4194
// // ViewController.swift // Sending HTTP Requests with NSURLConnection // // Created by Vandad Nahavandipoor on 7/9/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // override func viewDidLoad() { // super.viewDidLoad() // // let httpMethod = "GET" // // /* We have a 15 second timeout for our connection */ // let timeout = 15 // // /* You can choose your own URL here */ // var urlAsString = "<# place your url here #>" // // urlAsString += "?param1=First" // urlAsString += "&param2=Second" // // let url = NSURL(string: urlAsString) // // /* Set the timeout on our request here */ // let urlRequest = NSMutableURLRequest(URL: url!, // cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, // timeoutInterval: 15.0) // // urlRequest.HTTPMethod = httpMethod // // let queue = NSOperationQueue() // // NSURLConnection.sendAsynchronousRequest(urlRequest, // queue: queue, // completionHandler: {(response: NSURLResponse!, // data: NSData!, // error: NSError!) in // // /* Now we may have access to the data but check if an error came back // first or not */ // if data.length > 0 && error == nil{ // let html = NSString(data: data, encoding: NSUTF8StringEncoding) // println("html = \(html)") // } else if data.length == 0 && error == nil{ // println("Nothing was downloaded") // } else if error != nil{ // println("Error happened = \(error)") // } // // } // ) // // } // //} /* 2 */ import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let httpMethod = "POST" /* We have a 15 second timeout for our connection */ let timeout = 15 /* You can choose your own URL here */ var urlAsString = "<# place your url here #>" /* These are the parameters that will be sent as part of the URL */ urlAsString += "?param1=First" urlAsString += "&param2=Second" let url = NSURL(string: urlAsString) /* Set the timeout on our request here */ let urlRequest = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0) urlRequest.HTTPMethod = httpMethod /* These are the POST parameters */ let body = "bodyParam1=BodyValue1&bodyParam2=BodyValue2".dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false) urlRequest.HTTPBody = body let queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(urlRequest, queue: queue, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in /* Now we may have access to the data but check if an error came back first or not */ if data.length > 0 && error == nil{ let html = NSString(data: data, encoding: NSUTF8StringEncoding) println("html = \(html)") } else if data.length == 0 && error == nil{ println("Nothing was downloaded") } else if error != nil{ println("Error happened = \(error)") } } ) } }
isc
bc8e6a8b6239c0a52884b732e4bfff4e
28.957143
83
0.611826
4.25355
false
false
false
false
dev-gao/GYPageViewController
Example/UIView+GYPauseAnimation.swift
1
718
// // UIView+GYPauseAnimation.swift // GYPageViewController // // Created by GaoYu on 16/6/13. // Copyright © 2016年 GaoYu. All rights reserved. // import UIKit extension UIView { func pauseAnimations() { let paused_time = self.layer.convertTime(CACurrentMediaTime(), to: nil) self.layer.speed = 0.0 self.layer.timeOffset = paused_time } func resumeAnimations() { let paused_time = self.layer.timeOffset self.layer.speed = 1.0 self.layer.timeOffset = 0.0 self.layer.beginTime = 0.0 let time_since_pause = self.layer.convertTime(CACurrentMediaTime(), to: nil) - paused_time self.layer.beginTime = time_since_pause } }
mit
0fbf89ca98094561cd802a3d40158d25
26.5
98
0.644755
3.743455
false
false
false
false
RickieL/learn-swift
swift-type-casting.playground/section-1.swift
1
2931
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // defining a class hierarchy for type casting class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen kane", director: "Orson Welles"), Song(name: "The One And City", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Bick Astley") ] // checking type var movieCount = 0 var songCount = 0 for item in library { if item is Movie { ++movieCount } else if item is Song { ++songCount } } println("Media library contains \(movieCount) movies and \(songCount) songs") // downcasting for item in library { if let movie = item as? Movie { println("Movie: '\(movie.name)', dir. \(movie.director)") } else if let song = item as? Song { println("Song: '\(song.name)', by \(song.artist)") } } // type casting for any and anyobject // anyobject let someObjects: [AnyObject] = [ Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"), Movie(name: "Moon", director: "Duncan Jones"), Movie(name: "Alien", director: "Ridley Scott") ] for object in someObjects { let movie = object as Movie println("Movie: '\(movie.name)', dir. \(movie.director)") } for movie in someObjects as [Movie] { println("Movie: '\(movie.name)', dir. \(movie.director)") } var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({(name: String) -> String in "Hello, \(name)"}) for thing in things { switch thing { case 0 as Int: println("zero as an Int") case 0 as Double: println("zero as a Double") case let someInt as Int: println("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: println("a positive double value of \(someDouble)") case is Double: println("some other double value that I don't want to print") case let someString as String: println("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): println("an (x, y) point at \(x), \(y)") case let stringConverter as String -> String: println(stringConverter("Michael")) default: println("something else") } }
bsd-3-clause
4496a2d98af36ec31d422dc14ee3b30f
25.405405
77
0.630502
3.654613
false
false
false
false
KBryan/SwiftFoundation
Source/HTTPStatusCode.swift
1
684
// // HTTPStatusCode.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 6/29/15. // Copyright © 2015 PureSwift. All rights reserved. // /// The standard status codes used with the HTTP protocol. public enum HTTPStatusCode: UInt { case Continue = 100 case SwitchingProtocols = 101 case Processing = 102 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 case MultipleChoices = 300 init() { self = .OK } }
mit
acba96a9fb84e1d1dcf0a8875fc8e0ad
21.8
58
0.658858
4.406452
false
false
false
false
Look-ARound/LookARound2
lookaround2/Controllers/SearchResultsViewController.swift
1
2965
// // SearchResultsViewController.swift // LookARound // // Created by Angela Yu on 10/13/17. // Copyright © 2017 LookARound. All rights reserved. // import UIKit class SearchResultsViewController: UIViewController, UITableViewDataSource { @IBOutlet private var tableView: UITableView! var places: [Place]! override func viewDidLoad() { super.viewDidLoad() guard let tableView = tableView else { print("no tableview yet") return } tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 print("first place is \(places[0].name)") tableView.reloadData() let likeSortButton = UIBarButtonItem(title: "Visits", style: .plain, target: self, action: #selector(sortByCheckins)) let friendsSortButton = UIBarButtonItem(title: "Friends", style: .plain, target: self, action: #selector(sortByFriends)) navigationItem.rightBarButtonItems = [likeSortButton, friendsSortButton] } override func viewWillAppear(_ animated: Bool) { guard let tableView = tableView else { print("still no tableview yet") return } tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 print("first place is \(places[0].name)") tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc private func sortByCheckins() { places = sortPlaces(places: places, by: .checkins) tableView.reloadData() let indexPath = NSIndexPath(row: 0, section: 0) as IndexPath self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) } @objc private func sortByFriends() { places = sortPlaces(places: places, by: .friends) tableView.reloadData() let indexPath = NSIndexPath(row: 0, section: 0) as IndexPath self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) } } extension SearchResultsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let places = places else { print("empty places") return 0 } return places.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SearchResultsCell", for: indexPath) as! SearchResultsCell if let places = places { cell.place = places[indexPath.row] } return cell } }
apache-2.0
07c3f5b6a3336cda03ebeed8ba1895c8
32.303371
128
0.640688
5.172775
false
false
false
false
alexcomu/swift3-tutorial
13-pokedex/13-pokedex/DetailViewController.swift
1
2048
// // DetailViewController.swift // 13-pokedex // // Created by Alex Comunian on 07/03/17. // Copyright © 2017 Hackademy. All rights reserved. // import UIKit class DetailViewController: UIViewController { var pokemon: Pokemon! @IBOutlet weak var mainImg: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var defenseLabel: UILabel! @IBOutlet weak var heightLabel: UILabel! @IBOutlet weak var pokedexLabel: UILabel! @IBOutlet weak var weightLabel: UILabel! @IBOutlet weak var attackLabel: UILabel! @IBOutlet weak var evoLabel: UILabel! @IBOutlet weak var currentEvoImg: UIImageView! @IBOutlet weak var nextEvoImg: UIImageView! override func viewDidLoad() { super.viewDidLoad() let img = UIImage(named: "\(pokemon.pokedexId)") mainImg.image = img currentEvoImg.image = img pokedexLabel.text = "\(pokemon.pokedexId)" pokemon.downloadPokemonDetail{ // This code will be call after the network call is complete! self.updateUI() } } @IBAction func backBtnPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } func updateUI(){ attackLabel.text = pokemon.attack defenseLabel.text = pokemon.defense heightLabel.text = pokemon.height weightLabel.text = pokemon.weight nameLabel.text = pokemon.name typeLabel.text = pokemon.type descriptionLabel.text = pokemon.description if pokemon.nextEvolutionId == ""{ evoLabel.text = "No Evolutions" nextEvoImg.isHidden = true }else{ nextEvoImg.isHidden = false nextEvoImg.image = UIImage(named: pokemon.nextEvolutionId) evoLabel.text = "Next Evolution: \(pokemon.nextEvolutionName) - LVL \(pokemon.nextEvolutionLevel)" } } }
mit
9f02023507394efd5dc1822e695997b9
25.24359
110
0.638007
4.498901
false
false
false
false
brenoxp/iOS-Calculator
Calculator/AppDelegate.swift
1
4886
// // AppDelegate.swift // Calculator // // Created by Breno Xavier on 14/06/17. // Copyright © 2017 Breno Xavier. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // swiftlint:disable:next line_length func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UIApplication.shared.statusBarStyle = .lightContent return true } // swiftlint:disable:previous line_length func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS // message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games // should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate // timers, and store enough application state information to restore your // application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of // applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the // changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the // application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if // appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Calculator") container.loadPersistentStores(completionHandler: { (_, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and // terminate. You should not use this function in a shipping application, although it may be useful // during development. // Typical reasons for an error here include: // The parent directory does not exist, cannot be created, or disallows writing. // The persistent store is not accessible, due to permissions or data protection when the device is // locked. // The device is out of space. // The store could not be migrated to the current model version. // Check the error message to determine what the actual problem was. fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. // You should not use this function in a shipping application, although it may be useful // during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
gpl-3.0
beae254871403eeee68d813cd4a87b5e
44.654206
144
0.664688
5.822408
false
false
false
false
ozgur/TestApp
TestApp/Extensions/Rx/NSObject+Rx.swift
1
3979
// // NSObject+Rx.swift // TestApp // // Created by Ozgur on 15/02/2017. // Copyright © 2017 Ozgur. All rights reserved. // import Foundation import ObjectiveC import RxCocoa import RxSwift import SwiftyUserDefaults import UIKit extension NSObject { fileprivate struct AssociatedKeys { static var DisposeBag = "rx_disposeBag" } fileprivate func doLocked(_ closure: () -> Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } closure() } var rx_disposeBag: DisposeBag { get { var disposeBag: DisposeBag! doLocked { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag if let lookup = lookup { disposeBag = lookup } else { let newDisposeBag = DisposeBag() self.rx_disposeBag = newDisposeBag disposeBag = newDisposeBag } } return disposeBag } set { doLocked { objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } } extension Reactive where Base: NSObject { var disposeBag: DisposeBag { return base.rx_disposeBag } } extension Reactive where Base: NSObject { /// A binding observer that logs the given string. var log: UIBindingObserver<Base, CustomStringConvertible> { return UIBindingObserver(UIElement: base) { object, log in object.logger.debug(log.description) } } /// A binding observer responsible that logs the given error. var error: UIBindingObserver<Base, NSError> { return UIBindingObserver(UIElement: base) { object, error in object.logger.error(error.localizedDescription) } } /// A binding observer responsible for setting application's badge count. var badgeCount: UIBindingObserver<Base, Int> { return UIBindingObserver(UIElement: base) { object, count in UIApplication.shared.applicationIconBadgeNumber = count object.logger.debug("Set badge count to \(count)") } } /// A binding observer responsible for reseting application's badge count. var resetBadgeCount: UIBindingObserver<Base, Void> { return UIBindingObserver(UIElement: base) { object, count in if UIApplication.shared.applicationIconBadgeNumber != 0 { UIApplication.shared.applicationIconBadgeNumber = 0 object.logger.debug("Set badge count to 0") } } } /** A binding observer that tries to register for remote notifications only if user grants permission. It sets `wasRemoteNotificationPermissionRequested` value in user defaults. */ var registerForRemoteNotifications: UIBindingObserver<Base, Void> { return UIBindingObserver(UIElement: base) { object, void in Dependencies.shared.notificationService.getAuthorizationSettings { settings in if settings.authorizationStatus == .authorized { UIApplication.shared.registerForRemoteNotifications() object.logger.debug("Registered for remote notifications (2)") } } Defaults[.wasRemoteNotificationPermissionRequested] = true } } /** A binding observer that sets `NotificationService.shared.apns` to current `PushDevice` instance and logs it. */ var apns: UIBindingObserver<Base, PushDevice> { return UIBindingObserver(UIElement: base) { object, apns in Dependencies.shared.notificationService.apns = apns object.logger.debug("Saved device: \(apns)") } } /// A binding observer to start/stop CoreLocation services. var toggleGPS: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: base) { object, authorized in if authorized { Dependencies.shared.locationService.start() object.logger.debug("Started location services") } else { Dependencies.shared.locationService.stop() object.logger.debug("Stopped location services") } } } }
gpl-3.0
012ae583663dd62af329f393357b1bfa
28.466667
112
0.687531
4.905055
false
false
false
false
ksco/swift-algorithm-club-cn
Linked List/LinkedList.playground/Contents.swift
1
5163
//: Playground - noun: a place where people can play public class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? public init(value: T) { self.value = value } } public class LinkedList<T> { public typealias Node = LinkedListNode<T> private var head: Node? public var isEmpty: Bool { return head == nil } public var first: Node? { return head } public var last: Node? { if var node = head { while case let next? = node.next { node = next } return node } else { return nil } } public var count: Int { if var node = head { var c = 1 while case let next? = node.next { node = next c += 1 } return c } else { return 0 } } public func nodeAtIndex(index: Int) -> Node? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public subscript(index: Int) -> T { let node = nodeAtIndex(index) assert(node != nil) return node!.value } public func append(value: T) { let newNode = Node(value: value) if let lastNode = last { newNode.previous = lastNode lastNode.next = newNode } else { head = newNode } } private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) { assert(index >= 0) var i = index var next = head var prev: Node? while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) // if > 0, then specified index was too large return (prev, next) } public func insert(value: T, atIndex index: Int) { let (prev, next) = nodesBeforeAndAfter(index) let newNode = Node(value: value) newNode.previous = prev newNode.next = next prev?.next = newNode next?.previous = newNode if prev == nil { head = newNode } } public func removeAll() { head = nil } public func removeNode(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.value } public func removeLast() -> T { assert(!isEmpty) return removeNode(last!) } public func removeAtIndex(index: Int) -> T { let node = nodeAtIndex(index) assert(node != nil) return removeNode(node!) } } extension LinkedList: CustomStringConvertible { public var description: String { var s = "[" var node = head while node != nil { s += "\(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } } extension LinkedList { public func reverse() { var node = head while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) head = currentNode } } } extension LinkedList { public func map<U>(transform: T -> U) -> LinkedList<U> { let result = LinkedList<U>() var node = head while node != nil { result.append(transform(node!.value)) node = node!.next } return result } public func filter(predicate: T -> Bool) -> LinkedList<T> { let result = LinkedList<T>() var node = head while node != nil { if predicate(node!.value) { result.append(node!.value) } node = node!.next } return result } } let list = LinkedList<String>() list.isEmpty // true list.first // nil list.last // nil list.append("Hello") list.isEmpty list.first!.value // "Hello" list.last!.value // "Hello" list.count // 1 list.append("World") list.first!.value // "Hello" list.last!.value // "World" list.count // 2 list.first!.previous // nil list.first!.next!.value // "World" list.last!.previous!.value // "Hello" list.last!.next // nil list.nodeAtIndex(0)!.value // "Hello" list.nodeAtIndex(1)!.value // "World" list.nodeAtIndex(2) // nil list[0] // "Hello" list[1] // "World" //list[2] // crash! list.insert("Swift", atIndex: 1) list[0] list[1] list[2] print(list) list.reverse() // [World, Swift, Hello] list.nodeAtIndex(0)!.value = "Universe" list.nodeAtIndex(1)!.value = "Swifty" let m = list.map { s in s.characters.count } m // [8, 6, 5] let f = list.filter { s in s.characters.count > 5 } f // [Universe, Swifty] //list.removeAll() //list.isEmpty list.removeNode(list.first!) // "Hello" list.count // 2 list[0] // "Swift" list[1] // "World" list.removeLast() // "World" list.count // 1 list[0] // "Swift" list.removeAtIndex(0) // "Swift" list.count // 0
mit
3e01d763acf44a8aa99c9b12e99c0156
19.652
66
0.537866
3.701075
false
false
false
false
UPetersen/LibreMonitor
LibreMonitor/AppDelegate.swift
1
7833
// // AppDelegate.swift // LibreMonitor // // Created by Uwe Petersen on 14.10.16. // Copyright © 2016 Uwe Petersen. All rights reserved. // import UIKit import CoreBluetooth import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? var coreDataStack = CoreDataStack() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Allow local notifications for iOS 10 let center = UNUserNotificationCenter.current() let options: UNAuthorizationOptions = [.alert, .badge, .sound] center.requestAuthorization(options: options) { (granted, error) in if granted { // application.registerForRemoteNotifications() } } // Do not show a badge icon value unless data has been received UIApplication.shared.applicationIconBadgeNumber = 0 // hide badge number // Override point for customization after application launch. // let splitViewController = self.window!.rootViewController as! UISplitViewController // let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController // navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem // splitViewController.delegate = self // // let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController // let controller = masterNavigationController.topViewController as! MasterViewController // controller.managedObjectContext = self.persistentContainer.viewContext print("In didFinishLaunchingWithOptions") let tabBarController = self.window?.rootViewController as! UITabBarController if let childViewControllers = tabBarController.viewControllers { for childViewController in childViewControllers where childViewController is UINavigationController { let navigationController = childViewController as! UINavigationController let bloodSugarTableViewController = navigationController.topViewController as! BloodSugarTableViewController // Set core data stack in view controller bloodSugarTableViewController.coreDataStack = coreDataStack } } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. print("In applicationWillResignActive") } 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. print("In applicationDidEnterBackground") } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. print("In applicationWillEnterForeground") } 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. print("In applicationDidBecomeActive") } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. print("In applicationWillTerminate") // self.saveContext() coreDataStack.saveContext() } // // MARK: - Split view // // func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { // guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } // guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } // if topAsDetailController.detailItem == nil { // // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. // return true // } // return false // } // // MARK: - Core Data stack // // lazy var persistentContainer: NSPersistentContainer = { // /* // The persistent container for the application. This implementation // creates and returns a container, having loaded the store for the // application to it. This property is optional since there are legitimate // error conditions that could cause the creation of the store to fail. // */ // let container = NSPersistentContainer(name: "LibreMonitor") // container.loadPersistentStores(completionHandler: { (storeDescription, error) in // if let error = error as NSError? { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // // /* // Typical reasons for an error here include: // * The parent directory does not exist, cannot be created, or disallows writing. // * The persistent store is not accessible, due to permissions or data protection when the device is locked. // * The device is out of space. // * The store could not be migrated to the current model version. // Check the error message to determine what the actual problem was. // */ // fatalError("Unresolved error \(error), \(error.userInfo)") // } // }) // return container // }() // // // MARK: - Core Data Saving support // // func saveContext () { // let context = persistentContainer.viewContext // if context.hasChanges { // do { // try context.save() // } catch { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // let nserror = error as NSError // fatalError("Unresolved error \(nserror), \(nserror.userInfo)") // } // } // } }
apache-2.0
9a38f923a11090303b2f0472b4f8a391
50.86755
285
0.685904
5.955894
false
false
false
false
rmarinho/yoga
YogaKit/YogaKitSample/YogaKitSample/Views/SingleLabelCollectionCell.swift
1
1252
/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE-examples file in the root directory of this source tree. */ import UIKit import YogaKit final class SingleLabelCollectionCell: UICollectionViewCell { let label: UILabel = UILabel(frame: .zero) override init(frame: CGRect) { super.init(frame: frame) contentView.yoga.isEnabled = true contentView.yoga.flexDirection = .column contentView.yoga.justifyContent = .flexEnd label.textAlignment = .center label.numberOfLines = 1 label.yoga.isIncludedInLayout = false contentView.addSubview(label) let border = UIView(frame: .zero) border.backgroundColor = .lightGray border.yoga.isEnabled = true border.yoga.height = 0.5 border.yoga.marginHorizontal = 25 contentView.addSubview(border) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() contentView.yoga.applyLayout(preservingOrigin: false) label.frame = contentView.bounds } }
bsd-3-clause
1582cfed3941a2f013ab9f4b95a45704
26.822222
67
0.672524
4.455516
false
false
false
false
rambler-ios/RamblerConferences
Carthage/Checkouts/rides-ios-sdk/source/UberRides/RideRequestView.swift
1
10225
// // RideRequestView.swift // UberRides // // Copyright © 2016 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import WebKit import CoreLocation /** * Delegates are informed of events that occur in the RideRequestView such as errors. */ @objc(UBSDKRideRequestViewDelegate) public protocol RideRequestViewDelegate { /** An error has occurred in the Ride Request Control. - parameter rideRequestView: the RideRequestView - parameter error: the NSError that occured, with a code of RideRequestViewErrorType */ func rideRequestView(rideRequestView: RideRequestView, didReceiveError error: NSError) } /// A view that shows the embedded Uber experience. @objc(UBSDKRideRequestView) public class RideRequestView: UIView { /// The RideRequestViewDelegate of this view. public var delegate: RideRequestViewDelegate? /// The access token used to authorize the web view public var accessToken: AccessToken? /// Ther RideParameters to use for prefilling the RideRequestView public var rideParameters: RideParameters var webView: WKWebView let redirectURL = "uberconnect://oauth" static let sourceString = "ride_request_view" /** Initializes to show the embedded Uber ride request view. - parameter rideParameters: The RideParameters to use for presetting values; defaults to using the current location for pickup - parameter accessToken: specific access token to use with web view; defaults to using TokenManager's default token - parameter frame: frame of the view. Defaults to CGRectZero - returns: An initialized RideRequestView */ @objc public required init(rideParameters: RideParameters, accessToken: AccessToken?, frame: CGRect) { self.rideParameters = rideParameters self.accessToken = accessToken let configuration = WKWebViewConfiguration() configuration.processPool = Configuration.processPool webView = WKWebView(frame: CGRectZero, configuration: configuration) super.init(frame: frame) initialSetup() } /** Initializes to show the embedded Uber ride request view. Uses the TokenManager's default accessToken - parameter rideParameters: The RideParameters to use for presetting values - parameter frame: frame of the view - returns: An initialized RideRequestView */ @objc public convenience init(rideParameters: RideParameters, frame: CGRect) { self.init(rideParameters: rideParameters, accessToken: TokenManager.fetchToken(), frame: frame) } /** Initializes to show the embedded Uber ride request view. Frame defaults to CGRectZero Uses the TokenManager's default accessToken - parameter rideParameters: The RideParameters to use for presetting values - returns: An initialized RideRequestView */ @objc public convenience init(rideParameters: RideParameters) { self.init(rideParameters: rideParameters, accessToken: TokenManager.fetchToken(), frame: CGRectZero) } /** Initializes to show the embedded Uber ride request view. Uses the current location for pickup Uses the TokenManager's default accessToken - parameter frame: frame of the view - returns: An initialized RideRequestView */ @objc public convenience override init(frame: CGRect) { self.init(rideParameters: RideParametersBuilder().build(), accessToken: TokenManager.fetchToken(), frame: frame) } /** Initializes to show the embedded Uber ride request view. Uses the current location for pickup Uses the TokenManager's default accessToken Frame defaults to CGRectZero - returns: An initialized RideRequestView */ @objc public convenience init() { self.init(rideParameters: RideParametersBuilder().build(), accessToken: TokenManager.fetchToken(), frame: CGRectZero) } required public init?(coder aDecoder: NSCoder) { rideParameters = RideParametersBuilder().build() let configuration = WKWebViewConfiguration() configuration.processPool = Configuration.processPool webView = WKWebView(frame: CGRectZero, configuration: configuration) super.init(coder: aDecoder) initialSetup() } deinit { webView.scrollView.delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Public /** Load the Uber Ride Request Widget view. Requires that the access token has been retrieved. */ public func load() { guard let accessToken = accessToken else { self.delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.AccessTokenMissing)) return } let tokenString = accessToken.tokenString if rideParameters.source == nil { rideParameters.source = RideRequestView.sourceString } let endpoint = Components.RideRequestWidget(rideParameters: rideParameters) let request = Request(session: nil, endpoint: endpoint, bearerToken: tokenString) request.prepare() let urlRequest = request.urlRequest urlRequest.cachePolicy = .ReturnCacheDataElseLoad webView.loadRequest(urlRequest) } /** Stop loading the Ride Request Widget View and clears the view. If the view has already loaded, calling this still clears the view. */ public func cancelLoad() { webView.stopLoading() if let url = NSURL(string: "about:blank") { webView.loadRequest(NSURLRequest(URL: url)) } } // MARK: Private private func initialSetup() { webView.navigationDelegate = self webView.scrollView.delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardDidAppear(_:)), name: UIKeyboardDidShowNotification, object: nil) setupWebView() } private func setupWebView() { addSubview(webView) webView.translatesAutoresizingMaskIntoConstraints = false webView.scrollView.bounces = false let views = ["webView": webView] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) addConstraints(horizontalConstraints) addConstraints(verticalConstraints) } // MARK: Keyboard Notifications func keyboardWillAppear(notification: NSNotification) { webView.scrollView.scrollEnabled = false } func keyboardDidAppear(notification: NSNotification) { webView.scrollView.scrollEnabled = true } } // MARK: WKNavigationDelegate extension RideRequestView: WKNavigationDelegate { public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.URL { if url.absoluteString?.lowercaseString.hasPrefix(redirectURL.lowercaseString) ?? false { let error = OAuthUtil.parseRideWidgetErrorFromURL(url) delegate?.rideRequestView(self, didReceiveError: error) decisionHandler(.Cancel) return } else if url.scheme == "tel" || url.scheme == "sms" { if (!UIApplication.sharedApplication().openURL(url)) { delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.NotSupported)) } decisionHandler(.Cancel) return } } decisionHandler(.Allow) } public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.NetworkError)) } public func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { guard error.code != 102 else { return } delegate?.rideRequestView(self, didReceiveError: RideRequestViewErrorFactory.errorForType(.NetworkError)) } } // MARK: UIScrollViewDelegate extension RideRequestView : UIScrollViewDelegate { public func scrollViewDidScroll(scrollView: UIScrollView) { if !scrollView.scrollEnabled { scrollView.bounds = self.webView.bounds } } }
mit
7adc0f05b405bb0dadf0e3cc68b286dc
38.9375
172
0.692097
5.5747
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Settings/SettingsLogoutTableViewCell.swift
1
2264
// Copyright (c) 2016 Ark // // 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 class SettingsLogoutTableViewCell: UITableViewCell { var titleLabel : UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: "account") backgroundColor = ArkPalette.backgroundColor selectionStyle = .none titleLabel = UILabel() titleLabel.text = "Sign out" titleLabel.textColor = ArkPalette.highlightedTextColor titleLabel.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold) addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(15.0) make.width.equalTo(250.0) } let seperator = UIView() seperator.backgroundColor = ArkPalette.secondaryBackgroundColor addSubview(seperator) seperator.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(1.0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bc42019a024d1c25b0022d09fe9ab00f
44.28
137
0.704505
4.900433
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/Departure/BusStopViewController.swift
1
19041
import UIKit import RxSwift import RxCocoa import Realm import RealmSwift import Alamofire import StatefulViewController class BusStopViewController: MasterViewController, UITabBarDelegate, StatefulViewController { let dateFormat = "HH:mm" @IBOutlet weak var timeField: UITextField! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var autoCompleteTableView: UITableView! var selectedBusStop: BBusStop? var foundBusStations: [BBusStop] = [] var datePicker: UIDatePicker! var allDepartures: [Departure] = [] var disabledDepartures: [Departure] = [] var searchDate: Date! var refreshControl: UIRefreshControl! var working: Bool! = false var realm = Realm.busStops() init(busStop: BBusStop? = nil) { super.init(nibName: "BusStopViewController", title: L10n.Departures.title) self.selectedBusStop = busStop } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "DepartureViewCell", bundle: nil), forCellReuseIdentifier: "DepartureViewCell") tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() refreshControl = UIRefreshControl() refreshControl.tintColor = Theme.lightOrange refreshControl.addTarget(self, action: #selector(parseData), for: .valueChanged) refreshControl.attributedTitle = NSAttributedString( string: L10n.General.pullToRefresh, attributes: [NSForegroundColorAttributeName: Theme.darkGrey] ) tableView.refreshControl = refreshControl setupSearchDate() view.backgroundColor = Theme.darkGrey searchBar.barTintColor = .darkGray searchBar.tintColor = Theme.white searchBar.backgroundImage = UIImage() searchBar.setImage(Asset.icNavigationBus.image, for: UISearchBarIcon.search, state: UIControlState()) (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey (searchBar.value(forKey: "searchField") as! UITextField).clearButtonMode = UITextFieldViewMode.never navigationItem.rightBarButtonItem = getFilterButton() tabBar.items![0].title = L10n.Departures.Header.gps tabBar.items![1].title = L10n.Departures.Header.map tabBar.items![2].title = L10n.Departures.Header.favorites datePicker = UIDatePicker(frame: CGRect.zero) datePicker.datePickerMode = .dateAndTime datePicker.backgroundColor = Theme.darkGrey datePicker.tintColor = Theme.white datePicker.setValue(Theme.white, forKey: "textColor") timeField.textColor = Theme.white timeField.tintColor = Theme.transparent timeField.inputView = datePicker loadingView = LoadingView(frame: view.frame) emptyView = NoDeparturesView(frame: tableView.frame) errorView = ErrorView(frame: view.frame, target: self, action: #selector(parseData)) setupAutoCompleteTableView() setupBusStopSearchDate() if let stop = selectedBusStop { let tempStop = stop selectedBusStop = nil setBusStop(tempStop) } } override func leftDrawerButtonPress(_ sender: AnyObject?) { self.searchBar.endEditing(true) self.timeField.endEditing(true) super.leftDrawerButtonPress(sender) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let view = emptyView { view.frame = CGRect( x: view.frame.origin.x, y: view.frame.origin.y + tabBar.frame.size.height, width: view.frame.size.width, height: view.frame.size.height - 2 * tabBar.frame.size.height ) (view as? NoDeparturesView)?.setupView() } } override func viewDidAppear(_ animated: Bool) { tabBar.selectedItem = nil } fileprivate func setupAutoCompleteTableView() { self.autoCompleteTableView!.isHidden = true self.updateFoundBusStations("") self.view.addSubview(self.autoCompleteTableView!) self.autoCompleteTableView!.register(UINib(nibName: "DepartureAutoCompleteCell", bundle: nil), forCellReuseIdentifier: "DepartureAutoCompleteCell") } fileprivate func updateFoundBusStations(_ searchText: String) { let busStops: Results<BusStop> if searchText.isEmpty { busStops = realm.objects(BusStop.self) } else { busStops = realm.objects(BusStop.self) .filter("nameDe CONTAINS[c] %@ OR nameIt CONTAINS[c] %@ OR municDe CONTAINS[c] %@ OR municIt CONTAINS[c] %@", searchText, searchText, searchText, searchText) } let mapped = busStops.map { BBusStop(fromRealm: $0) } foundBusStations = Array(Set(mapped)) self.foundBusStations = foundBusStations.sorted(by: { $0.name(locale: Locales.get()) < $1.name(locale: Locales.get()) }) self.autoCompleteTableView.reloadData() } func setBusStationFromCurrentLocation() { // TODO /*if UserDefaultHelper.instance.isBeaconStationDetectionEnabled() { let currentBusStop = UserDefaultHelper.instance.getCurrentBusStop() if let stop = currentBusStop != nil { Log.info("Current bus stop: \(stop)") if let busStop = realm.objects(BusStop.self).filter("id == \(stop)").first { setBusStop(BBusStop(fromRealm: busStop)) setupBusStopSearchDate() autoCompleteTableView.isHidden = true tabBar.selectedItem = nil } } }*/ } func setupBusStopSearchDate() { setupSearchDate() datePicker.date = searchDate as Date let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat timeField.text = dateFormatter.string(from: searchDate as Date) } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 0 { let busStopGpsViewController = BusStopGpsViewController() navigationController!.pushViewController(busStopGpsViewController, animated: true) } else if item.tag == 1 { let busStopMapViewController = BusStopMapViewController() navigationController!.pushViewController(busStopMapViewController, animated: true) } else if item.tag == 2 { let busStopFavoritesViewController = BusStopFavoritesViewController(busStop: self.selectedBusStop) navigationController!.pushViewController(busStopFavoritesViewController, animated: true) } } func goToFilter() { let busStopFilterViewController = BusStopFilterViewController() navigationController!.pushViewController(busStopFilterViewController, animated: true) } func setBusStop(_ busStop: BBusStop) { if selectedBusStop != nil && selectedBusStop!.family == busStop.family { // Don't reload same bus stop return } Log.info("Setting bus stop '\(busStop.id)'") selectedBusStop = busStop autoCompleteTableView.isHidden = true searchBar.text = selectedBusStop?.name() searchBar.endEditing(true) searchBar.resignFirstResponder() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func parseData() { guard selectedBusStop != nil else { Log.error("No bus stop is currently selected") return } startLoading() _ = self.getDepartures() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { items in self.allDepartures.removeAll() self.allDepartures.append(contentsOf: items) self.updateFilter() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false) self.loadDelays() }, onError: { error in ErrorHelper.log(error, message: "Could not fetch departures") self.allDepartures.removeAll() self.tableView.reloadData() self.tableView.refreshControl?.endRefreshing() self.endLoading(animated: false, error: error) }) } func loadDelays() { _ = RealtimeApi.delays() .subscribeOn(MainScheduler.background) .observeOn(MainScheduler.instance) .subscribe(onNext: { buses in for bus in buses { for item in self.allDepartures { if item.trip == bus.trip { item.delay = bus.delay item.vehicle = bus.vehicle item.currentBusStop = bus.busStop break } } } self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }, onError: { error in ErrorHelper.log(error, message: "Could not load delays") self.allDepartures.filter { $0.delay == Config.BUS_STOP_DETAILS_OPERATION_RUNNING }.forEach { $0.delay = Config.BUS_STOP_DETAILS_NO_DELAY } if !self.allDepartures.isEmpty { self.tableView.reloadData() } }) } func updateFilter() { let disabledLines: [Int] = UserRealmHelper.getDisabledDepartures() disabledDepartures.removeAll() if disabledLines.isEmpty { disabledDepartures.append(contentsOf: allDepartures) } else { disabledDepartures.append(contentsOf: allDepartures.filter { !disabledLines.contains($0.lineId) }) } self.refreshControl.endRefreshing() self.tableView.reloadData() self.enableSearching() } func hasContent() -> Bool { return !allDepartures.isEmpty } func getDepartures() -> Observable<[Departure]> { return Observable.create { observer in let departures = DepartureMonitor() .atBusStopFamily(family: self.selectedBusStop?.family ?? 0) .at(date: self.searchDate) .collect() let mapped = departures.map { $0.asDeparture(busStopId: self.selectedBusStop?.id ?? 0) } observer.on(.next(mapped)) return Disposables.create() } } } extension BusStopViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { return self.foundBusStations.count } else { return disabledDepartures.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.autoCompleteTableView != nil && tableView.isEqual(self.autoCompleteTableView) { let busStation = self.foundBusStations[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureAutoCompleteCell", for: indexPath) as! DepartureAutoCompleteCell cell.label.text = busStation.name() return cell } let departure = disabledDepartures[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "DepartureViewCell", for: indexPath) as! DepartureViewCell cell.timeLabel.text = departure.time if departure.delay == Departure.OPERATION_RUNNING { cell.delayLabel.text = L10n.Departures.Cell.loading cell.delayColor = Theme.darkGrey } else if departure.delay == Departure.NO_DELAY { cell.delayLabel.text = L10n.Departures.Cell.noData cell.delayColor = Theme.darkGrey } if departure.vehicle != 0 { cell.delayColor = Color.delay(departure.delay) if departure.delay == 0 { cell.delayLabel.text = L10n.General.delayPunctual } else if departure.delay < 0 { cell.delayLabel.text = L10n.General.delayEarly(abs(departure.delay)) } else { cell.delayLabel.text = L10n.General.delayDelayed(departure.delay) } } cell.infoLabel.text = Lines.line(id: departure.lineId) cell.directionLabel.text = departure.destination return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if autoCompleteTableView != nil && tableView.isEqual(autoCompleteTableView) { navigationItem.rightBarButtonItem = getFilterButton() let busStop = foundBusStations[indexPath.row] // Is this the right place to put this? UserRealmHelper.addRecentDeparture(group: busStop.family) setBusStop(busStop) } else { let item = disabledDepartures[indexPath.row] let busStopTripViewController = LineCourseViewController( tripId: item.trip, lineId: item.lineId, vehicle: item.vehicle, currentBusStop: item.currentBusStop, busStopGroup: item.busStopGroup, date: searchDate ) self.navigationController!.pushViewController(busStopTripViewController, animated: true) } } } extension BusStopViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return false } func textFieldDidBeginEditing(_ textField: UITextField) { let datePickerDoneButton = UIBarButtonItem( title: L10n.Departures.Button.done, style: UIBarButtonItemStyle.done, target: self, action: #selector(setSearchDate) ) navigationItem.rightBarButtonItem = datePickerDoneButton } func textFieldDidEndEditing(_ textField: UITextField) { navigationItem.rightBarButtonItem = nil allDepartures.removeAll() tableView.reloadData() textField.resignFirstResponder() } } extension BusStopViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if selectedBusStop != nil { selectedBusStop = nil } updateFoundBusStations(searchText) } func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { return !working } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(searchBarCancel) ) searchBar.text = "" updateFoundBusStations(searchBar.text!) autoCompleteTableView.isHidden = false errorView?.isHidden = true loadingView?.isHidden = true emptyView?.isHidden = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { foundBusStations = [] autoCompleteTableView.isHidden = true autoCompleteTableView.reloadData() startLoading(animated: false) endLoading(animated: false) errorView?.isHidden = false loadingView?.isHidden = false emptyView?.isHidden = false } } extension BusStopViewController { internal func disableSearching() { self.working = true (self.searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.grey self.timeField.isUserInteractionEnabled = false self.searchBar.alpha = 0.7 self.timeField.alpha = 0.7 let items = self.tabBar.items for item in items! { item.isEnabled = false } self.tabBar.setItems(items, animated: false) } internal func enableSearching() { working = false (searchBar.value(forKey: "searchField") as! UITextField).textColor = Theme.darkGrey timeField.isUserInteractionEnabled = true searchBar.alpha = 1.0 timeField.alpha = 1.0 let items = tabBar.items for item in items! { item.isEnabled = true } tabBar.setItems(items, animated: false) } func searchBarCancel() { searchBar.endEditing(true) searchBar.resignFirstResponder() navigationItem.rightBarButtonItem = getFilterButton() } func setSearchDate() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat searchDate = datePicker.date timeField.text = dateFormatter.string(from: searchDate as Date) timeField.endEditing(true) navigationItem.rightBarButtonItem = getFilterButton() allDepartures.removeAll() disabledDepartures.removeAll() tableView.reloadData() parseData() } func setupSearchDate() { self.searchDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat } func getFilterButton() -> UIBarButtonItem { return UIBarButtonItem( image: Asset.filterIcon.image.withRenderingMode(UIImageRenderingMode.alwaysTemplate), style: .plain, target: self, action: #selector(goToFilter) ) } }
gpl-3.0
9622cb486f7a62beeccb02272bec941e
30.735
129
0.604695
5.363662
false
false
false
false
JohnEstropia/CoreStore
Demo/Sources/Demos/Classic/ColorsDemo/Classic.ColorsDemo.LIstView.swift
1
2536
// // Demo // Copyright © 2020 John Rommel Estropia, Inc. All rights reserved. import CoreStore import SwiftUI // MARK: - Classic.ColorsDemo extension Classic.ColorsDemo { // MARK: - Classic.ColorsDemo.ListView struct ListView: UIViewControllerRepresentable { // MARK: Internal init( listMonitor: ListMonitor<Classic.ColorsDemo.Palette>, onPaletteTapped: @escaping (Classic.ColorsDemo.Palette) -> Void ) { self.listMonitor = listMonitor self.onPaletteTapped = onPaletteTapped } // MARK: UIViewControllerRepresentable typealias UIViewControllerType = Classic.ColorsDemo.ListViewController func makeUIViewController(context: Self.Context) -> UIViewControllerType { return UIViewControllerType( listMonitor: self.listMonitor, onPaletteTapped: self.onPaletteTapped ) } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Self.Context) { uiViewController.setEditing( context.environment.editMode?.wrappedValue.isEditing == true, animated: true ) } static func dismantleUIViewController(_ uiViewController: UIViewControllerType, coordinator: Void) {} // MARK: Private private let listMonitor: ListMonitor<Classic.ColorsDemo.Palette> private let onPaletteTapped: (Classic.ColorsDemo.Palette) -> Void } } #if DEBUG struct _Demo_Classic_ColorsDemo_ListView_Preview: PreviewProvider { // MARK: PreviewProvider static var previews: some View { let minimumSamples = 10 try! Classic.ColorsDemo.dataStack.perform( synchronous: { transaction in let missing = minimumSamples - (try transaction.fetchCount(From<Classic.ColorsDemo.Palette>())) guard missing > 0 else { return } for _ in 0..<missing { let palette = transaction.create(Into<Classic.ColorsDemo.Palette>()) palette.setRandomHue() } } ) return Classic.ColorsDemo.ListView( listMonitor: Classic.ColorsDemo.palettesMonitor, onPaletteTapped: { _ in } ) } } #endif
mit
d0713c714245f2558018852f61e88b00
27.483146
109
0.577515
5.774487
false
false
false
false
Drusy/auvergne-webcams-ios
Carthage/Checkouts/Siren/Sources/Siren.swift
1
15253
// // Siren.swift // Siren // // Created by Arthur Sabintsev on 1/3/15. // Copyright (c) 2015 Sabintsev iOS Projects. All rights reserved. // import UIKit // MARK: - Siren /// The Siren Class. A singleton that is initialized using the `shared` constant. public final class Siren: NSObject { /// Current installed version of your app. internal var currentInstalledVersion: String? = { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String }() /// The error domain for all errors created by Siren. public let SirenErrorDomain = "Siren Error Domain" /// The `SirenDelegate` variable, which should be set if you'd like to be notified of any of specific user interactions or API success/failures. /// Also set this variable if you'd like to use custom UI for presesnting the update notification. public weak var delegate: SirenDelegate? /// The debug flag, which is disabled by default. /// When enabled, a stream of print() statements are logged to your console when a version check is performed. public lazy var debugEnabled = false /// Determines the type of alert that should be shown. /// See the Siren.AlertType enum for full details. public var alertType: AlertType = .option { didSet { majorUpdateAlertType = alertType minorUpdateAlertType = alertType patchUpdateAlertType = alertType revisionUpdateAlertType = alertType } } /// Determines the type of alert that should be shown for major version updates: A.b.c /// Defaults to Siren.AlertType.option. /// See the Siren.AlertType enum for full details. public lazy var majorUpdateAlertType: AlertType = .option /// Determines the type of alert that should be shown for minor version updates: a.B.c /// Defaults to Siren.AlertType.option. /// See the Siren.AlertType enum for full details. public lazy var minorUpdateAlertType: AlertType = .option /// Determines the type of alert that should be shown for minor patch updates: a.b.C /// Defaults to Siren.AlertType.option. /// See the Siren.AlertType enum for full details. public lazy var patchUpdateAlertType: AlertType = .option /// Determines the type of alert that should be shown for revision updates: a.b.c.D /// Defaults to Siren.AlertType.option. /// See the Siren.AlertType enum for full details. public lazy var revisionUpdateAlertType: AlertType = .option /// The name of your app. /// By default, it's set to the name of the app that's stored in your plist. public lazy var appName = Bundle.bestMatchingAppName() /// Overrides all the Strings to which Siren defaults. /// Defaults to the values defined in `SirenAlertMessaging.Constants` public var alertMessaging = SirenAlertMessaging() /// The region or country of an App Store in which your app is available. /// By default, all version checks are performed against the US App Store. /// If your app is not available in the US App Store, set it to the identifier of at least one App Store within which it is available. public var countryCode: String? /// Overrides the default localization of a user's device when presenting the update message and button titles in the alert. /// See the Siren.LanguageType enum for more details. public var forceLanguageLocalization: Siren.LanguageType? /// Overrides the tint color for UIAlertController. public var alertControllerTintColor: UIColor? /// When this is set, the alert will only show up if the current version has already been released for X days. /// Defaults to 1 day to avoid an issue where Apple updates the JSON faster than the app binary propogates to the App Store. public var showAlertAfterCurrentVersionHasBeenReleasedForDays: Int = 1 /// The current version of your app that is available for download on the App Store public internal(set) var currentAppStoreVersion: String? /// The `UIWindow` instance that presents the `SirenAlertViewController`. var updaterWindow: UIWindow? /// The last Date that a version check was performed. var lastVersionCheckPerformedOnDate: Date? fileprivate var appID: Int? fileprivate lazy var alertViewIsVisible: Bool = false /// Type of the available update fileprivate var updateType: UpdateType = .unknown /// The App's Singleton public static let shared = Siren() override init() { lastVersionCheckPerformedOnDate = UserDefaults.storedVersionCheckDate } /// Checks the currently installed version of your app against the App Store. /// The default check is against the US App Store, but if your app is not listed in the US, /// you should set the `countryCode` property before calling this method. Please refer to the countryCode property for more information. /// /// - Parameters: /// - checkType: The frequency in days in which you want a check to be performed. Please refer to the Siren.VersionCheckType enum for more details. public func checkVersion(checkType: VersionCheckType) { updateType = .unknown guard Bundle.bundleID() != nil else { printMessage("Please make sure that you have set a `Bundle Identifier` in your project.") return } if checkType == .immediately { performVersionCheck() } else if UserDefaults.shouldPerformVersionCheckOnSubsequentLaunch { UserDefaults.shouldPerformVersionCheckOnSubsequentLaunch = false performVersionCheck() } else { guard let lastVersionCheckPerformedOnDate = lastVersionCheckPerformedOnDate else { performVersionCheck() return } if Date.days(since: lastVersionCheckPerformedOnDate) >= checkType.rawValue { performVersionCheck() } else { postError(.recentlyCheckedAlready) } } } /// Launches the AppStore in two situations: /// /// - User clicked the `Update` button in the UIAlertController modal. /// - Developer built a custom alert modal and needs to be able to call this function when the user chooses to update the app in the aforementioned custom modal. public func launchAppStore() { guard let appID = appID, let url = URL(string: "https://itunes.apple.com/app/id\(appID)") else { return } DispatchQueue.main.async { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } } } // MARK: - Networking private extension Siren { func performVersionCheck() { do { let url = try iTunesURLFromString() let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) URLCache.shared.removeCachedResponse(for: request) URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in self?.processResults(withData: data, response: response, error: error) }).resume() } catch { postError(.malformedURL) } } func processResults(withData data: Data?, response: URLResponse?, error: Error?) { if let error = error { postError(.appStoreDataRetrievalFailure(underlyingError: error)) } else { guard let data = data else { return postError(.appStoreDataRetrievalFailure(underlyingError: nil)) } do { let decodedData = try JSONDecoder().decode(SirenLookupModel.self, from: data) guard !decodedData.results.isEmpty else { return postError(.appStoreDataRetrievalEmptyResults) } DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.printMessage("Decoded JSON results: \(decodedData)") self.delegate?.sirenNetworkCallDidReturnWithNewVersionInformation(lookupModel: decodedData) self.processVersionCheck(with: decodedData) } } catch { postError(.appStoreJSONParsingFailure(underlyingError: error)) } } } func processVersionCheck(with model: SirenLookupModel) { guard isUpdateCompatibleWithDeviceOS(for: model) else { return } guard let appID = model.results.first?.appID else { return postError(.appStoreAppIDFailure) } self.appID = appID guard let currentAppStoreVersion = model.results.first?.version else { return postError(.appStoreVersionArrayFailure) } self.currentAppStoreVersion = currentAppStoreVersion guard isAppStoreVersionNewer() else { delegate?.sirenLatestVersionInstalled() postError(.noUpdateAvailable) return } guard let currentVersionReleaseDate = model.results.first?.currentVersionReleaseDate, let daysSinceRelease = Date.days(since: currentVersionReleaseDate) else { return } guard daysSinceRelease >= showAlertAfterCurrentVersionHasBeenReleasedForDays else { let message = "Your app has been released for \(daysSinceRelease) days, but Siren cannot prompt the user until \(showAlertAfterCurrentVersionHasBeenReleasedForDays) days have passed." self.printMessage(message) return } showAlertIfCurrentAppStoreVersionNotSkipped() } func iTunesURLFromString() throws -> URL { var components = URLComponents() components.scheme = "https" components.host = "itunes.apple.com" components.path = "/lookup" var items: [URLQueryItem] = [URLQueryItem(name: "bundleId", value: Bundle.bundleID())] if let countryCode = countryCode { let item = URLQueryItem(name: "country", value: countryCode) items.append(item) } components.queryItems = items guard let url = components.url, !url.absoluteString.isEmpty else { throw SirenError.Known.malformedURL } return url } } // MARK: - Alert private extension Siren { func showAlertIfCurrentAppStoreVersionNotSkipped() { alertType = setAlertType() guard let previouslySkippedVersion = UserDefaults.storedSkippedVersion else { showAlert() return } if let currentAppStoreVersion = currentAppStoreVersion, currentAppStoreVersion != previouslySkippedVersion { showAlert() } } func showAlert() { storeVersionCheckDate() let updateAvailableMessage = localizedUpdateTitle() let newVersionMessage = localizedNewVersionMessage() let alertController = UIAlertController(title: updateAvailableMessage, message: newVersionMessage, preferredStyle: .alert) if let alertControllerTintColor = alertControllerTintColor { alertController.view.tintColor = alertControllerTintColor } switch alertType { case .force: alertController.addAction(updateAlertAction()) case .option: alertController.addAction(nextTimeAlertAction()) alertController.addAction(updateAlertAction()) case .skip: alertController.addAction(nextTimeAlertAction()) alertController.addAction(updateAlertAction()) alertController.addAction(skipAlertAction()) case .none: let updateTitle = localizedUpdateTitle() delegate?.sirenDidDetectNewVersionWithoutAlert(title: updateTitle, message: newVersionMessage, updateType: updateType) } if alertType != .none && !alertViewIsVisible { alertController.show() alertViewIsVisible = true delegate?.sirenDidShowUpdateDialog(alertType: alertType) } } func updateAlertAction() -> UIAlertAction { let title = localizedUpdateButtonTitle() let action = UIAlertAction(title: title, style: .default) { [weak self] _ in guard let self = self else { return } self.hideWindow() self.launchAppStore() self.delegate?.sirenUserDidLaunchAppStore() self.alertViewIsVisible = false return } return action } func nextTimeAlertAction() -> UIAlertAction { let title = localizedNextTimeButtonTitle() let action = UIAlertAction(title: title, style: .default) { [weak self] _ in guard let self = self else { return } self.hideWindow() self.delegate?.sirenUserDidCancel() self.alertViewIsVisible = false UserDefaults.shouldPerformVersionCheckOnSubsequentLaunch = true return } return action } func skipAlertAction() -> UIAlertAction { let title = localizedSkipButtonTitle() let action = UIAlertAction(title: title, style: .default) { [weak self] _ in guard let self = self else { return } if let currentAppStoreVersion = self.currentAppStoreVersion { UserDefaults.storedSkippedVersion = currentAppStoreVersion UserDefaults.standard.synchronize() } self.hideWindow() self.delegate?.sirenUserDidSkipVersion() self.alertViewIsVisible = false return } return action } func setAlertType() -> Siren.AlertType { guard let currentInstalledVersion = currentInstalledVersion, let currentAppStoreVersion = currentAppStoreVersion else { return .option } let oldVersion = (currentInstalledVersion).lazy.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0} let newVersion = (currentAppStoreVersion).lazy.split {$0 == "."}.map { String($0) }.map {Int($0) ?? 0} guard let newVersionFirst = newVersion.first, let oldVersionFirst = oldVersion.first else { return alertType // Default value is .Option } if newVersionFirst > oldVersionFirst { // A.b.c.d alertType = majorUpdateAlertType updateType = .major } else if newVersion.count > 1 && (oldVersion.count <= 1 || newVersion[1] > oldVersion[1]) { // a.B.c.d alertType = minorUpdateAlertType updateType = .minor } else if newVersion.count > 2 && (oldVersion.count <= 2 || newVersion[2] > oldVersion[2]) { // a.b.C.d alertType = patchUpdateAlertType updateType = .patch } else if newVersion.count > 3 && (oldVersion.count <= 3 || newVersion[3] > oldVersion[3]) { // a.b.c.D alertType = revisionUpdateAlertType updateType = .revision } return alertType } }
apache-2.0
a318370f1531a443e8a30c1ee139d40d
38.01023
195
0.650036
5.430046
false
false
false
false
SoneeJohn/WWDC
ConfCore/Track.swift
1
1702
// // Track.swift // WWDC // // Created by Guilherme Rambo on 06/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import RealmSwift /// Tracks represent a specific are of interest (ex: "System Frameworks", "Graphics and Games") public class Track: Object { /// Unique identifier @objc public dynamic var identifier = "" /// The name of the track @objc public dynamic var name = "" /// The order in which the track should be listed @objc public dynamic var order = 0 /// Dark theme color @objc public dynamic var darkColor = "" /// Color for light backgrounds @objc public dynamic var lightBackgroundColor = "" /// Color for light contexts @objc public dynamic var lightColor = "" /// Theme title color @objc public dynamic var titleColor = "" /// Sessions related to this track public let sessions = List<Session>() /// Instances related to this track public let instances = List<SessionInstance>() public override class func primaryKey() -> String? { return "name" } public static func make(identifier: String, name: String, darkColor: String, lightBackgroundColor: String, lightColor: String, titleColor: String) -> Track { let track = Track() track.identifier = identifier track.name = name track.darkColor = darkColor track.lightBackgroundColor = lightBackgroundColor track.lightColor = lightColor track.titleColor = titleColor return track } }
bsd-2-clause
787358b4773a1bdbd34699afbb78822d
25.578125
95
0.60729
5.170213
false
false
false
false
ShockUtility/ShockExtension
ShockExtension/Classes/AutoLayoutOperator.swift
1
1978
// // AutoLayoutOperator.swift // Pods // // Created by shock on 2017. 5. 10.. // // import UIKit precedencegroup LayoutPrecedence { associativity: left higherThan: BitwiseShiftPrecedence } // 좌측 뷰에 우측 뷰를 넣어주고 페이딩을 적용시킨다 infix operator <<== : LayoutPrecedence public func <<==(superView: UIView, subView: UIView) { superView <<== (subView, 0, 0, 0, 0) } public func <<==(superView: UIView, rhs:(UIView, CGFloat)) { superView <<== (rhs.0, rhs.1, rhs.1, rhs.1, rhs.1) } public func <<==(superView: UIView, rhs:(UIView, CGFloat, CGFloat, CGFloat, CGFloat)) { // left, right, top, bottom superView.addSubview(rhs.0) rhs.0 |-| (left:rhs.1, right:rhs.2, top:rhs.3, bottom:rhs.4) } // 뷰애 페이딩을 적용시킨다 infix operator |-| : LayoutPrecedence public func |-|(view: UIView, rhs:(CGFloat, CGFloat, CGFloat, CGFloat)) { view |-| (left: rhs.0, right: rhs.1) view |-| (top: rhs.2, bottom: rhs.3) } public func |-|(view: UIView, rhs:(left:CGFloat, right:CGFloat)) { if let superView = view.superview { superView |-| (format: "H:|-\(rhs.left)-[view0]-\(rhs.right)-|", views: [view]) } } public func |-|(view: UIView, rhs:(top:CGFloat, bottom:CGFloat)) { if let superView = view.superview { superView |-| (format: "V:|-\(rhs.top)-[view0]-\(rhs.bottom)-|", views: [view]) } } public func |-|(view: UIView, rhs:(format:String, views:[Any])) { let views = rhs.views.reduce([String: Any]()) { (arr, view) in if let v = view as? UIView { v.translatesAutoresizingMaskIntoConstraints = false } var totalMutable = arr totalMutable.updateValue(view, forKey: "view"+String(arr.count)) return totalMutable } view.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: rhs.format, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) }
mit
e305b5bb9fd8ee98b4fa80624deb631c
27.147059
115
0.623302
3.28866
false
false
false
false
SwiftOnEdge/Edge
Sources/HTTP/Server.swift
1
3118
// // HTTP.swift // Edge // // Created by Tyler Fleming Cloutier on 6/22/16. // // import Dispatch import StreamKit import POSIX import Foundation import TCP public protocol ServerDelegate { func handle(requests: Signal<Request>) -> Signal<Response> } public final class Server { let delegate: ServerDelegate private var disposable: ActionDisposable? = nil let reuseAddress: Bool let reusePort: Bool public init(delegate: ServerDelegate? = nil, reuseAddress: Bool = false, reusePort: Bool = false) { self.delegate = delegate ?? Router() self.reuseAddress = reuseAddress self.reusePort = reusePort } deinit { self.stop() } public func stop() { disposable?.dispose() } public func parse(data dataStream: Source<Data>) -> Source<Request> { return Source { observer in let parser = RequestParser() parser.onRequest = { request in observer.sendNext(request) } dataStream.onNext { data in do { try parser.parse(data) } catch { // Respond with 400 error observer.sendFailed(ClientError.badRequest) } } dataStream.onCompleted { observer.sendCompleted() } dataStream.onFailed { error in observer.sendFailed(error) } dataStream.start() return ActionDisposable { dataStream.stop() } } } public func serialize(responses: Signal<Response>) -> Signal<Data> { return responses.map { $0.serialized } } func clients(host: String, port: POSIX.Port) -> Source<Socket> { return Source { [reuseAddress, reusePort] observer in let tcpServer = try! TCP.Server(reuseAddress: reuseAddress, reusePort: reusePort) try! tcpServer.bind(host: host, port: port) let listen = tcpServer.listen() listen.onNext { socket in observer.sendNext(socket) } listen.onFailed { error in observer.sendFailed(error) } listen.start() return ActionDisposable { listen.stop() } } } public func listen(host: String, port: POSIX.Port) { let clients = self.clients(host: host, port: port) var connectedClients: [Socket] = [] clients.onNext { socket in connectedClients.append(socket) let requestStream = self.parse(data: socket.read()) let responses = self.delegate.handle(requests: requestStream.signal) let data = self.serialize(responses: responses) _ = socket.write(stream: data) requestStream.start() } disposable = ActionDisposable { clients.stop() for socket in connectedClients { socket.close() } } clients.start() } }
mit
f9938be60d9e532a1a12aa5e443f3d13
25.87931
103
0.552598
4.887147
false
false
false
false
MarekR22/xsd2cocoa
demos/weblinks-demo/weblinks-ios/ViewController.swift
3
610
// // ViewController.swift // addressTest_ios // // Created by Dominik Pich on 10/01/15. // Copyright (c) 2015 Dominik Pich. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let url = NSBundle.mainBundle().URLForResource("weblinks", withExtension: "xml") if(url != nil) { let addr = WLFG.FGFromURL(url!) if(addr != nil) { textView.text = addr!.dictionary.description } } } }
apache-2.0
cb85c2d95006d3f893d3b90d530e77bb
20.785714
88
0.590164
4.178082
false
false
false
false
rtoal/polyglot
swift/external_names.swift
2
353
func perimeter(base: Int, height: Int) -> Int { return 2 * (base + height) } func average(of x: Int, and y: Int) -> Double { return Double(x + y) / 2.0 } func middle(_ x: Int, _ y: Int) -> Double { return Double(x + y) / 2.0 } assert(perimeter(base: 4, height: 20) == 48) assert(average(of: 5, and: 8) == 6.5) assert(middle(5, 8) == 6.5)
mit
27e78345a2a7ebb3d5a067d0ce941337
22.533333
47
0.575071
2.557971
false
false
false
false
WilliamIzzo83/journal
journal/code/controllers/InsertTextEntryViewController.swift
1
3353
// // InsertTextEntryViewController.swift // journal // // Created by William Izzo on 12/01/2017. // Copyright © 2017 wizzo. All rights reserved. // import UIKit import Foundation @objc protocol InsertTextEntryViewControllerDelegate { @objc func dayToEdit(controller:InsertTextEntryViewController) -> DayDB? @objc optional func editingPosition(controller:InsertTextEntryViewController) -> Int @objc optional func didPressCancel(controller:InsertTextEntryViewController); @objc optional func didPressSave(controller:InsertTextEntryViewController, text:String); } /** * The controller lets user edit or create a new day entry. */ class InsertTextEntryViewController: UIViewController { var textEntryTextView: UITextView! weak open var delegate : InsertTextEntryViewControllerDelegate? var notifHandle : NSObjectProtocol! var editing_day_ = DayDB() var text_storage_ = DianeDayPagesTextStorage() deinit { NotificationCenter.default.removeObserver(notifHandle) } override func viewDidLoad() { super.viewDidLoad() let text_layout = NSLayoutManager() let text_container = NSTextContainer() text_storage_.addLayoutManager(text_layout) text_layout.addTextContainer(text_container) textEntryTextView = UITextView(frame: CGRect.zero, textContainer: text_container) textEntryTextView.textContainerInset = UIEdgeInsetsMake(16, 16, 16, 16) self.view.addSubview(textEntryTextView) guard let the_delegate = delegate else { return } let initial_string : String! if let day_to_edit = the_delegate.dayToEdit(controller: self) { editing_day_ = day_to_edit initial_string = editing_day_.text.text }else { initial_string = "" } text_storage_.append(NSAttributedString(string: initial_string)) } override func viewWillLayoutSubviews() { textEntryTextView.frame = self.view.bounds textEntryTextView.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body) } override func viewWillAppear(_ animated: Bool) { notifHandle = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillShow, object: nil, queue: nil) { (note) in if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { self.textEntryTextView.contentInset.bottom = keyboardSize.height } } textEntryTextView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { textEntryTextView.resignFirstResponder() NotificationCenter.default.removeObserver(notifHandle) } @IBAction func doneButtonAction(_ sender: Any) { guard let the_delegate = delegate else { return } the_delegate.didPressSave?(controller: self, text: textEntryTextView.text) } @IBAction func cancelButtonAction(_ sender: Any) { delegate?.didPressCancel?(controller: self) } }
bsd-3-clause
a1ef43957eb1dd5f58437df0273cc11c
30.92381
136
0.642601
5.329094
false
false
false
false
TempoDiValse/DCHelper
DCHelper/SafariExtensionViewController.swift
1
4290
// // SafariExtensionViewController.swift // DCHelper // // Created by LaValse on 2016. 11. 1.. // Copyright © 2016년 LaValse. All rights reserved. // import SafariServices class SafariExtensionViewController: SFSafariExtensionViewController, NSComboBoxDelegate, NSComboBoxDataSource{ static let shared = SafariExtensionViewController() let defaults = UserDefaults.standard @IBOutlet var btnList: NSButton! @IBOutlet var btnBTitle: NSButton! @IBOutlet var btnOpen: NSButton! @IBOutlet var checkAuto: NSButton! @IBOutlet var btnDownload: NSButton! @IBOutlet var selectRecentVisited: NSComboBox! @IBOutlet var bgLabel1: NSVisualEffectView! var vList = [[String:String]]() override func viewDidLoad() { super.viewDidLoad() let _view = self.view as! NSVisualEffectView _view.blendingMode = .behindWindow _view.material = .ultraDark bgLabel1.layer?.backgroundColor = CGColor(red: 174.0/255.0, green: 118.0/255.0, blue: 232.0/255.0, alpha: 1.0) bgLabel1.blendingMode = .withinWindow bgLabel1.material = .dark selectRecentVisited.delegate = self selectRecentVisited.dataSource = self } override func viewDidAppear() { super.viewDidAppear() let autoState = defaults.bool(forKey: Const.USER_IMG_ADD_AUTO) ? 1 : 0 checkAuto.state = autoState vList = defaults.array(forKey: Const.USER_RECENT_VISITED) as! [[String : String]] selectRecentVisited.reloadData() selectRecentVisited.selectItem(at: 0) } @IBAction func openBlockTitle(_ sender: Any) { self.presentViewController(TitleBlockController(), asPopoverRelativeTo: NSRect(), of: self.view, preferredEdge: NSRectEdge.maxX, behavior: .transient) } @IBAction func openBlocker(_ sender: Any) { self.presentViewController(BlockerController(), asPopoverRelativeTo: NSRect(x: 0, y: 100, width: 0, height: 0), of: self.view, preferredEdge: NSRectEdge.maxX, behavior: .transient) } @IBAction func openFileDialog(_ sender: Any) { self.presentViewController(OptionController(), asPopoverRelativeTo: NSRect(x: 0, y: 100, width: 0, height: 0), of: self.view, preferredEdge: NSRectEdge.maxX, behavior: .transient) } @IBAction func isAutoMode(_ sender: Any) { let btn = sender as! NSButton print(btn.state == 1) defaults.set(btn.state == 1, forKey: Const.USER_IMG_ADD_AUTO) } @IBAction func downloadAll(_ sender: Any) { SFSafariApplication.getActiveWindow(completionHandler: { $0?.getActiveTab(completionHandler: { $0?.getActivePage(completionHandler: { let page = $0 $0?.getPropertiesWithCompletionHandler({ (props) in let url = props?.url?.absoluteString guard url != nil else { return } guard (url?.hasPrefix(Const.Page.DOMAIN_PREFIX))! else { return } if (url?.contains(Const.Page.View))! { page?.dispatchMessageToScript(withName: "fromExtension", userInfo: ["type" : Const.MessageType.Download]) } }) }) }) }) } func comboBoxSelectionDidChange(_ notification: Notification) { let _i = selectRecentVisited.indexOfSelectedItem guard _i != 0 else { return } let _u = URL(string:"\(Const.Page.DOMAIN_PREFIX)\(vList[_i]["id"]!)") SFSafariApplication.getActiveWindow(completionHandler: { $0?.openTab(with: _u!, makeActiveIfPossible: true, completionHandler: { $0?.activate(completionHandler: { print("new tab opened") }) }) }) } func numberOfItems(in comboBox: NSComboBox) -> Int { return vList.count } func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? { return vList[index]["name"] } }
mit
07aaf7bdeb2382bcbf4e834de52b58c5
35.330508
188
0.595055
4.726571
false
false
false
false
xpush/lib-xpush-ios
XpushFramework/ServerTrustPolicy.swift
32
13236
// ServerTrustPolicy.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. :param: policies A dictionary of all policies mapped to a particular host. :returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. By default, this method will return the policy that perfectly matches the given host. Subclasses could override this method and implement more complex mapping implementations such as wildcards. - parameter host: The host to use when searching for a matching policy. - returns: The server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. Applications are encouraged to always validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. By validating both the certificate chain and host, certificate pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. By validating both the certificate chain and host, public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. :param: bundle The bundle to search for all `.cer` files. :returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] for path in bundle.pathsForResourcesOfType(".cer", inDirectory: nil) as! [String] { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData)?.takeRetainedValue() { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. :param: bundle The bundle to search for all `*.cer` files. :returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle: bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. :param: serverTrust The server trust to evaluate. :param: host The host of the challenge protection space. :returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509() SecTrustSetPolicies(serverTrust, [policy.takeRetainedValue()]) serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509() SecTrustSetPolicies(serverTrust, [policy.takeRetainedValue()]) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, 1) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509() SecTrustSetPolicies(serverTrust, [policy.takeRetainedValue()]) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { let serverKeys = ServerTrustPolicy.publicKeysForTrust(serverTrust) outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType(kSecTrustResultInvalid) let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType(kSecTrustResultUnspecified) let proceed = SecTrustResultType(kSecTrustResultProceed) isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { let certificate = SecTrustGetCertificateAtIndex(trust, index).takeUnretainedValue() certificates.append(certificate) } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0).takeRetainedValue() as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { let certificate = SecTrustGetCertificateAtIndex(trust, index).takeUnretainedValue() if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509().takeRetainedValue() var unmanagedTrust: Unmanaged<SecTrust>? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &unmanagedTrust) if let trust = unmanagedTrust?.takeRetainedValue() where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust).takeRetainedValue() } return publicKey } }
mit
8f897a737c73cda0b597f29cd22dea99
43.558923
121
0.670999
6.138219
false
false
false
false
chengxianghe/MissGe
MissGe/MissGe/Class/Project/UI/Controller/Mine/MLUserController.swift
1
13648
// // MLUserController.swift // MissLi // // Created by chengxianghe on 16/7/23. // Copyright © 2016年 cn. All rights reserved. // import UIKit import MJRefresh import YYText import XHPhotoBrowser import ObjectMapper class MLUserController: UITableViewController { @IBOutlet weak var bestAnswerLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var followButton: UIButton! @IBOutlet weak var followNumButton: UIButton! @IBOutlet weak var fansNumButton: UIButton! @IBOutlet weak var headerView: UIView! @IBOutlet weak var userEditButton: UIButton! var uid = "" fileprivate var dataSource = [MLTopicCellLayout]() fileprivate let infoRequest = MLUserInfoRequest() fileprivate let followRequest = MLUserFollowRequest() fileprivate let topicListRequest = MLUserTopicListRequest() fileprivate var currentIndex = 0 fileprivate var isNeedEdit = false override func viewDidLoad() { super.viewDidLoad() if uid == MLNetConfig.shareInstance.userId { self.userEditButton.isHidden = false self.followButton.isHidden = true } else { self.userEditButton.isHidden = true self.followButton.isHidden = false } self.configRefresh() } //MARK: - 刷新 func configRefresh() { self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[unowned self] () -> Void in if self.tableView.mj_footer.isRefreshing { return } self.loadData(1) }) self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[unowned self] () -> Void in if self.tableView.mj_header.isRefreshing { return } self.loadData(self.currentIndex + 1) }) (self.tableView.mj_footer as! MJRefreshAutoNormalFooter).huaBanFooterConfig() (self.tableView.mj_header as! MJRefreshNormalHeader).huaBanHeaderConfig() self.tableView.mj_header.beginRefreshing() } //MARK: - 数据请求 func loadData(_ page: Int){ self.showLoading("正在加载...") if page == 1 { infoRequest.uid = self.uid infoRequest.send(success: {[unowned self] (baseRequest, responseObject) in self.tableView.mj_header.endRefreshing() let user = MLUserModel(JSON: (((responseObject as! [String:Any])["content"])as! [String:Any])["userinfo"] as! [String:Any])! // let user = MLUserModel(JSON: ((responseObject as! NSDictionary)["content"] as! NSDictionary)["userinfo"]!) as MLUserModel print(user) self.bestAnswerLabel.text = "最佳答案\(user.p_bests)个" self.nameLabel.text = user.nickname self.followNumButton.setTitle("关注\(user.follow_cnt)", for: UIControlState()) self.fansNumButton.setTitle("粉丝\(user.fans_cnt)", for: UIControlState()) self.descLabel.text = "简介: \(user.autograph ?? "")" self.followButton.isSelected = user.relation != 0 self.iconImageView.yy_setImage(with: user.avatar, placeholder: nil) self.tableView.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 240 + self.descLabel.text!.height(UIFont.systemFont(ofSize: 17.0), maxWidth: kScreenWidth - 20)) if user.uid == MLNetConfig.shareInstance.userId { MLNetConfig.updateUser(user) } }) { (baseRequest, error) in print(error) } } topicListRequest.page = page topicListRequest.uid = self.uid topicListRequest.send(success: {[unowned self] (baseRequest, responseObject) in self.hideHud() self.tableView.mj_header.endRefreshing() guard let artlist = (((responseObject as? NSDictionary)?["content"] as? NSDictionary)?["artlist"]) as? [[String:Any]] else { return } let tempArr = artlist.map({ MLSquareModel(JSON: $0) }) guard let modelArray = tempArr as? [MLSquareModel] else { return } let array = modelArray.map({ (model) -> MLTopicCellLayout in return MLTopicCellLayout(model: model) }) if array.count > 0 { if page == 1 { self.dataSource.removeAll() self.dataSource.append(contentsOf: array ) self.tableView.reloadData() } else { self.tableView.beginUpdates() let lastItem = self.dataSource.count self.dataSource.append(contentsOf: array) let indexPaths = (lastItem..<self.dataSource.count).map { IndexPath(row: $0, section: 0) } self.tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.fade) self.tableView.endUpdates() } if array.count < 20 { self.tableView.mj_footer.endRefreshingWithNoMoreData() } else { self.currentIndex = page self.tableView.mj_footer.endRefreshing() } } else { if page == 1 { self.dataSource.removeAll() self.tableView.reloadData() } self.tableView.mj_footer.endRefreshingWithNoMoreData() } }) { (baseRequest, error) in self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() print(error) } } // MARK: - Action @IBAction func onFollowBtnClick(_ sender: UIButton) { if !MLNetConfig.isUserLogin() { let goLogin = UIAlertAction.init(title: "去登录", style: UIAlertActionStyle.default, handler: {[weak self] (action) in let loginVCNav = kLoadVCFromSB(nil, stroyBoard: "Account")! self?.present(loginVCNav, animated: true, completion: nil) }) let cancel = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) self.showAlert("您还未登录", message: nil, actions: [cancel, goLogin]) return } if !sender.isSelected { // 去关注 MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in self.showSuccess("关注成功") sender.isSelected = true }, failed: { (base, err) in self.showError("网络错误") print(err) }) } else { // 取消关注 MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in self.showSuccess("已取消关注") sender.isSelected = false }, failed: { (base, err) in self.showError("网络错误") print(err) }) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "MLTopicCell") as? MLTopicCell if cell == nil { cell = MLTopicCell(style: .default, reuseIdentifier: "MLTopicCell") cell?.delegate = self } cell!.setInfo(self.dataSource[(indexPath as NSIndexPath).row]); return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model = self.dataSource[(indexPath as NSIndexPath).row] return MLTopicCell.height(model) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "闺蜜圈" } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "UserToTopicDetail" { let vc = segue.destination as! MLTopicDetailController vc.topic = sender as! MLTopicCellLayout } else if segue.identifier == "UserToUserModify" { let vc = segue.destination as! MLUserController vc.uid = (sender as! MLTopicCellLayout).joke.uid } else if segue.identifier == "UserToEdit" { // let vc = segue.destinationViewController as! MLUserEditController // vc.uid = (sender as! MLTopicCellLayout).joke.uid } else if segue.identifier == "UserToFans" { let vc = segue.destination as! MLUserFansController vc.uid = self.uid vc.isFans = true } else if segue.identifier == "UserToFollowers" { let vc = segue.destination as! MLUserFansController vc.uid = self.uid vc.isFans = false } } } extension MLUserController: MLSquareCellDelegate { func topicCellDidClickOther(_ cell: MLTopicCell) { if MLNetConfig.isUserLogin() && MLNetConfig.shareInstance.userId == cell.layout.joke.uid { // 删除 MLRequestHelper.deleteTopicWith(cell.layout.joke.pid, succeed: {[weak self] (base, res) in guard let _self = self else { return } _self.showSuccess("已删除") let index = _self.dataSource.index(of: cell.layout)! _self.dataSource.remove(at: index) _self.tableView.deleteRows(at: [IndexPath.init(row: index, section: 0)], with: .automatic) }, failed: {[weak self] (base, error) in guard let _self = self else { return } _self.showError("删除失败\n\(error.localizedDescription)") }) } else { // 举报 self.showSuccess("已举报") } } /// 点击了评论 func topicCellDidClickComment(_ cell: MLTopicCell) { self.performSegue(withIdentifier: "UserToTopicDetail", sender: cell.layout) } /// 点击了图片 func topicCell(_ cell: MLTopicCell, didClickImageAtIndex index: UInt) { print("点击了图片") var items = [XHPhotoItem]() let status = cell.layout.joke; guard let thumb = status?.thumb else { return } for i in 0..<thumb.count { let imgView = cell.statusView.picViews![i]; let pic = thumb[i]; let item = XHPhotoItem() item.thumbView = imgView; item.largeImageURL = URL(string: pic); // item.largeImageSize = CGSizeMake(layout.iconWidth, layout.iconHeight); items.append(item) } let v = XHPhotoBrowser.init(groupItems: items) v.fromItemIndex = Int(index) v.toolBarShowStyle = .show v.showCloseButton = false v.show(inContaioner: self.tabBarController!.view, animated: true, completion: nil) } /// 点击了 Label 的链接 func topicCell(_ cell: MLTopicCell, didClickInLabel label: YYLabel!, textRange: NSRange) { let text = label.textLayout!.text; if (textRange.location >= text.length) {return}; let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(textRange.location)) as! YYTextHighlight let info = highlight.userInfo; if (info?.count == 0) {return}; if (info?[kSquareLinkAtName] != nil) { let name = info![kSquareLinkAtName] as! String print("kJokeLinkAtName: \(name)"); // name = [name stringByURLEncode]; // if (name.length) { // NSString *url = [NSString stringWithFormat:@"http://m.weibo.cn/n/%@",name]; // YYSimpleWebViewController *vc = [[YYSimpleWebViewController alloc] initWithURL:[NSURL URLWithString:url]]; // [self.navigationController pushViewController:vc animated:YES]; // } return; } } }
mit
b88215a1c157a61a39e2a89431a4ea78
37.56447
200
0.57025
4.883527
false
false
false
false
DAloG/BlueCap
BlueCap/AppDelegate.swift
1
2512
// // AppDelegate.swift // BlueCap // // Created by Troy Stribling on 6/6/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit struct BlueCapNotification { static let peripheralDisconnected = "PeripheralDisconnected" static let didUpdateBeacon = "DidUpdateBeacon" static let didBecomeActive = "DidBecomeActive" static let didResignActive = "DidResignActive" } enum AppError : Int { case rangingBeacons = 0 case outOfRegion = 1 } struct BCAppError { static let domain = "BlueCapApp" static let rangingBeacons = NSError(domain:domain, code:AppError.rangingBeacons.rawValue, userInfo:[NSLocalizedDescriptionKey:"Ranging beacons"]) static let outOfRegion = NSError(domain:domain, code:AppError.outOfRegion.rawValue, userInfo:[NSLocalizedDescriptionKey:"Out of region"]) } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { TISensorTagServiceProfiles.create() BLESIGGATTProfiles.create() GnosusProfiles.create() NordicProfiles.create() application.registerUserNotificationSettings( UIUserNotificationSettings(forTypes:[UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories:nil)) return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { NSUserDefaults.standardUserDefaults().synchronize() NSNotificationCenter.defaultCenter().postNotificationName(BlueCapNotification.didResignActive, object:nil) let central = CentralManager.sharedInstance if central.isScanning { central.stopScanning() central.disconnectAllPeripherals() central.removeAllPeripherals() } } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { Notify.resetEventCount() NSNotificationCenter.defaultCenter().postNotificationName(BlueCapNotification.didBecomeActive, object:nil) } func applicationWillTerminate(application: UIApplication) { NSUserDefaults.standardUserDefaults().synchronize() } }
mit
17926b605e78a58652da511ea9c0ccc4
32.945946
156
0.723726
5.73516
false
false
false
false
nicolastinkl/swift
AdventureBuildingaSpriteKitgameusingSwift/Adventure/AppDelegate.swift
1
1648
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Application delegate for OS X Adventure */ import SpriteKit class AppDelegate: NSObject, NSApplicationDelegate { var scene: AdventureScene! func applicationDidFinishLaunching(aNotification: NSNotification) { loadingProgressIndicator.startAnimation(self) AdventureScene.loadSceneAssetsWithCompletionHandler { self.scene = AdventureScene(size: CGSize(width: 1024, height: 768)) self.scene.scaleMode = SKSceneScaleMode.AspectFit self.skView.presentScene(self.scene) self.loadingProgressIndicator.stopAnimation(self) self.loadingProgressIndicator.hidden = true self.archerButton.alphaValue = 1.0 self.warriorButton.alphaValue = 1.0 } skView.showsFPS = true skView.showsNodeCount = true skView.showsDrawCount = true } @IBAction func chooseArcher(sender: AnyObject) { scene.startLevel(.Archer) gameLogo.hidden = true archerButton.alphaValue = 0.0 warriorButton.alphaValue = 0.0 } @IBAction func chooseWarrior(sender: AnyObject) { scene.startLevel(.Warrior) gameLogo.hidden = true archerButton.alphaValue = 0.0 warriorButton.alphaValue = 0.0 } @IBOutlet var skView: SKView @IBOutlet var loadingProgressIndicator: NSProgressIndicator @IBOutlet var gameLogo: NSImageView @IBOutlet var archerButton : NSButton @IBOutlet var warriorButton : NSButton }
mit
dd2cc97832806cff48028ef5f42776c7
26.898305
79
0.67983
4.942943
false
false
false
false
dbahat/conventions-ios
Conventions/Conventions/feedback/FeedbackQuestionCell.swift
1
1271
// // FeedbackQuestionCell.swift // Conventions // // Created by David Bahat on 7/2/16. // Copyright © 2016 Amai. All rights reserved. // import Foundation protocol FeedbackQuestionProtocol : class { func questionWasAnswered(_ answer: FeedbackAnswer) func questionCleared(_ question: FeedbackQuestion) func questionViewHeightChanged(caller: UITableViewCell, newHeight: CGFloat) } /* abstract */ class FeedbackQuestionCell : UITableViewCell { var question: FeedbackQuestion? { didSet { if let feedbackQuestion = question { questionDidSet(feedbackQuestion) } } } weak var delegate: FeedbackQuestionProtocol? // Since the question cell can change based on it's content, keep the delta from default here var cellHeightDelta = CGFloat(0) // Allow disabling the interactions inside the question cell var enabled = true var feedbackTextColor = Colors.textColor var feedbackAnswerColor = Colors.feedbackButtonColorConvetion var feedbackAnswerPressedColor = Colors.feedbackButtonPressedColor /* abstract */ func questionDidSet(_ question: FeedbackQuestion) {} /* abstract */ func setAnswer(_ answer: FeedbackAnswer) {} }
apache-2.0
fe04a7581f41a9a5543e864cbe332476
29.238095
97
0.69685
4.903475
false
false
false
false
mixpanel/mixpanel-swift
MixpanelDemo/MixpanelDemo/ActionCompleteViewController.swift
1
1111
// // ActionCompleteViewController.swift // MixpanelDemo // // Created by Yarden Eitan on 7/18/16. // Copyright © 2016 Mixpanel. All rights reserved. // import UIKit class ActionCompleteViewController: UIViewController { @IBOutlet weak var popupView: UIView! @IBOutlet weak var actionLabel: UILabel! @IBOutlet weak var descLabel: UILabel! var actionStr: String? var descStr: String? override func viewDidLoad() { super.viewDidLoad() popupView.clipsToBounds = true popupView.layer.cornerRadius = 6 let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) view.addGestureRecognizer(tap) actionLabel.text = actionStr descLabel.text = descStr } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.asyncAfter(deadline: .now() + 5) { self.dismiss(animated: true, completion: nil) } } @objc func handleTap(gesture: UITapGestureRecognizer) { dismiss(animated: true, completion: nil) } }
apache-2.0
0bd66404aa29486d919f839592523082
24.813953
84
0.664865
4.605809
false
false
false
false
Workpop/meteor-ios
Examples/Todos/Todos/SignInViewController.swift
1
2534
// Copyright (c) 2014-2015 Martijn Walraven // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreData import Meteor class SignInViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var errorMessageLabel: UILabel! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! // MARK: View Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) errorMessageLabel.text = nil } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) emailField.becomeFirstResponder() } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == emailField { passwordField.becomeFirstResponder() } else if textField == passwordField { passwordField.resignFirstResponder() signIn() } return false } // MARK: IBActions @IBAction func signIn() { errorMessageLabel.text = nil let email = emailField.text let password = passwordField.text if email.isEmpty || password.isEmpty { errorMessageLabel.text = "Email and password are required" return } Meteor.loginWithEmail(email, password: password) { (error) -> Void in if error != nil { self.errorMessageLabel.text = error.localizedFailureReason } else { self.performSegueWithIdentifier("Unwind", sender: self) } } } }
mit
2d3ea887c5a52fbef8284097a19e23aa
31.909091
80
0.720205
4.978389
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/BasicRenderer.swift
1
2832
import Foundation import GLKit import Metal private let kInFlightCommandBuffers = 3 class BasicRenderer: Renderer { private var modelMatrixStack = [GLKMatrix4](repeating: GLKMatrix4Identity, count: 1) func pushModelMatrix(_ mtrx: GLKMatrix4) { modelMatrixStack.append(mtrx) } func popModelMatrix() -> GLKMatrix4 { return modelMatrixStack.popLast()! } var modelMatrix: GLKMatrix4 { get { return modelMatrixStack[modelMatrixStack.endIndex] } set (value) { modelMatrixStack[modelMatrixStack.endIndex] = value } } var viewMatrix = GLKMatrix4Identity var projectionMatrix = GLKMatrix4Identity var textureResources = [String:MTLTexture]() var commandBuffer: MTLCommandBuffer? var renderCommandEncoderStack: [MTLRenderCommandEncoder] = [] var renderCommandEncoder: MTLRenderCommandEncoder? { return renderCommandEncoderStack.last } private var device: MTLDevice? private var commandQueue: MTLCommandQueue? private var shaderLibrary: MTLLibrary? private let inflightSemaphore: DispatchSemaphore private var mnOrientation = UIInterfaceOrientation.unknown private var onEndHandler: ((Renderer) -> Void)? init() { inflightSemaphore = DispatchSemaphore(value: kInFlightCommandBuffers) } func configure(_ device: MTLDevice) { guard let defaultLibrary = device.makeDefaultLibrary() else { fatalError("failed to create a default library") } shaderLibrary = defaultLibrary self.device = device commandQueue = device.makeCommandQueue() viewMatrix = GLKMatrix4MakeLookAt(0, 10, 20, 0, 10, 0, 0, 1, 0) projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(85.0), 1.0, 0.01, 100.0) } func begin() { _ = inflightSemaphore.wait(timeout: DispatchTime.distantFuture) commandBuffer = commandQueue!.makeCommandBuffer() commandBuffer!.addCompletedHandler { (commandBuffer) -> Void in self.inflightSemaphore.signal() } } func end() { if let onEndHandler = onEndHandler { onEndHandler(self) } commandBuffer = nil } func reshape(_ bounds: CGRect) { let orientation = UIApplication.shared.statusBarOrientation if mnOrientation != orientation { mnOrientation = orientation let aspect = Float(bounds.size.width / bounds.size.height) projectionMatrix = GLKMatrix4MakePerspective( GLKMathDegreesToRadians(85.0), aspect, 0.01, 100.0) } } func setEndHandler(_ handler: @escaping (Renderer) -> Void) { self.onEndHandler = handler } }
mit
7c0d2cc90e636d7b47ca3d722357c6bf
28.195876
101
0.652189
5.102703
false
false
false
false
areschoug/animator-swift
AnimatorObject.swift
1
3919
// // AnimatorObject.swift // // Created by areschoug on 23/11/14. // import Foundation class AnimatorObject:Equatable { var randomId:UInt32 var progress:Float var duration:Float var delay:Float var interpolator:AnimatorInterpolator var updateBlock:((progress:Float) -> Void) var completeBlock:((completed:Bool) -> Void) var started:Bool = false var completed:Bool = false var paused:Bool = false var loop:Bool = false var autoReverse:Bool = false private var reverse:Bool = false var afterAnimations:[AnimatorObject] = [AnimatorObject]() init(duration:Float = 0.0, delay:Float = 0.0, interpolator:AnimatorInterpolator = AnimatorInterpolator(), updateBlock:((progress:Float) -> Void) = {value in }, completionBlock:((completed:Bool) -> Void) = {value in }){ self.randomId = arc4random() self.progress = 0 self.delay = delay self.duration = duration self.interpolator = interpolator self.updateBlock = updateBlock self.completeBlock = completionBlock } func addProgress(add:Float){ if paused { return } if reverse { self.progress -= add } else { self.progress += add } let progress = self.progress - delay if progress >= self.duration { if autoReverse { if progress > duration { reverse = true } } else { self.updateBlock(progress: 1.0) if self.loop { self.reverse = false self.progress = 0 } else { self.completed = true self.completeBlock(completed: self.completed) self.completeBlock = { x in } for object in afterAnimations { object.start() } } } } else if progress > 0 { self.updateBlock(progress: self.interpolator.valueForProgress(progress/self.duration)) } else if progress < 0 && self.autoReverse { self.updateBlock(progress: 0.0) if self.loop { self.reverse = false self.progress = 0 } else { self.completed = true self.completeBlock(completed: self.completed) self.completeBlock = { x in } for object in afterAnimations { object.start() } } } } func interpolator(block:((progress:Float) -> Float)) -> AnimatorObject{ self.interpolator = AnimatorInterpolator(block: block) return self } func interpolator(interpolator:AnimatorInterpolator) -> AnimatorObject{ self.interpolator = interpolator return self } func delay(delay:Float) -> AnimatorObject { self.delay = delay return self } func duration(duration:Float) -> AnimatorObject { self.duration = duration return self } func completionBlock(block:((completed:Bool) -> Void)) -> AnimatorObject { return self.completion(block) } func completion(block:((completed:Bool) -> Void)) -> AnimatorObject { self.completeBlock = block return self } func updateBlock(block:((progress:Float) -> Void)) -> AnimatorObject { return self.update(block) } func update(block:((progress:Float) -> Void)) -> AnimatorObject { self.updateBlock = block return self } func appendAnimationAfter(object:AnimatorObject) -> AnimatorObject { if !completed { afterAnimations.append(object) } return self } func start(){ if started { self.paused = false} else { Animator.addAnimatorObject(self) } } func stop(){ Animator.removeAnimatorObject(self) } func pause(){ self.paused = true } } func ==(first: AnimatorObject, second: AnimatorObject) -> Bool{ return first.randomId == second.randomId }
mit
71290f38cb80d0ed0d14fe9677e26328
22.327381
98
0.599388
4.264418
false
false
false
false
bfolder/Sweather
Sweather/Sweather.swift
1
6161
// // Sweather.swift // // Created by Heiko Dreyer on 08/12/14. // Copyright (c) 2014 boxedfolder.com. All rights reserved. // import Foundation import CoreLocation extension String { func replace(_ string:String, replacement:String) -> String { return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil) } func replaceWhitespace() -> String { return self.replace(" ", replacement: "+") } } open class Sweather { public enum TemperatureFormat: String { case Celsius = "metric" case Fahrenheit = "imperial" } public enum Result { case success(URLResponse?, NSDictionary?) case Error(URLResponse?, NSError?) public func data() -> NSDictionary? { switch self { case .success(_, let dictionary): return dictionary case .Error(_, _): return nil } } public func response() -> URLResponse? { switch self { case .success(let response, _): return response case .Error(let response, _): return response } } public func error() -> NSError? { switch self { case .success(_, _): return nil case .Error(_, let error): return error } } } open var apiKey: String open var apiVersion: String open var language: String open var temperatureFormat: TemperatureFormat fileprivate struct Const { static let basePath = "http://api.openweathermap.org/data/" } // MARK: - // MARK: Initialization public convenience init(apiKey: String) { self.init(apiKey: apiKey, language: "en", temperatureFormat: .Fahrenheit, apiVersion: "2.5") } public convenience init(apiKey: String, temperatureFormat: TemperatureFormat) { self.init(apiKey: apiKey, language: "en", temperatureFormat: temperatureFormat, apiVersion: "2.5") } public convenience init(apiKey: String, language: String, temperatureFormat: TemperatureFormat) { self.init(apiKey: apiKey, language: language, temperatureFormat: temperatureFormat, apiVersion: "2.5") } public init(apiKey: String, language: String, temperatureFormat: TemperatureFormat, apiVersion: String) { self.apiKey = apiKey self.temperatureFormat = temperatureFormat self.apiVersion = apiVersion self.language = language } // MARK: - // MARK: Retrieving current weather data open func currentWeather(_ cityName: String, callback: @escaping (Result) -> ()) { call("/weather?q=\(cityName.replaceWhitespace())", callback: callback) } open func currentWeather(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { let coordinateString = "lat=\(coordinate.latitude)&lon=\(coordinate.longitude)" call("/weather?\(coordinateString)", callback: callback) } open func currentWeather(_ cityId: Int, callback: @escaping (Result) -> ()) { call("/weather?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving daily forecast open func dailyForecast(_ cityName: String, callback: @escaping (Result) -> ()) { call("/forecast/daily?q=\(cityName.replaceWhitespace())", callback: callback) } open func dailyForecast(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { call("/forecast/daily?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } open func dailyForecast(_ cityId: Int, callback: @escaping (Result) -> ()) { call("/forecast/daily?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving forecast open func forecast(_ cityName: String, callback: @escaping (Result) -> ()) { call("/forecast?q=\(cityName.replaceWhitespace())", callback: callback) } open func forecast(_ coordinate: CLLocationCoordinate2D, callback:@escaping (Result) -> ()) { call("/forecast?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } open func forecast(_ cityId: Int, callback: @escaping (Result) ->()) { call("/forecast?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving city open func findCity(_ cityName: String, callback: @escaping (Result) -> ()) { call("/find?q=\(cityName.replaceWhitespace())", callback: callback) } open func findCity(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { call("/find?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } // MARK: - // MARK: Call the api fileprivate func call(_ method: String, callback: @escaping (Result) -> ()) { let url = Const.basePath + apiVersion + method + "&APPID=\(apiKey)&lang=\(language)&units=\(temperatureFormat.rawValue)" let request = URLRequest(url: URL(string: url)!) let currentQueue = OperationQueue.current let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in var error: NSError? = error as NSError? var dictionary: NSDictionary? if let data = data { do { dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary } catch let e as NSError { error = e } } currentQueue?.addOperation { var result = Result.success(response, dictionary) if error != nil { result = Result.Error(response, error) } callback(result) } }) task.resume() } }
mit
d7517f03c9afcb6a7cae5d8d8eef9333
33.227778
128
0.585295
4.9288
false
false
false
false
klaus01/Centipede
Centipede/UIKit/CE_UIScrollView.swift
1
8729
// // CE_UIScrollView.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import UIKit extension UIScrollView { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: UIScrollView_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIScrollView_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: UIScrollView_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is UIScrollView_Delegate { return obj as! UIScrollView_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal func getDelegateInstance() -> UIScrollView_Delegate { return UIScrollView_Delegate() } @discardableResult public func ce_scrollViewDidScroll(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewDidScroll = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidZoom(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewDidZoom = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewWillBeginDragging(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewWillBeginDragging = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewWillEndDragging_withVelocity(handle: @escaping (UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>) -> Void) -> Self { ce._scrollViewWillEndDragging_withVelocity = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidEndDragging_willDecelerate(handle: @escaping (UIScrollView, Bool) -> Void) -> Self { ce._scrollViewDidEndDragging_willDecelerate = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewWillBeginDecelerating(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewWillBeginDecelerating = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidEndDecelerating(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewDidEndDecelerating = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidEndScrollingAnimation(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewDidEndScrollingAnimation = handle rebindingDelegate() return self } @discardableResult public func ce_viewForZooming_in(handle: @escaping (UIScrollView) -> UIView?) -> Self { ce._viewForZooming_in = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewWillBeginZooming_with(handle: @escaping (UIScrollView, UIView?) -> Void) -> Self { ce._scrollViewWillBeginZooming_with = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidEndZooming_with(handle: @escaping (UIScrollView, UIView?, CGFloat) -> Void) -> Self { ce._scrollViewDidEndZooming_with = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewShouldScrollToTop(handle: @escaping (UIScrollView) -> Bool) -> Self { ce._scrollViewShouldScrollToTop = handle rebindingDelegate() return self } @discardableResult public func ce_scrollViewDidScrollToTop(handle: @escaping (UIScrollView) -> Void) -> Self { ce._scrollViewDidScrollToTop = handle rebindingDelegate() return self } } internal class UIScrollView_Delegate: NSObject, UIScrollViewDelegate { var _scrollViewDidScroll: ((UIScrollView) -> Void)? var _scrollViewDidZoom: ((UIScrollView) -> Void)? var _scrollViewWillBeginDragging: ((UIScrollView) -> Void)? var _scrollViewWillEndDragging_withVelocity: ((UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>) -> Void)? var _scrollViewDidEndDragging_willDecelerate: ((UIScrollView, Bool) -> Void)? var _scrollViewWillBeginDecelerating: ((UIScrollView) -> Void)? var _scrollViewDidEndDecelerating: ((UIScrollView) -> Void)? var _scrollViewDidEndScrollingAnimation: ((UIScrollView) -> Void)? var _viewForZooming_in: ((UIScrollView) -> UIView?)? var _scrollViewWillBeginZooming_with: ((UIScrollView, UIView?) -> Void)? var _scrollViewDidEndZooming_with: ((UIScrollView, UIView?, CGFloat) -> Void)? var _scrollViewShouldScrollToTop: ((UIScrollView) -> Bool)? var _scrollViewDidScrollToTop: ((UIScrollView) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(scrollViewDidScroll(_:)) : _scrollViewDidScroll, #selector(scrollViewDidZoom(_:)) : _scrollViewDidZoom, #selector(scrollViewWillBeginDragging(_:)) : _scrollViewWillBeginDragging, #selector(scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)) : _scrollViewWillEndDragging_withVelocity, #selector(scrollViewDidEndDragging(_:willDecelerate:)) : _scrollViewDidEndDragging_willDecelerate, #selector(scrollViewWillBeginDecelerating(_:)) : _scrollViewWillBeginDecelerating, #selector(scrollViewDidEndDecelerating(_:)) : _scrollViewDidEndDecelerating, ] if let f = funcDic1[aSelector] { return f != nil } let funcDic2: [Selector : Any?] = [ #selector(scrollViewDidEndScrollingAnimation(_:)) : _scrollViewDidEndScrollingAnimation, #selector(viewForZooming(in:)) : _viewForZooming_in, #selector(scrollViewWillBeginZooming(_:with:)) : _scrollViewWillBeginZooming_with, #selector(scrollViewDidEndZooming(_:with:atScale:)) : _scrollViewDidEndZooming_with, #selector(scrollViewShouldScrollToTop(_:)) : _scrollViewShouldScrollToTop, #selector(scrollViewDidScrollToTop(_:)) : _scrollViewDidScrollToTop, ] if let f = funcDic2[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func scrollViewDidScroll(_ scrollView: UIScrollView) { _scrollViewDidScroll!(scrollView) } @objc func scrollViewDidZoom(_ scrollView: UIScrollView) { _scrollViewDidZoom!(scrollView) } @objc func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { _scrollViewWillBeginDragging!(scrollView) } @objc func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { _scrollViewWillEndDragging_withVelocity!(scrollView, velocity, targetContentOffset) } @objc func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { _scrollViewDidEndDragging_willDecelerate!(scrollView, decelerate) } @objc func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { _scrollViewWillBeginDecelerating!(scrollView) } @objc func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { _scrollViewDidEndDecelerating!(scrollView) } @objc func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { _scrollViewDidEndScrollingAnimation!(scrollView) } @objc func viewForZooming(in scrollView: UIScrollView) -> UIView? { return _viewForZooming_in!(scrollView) } @objc func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { _scrollViewWillBeginZooming_with!(scrollView, view) } @objc func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { _scrollViewDidEndZooming_with!(scrollView, view, scale) } @objc func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { return _scrollViewShouldScrollToTop!(scrollView) } @objc func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { _scrollViewDidScrollToTop!(scrollView) } }
mit
1ab8df614b6372071cbd8200b61629f6
40.36019
154
0.6795
5.752802
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.CurrentHeatingCoolingState.swift
1
2225
import Foundation public extension AnyCharacteristic { static func currentHeatingCoolingState( _ value: Enums.CurrentHeatingCoolingState = .cool, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Current Heating Cooling State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.currentHeatingCoolingState( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func currentHeatingCoolingState( _ value: Enums.CurrentHeatingCoolingState = .cool, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Current Heating Cooling State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Enums.CurrentHeatingCoolingState> { GenericCharacteristic<Enums.CurrentHeatingCoolingState>( type: .currentHeatingCoolingState, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
fd7e0fdd12b47f2ee4750cef301f9573
35.47541
67
0.60764
5.272512
false
false
false
false
slepcat/mint
MINT/AppDelegate.swift
1
1577
// // AppDelegate.swift // MINT // // Created by NemuNeko on 2014/10/15. // Copyright (c) 2014年 Taizo A. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var leafpanel : MintLeafPanelController! @IBOutlet var modelView: MintModelViewController! @IBOutlet var workspace: MintWorkspaceController! @IBOutlet var controller: MintController! // MINT Controller func applicationDidFinishLaunching(_ notification: Notification) { // Insert code here to initialize your application // prepare MintInterpreter let interpreter = MintInterpreter() interpreter.controller = controller controller.interpreter = interpreter workspace.interpreter = interpreter if let port3d = MintStdPort.get.port as? Mint3DPort { port3d.viewctrl = modelView } //prepare leafpanel leafpanel.updateContents(interpreter.defined_exps()) } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply { let command = AppQuit() controller.sendCommand(command) if command.willQuit { return .terminateNow } else { return .terminateCancel } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
gpl-3.0
c82e0091cab285aedf081802456b2aa9
26.631579
93
0.64127
5.338983
false
false
false
false
TheBudgeteers/CartTrackr
CartTrackr/Carthage/Checkouts/SwiftyCam/Source/SwiftyCamViewController.swift
1
30860
/*Copyright (c) 2016, Andrew Walz. 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. 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 AVFoundation // MARK: View Controller Declaration /// A UIViewController Camera View Subclass open class SwiftyCamViewController: UIViewController { // MARK: Enumeration Declaration /// Enumeration for Camera Selection public enum CameraSelection { /// Camera on the back of the device case rear /// Camera on the front of the device case front } /// Enumeration for video quality of the capture session. Corresponds to a AVCaptureSessionPreset public enum VideoQuality { /// AVCaptureSessionPresetHigh case high /// AVCaptureSessionPresetMedium case medium /// AVCaptureSessionPresetLow case low /// AVCaptureSessionPreset352x288 case resolution352x288 /// AVCaptureSessionPreset640x480 case resolution640x480 /// AVCaptureSessionPreset1280x720 case resolution1280x720 /// AVCaptureSessionPreset1920x1080 case resolution1920x1080 /// AVCaptureSessionPreset3840x2160 case resolution3840x2160 /// AVCaptureSessionPresetiFrame960x540 case iframe960x540 /// AVCaptureSessionPresetiFrame1280x720 case iframe1280x720 } /** Result from the AVCaptureSession Setup - success: success - notAuthorized: User denied access to Camera of Microphone - configurationFailed: Unknown error */ fileprivate enum SessionSetupResult { case success case notAuthorized case configurationFailed } // MARK: Public Variable Declarations /// Public Camera Delegate for the Custom View Controller Subclass public var cameraDelegate: SwiftyCamViewControllerDelegate? /// Maxiumum video duration if SwiftyCamButton is used public var maximumVideoDuration : Double = 0.0 /// Video capture quality public var videoQuality : VideoQuality = .high /// Sets whether flash is enabled for photo and video capture public var flashEnabled = false /// Sets whether Pinch to Zoom is enabled for the capture session public var pinchToZoom = true /// Sets the maximum zoom scale allowed during Pinch gesture public var maxZoomScale = CGFloat(4.0) /// Sets whether Tap to Focus and Tap to Adjust Exposure is enabled for the capture session public var tapToFocus = true /// Sets whether the capture session should adjust to low light conditions automatically /// /// Only supported on iPhone 5 and 5C public var lowLightBoost = true /// Set whether SwiftyCam should allow background audio from other applications public var allowBackgroundAudio = true /// Sets whether a double tap to switch cameras is supported public var doubleTapCameraSwitch = true /// Set default launch camera public var defaultCamera = CameraSelection.rear /// Sets wether the taken photo or video should be oriented according to the device orientation public var shouldUseDeviceOrientation = false // MARK: Public Get-only Variable Declarations /// Returns true if video is currently being recorded private(set) public var isVideoRecording = false /// Returns true if the capture session is currently running private(set) public var isSessionRunning = false /// Returns the CameraSelection corresponding to the currently utilized camera private(set) public var currentCamera = CameraSelection.rear // MARK: Private Constant Declarations /// Current Capture Session fileprivate let session = AVCaptureSession() /// Serial queue used for setting up session fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: []) // MARK: Private Variable Declarations /// Variable for storing current zoom scale fileprivate var zoomScale = CGFloat(1.0) /// Variable for storing initial zoom scale before Pinch to Zoom begins fileprivate var beginZoomScale = CGFloat(1.0) /// Returns true if the torch (flash) is currently enabled fileprivate var isCameraTorchOn = false /// Variable to store result of capture session setup fileprivate var setupResult = SessionSetupResult.success /// BackgroundID variable for video recording fileprivate var backgroundRecordingID : UIBackgroundTaskIdentifier? = nil /// Video Input variable fileprivate var videoDeviceInput : AVCaptureDeviceInput! /// Movie File Output variable fileprivate var movieFileOutput : AVCaptureMovieFileOutput? /// Photo File Output variable fileprivate var photoFileOutput : AVCaptureStillImageOutput? /// Video Device variable fileprivate var videoDevice : AVCaptureDevice? /// PreviewView for the capture session fileprivate var previewLayer : PreviewView! /// UIView for front facing flash fileprivate var flashView : UIView? /// Last changed orientation fileprivate var deviceOrientation : UIDeviceOrientation? /// Disable view autorotation for forced portrait recorindg override open var shouldAutorotate: Bool { return false } // MARK: ViewDidLoad /// ViewDidLoad Implementation override open func viewDidLoad() { super.viewDidLoad() previewLayer = PreviewView(frame: self.view.frame) // Add Gesture Recognizers addGestureRecognizersTo(view: previewLayer) self.view.addSubview(previewLayer) previewLayer.session = session // Test authorization status for Camera and Micophone switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo){ case .authorized: // already authorized break case .notDetermined: // not yet determined sessionQueue.suspend() AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in if !granted { self.setupResult = .notAuthorized } self.sessionQueue.resume() }) default: // already been asked. Denied access setupResult = .notAuthorized } sessionQueue.async { [unowned self] in self.configureSession() } } // MARK: ViewDidAppear /// ViewDidAppear(_ animated:) Implementation override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Subscribe to device rotation notifications if shouldUseDeviceOrientation { subscribeToDeviceOrientationChangeNotifications() } // Set background audio preference setBackgroundAudioPreference() sessionQueue.async { switch self.setupResult { case .success: // Begin Session self.session.startRunning() self.isSessionRunning = self.session.isRunning case .notAuthorized: // Prompt to App Settings self.promptToAppSettings() case .configurationFailed: // Unknown Error DispatchQueue.main.async(execute: { [unowned self] in let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration") let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) }) } } } // MARK: ViewDidDisappear /// ViewDidDisappear(_ animated:) Implementation override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // If session is running, stop the session if self.isSessionRunning == true { self.session.stopRunning() self.isSessionRunning = false } //Disble flash if it is currently enabled disableFlash() // Unsubscribe from device rotation notifications if shouldUseDeviceOrientation { unsubscribeFromDeviceOrientationChangeNotifications() } } // MARK: Public Functions /** Capture photo from current session UIImage will be returned with the SwiftyCamViewControllerDelegate function SwiftyCamDidTakePhoto(photo:) */ public func takePhoto() { guard let device = videoDevice else { return } if device.hasFlash == true && flashEnabled == true /* TODO: Add Support for Retina Flash and add front flash */ { changeFlashSettings(device: device, mode: .on) capturePhotoAsyncronously(completionHandler: { (_) in }) } else if device.hasFlash == false && flashEnabled == true && currentCamera == .front { flashView = UIView(frame: view.frame) flashView?.alpha = 0.0 flashView?.backgroundColor = UIColor.white previewLayer.addSubview(flashView!) UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 1.0 }, completion: { (_) in self.capturePhotoAsyncronously(completionHandler: { (success) in UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 0.0 }, completion: { (_) in self.flashView?.removeFromSuperview() }) }) }) } else { if device.isFlashActive == true { changeFlashSettings(device: device, mode: .off) } capturePhotoAsyncronously(completionHandler: { (_) in }) } } /** Begin recording video of current session SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called */ public func startVideoRecording() { guard let movieFileOutput = self.movieFileOutput else { return } if currentCamera == .rear && flashEnabled == true { enableFlash() } if currentCamera == .front && flashEnabled == true { flashView = UIView(frame: view.frame) flashView?.backgroundColor = UIColor.white flashView?.alpha = 0.85 previewLayer.addSubview(flashView!) } sessionQueue.async { [unowned self] in if !movieFileOutput.isRecording { if UIDevice.current.isMultitaskingSupported { self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) } // Update the orientation on the movie file output video connection before starting recording. let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo) //flip video output if front facing camera is selected if self.currentCamera == .front { movieFileOutputConnection?.isVideoMirrored = true } movieFileOutputConnection?.videoOrientation = self.getVideoOrientation() // Start recording to a temporary file. let outputFileName = UUID().uuidString let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!) movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self) self.isVideoRecording = true DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera) } } else { movieFileOutput.stopRecording() } } } /** Stop video recording video of current session SwiftyCamViewControllerDelegate function SwiftyCamDidFinishRecordingVideo() will be called When video has finished processing, the URL to the video location will be returned by SwiftyCamDidFinishProcessingVideoAt(url:) */ public func stopVideoRecording() { if self.movieFileOutput?.isRecording == true { self.isVideoRecording = false movieFileOutput!.stopRecording() disableFlash() if currentCamera == .front && flashEnabled == true && flashView != nil { UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: { self.flashView?.alpha = 0.0 }, completion: { (_) in self.flashView?.removeFromSuperview() }) } DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFinishRecordingVideo: self.currentCamera) } } } /** Switch between front and rear camera SwiftyCamViewControllerDelegate function SwiftyCamDidSwitchCameras(camera: will be return the current camera selection */ public func switchCamera() { guard isVideoRecording != true else { //TODO: Look into switching camera during video recording print("[SwiftyCam]: Switching between cameras while recording video is not supported") return } switch currentCamera { case .front: currentCamera = .rear case .rear: currentCamera = .front } session.stopRunning() sessionQueue.async { [unowned self] in // remove and re-add inputs and outputs for input in self.session.inputs { self.session.removeInput(input as! AVCaptureInput) } self.addInputs() DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didSwitchCameras: self.currentCamera) } self.session.startRunning() } // If flash is enabled, disable it as the torch is needed for front facing camera disableFlash() } // MARK: Private Functions /// Configure session, add inputs and outputs fileprivate func configureSession() { guard setupResult == .success else { return } // Set default camera currentCamera = defaultCamera // begin configuring session session.beginConfiguration() configureVideoPreset() addVideoInput() addAudioInput() configureVideoOutput() configurePhotoOutput() session.commitConfiguration() } /// Add inputs after changing camera() fileprivate func addInputs() { session.beginConfiguration() configureVideoPreset() addVideoInput() addAudioInput() session.commitConfiguration() } // Front facing camera will always be set to VideoQuality.high // If set video quality is not supported, videoQuality variable will be set to VideoQuality.high /// Configure image quality preset fileprivate func configureVideoPreset() { if currentCamera == .front { session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high) } else { if session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)) { session.sessionPreset = videoInputPresetFromVideoQuality(quality: videoQuality) } else { session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high) } } } /// Add Video Inputs fileprivate func addVideoInput() { switch currentCamera { case .front: videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .front) case .rear: videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .back) } if let device = videoDevice { do { try device.lockForConfiguration() if device.isFocusModeSupported(.continuousAutoFocus) { device.focusMode = .continuousAutoFocus if device.isSmoothAutoFocusSupported { device.isSmoothAutoFocusEnabled = true } } if device.isExposureModeSupported(.continuousAutoExposure) { device.exposureMode = .continuousAutoExposure } if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) { device.whiteBalanceMode = .continuousAutoWhiteBalance } if device.isLowLightBoostSupported && lowLightBoost == true { device.automaticallyEnablesLowLightBoostWhenAvailable = true } device.unlockForConfiguration() } catch { print("[SwiftyCam]: Error locking configuration") } } do { let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) if session.canAddInput(videoDeviceInput) { session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput } else { print("[SwiftyCam]: Could not add video device input to the session") print(session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality))) setupResult = .configurationFailed session.commitConfiguration() return } } catch { print("[SwiftyCam]: Could not create video device input: \(error)") setupResult = .configurationFailed return } } /// Add Audio Inputs fileprivate func addAudioInput() { do { let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice) if session.canAddInput(audioDeviceInput) { session.addInput(audioDeviceInput) } else { print("[SwiftyCam]: Could not add audio device input to the session") } } catch { print("[SwiftyCam]: Could not create audio device input: \(error)") } } /// Configure Movie Output fileprivate func configureVideoOutput() { let movieFileOutput = AVCaptureMovieFileOutput() if self.session.canAddOutput(movieFileOutput) { self.session.addOutput(movieFileOutput) if let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo) { if connection.isVideoStabilizationSupported { connection.preferredVideoStabilizationMode = .auto } } self.movieFileOutput = movieFileOutput } } /// Configure Photo Output fileprivate func configurePhotoOutput() { let photoFileOutput = AVCaptureStillImageOutput() if self.session.canAddOutput(photoFileOutput) { photoFileOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] self.session.addOutput(photoFileOutput) self.photoFileOutput = photoFileOutput } } /// Orientation management fileprivate func subscribeToDeviceOrientationChangeNotifications() { self.deviceOrientation = UIDevice.current.orientation NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } fileprivate func unsubscribeFromDeviceOrientationChangeNotifications() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) self.deviceOrientation = nil } @objc fileprivate func deviceDidRotate() { if !UIDevice.current.orientation.isFlat { self.deviceOrientation = UIDevice.current.orientation } } fileprivate func getVideoOrientation() -> AVCaptureVideoOrientation { guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return previewLayer!.videoPreviewLayer.connection.videoOrientation } switch deviceOrientation { case .landscapeLeft: return .landscapeRight case .landscapeRight: return .landscapeLeft case .portraitUpsideDown: return .portraitUpsideDown default: return .portrait } } fileprivate func getImageOrientation(forCamera: CameraSelection) -> UIImageOrientation { guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return forCamera == .rear ? .right : .leftMirrored } switch deviceOrientation { case .landscapeLeft: return forCamera == .rear ? .up : .downMirrored case .landscapeRight: return forCamera == .rear ? .down : .upMirrored case .portraitUpsideDown: return forCamera == .rear ? .left : .rightMirrored default: return forCamera == .rear ? .right : .leftMirrored } } /** Returns a UIImage from Image Data. - Parameter imageData: Image Data returned from capturing photo from the capture session. - Returns: UIImage from the image data, adjusted for proper orientation. */ fileprivate func processPhoto(_ imageData: Data) -> UIImage { let dataProvider = CGDataProvider(data: imageData as CFData) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) // Set proper orientation for photo // If camera is currently set to front camera, flip image let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.currentCamera)) return image } fileprivate func capturePhotoAsyncronously(completionHandler: @escaping(Bool) -> ()) { if let videoConnection = photoFileOutput?.connection(withMediaType: AVMediaTypeVideo) { photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in if (sampleBuffer != nil) { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let image = self.processPhoto(imageData!) // Call delegate and return new image DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didTake: image) } completionHandler(true) } else { completionHandler(false) } }) } else { completionHandler(false) } } /// Handle Denied App Privacy Settings fileprivate func promptToAppSettings() { // prompt User with UIAlertView DispatchQueue.main.async(execute: { [unowned self] in let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera") let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in if #available(iOS 10.0, *) { UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } else { if let appSettings = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(appSettings) } } })) self.present(alertController, animated: true, completion: nil) }) } /** Returns an AVCapturePreset from VideoQuality Enumeration - Parameter quality: ViewQuality enum - Returns: String representing a AVCapturePreset */ fileprivate func videoInputPresetFromVideoQuality(quality: VideoQuality) -> String { switch quality { case .high: return AVCaptureSessionPresetHigh case .medium: return AVCaptureSessionPresetMedium case .low: return AVCaptureSessionPresetLow case .resolution352x288: return AVCaptureSessionPreset352x288 case .resolution640x480: return AVCaptureSessionPreset640x480 case .resolution1280x720: return AVCaptureSessionPreset1280x720 case .resolution1920x1080: return AVCaptureSessionPreset1920x1080 case .iframe960x540: return AVCaptureSessionPresetiFrame960x540 case .iframe1280x720: return AVCaptureSessionPresetiFrame1280x720 case .resolution3840x2160: if #available(iOS 9.0, *) { return AVCaptureSessionPreset3840x2160 } else { print("[SwiftyCam]: Resolution 3840x2160 not supported") return AVCaptureSessionPresetHigh } } } /// Get Devices fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? { if let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] { return devices.filter({ $0.position == position }).first } return nil } /// Enable or disable flash for photo fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) { do { try device.lockForConfiguration() device.flashMode = mode device.unlockForConfiguration() } catch { print("[SwiftyCam]: \(error)") } } /// Enable flash fileprivate func enableFlash() { if self.isCameraTorchOn == false { toggleFlash() } } /// Disable flash fileprivate func disableFlash() { if self.isCameraTorchOn == true { toggleFlash() } } /// Toggles between enabling and disabling flash fileprivate func toggleFlash() { guard self.currentCamera == .rear else { // Flash is not supported for front facing camera return } let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) // Check if device has a flash if (device?.hasTorch)! { do { try device?.lockForConfiguration() if (device?.torchMode == AVCaptureTorchMode.on) { device?.torchMode = AVCaptureTorchMode.off self.isCameraTorchOn = false } else { do { try device?.setTorchModeOnWithLevel(1.0) self.isCameraTorchOn = true } catch { print("[SwiftyCam]: \(error)") } } device?.unlockForConfiguration() } catch { print("[SwiftyCam]: \(error)") } } } /// Sets whether SwiftyCam should enable background audio from other applications or sources fileprivate func setBackgroundAudioPreference() { guard allowBackgroundAudio == true else { return } do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.duckOthers, .defaultToSpeaker]) session.automaticallyConfiguresApplicationAudioSession = false } catch { print("[SwiftyCam]: Failed to set background audio preference") } } } extension SwiftyCamViewController : SwiftyCamButtonDelegate { /// Sets the maximum duration of the SwiftyCamButton public func setMaxiumVideoDuration() -> Double { return maximumVideoDuration } /// Set UITapGesture to take photo public func buttonWasTapped() { takePhoto() } /// Set UILongPressGesture start to begin video public func buttonDidBeginLongPress() { startVideoRecording() } /// Set UILongPressGesture begin to begin end video public func buttonDidEndLongPress() { stopVideoRecording() } /// Called if maximum duration is reached public func longPressDidReachMaximumDuration() { stopVideoRecording() } } // MARK: AVCaptureFileOutputRecordingDelegate extension SwiftyCamViewController : AVCaptureFileOutputRecordingDelegate { /// Process newly captured video and write it to temporary directory public func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { if let currentBackgroundRecordingID = backgroundRecordingID { backgroundRecordingID = UIBackgroundTaskInvalid if currentBackgroundRecordingID != UIBackgroundTaskInvalid { UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID) } } if error != nil { print("[SwiftyCam]: Movie file finishing error: \(error)") } else { //Call delegate function with the URL of the outputfile DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFinishProcessVideoAt: outputFileURL) } } } } // Mark: UIGestureRecognizer Declarations extension SwiftyCamViewController { /// Handle pinch gesture @objc fileprivate func zoomGesture(pinch: UIPinchGestureRecognizer) { guard pinchToZoom == true && self.currentCamera == .rear else { //ignore pinch if pinchToZoom is set to false return } do { let captureDevice = AVCaptureDevice.devices().first as? AVCaptureDevice try captureDevice?.lockForConfiguration() zoomScale = min(maxZoomScale, max(1.0, min(beginZoomScale * pinch.scale, captureDevice!.activeFormat.videoMaxZoomFactor))) captureDevice?.videoZoomFactor = zoomScale // Call Delegate function with current zoom scale DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale) } captureDevice?.unlockForConfiguration() } catch { print("[SwiftyCam]: Error locking configuration") } } /// Handle single tap gesture @objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) { guard tapToFocus == true else { // Ignore taps return } let screenSize = previewLayer!.bounds.size let tapPoint = tap.location(in: previewLayer!) let x = tapPoint.y / screenSize.height let y = 1.0 - tapPoint.x / screenSize.width let focusPoint = CGPoint(x: x, y: y) if let device = videoDevice { do { try device.lockForConfiguration() if device.isFocusPointOfInterestSupported == true { device.focusPointOfInterest = focusPoint device.focusMode = .autoFocus } device.exposurePointOfInterest = focusPoint device.exposureMode = AVCaptureExposureMode.continuousAutoExposure device.unlockForConfiguration() //Call delegate function and pass in the location of the touch DispatchQueue.main.async { self.cameraDelegate?.swiftyCam(self, didFocusAtPoint: tapPoint) } } catch { // just ignore } } } /// Handle double tap gesture @objc fileprivate func doubleTapGesture(tap: UITapGestureRecognizer) { guard doubleTapCameraSwitch == true else { return } switchCamera() } /** Add pinch gesture recognizer and double tap gesture recognizer to currentView - Parameter view: View to add gesture recognzier */ fileprivate func addGestureRecognizersTo(view: UIView) { let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(zoomGesture(pinch:))) pinchGesture.delegate = self view.addGestureRecognizer(pinchGesture) let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:))) singleTapGesture.numberOfTapsRequired = 1 singleTapGesture.delegate = self view.addGestureRecognizer(singleTapGesture) let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture(tap:))) doubleTapGesture.numberOfTapsRequired = 2 doubleTapGesture.delegate = self view.addGestureRecognizer(doubleTapGesture) } } // MARK: UIGestureRecognizerDelegate extension SwiftyCamViewController : UIGestureRecognizerDelegate { /// Set beginZoomScale when pinch begins public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) { beginZoomScale = zoomScale; } return true } }
mit
6a5b985e2aad77ab75de71d8e1eb7e30
27.868101
189
0.740797
4.51764
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Themes/WPStyleGuide+Themes.swift
2
6046
import Foundation import WordPressShared /// A WPStyleGuide extension with styles and methods specific to the Themes feature. /// extension WPStyleGuide { public struct Themes { // MARK: - Current Theme Styles public static let currentThemeBackgroundColor: UIColor = .listForeground public static let currentThemeDividerColor: UIColor = .divider public static let currentThemeLabelFont = WPFontManager.systemRegularFont(ofSize: 11) public static let currentThemeLabelColor: UIColor = .textSubtle public static let currentThemeNameFont = WPFontManager.systemSemiBoldFont(ofSize: 14) public static let currentThemeNameColor: UIColor = .text public static let currentThemeButtonFont = WPFontManager.systemRegularFont(ofSize: 13) public static let currentThemeButtonColor: UIColor = .text public static func styleCurrentThemeButton(_ button: UIButton) { button.titleLabel?.font = currentThemeButtonFont button.setTitleColor(currentThemeButtonColor, for: UIControl.State()) button.backgroundColor = currentThemeBackgroundColor } // MARK: - Search Styles public static let searchBarBackgroundColor: UIColor = .listBackground public static let searchBarBorderColor: UIColor = .neutral(.shade10) public static let searchTypeTitleFont = WPFontManager.systemSemiBoldFont(ofSize: 14) public static let searchTypeTitleColor: UIColor = .neutral(.shade70) public static func styleSearchTypeButton(_ button: UIButton, title: String) { button.setTitleColor(searchTypeTitleColor, for: UIControl.State()) button.setTitle(title, for: UIControl.State()) button.titleLabel?.font = searchTypeTitleFont let imageWidth = button.imageView?.frame.size.width ?? 0 button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: 0, right: imageWidth) let titleWidth = button.titleLabel?.frame.size.width ?? 0 button.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleWidth, bottom: 0, right: -titleWidth) } // MARK: - Cell Styles public static let cellNameFont = WPFontManager.systemSemiBoldFont(ofSize: 14) public static let cellInfoFont = WPFontManager.systemSemiBoldFont(ofSize: 12) public static let placeholderColor: UIColor = .neutral(.shade10) public static let activeCellBackgroundColor: UIColor = .neutral(.shade40) public static let activeCellBorderColor: UIColor = .neutral(.shade40) public static let activeCellDividerColor: UIColor = .neutral(.shade20) public static let activeCellNameColor: UIColor = .textInverted public static let activeCellInfoColor: UIColor = .primaryLight public static let inactiveCellBackgroundColor: UIColor = .listForeground public static let inactiveCellBorderColor: UIColor = .neutral(.shade10) public static let inactiveCellDividerColor: UIColor = .neutral(.shade5) public static let inactiveCellNameColor: UIColor = .neutral(.shade70) public static let inactiveCellPriceColor: UIColor = .success // MARK: - Metrics public static let currentBarLineHeight: CGFloat = 53 public static let currentBarSeparator: CGFloat = 1 public static let searchBarHeight: CGFloat = 53 public static let cellBorderWidth: CGFloat = 1 public static func headerHeight(_ horizontallyCompact: Bool, includingSearchBar: Bool) -> CGFloat { var headerHeight = (currentBarSeparator * 2) if includingSearchBar { headerHeight += searchBarHeight } if horizontallyCompact { headerHeight += (currentBarLineHeight * 2) + currentBarSeparator } else { headerHeight += currentBarLineHeight } return headerHeight } public static let columnMargin: CGFloat = 7 public static let rowMargin: CGFloat = 10 public static let minimumColumnWidth: CGFloat = 330 public static let cellImageInset: CGFloat = 2 public static let cellImageRatio: CGFloat = 0.75 public static let cellInfoBarHeight: CGFloat = 55 public static func cellWidthForFrameWidth(_ width: CGFloat) -> CGFloat { let numberOfColumns = max(1, trunc(width / minimumColumnWidth)) let numberOfMargins = numberOfColumns + 1 let marginsWidth = numberOfMargins * columnMargin let columnsWidth = width - marginsWidth let columnWidth = trunc(columnsWidth / numberOfColumns) return columnWidth } public static func cellHeightForCellWidth(_ width: CGFloat) -> CGFloat { let imageHeight = (width - cellImageInset) * cellImageRatio return imageHeight + cellInfoBarHeight } public static func cellHeightForFrameWidth(_ width: CGFloat) -> CGFloat { let cellWidth = cellWidthForFrameWidth(width) return cellHeightForCellWidth(cellWidth) } public static func cellSizeForFrameWidth(_ width: CGFloat) -> CGSize { let cellWidth = cellWidthForFrameWidth(width) let cellHeight = cellHeightForCellWidth(cellWidth) return CGSize(width: cellWidth.zeroIfNaN(), height: cellHeight.zeroIfNaN()) } public static func imageWidthForFrameWidth(_ width: CGFloat) -> CGFloat { let cellWidth = cellWidthForFrameWidth(width) return cellWidth - cellImageInset } public static let footerHeight: CGFloat = 50 public static let themeMargins = UIEdgeInsets(top: rowMargin, left: columnMargin, bottom: rowMargin, right: columnMargin) public static let infoMargins = UIEdgeInsets() public static let minimumSearchHeight: CGFloat = 44 public static let searchAnimationDuration: TimeInterval = 0.2 } }
gpl-2.0
93728d1baa79a7d4e7590abc11dde136
46.234375
129
0.685743
5.546789
false
false
false
false
swifth/SwifthDB
Pod/Classes/Filter.swift
2
14435
// // Filter.swift // SwiftyDB // // Created by Øyvind Grimnes on 17/01/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation /** An instance of the Filter class is used to filter query results All filters are automatically converted into SQLite statements when querying the database. To make filtering easier, and backwards compatibility, it is possible to instantiate a filter object as a dictionary literal **Example:** Return any objects with the name 'Ghost' ``` let filter: Filter = ["name": "Ghost"] let filter = Filter.equal("name", value: "Ghost") ``` */ public class Filter: DictionaryLiteralConvertible { public typealias Key = String // Already satisified by the original SwiftyDB Value protocol // public typealias Value = Value; private enum Relationship: String { case Equal = "=" case Less = "<" case Greater = ">" case NotEqual = "!=" case In = "IN" case NotIn = "NOT IN" case Like = "LIKE" case NotLike = "NOT LIKE" case LessOrEqual = "<=" case GreaterOrEqual = ">=" } /** Represent a part of the total filters (e.g. 'id = 2') */ private struct FilterComponent { let propertyName: String let relationship: Relationship let value: Any? private let uniqueifier: UInt32 = arc4random() var uniquePropertyName: String { return "\(propertyName)\(uniqueifier)" } func statement() -> String { switch relationship { case .Equal, .NotEqual, .Greater, .GreaterOrEqual, .Less, .LessOrEqual, .Like, .NotLike: return "\(propertyName) \(relationship.rawValue) :\(uniquePropertyName)" case .In, .NotIn: let array = value as! [Value?] let placeholderString = (0..<array.count).map {":\(uniquePropertyName)\($0)"} .joinWithSeparator(", ") return "\(propertyName) \(relationship.rawValue) (\(placeholderString))" } } } private var components: [FilterComponent] = [] // MARK: - Initializers /** Initialize a Filter object using a dictionary. All property-value pairs will limit the results to objects where property's value is equal to the provided value */ public required init(dictionaryLiteral elements: (Key, Value)...) { elements.forEach { (propertyName, value) in components.append(FilterComponent(propertyName: propertyName, relationship: .Equal, value: value)) } } /** Initialize a new, empty Filter object */ public init() {} // MARK: - Filters /** Evaluated as true if the value of the property is equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func equal(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .Equal, value: value)) return self } /** Evaluated as true if the value of the property is less than the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func lessThan(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .Less, value: value)) return self } /** Evaluated as true if the value of the property is less or equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func lessOrEqual(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .LessOrEqual, value: value)) return self } /** Evaluated as true if the value of the property is less than the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func greaterThan(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .Greater, value: value)) return self } /** Evaluated as true if the value of the property is greater or equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func greaterOrEqual(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .GreaterOrEqual, value: value)) return self } /** Evaluated as true if the value of the property is not equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `self`, to enable chaining of statements */ public func notEqual(propertyName: String, value: Value?) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .NotEqual, value: value)) return self } /** Evaluated as true if the value of the property is contained in the array - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `self`, to enable chaining of statements */ public func contains(propertyName: String, array: [Value?]) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .In, value: array)) return self } /** Evaluated as true if the value of the property is not contained in the array - parameter propertyName: name of the property to be evaluated - parameter array: array that should not contain the property value - returns: `self`, to enable chaining of statements */ public func notContains(propertyName: String, array: [Value?]) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .NotIn, value: array)) return self } /** Evaluated as true if the value of the property matches the pattern. **%** matches any string **_** matches a single character 'Dog' LIKE 'D_g' = true 'Dog' LIKE 'D%' = true - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `self`, to enable chaining of statements */ public func like(propertyName: String, pattern: String) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .Like, value: pattern)) return self } /** Evaluated as true if the value of the property matches the pattern. **%** matches any string **_** matches a single character 'Dog' NOT LIKE 'D_g' = false 'Dog' NOT LIKE 'D%' = false - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `Filter` intance */ public func notLike(propertyName: String, pattern: String) -> Filter { components.append(FilterComponent(propertyName: propertyName, relationship: .NotLike, value: pattern)) return self } // MARK: - Internal methods internal func whereStatement() -> String { let statement = "WHERE " + self.components.map {$0.statement()}.joinWithSeparator(" AND ") return statement } internal func parameters() -> [String: SQLiteValue?] { var parameters: [String: SQLiteValue?] = [:] for filterComponent in components { if let arrayValue = filterComponent.value as? [Value?] { for (index, value) in arrayValue.enumerate() { parameters["\(filterComponent.uniquePropertyName)\(index)"] = value as? SQLiteValue } } else { parameters[filterComponent.uniquePropertyName] = filterComponent.value as? SQLiteValue } } return parameters } } /** Convenience methods */ extension Filter { // MARK: - Convenience filter initializers /** Evaluated as true if the value of the property is equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func equal(propertyName: String, value: Value?) -> Filter { return Filter().equal(propertyName, value: value) } /** Evaluated as true if the value of the property is less than the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func lessThan(propertyName: String, value: Value?) -> Filter { return Filter().lessThan(propertyName, value: value) } /** Evaluated as true if the value of the property is less or equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func lessOrEqual(propertyName: String, value: Value?) -> Filter { return Filter().lessOrEqual(propertyName, value: value) } /** Evaluated as true if the value of the property is greater than the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func greaterThan(propertyName: String, value: Value?) -> Filter { return Filter().greaterThan(propertyName, value: value) } /** Evaluated as true if the value of the property is greater or equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func greaterOrEqual(propertyName: String, value: Value?) -> Filter { return Filter().greaterOrEqual(propertyName, value: value) } /** Evaluated as true if the value of the property is not equal to the provided value - parameter propertyName: name of the property to be evaluated - parameter array: value that will be compared to the property value - returns: `Filter` intance */ public class func notEqual(propertyName: String, value: Value?) -> Filter { return Filter().notEqual(propertyName, value: value) } /** Evaluated as true if the value of the property is contained in the array - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `Filter` intance */ public class func contains(propertyName: String, array: [Value?]) -> Filter { return Filter().contains(propertyName, array: array) } /** Evaluated as true if the value of the property is not contained in the array - parameter propertyName: name of the property to be evaluated - parameter array: array that should not contain the property value - returns: `Filter` intance */ public class func notContains(propertyName: String, array: [Value?]) -> Filter { return Filter().notContains(propertyName, array: array) } /** Evaluated as true if the value of the property matches the pattern. **%** matches any string **_** matches a single character 'Dog' LIKE 'D_g' = true 'Dog' LIKE 'D%' = true - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `Filter` intance */ public class func like(propertyName: String, pattern: String) -> Filter { return Filter().like(propertyName, pattern: pattern) } /** Evaluated as true if the value of the property matches the pattern. **%** matches any string **_** matches a single character 'Dog' NOT LIKE 'D_g' = false 'Dog' NOT LIKE 'D%' = false - parameter propertyName: name of the property to be evaluated - parameter array: array that should contain the property value - returns: `Filter` intance */ public class func notLike(propertyName: String, pattern: String) -> Filter { return Filter().notLike(propertyName, pattern: pattern) } }
apache-2.0
dc6b8aa11982a4f3bb1027e85fe3889c
35.44697
170
0.616365
5.065988
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/WPContentSyncHelper.swift
2
3619
import UIKit import CocoaLumberjack @objc protocol WPContentSyncHelperDelegate: NSObjectProtocol { func syncHelper(_ syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) func syncHelper(_ syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) @objc optional func syncContentStart(_ syncHelper: WPContentSyncHelper) @objc optional func syncContentEnded(_ syncHelper: WPContentSyncHelper) @objc optional func syncContentFailed(_ syncHelper: WPContentSyncHelper) @objc optional func hasNoMoreContent(_ syncHelper: WPContentSyncHelper) } class WPContentSyncHelper: NSObject { @objc weak var delegate: WPContentSyncHelperDelegate? @objc var isSyncing: Bool = false { didSet { if isSyncing { delegate?.syncContentStart?(self) } } } @objc var isLoadingMore: Bool = false @objc var hasMoreContent: Bool = true { didSet { if hasMoreContent == oldValue { return } if hasMoreContent == false { delegate?.hasNoMoreContent?(self) } } } // MARK: - Syncing @objc @discardableResult func syncContent() -> Bool { return syncContentWithUserInteraction(false) } @objc @discardableResult func syncContentWithUserInteraction() -> Bool { return syncContentWithUserInteraction(true) } @objc @discardableResult func syncContentWithUserInteraction(_ userInteraction: Bool) -> Bool { guard !isSyncing else { return false } isSyncing = true delegate?.syncHelper(self, syncContentWithUserInteraction: userInteraction, success: { [weak self] (hasMore: Bool) -> Void in self?.hasMoreContent = hasMore self?.syncContentEnded() }, failure: { [weak self] (error: NSError) -> Void in self?.syncContentEnded(error: true) }) return true } @objc @discardableResult func syncMoreContent() -> Bool { guard !isSyncing else { return false } isSyncing = true isLoadingMore = true delegate?.syncHelper(self, syncMoreWithSuccess: { [weak self] (hasMore: Bool) in self?.hasMoreContent = hasMore self?.syncContentEnded() }, failure: { [weak self] (error: NSError) in DDLogInfo("Error syncing more: \(error)") self?.syncContentEnded(error: true) }) return true } @objc func backgroundSync(success: (() -> Void)?, failure: ((_ error: NSError?) -> Void)?) { guard !isSyncing else { success?() return } isSyncing = true delegate?.syncHelper(self, syncContentWithUserInteraction: false, success: { [weak self] (hasMore: Bool) -> Void in self?.hasMoreContent = hasMore self?.syncContentEnded() success?() }, failure: { [weak self] (error: NSError) -> Void in self?.syncContentEnded() failure?(error) }) } @objc func syncContentEnded(error: Bool = false) { isSyncing = false isLoadingMore = false if error { delegate?.syncContentFailed?(self) } else { delegate?.syncContentEnded?(self) } } }
gpl-2.0
0f6153ccbd71b41332dbb143e7585f5e
28.663934
187
0.592981
5.222222
false
false
false
false
sssbohdan/Design-Patterns-In-Swift
source/behavioral/mediator.swift
2
1718
/*: 💐 Mediator ----------- The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object. ### Example */ class Colleague { let name: String let mediator: Mediator init(name: String, mediator: Mediator) { self.name = name self.mediator = mediator } func send(message: String) { mediator.send(message, colleague: self) } func receive(message: String) { assert(false, "Method should be overriden") } } protocol Mediator { func send(message: String, colleague: Colleague) } class MessageMediator: Mediator { private var colleagues: [Colleague] = [] func addColleague(colleague: Colleague) { colleagues.append(colleague) } func send(message: String, colleague: Colleague) { for c in colleagues { if c !== colleague { //for simplicity we compare object references c.receive(message) } } } } class ConcreteColleague: Colleague { override func receive(message: String) { print("Colleague \(name) received: \(message)") } } /*: ### Usage */ let messagesMediator = MessageMediator() let user0 = ConcreteColleague(name: "0", mediator: messagesMediator) let user1 = ConcreteColleague(name: "1", mediator: messagesMediator) messagesMediator.addColleague(user0) messagesMediator.addColleague(user1) user0.send("Hello") // user1 receives message /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator) */
gpl-3.0
9c6d39409780fe1e6152b795dc9ec8d9
24.597015
243
0.667055
4.330808
false
false
false
false
bmichotte/HSTracker
HSTracker/UIs/DeckManager/CardCell.swift
2
3056
// // CardCell.swift // HSTracker // // Created by Benjamin Michotte on 3/03/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation class CardCell: JNWCollectionViewCell { private var _card: Card? var showCard = true var isArena = false var cellView: CardBar? func set(card: Card) { _card = card if showCard { if let cellView = cellView { cellView.removeFromSuperview() self.cellView = nil } self.backgroundImage = ImageUtils.image(for: card) } else { if let cellView = cellView { cellView.card = card } else { cellView = CardBar.factory() cellView?.frame = NSRect(x: 0, y: 0, width: CGFloat(kFrameWidth), height: CGFloat(kRowHeight)) cellView?.card = card cellView?.playerType = .cardList self.addSubview(cellView!) } } } var card: Card? { return _card } func set(count: Int) { var alpha: Float = 1.0 if !isArena { if count == 2 || (count == 1 && _card!.rarity == .legendary) { alpha = 0.5 } } self.layer!.opacity = alpha self.layer!.setNeedsDisplay() } func flash() { if !showCard { return } self.layer!.masksToBounds = false self.layerUsesCoreImageFilters = true // glow let glowFilter = GlowFilter() glowFilter.glowColor = CIColor(red: 0, green: 0, blue: 0, alpha: 1) glowFilter.strength = 0.0 glowFilter.inputRadius = 20 glowFilter.name = "glow" // exposure let expFilter: CIFilter = CIFilter(name: "CIExposureAdjust")! expFilter.setDefaults() expFilter.setValue(NSNumber(value: 0), forKey: "inputEV") expFilter.name = "exposure" self.layer!.filters = [expFilter, glowFilter] let expAnim: CABasicAnimation = CABasicAnimation() expAnim.keyPath = "filters.exposure.inputEV" expAnim.fromValue = NSNumber(value: 5.0) expAnim.toValue = NSNumber(value: 0.0) expAnim.duration = 0.5 let glowAnim: CABasicAnimation = CABasicAnimation() glowAnim.keyPath = "filters.glow.strength" glowAnim.fromValue = NSNumber(value: 0.1) glowAnim.toValue = NSNumber(value: 0.0) glowAnim.duration = 0.5 let animgroup: CAAnimationGroup = CAAnimationGroup() animgroup.animations = [expAnim, glowAnim] animgroup.duration = 0.35 self.layer!.add(animgroup, forKey: "animgroup") // final value self.layer!.setValue(NSNumber(value: 0), forKey: "filters.exposure.inputEV") self.layer!.setValue(NSNumber(value: 0), forKey: "filters.glow.strength") } }
mit
ac55940e437ddae0be48988427870e71
29.858586
84
0.545008
4.44687
false
false
false
false
caopengxu/scw
scw/scw/Code/Main/View/TabBarView.swift
1
2780
// // TabBarView.swift // scw // // Created by cpx on 2017/7/6. // Copyright © 2017年 scw. All rights reserved. // import UIKit class TabBarView: UIView { var itemClickBack: ((NSInteger) -> Void)? var isHome = false var isClass = false var isShoppingCart = false var isMine = false @IBOutlet weak var homeBtn: TabBarButton! @IBOutlet weak var classBtn: TabBarButton! @IBOutlet weak var shoppingCartBtn: TabBarButton! @IBOutlet weak var mineBtn: TabBarButton! // MARK:=== 初始化 func setUp() { btnClick(homeBtn) } // MARK:=== 按钮点击 @IBAction func btnClick(_ sender: TabBarButton) { if let itemClickBack = itemClickBack { itemClickBack(sender.tag) } if (sender.tag == 0) { if (!isHome) { isHome = true; isClass = false; isShoppingCart = false; isMine = false; classBtn.isSelected = sender.isSelected; shoppingCartBtn.isSelected = sender.isSelected; mineBtn.isSelected = sender.isSelected; sender.isSelected = !sender.isSelected; } } else if (sender.tag == 1) { if (!isClass) { isClass = true; isHome = false; isShoppingCart = false; isMine = false; homeBtn.isSelected = sender.isSelected; shoppingCartBtn.isSelected = sender.isSelected; mineBtn.isSelected = sender.isSelected; sender.isSelected = !sender.isSelected; } } else if (sender.tag == 2) { if (!isShoppingCart) { isShoppingCart = true; isClass = false; isHome = false; isMine = false; classBtn.isSelected = sender.isSelected; homeBtn.isSelected = sender.isSelected; mineBtn.isSelected = sender.isSelected; sender.isSelected = !sender.isSelected; } } else if (sender.tag == 3) { if (!isMine) { isMine = true; isClass = false; isShoppingCart = false; isHome = false; classBtn.isSelected = sender.isSelected; shoppingCartBtn.isSelected = sender.isSelected; homeBtn.isSelected = sender.isSelected; sender.isSelected = !sender.isSelected; } } } }
mit
e60afb484b251f5c5c99f8397aa02440
25.825243
63
0.482447
5.097786
false
false
false
false
Samarkin/PixelEditor
PixelEditor/Extensions.swift
1
1409
import Cocoa extension Int { func asColor() -> NSColor { let blue = self & 0xFF let green = (self >> 8) & 0xFF let red = (self >> 16) & 0xFF return NSColor(calibratedRed: CGFloat(red)/0xFF, green: CGFloat(green)/0xFF, blue: CGFloat(blue)/0xFF, alpha: 1) } func asARGBColor() -> NSColor { let blue = self & 0xFF let green = (self >> 8) & 0xFF let red = (self >> 16) & 0xFF let alpha = (self >> 24) & 0xFF return NSColor(calibratedRed: CGFloat(red)/0xFF, green: CGFloat(green)/0xFF, blue: CGFloat(blue)/0xFF, alpha: CGFloat(alpha)/0xFF) } } extension UInt32 { func asARGBColor() -> NSColor { let blue = self & 0xFF let green = (self >> 8) & 0xFF let red = (self >> 16) & 0xFF let alpha = (self >> 24) & 0xFF return NSColor(calibratedRed: CGFloat(red)/0xFF, green: CGFloat(green)/0xFF, blue: CGFloat(blue)/0xFF, alpha: CGFloat(alpha)/0xFF) } } extension NSColor { func asARGB() -> UInt32 { let color = self.colorUsingColorSpace(NSColorSpace.genericRGBColorSpace())! let blue = UInt32(0xFF * color.blueComponent) let green = UInt32(0xFF * color.greenComponent) let red = UInt32(0xFF * color.redComponent) let alpha = UInt32(0xFF * color.alphaComponent) return (alpha << 24) | (red << 16) | (green << 8) | blue } }
mit
25428a13f5e7e1e1966760c4edab7eda
35.153846
138
0.591909
3.576142
false
false
false
false
JeanetteMueller/fyydAPI
fyydAPI/Classes/FyydRequest+Podcast.swift
1
7482
// // FyydRequest+Podcast.swift // Podcat 2 // // Created by Jeanette Müller on 10.04.17. // Copyright © 2017 Jeanette Müller. All rights reserved. // import Foundation import Alamofire public extension FyydRequest { func loadPodcast(by identifier:Int, callback: @escaping (FyydPodcast?) -> Void) { // https://api.fyyd.de/podcast/show?id=85 guard self.state == .new else{ return } var urlComponents = URLComponents(string: kfyydUrlApi)! urlComponents.path = "/podcast/show" var query = [URLQueryItem]() query.append(URLQueryItem(name: "id", value: String(format: "%d", identifier))) urlComponents.queryItems = query guard let url = urlComponents.url else { return } self.state = .loading let aRequest = FyydManager.shared.sessionManager.request(url) // if let user = feedRecord.username, let pass = feedRecord.password{ // if !user.isEqual("") && !pass.isEqual(""){ // // aRequest.authenticate(user: user, password: pass) // } // } aRequest.validate().responseJSON(completionHandler: { (response) in switch response.result { case .success: if let data = response.result.value as? [String:Any]{ if let item = data["data"] as? [String:Any]{ self.state = .done callback(FyydPodcast(item)) } } case .failure(let error): self.state = .failed if let httpResponse = response.response { switch httpResponse.statusCode{ case 401: log("passwort benötigt") break default: log("anderer Fehler", error as Any) break } }else{ log("anderer Fehler ohne response", error as Any) } } callback(nil) }) } func loadPodcasts(_ count:Int, offset start:Int = 0, searchTerm:String? = nil, categorie:FyydCategory? = nil, recommendId:Int32? = nil, recommendSlug:String? = nil, apiBase: String = kfyydUrlApi, callback: @escaping ([FyydPodcast]?, Int) -> Void){ //allgemein alle podcasts sortiert nach ranking //https://api.fyyd.de/podcasts/show?count=99 //podcasts nach sucheingabe //https://api.fyyd.de/sucheingabe/iphone/99 //podcasts einer categorie //https://api.fyyd.de/category?category_id=62&count=99 guard self.state == .new else{ return } var urlComponents = URLComponents(string: apiBase)! var query = [URLQueryItem]() let params = [String:Any]() let method: HTTPMethod = .get if let search = searchTerm{ urlComponents.path = String(format: "/search/%@/%d", search.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!, count); }else if let cat = categorie{ urlComponents.path = "/category" query.append(URLQueryItem(name: "category_id", value: String(format: "%d", cat.identifier))) }else if let rID = recommendId{ urlComponents.path = urlComponents.path + "/podcast/recommend" query.append(URLQueryItem(name: "podcast_id", value: String(format: "%d", rID))) }else if let rSlug = recommendSlug{ urlComponents.path = urlComponents.path + "/podcast/recommend" query.append(URLQueryItem(name: "podcast_slug", value: rSlug)) }else{ urlComponents.path = "/podcasts/show" } query.append(URLQueryItem(name: "count", value: String(format: "%d", count))) if start > 0{ query.append(URLQueryItem(name: "from", value: String(format: "%d", start))) } urlComponents.queryItems = query guard let url = urlComponents.url else { return } self.state = .loading var headers: HTTPHeaders? if let token = FyydAPI.getFyydToken(){ headers = [ "Authorization": "Bearer \(token)" ] } log("url: ", url.absoluteString) let aRequest = FyydManager.shared.sessionManager.request(url, method: method, parameters: params, headers: headers) // if let user = feedRecord.username, let pass = feedRecord.password{ // if !user.isEqual("") && !pass.isEqual(""){ // // aRequest.authenticate(user: user, password: pass) // } // } aRequest.validate().responseJSON(completionHandler: { (response) in switch response.result { case .success: if let data = response.result.value as? [String:Any]{ var p = [FyydPodcast]() if let items = data["data"] as? [Any]{ for item in items{ if let i = item as? [String:Any]{ p.append(FyydPodcast(i)) } } }else if let items = data["data"] as? [String:Any]{ for item in Array(items.values){ if let i = item as? [String:Any]{ p.append(FyydPodcast(i)) } } }else if let items = data["data"] as? [[String:Any]]{ for item in items{ p.append(FyydPodcast(item)) } } if p.count > 0{ self.podcasts = p } if let m = data["meta"] as? [String:Any]{ self.meta = m } self.state = .done } case .failure(let error): self.state = .failed if let httpResponse = response.response { switch httpResponse.statusCode{ case 401: log("passwort benötigt") break default: log("anderer Fehler", error as Any) break } }else{ log("anderer Fehler ohne response", error as Any) } } callback(self.podcasts, start) }) } }
mit
2ff8dc66502f4342b0aad485051081f8
34.103286
251
0.444563
5.258087
false
false
false
false
crepashok/encryptor-swift
ios-swift/encryptor-swift/ViewControllers/PGP/CPPGPViewController.swift
1
1499
// // CPPGPViewController.swift // encryptor-swift // // Created by Pavlo Cretsu on 11/22/16. // Copyright © 2016 Pavlo Cretsu. All rights reserved. // import UIKit class CPPGPViewController: UIViewController { @IBOutlet weak var randomizeBtn: UIButton! @IBOutlet weak var inputTextView: UITextView! @IBOutlet weak var outputTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() randomizeInput(randomizeBtn) } @IBAction func clearInput(_ sender: UIButton) { inputTextView.text = .none encodeInput() } @IBAction func randomizeInput(_ sender: UIButton) { inputTextView.text = CPDummyManager.getRandomQuote() encodeInput() } @IBAction func encodeInput(_ sender: UIButton) { encodeInput() } @IBAction func clearResult(_ sender: UIButton) { outputTextView.text = .none decodeOutput() } @IBAction func decodeResult(_ sender: UIButton) { decodeOutput() } private func encodeInput() { // Message encryption let encrypted = CPPGPManager.shared.encode(string: inputTextView.text!) outputTextView.text = encrypted } private func decodeOutput() { // Message decryption if let decrypted = CPPGPManager.shared.decode(string: outputTextView.text!) { inputTextView.text = decrypted } } }
gpl-3.0
8face1127603d025b5c4ed2f5ab933a8
21.69697
85
0.61482
4.801282
false
false
false
false
omondigeno/ActionablePushMessages
Pods/MK/Sources/MaterialTransitionAnimation.swift
1
3208
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * 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 MaterialKit 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 public typealias MaterialAnimationTransitionType = String public typealias MaterialAnimationTransitionSubTypeType = String public enum MaterialAnimationTransition { case Fade case MoveIn case Push case Reveal } public enum MaterialAnimationTransitionSubType { case Right case Left case Top case Bottom } /** :name: MaterialAnimationTransitionToValue */ public func MaterialAnimationTransitionToValue(transition: MaterialAnimationTransition) -> MaterialAnimationTransitionType { switch transition { case .Fade: return kCATransitionFade case .MoveIn: return kCATransitionMoveIn case .Push: return kCATransitionPush case .Reveal: return kCATransitionReveal } } /** :name: MaterialAnimationTransitionSubTypeToValue */ public func MaterialAnimationTransitionSubTypeToValue(direction: MaterialAnimationTransitionSubType) -> MaterialAnimationTransitionSubTypeType { switch direction { case .Right: return kCATransitionFromRight case .Left: return kCATransitionFromLeft case .Top: return kCATransitionFromTop case .Bottom: return kCATransitionFromBottom } } public extension MaterialAnimation { /** :name: transition */ public static func transition(type: MaterialAnimationTransition, direction: MaterialAnimationTransitionSubType? = nil, duration: CFTimeInterval? = nil) -> CATransition { let animation: CATransition = CATransition() animation.type = MaterialAnimationTransitionToValue(type) if let d = direction { animation.subtype = MaterialAnimationTransitionSubTypeToValue(d) } if let d = duration { animation.duration = d } return animation } }
apache-2.0
f0ab93a1c9a417df6cd8c109480e3bb0
32.082474
170
0.791147
4.394521
false
false
false
false
mattrajca/swift-corelibs-foundation
Foundation/URLSession/http/HTTPURLProtocol.swift
4
18451
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation import Dispatch internal class _HTTPURLProtocol: _NativeProtocol { public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(task: task, cachedResponse: cachedResponse, client: client) } public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { super.init(request: request, cachedResponse: cachedResponse, client: client) } override class func canInit(with request: URLRequest) -> Bool { guard request.url?.scheme == "http" || request.url?.scheme == "https" else { return false } return true } override func didReceive(headerData data: Data, contentLength: Int64) -> _EasyHandle._Action { guard case .transferInProgress(let ts) = internalState else { fatalError("Received header data, but no transfer in progress.") } guard let task = task else { fatalError("Received header data but no task available.") } task.countOfBytesExpectedToReceive = contentLength > 0 ? contentLength : NSURLSessionTransferSizeUnknown do { let newTS = try ts.byAppending(headerLine: data) internalState = .transferInProgress(newTS) let didCompleteHeader = !ts.isHeaderComplete && newTS.isHeaderComplete if didCompleteHeader { // The header is now complete, but wasn't before. didReceiveResponse() } return .proceed } catch { return .abort } } /// Set options on the easy handle to match the given request. /// /// This performs a series of `curl_easy_setopt()` calls. override func configureEasyHandle(for request: URLRequest) { // At this point we will call the equivalent of curl_easy_setopt() // to configure everything on the handle. Since we might be re-using // a handle, we must be sure to set everything and not rely on default // values. //TODO: We could add a strong reference from the easy handle back to // its URLSessionTask by means of CURLOPT_PRIVATE -- that would ensure // that the task is always around while the handle is running. // We would have to break that retain cycle once the handle completes // its transfer. // Behavior Options easyHandle.set(verboseModeOn: enableLibcurlDebugOutput) easyHandle.set(debugOutputOn: enableLibcurlDebugOutput, task: task!) easyHandle.set(passHeadersToDataStream: false) easyHandle.set(progressMeterOff: true) easyHandle.set(skipAllSignalHandling: true) // Error Options: easyHandle.set(errorBuffer: nil) easyHandle.set(failOnHTTPErrorCode: false) // Network Options: guard let url = request.url else { fatalError("No URL in request.") } easyHandle.set(url: url) easyHandle.setAllowedProtocolsToHTTPAndHTTPS() easyHandle.set(preferredReceiveBufferSize: Int.max) do { switch (task?.body, try task?.body.getBodyLength()) { case (.none, _): set(requestBodyLength: .noBody) case (_, .some(let length)): set(requestBodyLength: .length(length)) task!.countOfBytesExpectedToSend = Int64(length) case (_, .none): set(requestBodyLength: .unknown) } } catch let e { // Fail the request here. // TODO: We have multiple options: // NSURLErrorNoPermissionsToReadFile // NSURLErrorFileDoesNotExist self.internalState = .transferFailed let error = NSError(domain: NSURLErrorDomain, code: errorCode(fileSystemError: e), userInfo: [NSLocalizedDescriptionKey: "File system error"]) failWith(error: error, request: request) return } // HTTP Options: easyHandle.set(followLocation: false) // The httpAdditionalHeaders from session configuration has to be added to the request. // The request.allHTTPHeaders can override the httpAdditionalHeaders elements. Add the // httpAdditionalHeaders from session configuration first and then append/update the // request.allHTTPHeaders so that request.allHTTPHeaders can override httpAdditionalHeaders. let httpSession = self.task?.session as! URLSession var httpHeaders: [AnyHashable : Any]? if let hh = httpSession.configuration.httpAdditionalHeaders { httpHeaders = hh } if let hh = self.task?.originalRequest?.allHTTPHeaderFields { if httpHeaders == nil { httpHeaders = hh } else { hh.forEach { httpHeaders![$0] = $1 } } } let customHeaders: [String] let headersForRequest = curlHeaders(for: httpHeaders) if ((request.httpMethod == "POST") && (request.value(forHTTPHeaderField: "Content-Type") == nil)) { customHeaders = headersForRequest + ["Content-Type:application/x-www-form-urlencoded"] } else { customHeaders = headersForRequest } easyHandle.set(customHeaders: customHeaders) //TODO: The CURLOPT_PIPEDWAIT option is unavailable on Ubuntu 14.04 (libcurl 7.36) //TODO: Introduce something like an #if, if we want to set them here //set the request timeout //TODO: the timeout value needs to be reset on every data transfer var timeoutInterval = Int(httpSession.configuration.timeoutIntervalForRequest) * 1000 if request.isTimeoutIntervalSet { timeoutInterval = Int(request.timeoutInterval) * 1000 } let timeoutHandler = DispatchWorkItem { [weak self] in guard let _ = self?.task else { fatalError("Timeout on a task that doesn't exist") } //this guard must always pass self?.internalState = .transferFailed let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil)) self?.completeTask(withError: urlError) self?.client?.urlProtocol(self!, didFailWithError: urlError) } guard let task = self.task else { fatalError() } easyHandle.timeoutTimer = _TimeoutSource(queue: task.workQueue, milliseconds: timeoutInterval, handler: timeoutHandler) easyHandle.set(automaticBodyDecompression: true) easyHandle.set(requestMethod: request.httpMethod ?? "GET") if request.httpMethod == "HEAD" { easyHandle.set(noBody: true) } } /// What action to take override func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction { // Redirect: guard let httpURLResponse = response as? HTTPURLResponse else { fatalError("Reponse was not HTTPURLResponse") } if let request = redirectRequest(for: httpURLResponse, fromRequest: request) { return .redirectWithRequest(request) } return .completeTask } override func redirectFor(request: URLRequest) { //TODO: Should keep track of the number of redirects that this // request has gone through and err out once it's too large, i.e. // call into `failWith(errorCode: )` with NSURLErrorHTTPTooManyRedirects guard case .transferCompleted(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else { fatalError("Trying to redirect, but the transfer is not complete.") } guard let session = task?.session as? URLSession else { fatalError() } switch session.behaviour(for: task!) { case .taskDelegate(let delegate): // At this point we need to change the internal state to note // that we're waiting for the delegate to call the completion // handler. Then we'll call the delegate callback // (willPerformHTTPRedirection). The task will then switch out of // its internal state once the delegate calls the completion // handler. //TODO: Should the `public response: URLResponse` property be updated // before we call delegate API self.internalState = .waitingForRedirectCompletionHandler(response: response, bodyDataDrain: bodyDataDrain) // We need this ugly cast in order to be able to support `URLSessionTask.init()` session.delegateQueue.addOperation { delegate.urlSession(session, task: self.task!, willPerformHTTPRedirection: response as! HTTPURLResponse, newRequest: request) { [weak self] (request: URLRequest?) in guard let task = self else { return } self?.task?.workQueue.async { task.didCompleteRedirectCallback(request) } } } case .noDelegate, .dataCompletionHandler, .downloadCompletionHandler: // Follow the redirect. startNewTransfer(with: request) } } override func validateHeaderComplete(transferState: _NativeProtocol._TransferState) -> URLResponse? { if !transferState.isHeaderComplete { return HTTPURLResponse(url: transferState.url, statusCode: 200, httpVersion: "HTTP/0.9", headerFields: [:]) /* we received body data before CURL tells us that the headers are complete, that happens for HTTP/0.9 simple responses, see - https://www.w3.org/Protocols/HTTP/1.0/spec.html#Message-Types - https://github.com/curl/curl/issues/467 */ } return nil } } fileprivate extension _HTTPURLProtocol { /// These are a list of headers that should be passed to libcurl. /// /// Headers will be returned as `Accept: text/html` strings for /// setting fields, `Accept:` for disabling the libcurl default header, or /// `Accept;` for a header with no content. This is the format that libcurl /// expects. /// /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html func curlHeaders(for httpHeaders: [AnyHashable : Any]?) -> [String] { var result: [String] = [] var names = Set<String>() if let hh = httpHeaders as? [String : String] { hh.forEach { let name = $0.0.lowercased() guard !names.contains(name) else { return } names.insert(name) if $0.1.isEmpty { result.append($0.0 + ";") } else { result.append($0.0 + ": " + $0.1) } } } curlHeadersToSet.forEach { let name = $0.0.lowercased() guard !names.contains(name) else { return } names.insert(name) if $0.1.isEmpty { result.append($0.0 + ";") } else { result.append($0.0 + ": " + $0.1) } } curlHeadersToRemove.forEach { let name = $0.lowercased() guard !names.contains(name) else { return } names.insert(name) result.append($0 + ":") } return result } /// Any header values that should be passed to libcurl /// /// These will only be set if not already part of the request. /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html var curlHeadersToSet: [(String,String)] { var result = [("Connection", "keep-alive"), ("User-Agent", userAgentString), ] if let language = NSLocale.current.languageCode { result.append(("Accept-Language", language)) } return result } /// Any header values that should be removed from the ones set by libcurl /// - SeeAlso: https://curl.haxx.se/libcurl/c/CURLOPT_HTTPHEADER.html var curlHeadersToRemove: [String] { if case .none = task?.body { return [] } else { return ["Expect"] } } } fileprivate var userAgentString: String = { // Darwin uses something like this: "xctest (unknown version) CFNetwork/760.4.2 Darwin/15.4.0 (x86_64)" let info = ProcessInfo.processInfo let name = info.processName let curlVersion = CFURLSessionCurlVersionInfo() //TODO: Should probably use sysctl(3) to get these: // kern.ostype: Darwin // kern.osrelease: 15.4.0 //TODO: Use Bundle to get the version number? return "\(name) (unknown version) curl/\(curlVersion.major).\(curlVersion.minor).\(curlVersion.patch)" }() /// State Transfers extension _HTTPURLProtocol { fileprivate func didCompleteRedirectCallback(_ request: URLRequest?) { guard case .waitingForRedirectCompletionHandler(response: let response, bodyDataDrain: let bodyDataDrain) = self.internalState else { fatalError("Received callback for HTTP redirection, but we're not waiting for it. Was it called multiple times?") } // If the request is `nil`, we're supposed to treat the current response // as the final response, i.e. not do any redirection. // Otherwise, we'll start a new transfer with the passed in request. if let r = request { startNewTransfer(with: r) } else { self.internalState = .transferCompleted(response: response, bodyDataDrain: bodyDataDrain) completeTask() } } } /// Response processing internal extension _HTTPURLProtocol { /// Whenever we receive a response (i.e. a complete header) from libcurl, /// this method gets called. func didReceiveResponse() { guard let _ = task as? URLSessionDataTask else { return } guard case .transferInProgress(let ts) = self.internalState else { fatalError("Transfer not in progress.") } guard let response = ts.response as? HTTPURLResponse else { fatalError("Header complete, but not URL response.") } guard let session = task?.session as? URLSession else { fatalError() } switch session.behaviour(for: self.task!) { case .noDelegate: break case .taskDelegate(_): //TODO: There's a problem with libcurl / with how we're using it. // We're currently unable to pause the transfer / the easy handle: // https://curl.haxx.se/mail/lib-2016-03/0222.html // // For now, we'll notify the delegate, but won't pause the transfer, // and we'll disregard the completion handler: switch response.statusCode { case 301, 302, 303, 307: break default: self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } case .dataCompletionHandler: break case .downloadCompletionHandler: break } } /// If the response is a redirect, return the new request /// /// RFC 7231 section 6.4 defines redirection behavior for HTTP/1.1 /// /// - SeeAlso: <https://tools.ietf.org/html/rfc7231#section-6.4> func redirectRequest(for response: HTTPURLResponse, fromRequest: URLRequest) -> URLRequest? { //TODO: Do we ever want to redirect for HEAD requests? func methodAndURL() -> (String, URL)? { guard let location = response.value(forHeaderField: .location, response: response), let targetURL = URL(string: location) else { // Can't redirect when there's no location to redirect to. return nil } // Check for a redirect: switch response.statusCode { //TODO: Should we do this for 300 "Multiple Choices", too? case 301, 302, 303: // Change into "GET": return ("GET", targetURL) case 307: // Re-use existing method: return (fromRequest.httpMethod ?? "GET", targetURL) default: return nil } } guard let (method, targetURL) = methodAndURL() else { return nil } var request = fromRequest request.httpMethod = method // If targetURL has only relative path of url, create a new valid url with relative path // Otherwise, return request with targetURL ie.url from location field guard targetURL.scheme == nil || targetURL.host == nil else { request.url = targetURL return request } let scheme = request.url?.scheme let host = request.url?.host var components = URLComponents() components.scheme = scheme components.host = host components.path = targetURL.relativeString guard let urlString = components.string else { fatalError("Invalid URL") } request.url = URL(string: urlString) let timeSpent = easyHandle.getTimeoutIntervalSpent() request.timeoutInterval = fromRequest.timeoutInterval - timeSpent return request } } fileprivate extension HTTPURLResponse { /// Type safe HTTP header field name(s) enum _Field: String { /// `Location` /// - SeeAlso: RFC 2616 section 14.30 <https://tools.ietf.org/html/rfc2616#section-14.30> case location = "Location" } func value(forHeaderField field: _Field, response: HTTPURLResponse?) -> String? { let value = field.rawValue guard let response = response else { fatalError("Response is nil") } if let location = response.allHeaderFields[value] as? String { return location } return nil } }
apache-2.0
02959b8284d05f5786c2e7ec2aa32e9e
41.909302
181
0.615847
4.978683
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Settings/HomePageSettingViewController.swift
1
5988
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class HomePageSettingViewController: SettingsTableViewController { /* variables for checkmark settings */ let prefs: Prefs var currentChoice: NewTabPage! var hasHomePage = false init(prefs: Prefs) { self.prefs = prefs super.init(style: .grouped) self.title = Strings.AppMenuOpenHomePageTitleString hasSectionSeparatorLine = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func generateSettings() -> [SettingSection] { // The Home button and the New Tab page can be set independently self.currentChoice = NewTabAccessors.getHomePage(self.prefs) self.hasHomePage = HomeButtonHomePageAccessors.getHomePage(self.prefs) != nil let onFinished = { self.prefs.removeObjectForKey(PrefsKeys.HomeButtonHomePageURL) self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey) self.tableView.reloadData() } let showTopSites = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabTopSites), subtitle: nil, accessibilityIdentifier: "HomeAsFirefoxHome", isEnabled: {return self.currentChoice == NewTabPage.topSites}, onChanged: { self.currentChoice = NewTabPage.topSites onFinished() }) let showWebPage = WebPageSetting(prefs: prefs, prefKey: PrefsKeys.HomeButtonHomePageURL, defaultValue: nil, placeholder: Strings.CustomNewPageURL, accessibilityIdentifier: "HomeAsCustomURL", settingDidChange: { (string) in self.currentChoice = NewTabPage.homePage self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey) self.tableView.reloadData() }) showWebPage.textField.textAlignment = .natural let section = SettingSection(title: NSAttributedString(string: Strings.NewTabSectionName), footerTitle: NSAttributedString(string: Strings.NewTabSectionNameFooter), children: [showTopSites, showWebPage]) let topsitesSection = SettingSection(title: NSAttributedString(string: Strings.SettingsTopSitesCustomizeTitle), footerTitle: NSAttributedString(string: Strings.SettingsTopSitesCustomizeFooter), children: [TopSitesSettings(settings: self)]) let isPocketEnabledDefault = Pocket.IslocaleSupported(Locale.current.identifier) let pocketSetting = BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.ASPocketStoriesVisible, defaultValue: isPocketEnabledDefault, attributedTitleText: NSAttributedString(string: Strings.SettingsNewTabPocket)) let pocketSection = SettingSection(title: NSAttributedString(string: Strings.SettingsNewTabASTitle), footerTitle: NSAttributedString(string: Strings.SettingsNewTabPocketFooter), children: [pocketSetting]) return [section, topsitesSection, pocketSection] } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.post(name: .HomePanelPrefsChanged, object: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.keyboardDismissMode = .onDrag } class TopSitesSettings: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var status: NSAttributedString { let num = self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows return NSAttributedString(string: String(format: Strings.TopSitesRowCount, num)) } override var accessibilityIdentifier: String? { return "TopSitesRows" } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.ASTopSitesTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = TopSitesRowCountSettingsController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } } class TopSitesRowCountSettingsController: SettingsTableViewController { let prefs: Prefs var numberOfRows: Int32 static let defaultNumberOfRows: Int32 = 2 init(prefs: Prefs) { self.prefs = prefs numberOfRows = self.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows super.init(style: .grouped) self.title = Strings.AppMenuTopSitesTitleString hasSectionSeparatorLine = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func generateSettings() -> [SettingSection] { let createSetting: (Int32) -> CheckmarkSetting = { num in return CheckmarkSetting(title: NSAttributedString(string: "\(num)"), subtitle: nil, isEnabled: { return num == self.numberOfRows }, onChanged: { self.numberOfRows = num self.prefs.setInt(Int32(num), forKey: PrefsKeys.NumberOfTopSiteRows) self.tableView.reloadData() }) } let rows = [1, 2, 3, 4].map(createSetting) let section = SettingSection(title: NSAttributedString(string: Strings.TopSitesRowSettingFooter), footerTitle: nil, children: rows) return [section] } }
mpl-2.0
b0ca4c9aa50306c56cbe36afac982fd1
47.290323
247
0.718437
5.206957
false
false
false
false
NordRosann/Analysis
Sources/Analysis/RowSchema.swift
1
1470
public struct RowSchema { public var variables: [Variable] public init(variables: Variable...) { self.variables = variables } public init(variables: [Variable]) { self.variables = variables } } extension RowSchema { public var length: Int { return variables.count } public func makeDataFrame(rows: [List]) -> DataFrame { return DataFrame(schema: self, rows: rows) } public func makeDataFrame(columns: [List]) -> DataFrame { return DataFrame(schema: self, columns: columns) } } extension RowSchema: Equatable { } public func == (lhs: RowSchema, rhs: RowSchema) -> Bool { return lhs.variables == rhs.variables } extension List { mutating func adjust(to schema: RowSchema) { self = adjusted(to: schema) } func adjusted(to schema: RowSchema) -> List { let sizeDiff = schema.length - elements.count let curElements = sizeDiff > 0 ? elements + [DataPoint](repeating: .nullValue, count: sizeDiff) : elements let zipped = zip(curElements, schema.variables) let newElements: [DataPoint] = zipped.map { element, description in if let newElement = try? description.type.init(dataPoint: element) { return newElement.dataPoint } else { return .nullValue } } return List(elements: newElements) } }
mit
401a7b83fbc68f6d4ea5940d0be532d0
24.807018
114
0.60068
4.551084
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/Keyknox/SyncKeyStorage/KeychainUtils.swift
1
3763
// // Copyright (C) 2015-2020 Virgil Security Inc. // // 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 AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation internal final class KeychainUtils { internal static let keyknoxMetaCreationDateKey = "k_cda" internal static let keyknoxMetaModificationDateKey = "k_mda" internal func extractModificationDate(fromKeychainEntry keychainEntry: KeychainEntry) throws -> (creationDate: Date, modificationDate: Date) { guard let meta = keychainEntry.meta else { throw SyncKeyStorageError.noMetaInKeychainEntry } guard let modificationTimestampStr = meta[KeychainUtils.keyknoxMetaModificationDateKey], let modificationTimestamp = Int64(modificationTimestampStr) else { throw SyncKeyStorageError.invalidModificationDateInKeychainEntry } guard let creationTimestampStr = meta[KeychainUtils.keyknoxMetaCreationDateKey], let creationTimestamp = Int64(creationTimestampStr) else { throw SyncKeyStorageError.invalidCreationDateInKeychainEntry } return (DateUtils.dateFromMilliTimestamp(creationTimestamp), DateUtils.dateFromMilliTimestamp(modificationTimestamp)) } internal func filterKeyknoxKeychainEntry(_ keychainEntry: KeychainEntry) -> KeychainEntry? { do { _ = try self.extractModificationDate(fromKeychainEntry: keychainEntry) return keychainEntry } catch { return nil } } internal func createMetaForKeychain(from cloudEntry: CloudEntry) throws -> [String: String] { var additionalDict = [ KeychainUtils.keyknoxMetaCreationDateKey: "\(DateUtils.dateToMilliTimestamp(date: cloudEntry.creationDate))", KeychainUtils.keyknoxMetaModificationDateKey: "\(DateUtils.dateToMilliTimestamp(date: cloudEntry.modificationDate))" ] if let meta = cloudEntry.meta { try additionalDict.merge(meta) { _, _ in throw SyncKeyStorageError.invalidKeysInEntryMeta } } return additionalDict } }
bsd-3-clause
507c4aa70ca97ca2470ecfc047e623da
41.280899
100
0.699176
5.147743
false
false
false
false
madeatsampa/MacMagazine-iOS
MacMagazineWatchExtension/ComplicationController.swift
2
5519
// // ComplicationController.swift // MacMagazineWatch Extension // // Created by Cassio Rossi on 08/04/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import ClockKit import WatchKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Properties - struct Complication { var header: String? var line1: String? var line2: String? init(header: String?, line1: String?, line2: String) { self.header = header self.line1 = line1 self.line2 = line2 } } // MARK: - Timeline Configuration - func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler([.forward]) } func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(Date()) } func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { let currentDate = Date() let endDate = currentDate.addingTimeInterval(TimeInterval(1 * 60 * 60)) handler(endDate) } func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { handler(.showOnLockScreen) } // MARK: - Timeline Population - func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { // Call the handler with the current timeline entry API().getComplications { post in guard let post = post else { return } let entry = self.prepareEntry(with: post, for: complication) handler(entry) } } func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Placeholder Templates - func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached let message = Complication(header: "MacMagazine", line1: "Veja nossas últimas", line2: "publicações") let entry = createComplicationTemplate(for: complication, message: message) handler(entry) } // MARK: - Methods - func prepareEntry(with post: XMLPost, for complication: CLKComplication) -> CLKComplicationTimelineEntry? { let timeString = post.pubDate.toComplicationDate() var message = Complication(header: "\(timeString)", line1: post.title, line2: "") var texts = post.title.pairs if !texts.isEmpty { let line1 = texts.first texts.removeFirst() let line2 = texts.joined() message = Complication(header: "\(timeString)", line1: line1, line2: line2) } let entry = self.createTimeLineEntry(for: complication, message: message, date: post.pubDate.toDate()) return entry } func createComplicationTemplate(for complication: CLKComplication, message: Complication) -> CLKComplicationTemplate? { if complication.family == .modularLarge { let template = CLKComplicationTemplateModularLargeStandardBody() template.headerTextProvider = CLKSimpleTextProvider(text: message.header ?? "") template.body1TextProvider = CLKSimpleTextProvider(text: message.line1 ?? "") template.body2TextProvider = CLKSimpleTextProvider(text: message.line2 ?? "") return(template) } else if complication.family == .utilitarianLarge { let template = CLKComplicationTemplateUtilitarianLargeFlat() template.textProvider = CLKSimpleTextProvider(text: message.line1 ?? "") return(template) } else if complication.family == .graphicRectangular { let template = CLKComplicationTemplateGraphicRectangularStandardBody() template.headerTextProvider = CLKSimpleTextProvider(text: message.line1 ?? "") template.body1TextProvider = CLKSimpleTextProvider(text: message.line2 ?? "") template.body2TextProvider = CLKSimpleTextProvider(text: message.header ?? "") return(template) } else { return nil } } func createTimeLineEntry(for complication: CLKComplication, message: Complication, date: Date) -> CLKComplicationTimelineEntry? { guard let template = createComplicationTemplate(for: complication, message: message) else { return nil } let entry = CLKComplicationTimelineEntry(date: date, complicationTemplate: template) return(entry) } func reloadData() { let server = CLKComplicationServer.sharedInstance() guard let complications = server.activeComplications, !complications.isEmpty else { return } for complication in complications { server.reloadTimeline(for: complication) } } } extension Collection { var pairs: [String] { let size = 18 var startIndex = self.startIndex let count = self.count let n = count / size + (count % size == 0 ? 0 : 1) return (0..<n).map { _ in let endIndex = index(startIndex, offsetBy: size, limitedBy: self.endIndex) ?? self.endIndex defer { startIndex = endIndex } return "\(self[startIndex..<endIndex])" } } }
mit
6872fdd4a54f23811cec40f405a30c4b
33.905063
169
0.730372
4.332286
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Drum Synthesizers.xcplaygroundpage/Contents.swift
1
933
//: ## Drum Synthesizers //: These can also be hooked up to MIDI or a sequencer. import XCPlayground import AudioKit //: Set up instruments: var kick = AKSynthKick() var snare = AKSynthSnare(duration: 0.07) var mix = AKMixer(kick, snare) var reverb = AKReverb(mix) AudioKit.output = reverb AudioKit.start() reverb.loadFactoryPreset(.MediumRoom) //: Generate a cheap electro beat var counter = 0 AKPlaygroundLoop(frequency: 4.44) { let onFirstBeat = counter == 0 let everyOtherBeat = counter % 4 == 2 let randomHit = (0...3).randomElement() == 0 if onFirstBeat || randomHit { kick.play(noteNumber:60, velocity: 100) kick.stop(noteNumber:60) } if everyOtherBeat { let velocity = (1...100).randomElement() snare.play(noteNumber:60, velocity: velocity) snare.stop(noteNumber:60) } counter += 1 } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
b550e93183f6d09169cb66305bb5a76b
23.552632
60
0.684887
3.746988
false
false
false
false
nathawes/swift
test/SILOptimizer/definite_init_diagnostics_objc.swift
20
1035
// RUN: %target-swift-frontend -emit-sil -sdk %S/../SILGen/Inputs %s -I %S/../SILGen/Inputs -enable-source-import -parse-stdlib -o /dev/null -verify // RUN: %target-swift-frontend -emit-sil -sdk %S/../SILGen/Inputs %s -I %S/../SILGen/Inputs -enable-source-import -parse-stdlib -o /dev/null -verify // REQUIRES: objc_interop import Swift import gizmo @requires_stored_property_inits class RequiresInitsDerived : Gizmo { var a = 1 var b = 2 var c = 3 override init() { super.init() } init(i: Int) { if i > 0 { super.init() } } // expected-error{{'super.init' isn't called on all paths before returning from initializer}} init(d: Double) { f() // expected-error {{'self' used in method call 'f' before 'super.init' call}} super.init() } init(t: ()) { a = 5 // expected-error {{'self' used in property access 'a' before 'super.init' call}} b = 10 // expected-error {{'self' used in property access 'b' before 'super.init' call}} super.init() c = 15 } func f() { } }
apache-2.0
1bb1e00fb704afe6095535d05dc956b7
26.972973
148
0.626087
3.184615
false
false
false
false
DevHospital/RealmDataStore
RealmDataStore/RealmStorage.swift
1
7892
// // RealmStorage.swift // RealmDataStore // // Created by Andrzej Spiess on 26/10/15. // Copyright © 2015 Dev-Hospital. All rights reserved. // import Foundation import RealmSwift import OperationDispatcher public typealias Storable = Object public enum StoreResult<T:Storable, E:ErrorType> { case Success([T]) case Failure(ErrorType) public var storables: [T] { switch (self) { case .Success(let items): return items case .Failure: return [] } } } public protocol Store { func add<S:Storable>( obj: S, dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func add<S:Storable>( objs: [S], dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func update( action: (Void -> Void), dispatcher: OperationDispatcher, callback: (StoreResult<Storable, DataStoreError> -> Void)?) -> Void func updateOrCreate<S:Storable>( obj: S, dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func updateOrCreate<S:Storable>( objs: [S], dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func delete<S:Storable>( obj: S, dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func deleteAll<S:Storable>( objs: [S], dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func loadAll<S:Storable>( dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void func load<S:Storable>( predicate: NSPredicate, dispatcher: OperationDispatcher, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void } public class DataStore<T:Storage>: Store { public init() { } public func add<S:Storable>( obj: S, dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.add(obj) } callback?(StoreResult.Success([obj])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not add object \(obj)", callback: callback) } public func add<S:Storable>( objs: [S], dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.add(objs) } callback?(StoreResult.Success(objs)) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not add objects", callback: callback) } public func updateOrCreate<S:Storable>( obj: S, dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.add(obj, update: true) } callback?(StoreResult.Success([obj])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not update object \(obj)", callback: callback) } public func updateOrCreate<S:Storable>( objs: [S], dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.add(objs, update: true) } callback?(StoreResult.Success(objs)) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not update objects", callback: callback) } public func update( action: (Void -> Void), dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<Storable, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { action() } callback?(StoreResult.Success([])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not update object with action", callback: callback) } public func delete<S:Storable>( obj: S, dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.delete(obj) } callback?(StoreResult.Success([])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not delete object \(obj)", callback: callback) } public func deleteAll<S:Storable>( objs: [S], dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)? = nil) { let operation = { (usedStorage: Realm) -> Void in try usedStorage.write { usedStorage.delete(objs) } callback?(StoreResult.Success([])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not delete object \(objs)", callback: callback) } public func load<S:Storable>( predicate: NSPredicate, dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in var objs: [S]? try usedStorage.write { objs = usedStorage.objects(S).filter(predicate).toArray() } callback?(StoreResult.Success(objs ?? [])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not load objects of type \(S.self)", callback: callback) } public func loadAll<S:Storable>( dispatcher: OperationDispatcher = .Synchronous, callback: (StoreResult<S, DataStoreError> -> Void)?) { let operation = { (usedStorage: Realm) -> Void in var objs: [S]? try usedStorage.write { objs = usedStorage.objects(S).toArray() } callback?(StoreResult.Success(objs ?? [])) } doOperation(operation, dispatcher: dispatcher, errorMessage: "Could not load objects of type \(S.self)", callback: callback) } // MARK: Private private func doOperation<S:Storable>(operation: Realm throws -> Void, dispatcher: OperationDispatcher, errorMessage: String, callback: (StoreResult<S, DataStoreError> -> Void)?) -> Void { do { let usedStorage = try T.internalStorage() let transactionBlock = { do { try operation(usedStorage) } catch _ { callback?(StoreResult.Failure(DataStoreError.StorageOperationError(errorMessage))) } } // Dispatch operation dispatcher.dispatch(transactionBlock) } catch let error { callback?(StoreResult.Failure(error)) } } }
mit
16dbcdf9a883d1dc6538383023137a30
27.908425
191
0.567609
4.85899
false
false
false
false
ddki/my_study_project
language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/SimpleTunnel/StringListController.swift
1
2714
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the StringListController class, which controls a list of strings. */ import UIKit /// A view controller of a view that displays an editable list of strings. class StringListController: ListViewController { // MARK: Properties /// The current list of strings. var targetStrings = [String]() /// The text to display in the "add a string" text field. var addText: String? /// The title to display for the list. var listTitle: String? /// The block to execute when the list of strings changes. var stringsChangedHandler: ([String]) -> Void = { strings in return } /// A table view cell containing a text field used to enter new strings to be added to the list. @IBOutlet weak var addStringCell: TextFieldCell! /// The number of strings in the list. override var listCount: Int { return targetStrings.count } /// Returns UITableViewCellSelectionStyle.None override var listCellSelectionStyle: UITableViewCellSelectionStyle { return .none } // MARK: UIViewController /// Handle the event when the view is loaded into memory. override func viewDidLoad() { isAddEnabled = true isAlwaysEditing = true addStringCell.valueChanged = { guard let enteredText = self.addStringCell.textField.text else { return } self.targetStrings.append(enteredText) self.listInsertItemAtIndex(self.targetStrings.count - 1) self.addStringCell.textField.text = "" self.stringsChangedHandler(self.targetStrings) } // Set addStringCell as a custom "add a new item" cell. addCell = addStringCell super.viewDidLoad() } /// Handle the event when the view is being displayed. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) addStringCell.textField.placeholder = addText navigationItem.title = listTitle } // MARK: ListViewController /// Return the string at the given index. override func listTextForItemAtIndex(_ index: Int) -> String { return targetStrings[index] } /// Remove the string at the given index. override func listRemoveItemAtIndex(_ index: Int) { targetStrings.remove(at: index) stringsChangedHandler(targetStrings) } // MARK: Interface /// Set the list of strings, the title to display for the list, the text used to prompt the user for a new string, and a block to execute when the list of strings changes. func setTargetStrings(_ strings: [String]?, title: String, addTitle: String, saveHandler: @escaping ([String]) -> Void) { targetStrings = strings ?? [String]() listTitle = title addText = addTitle stringsChangedHandler = saveHandler } }
mit
b007f56f04e0be3aba324a92e299de60
28.478261
172
0.74115
3.982379
false
false
false
false
KikurageChan/SimpleConsoleView
SimpleConsoleView/Classes/Views/Tools/HideButton.swift
1
838
// // HideButton.swift // SimpleConsoleView // // Created by 木耳ちゃん on 2017/01/12. // Copyright © 2017年 木耳ちゃん. All rights reserved. // import UIKit final class HideButton: UIButton { var upImage = UIImage(named: "Hide_up", in: Bundle(for: DotImageView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) var downImage = UIImage(named: "Hide_down", in: Bundle(for: DotImageView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) var isPressed = false { didSet { let image = isPressed ? upImage : downImage setImage(image, for: .normal) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setImage(downImage, for: .normal) tintColor = UIColor(hex: 0x979797) } }
mit
d00e4bb7793b9362c3f9bb7fb4bff487
28.107143
140
0.645399
3.899522
false
false
false
false
DDSSwiftTech/SwiftGtk
Sources/Value.swift
2
1604
// // Copyright © 2016 Tomas Linhart. All rights reserved. // import CGtk // This is from GLib and one day could be moved to GLib binding. It also not very perfect because original GValue heavily depends on macros that are not available in Swift. It might be best to introduce Object superclass and define these methods on it. func getProperty(_ pointer: UnsafeMutablePointer<GObject>?, name: String) -> Bool { var v = GValue() let type = GType(5 << G_TYPE_FUNDAMENTAL_SHIFT) let value = g_value_init(&v, type) g_object_get_property(UnsafeMutablePointer(pointer), name, value) return g_value_get_boolean(value).toBool() } func setProperty(_ pointer: UnsafeMutablePointer<GObject>?, name: String, newValue: Bool) { var v = GValue() let type = GType(5 << G_TYPE_FUNDAMENTAL_SHIFT) let value = g_value_init(&v, type) g_value_set_boolean(value, newValue.toGBoolean()) g_object_set_property(UnsafeMutablePointer(pointer), name, value) } func getProperty(_ pointer: UnsafeMutablePointer<GObject>?, name: String) -> Int { var v = GValue() let type = GType(6 << G_TYPE_FUNDAMENTAL_SHIFT) let value = g_value_init(&v, type) g_object_get_property(UnsafeMutablePointer(pointer), name, value) return Int(g_value_get_int(value)) } func setProperty(_ pointer: UnsafeMutablePointer<GObject>?, name: String, newValue: Int) { var v = GValue() let type = GType(6 << G_TYPE_FUNDAMENTAL_SHIFT) let value = g_value_init(&v, type) g_value_set_int(value, gint(newValue)) g_object_set_property(UnsafeMutablePointer(pointer), name, value) }
mit
7aceb1c19083ba4d14d70c4a8c8b03ff
40.102564
252
0.705552
3.626697
false
false
false
false
huonw/swift
test/decl/ext/generic.swift
3
3642
// RUN: %target-typecheck-verify-swift protocol P1 { associatedtype AssocType } protocol P2 : P1 { } protocol P3 { } struct X<T : P1, U : P2, V> { struct Inner<A, B : P3> { } struct NonGenericInner { } } extension Int : P1 { typealias AssocType = Int } extension Double : P2 { typealias AssocType = Double } extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} typealias GGG = X<Int, Double, String> extension GGG { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { let x = 0 } extension LValueCheck { init(newY: Int) { x = 42 } } // Member type references into another extension. struct MemberTypeCheckA<T> { } protocol MemberTypeProto { associatedtype AssocType func foo(_ a: AssocType) init(_ assoc: MemberTypeCheckA<AssocType>) } struct MemberTypeCheckB<T> : MemberTypeProto { func foo(_ a: T) {} typealias Element = T var t1: T } extension MemberTypeCheckB { typealias Underlying = MemberTypeCheckA<T> } extension MemberTypeCheckB { init(_ x: Underlying) { } } extension MemberTypeCheckB { var t2: Element { return t1 } } // rdar://problem/19795284 extension Array { var pairs: [(Element, Element)] { get { return [] } } } // rdar://problem/21001937 struct GenericOverloads<T, U> { var t: T var u: U init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 0 } subscript (i: Int) -> Int { return i } } extension GenericOverloads where T : P1, U : P2 { init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 1 } subscript (i: Int) -> Int { return i } } extension Array where Element : Hashable { var worseHashEver: Int { var result = 0 for elt in self { result = (result << 1) ^ elt.hashValue } return result } } func notHashableArray<T>(_ x: [T]) { x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}} } func hashableArray<T : Hashable>(_ x: [T]) { // expected-warning @+1 {{unused}} x.worseHashEver // okay } func intArray(_ x: [Int]) { // expected-warning @+1 {{unused}} x.worseHashEver } class GenericClass<T> { } extension GenericClass where T : Equatable { func foo(_ x: T, y: T) -> Bool { return x == y } } func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) { _ = gc.foo(x, y: y) } func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) { gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}} } extension Array where Element == String { } extension GenericClass : P3 where T : P3 { } extension GenericClass where Self : P3 { } // expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}} // expected-error@-2{{type 'GenericClass<T>' in conformance requirement does not refer to a generic parameter or associated type}} protocol P4 { associatedtype T init(_: T) } protocol P5 { } struct S4<Q>: P4 { init(_: Q) { } } extension S4 where T : P5 {} struct S5<Q> { init(_: Q) { } } extension S5 : P4 {} // rdar://problem/21607421 public typealias Array2 = Array extension Array2 where QQQ : VVV {} // expected-error@-1 {{use of undeclared type 'QQQ'}} // expected-error@-2 {{use of undeclared type 'VVV'}}
apache-2.0
f216aeaf7713db9ada7f8ac027629558
20.423529
181
0.65486
3.292948
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LayoutInspector/LayoutInspector/Classes/UI Layer/LayoutInspectorContainer/LayoutInspectorContainerViewController.swift
2
2605
// // LayoutInspectorContainerViewController.swift // LayoutInspectorExample // // Created by Igor Savynskyi on 12/25/18. // Copyright © 2018 Igor Savynskyi. All rights reserved. // import UIKit import SceneKit class LayoutInspectorContainerViewController: UIViewController { // Props var output: LayoutInspectorViewOutput? private var menuWidget: MenuWidgetProtocol? private var sceneWidget: SceneWidgetProtocol? private var objectInspectionWidget: AttributesManagerProtocol? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() loadWidgets() configureStyles() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier, let segueCase = Segue(rawValue: identifier) else { return } switch segueCase { case .toMenuWidgetViewControler: menuWidget = segue.destination as? MenuWidgetProtocol menuWidget?.delegate = self case .toAttributesWidgetViewController: objectInspectionWidget = segue.destination as? AttributesManagerProtocol case .toSceneWidgetViewController: sceneWidget = segue.destination as? SceneWidgetProtocol sceneWidget?.delegate = self } } // MARK: - Private API private func loadWidgets() { performSegue(withIdentifier: Segue.toMenuWidgetViewControler.rawValue, sender: self) performSegue(withIdentifier: Segue.toAttributesWidgetViewController.rawValue, sender: self) performSegue(withIdentifier: Segue.toSceneWidgetViewController.rawValue, sender: self) } } extension LayoutInspectorContainerViewController: LayoutInspectorViewInput { func rootView() -> UIView { return view } func addNode(_ node: SCNNode) { sceneWidget?.addNode(node) } func removeNode(_ node: SCNNode) { sceneWidget?.removeNode(node) } } extension LayoutInspectorContainerViewController: SceneViewManagerDelegate { func selectedViewMetadataDidUpdate(_ metadata: ViewMetadataProtocol?) { objectInspectionWidget?.renderViewMetadata(metadata) } } extension LayoutInspectorContainerViewController: MenuWidgetDelegate { func didCloseAction() { output?.didCloseAction() } func didResetCameraPositionAction() { sceneWidget?.resetPointOfViewToDefaults() } } extension LayoutInspectorContainerViewController: Themeable { func configureStyles() { view.backgroundColor = .sceneBackground } }
mit
018ce24f2980d39d544aa554bb37c7ec
30
108
0.706989
5.146245
false
false
false
false
urbn/URBNValidator
Example/Example/MasterViewController.swift
1
3540
// // MasterViewController.swift // Example // // Created by Joseph Ridenour on 12/2/15. // Copyright © 2015 URBN. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(_ sender: AnyObject) { objects.insert(Date() as AnyObject, at: 0) let indexPath = IndexPath(row: 0, section: 0) self.tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[(indexPath as NSIndexPath).row] as! Date let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object as AnyObject? controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[(indexPath as NSIndexPath).row] as! Date cell.textLabel!.text = object.description return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
bc78fd1e84224bec7d4511103874afb3
36.648936
144
0.679853
5.453005
false
false
false
false
boxcast/boxcast-sdk-apple
Tests/MockedURLProtocol.swift
1
2162
// // MockedURLProtocol.swift // BoxCast // // Created by Camden Fullmer on 5/15/17. // Copyright © 2017 BoxCast, Inc. All rights reserved. // import Foundation class MockedURLProtocol : URLProtocol { static var mockedData: Data? static var mockedStatusCode: Int? static let mockedHeaders = ["Content-Type" : "application/json; charset=utf-8"] static var requestHandler: ((URLRequest) -> Void)? static var requestDataHandler: ((Data?) -> Void)? override func startLoading() { let request = self.request MockedURLProtocol.requestHandler?(request) if let httpBodyStream = request.httpBodyStream { httpBodyStream.open() let bufferSize = 1024 let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize) let length = httpBodyStream.read(buffer, maxLength: bufferSize) let httpBody = Data(bytes: buffer, count: length) buffer.deallocate() MockedURLProtocol.requestDataHandler?(httpBody) } let client = self.client let statusCode = MockedURLProtocol.mockedStatusCode ?? 200 let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: MockedURLProtocol.mockedHeaders) client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) if let data = MockedURLProtocol.mockedData { client?.urlProtocol(self, didLoad: data) } client?.urlProtocolDidFinishLoading(self) // Reset. MockedURLProtocol.mockedData = nil MockedURLProtocol.requestDataHandler = nil MockedURLProtocol.requestHandler = nil } override func stopLoading() { //noop } override internal class func canInit(with request: URLRequest) -> Bool { return request.url?.scheme == "https" } override internal class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } }
mit
3ccfd52132d0c0391880f2b2592569ff
33.854839
90
0.627025
5.207229
false
false
false
false