repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
futureinapps/FIADatePickerDialog | refs/heads/master | FIADatePickerDialog/UIButton+FIADatePickerDialog.swift | mit | 1 | //
// UIButton+FIAButton.swift
// FIADatePickerDialog
//
// Created by Айрат Галиуллин on 14.12.16.
// Copyright © 2016 Fucher in Apps OOO. All rights reserved.
//
import UIKit
fileprivate var rawPointer: UInt8 = 0
fileprivate var rawPointer_Bool: UInt8 = 1
protocol FIADatePickerDialogActionDelegate {
func submit()
func cancel()
}
extension UIButton {
var delegate:FIADatePickerDialogActionDelegate?{
set{
objc_setAssociatedObject(self, &rawPointer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer) as? FIADatePickerDialogActionDelegate
}
}
var isDatePickerAction:Bool?{
set{
objc_setAssociatedObject(self, &rawPointer_Bool, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer_Bool) as? Bool
}
}
private var defaultBGRColor:UIColor?{
set{
objc_setAssociatedObject(self, &rawPointer_Bool, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer_Bool) as? UIColor
}
}
func submit(_ sender:UIButton!){
guard delegate != nil else {
fatalError("DatePickerDialogActions delegate should not be nil")
}
delegate?.submit()
}
func cancel(_ sender:UIButton!){
guard delegate != nil else {
fatalError("DatePickerDialogActions delegate should not be nil")
}
delegate?.cancel()
}
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isDatePickerAction != nil && isDatePickerAction! {
backgroundColor = UIColor.hexStringToUIColor(hex: "222222",alpha:0.3)
}
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
if isDatePickerAction != nil && isDatePickerAction! {
backgroundColor = UIColor.clear
}
}
}
| 306c1797bfb3b404e915129a21dbea53 | 28.479452 | 118 | 0.6329 | false | false | false | false |
900116/GodEyeClear | refs/heads/master | Classes/Extension/UI/UIScreen+GodEye.swift | mit | 3 | //
// UIScreen+GodEye.swift
// Pods
//
// Created by zixun on 16/12/27.
//
//
import Foundation
extension UIScreen {
class func onscreenFrame() -> CGRect {
return self.main.applicationFrame
}
class func offscreenFrame() -> CGRect {
var frame = self.onscreenFrame()
switch UIApplication.shared.statusBarOrientation {
case .portraitUpsideDown:
frame.origin.y = -frame.size.height
case .landscapeLeft:
frame.origin.x = frame.size.width
case .landscapeRight:
frame.origin.x = -frame.size.width;
default:
frame.origin.y = frame.size.height
}
return frame
}
}
| 3e1f0bdc7947573bb37c8a830a91dd0c | 22.333333 | 58 | 0.594286 | false | false | false | false |
Parallaxer/PhotoBook | refs/heads/master | Sources/Views/InfinitePageView/InfinitePageView.swift | mit | 1 | import Parallaxer
import RxCocoa
import RxSwift
import UIKit
//------------------------------------------------------------------------------------------------------------
// Number of pages: 1
// Number of waypoints: 1 (min/max)
// 0
//(a)
// a
// X <- Left edge interval: [nil]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 2
// Number of waypoints: 1
// 0 1
//(a)
// (a)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 2
// Number of waypoints: 2 (min/max)
// 0 1
//(a)b
// a(b)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 3
// Number of waypoints: 3 (min/max)
// 0 1 2
//(a)b c
// a(b)c
// a b(c)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// [ ] <- Right edge interval: [1,2]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 4
// Number of waypoints: 3 (min)
// 0 1 2 3
//(a)b c
// a(b)c
// b(c)a
// [ ] <- Left edge interval: [0,1]
// [ ] <- Wrapping interval: [1,2]
// [ ] <- Right edge interval: [2,3]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 3 (min)
// 0 1 2 3 4
//(a)b c
// a(b)c
// . b(c)a
// . . c(a)b
// c a(b)
// [ ] <- Left edge interval: [0,1]
// [ ] <- Wrapping interval: [1,3]
// [ ] <- Right edge interval: [3,4]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 4
// 0 1 2 3 4
//(a)b c d
// a(b)c d
// a b(c)d
// . b c(d)a
// b c d(a)
// [ ] <- Left edge interval: [0,2]
// [ ] <- Wrapping interval: [2,3]
// [ ] <- Right edge interval: [3,4]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 5 (max)
// 0 1 2 3 4
//(a)b c d e
// a(b)c d e
// a b(c)d e
// a b c(d)e
// a b c d(e)
// [ ] <- Left edge interval: [0,2]
// X <- Wrapping interval: [nil]
// [ ] <- Right edge interval: [2,4]
/// Used for the "cursor" and "waypoint" views in an `InfinitePageView`.
final class CircleView: UIView {
/// The circle's scale transform.
var scaleTransform: CGAffineTransform = .identity {
didSet { updateTransform() }
}
/// The circle's translation transform.
var translationTransform: CGAffineTransform = .identity {
didSet { updateTransform() }
}
private func updateTransform() {
transform = scaleTransform.concatenating(translationTransform)
}
}
@IBDesignable
public final class InfinitePageView: UIView {
// The total number of pages the view can represent. Set this equal to the number of pages in your table
// view or collection view.
@IBInspectable
public var numberOfPages: Int {
get { numberOfPagesRelay.value }
set {
numberOfPagesRelay.accept(newValue)
buildUI()
}
}
/// The maximum number of waypoints shown in the view at one time. For best results, use an odd number
/// so that the middle waypoint is rendered at the center of the view.
@IBInspectable
public var maxNumberOfWaypoints: Int {
get { maxNumberOfWaypointsRelay.value }
set {
maxNumberOfWaypointsRelay.accept(newValue)
buildUI()
}
}
private(set) var waypointViews: [CircleView] = []
private(set) weak var cursorView: CircleView?
/// The current cursor position.
var cursorPosition: CGFloat = 0 {
didSet {
let translation = CGAffineTransform(translationX: cursorPosition, y: 0)
cursorView?.translationTransform = translation
}
}
/// The current cursor size.
var cursorScale: CGFloat = 1 {
didSet {
let scale = CGAffineTransform(scaleX: cursorScale, y: cursorScale)
cursorView?.scaleTransform = scale
}
}
private let numberOfPagesRelay = BehaviorRelay<Int>(value: 0)
private let maxNumberOfWaypointsRelay = BehaviorRelay<Int>(value: 5)
private lazy var numberOfWaypoints: Observable<Int> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
maxNumberOfWaypointsRelay.asObservable())
.map { numberOfPages, maxNumberOfWaypoints in
return InfinitePageView.numberOfWaypoints(
numberOfPages: numberOfPages,
maxNumberOfWaypoints: maxNumberOfWaypoints)
}
private lazy var fullPageInterval: Observable<ParallaxInterval<CGFloat>?> = numberOfPagesRelay
.asObservable()
.map { numberOfPages in
let lastPageIndex = CGFloat(numberOfPages - 1)
return try ParallaxInterval<CGFloat>(from: 0, to: lastPageIndex)
}
.share(replay: 1)
/// The left edge interval starts at the first page index and extends to the center waypoint index.
///
/// The left edge interval may be `nil` in the following cases:
/// - The number of pages is 1 or less. (The center page index and the first page index are equal.)
private lazy var leftEdgeInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
numberOfWaypoints)
.map { numberOfPages, numberOfWaypoints -> ParallaxInterval<CGFloat>? in
let firstPageIndex = CGFloat(0)
let centerPageIndex =
CGFloat(InfinitePageView.indexOfCenterWaypoint(numberOfWaypoints: numberOfWaypoints))
return try ParallaxInterval<CGFloat>(from: firstPageIndex, to: centerPageIndex)
}
.share(replay: 1)
/// The wrapping interval starts where the left edge interval stopped and extends over the number of
/// wrapped indices (the difference between the number of pages and the number of waypoints.)
///
/// The wrapping interval may be `nil` in the following cases:
/// - The left edge interval is `nil`.
/// - The number of wrapped indices is 0. (The number of pages and the number of waypoints are equal.)
private lazy var wrappingInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
numberOfWaypoints,
leftEdgeInterval)
.map { numberOfPages, numberOfWaypoints, leftEdgeInterval -> ParallaxInterval<CGFloat>? in
guard let leftEdgeInterval = leftEdgeInterval else {
return nil
}
let numberOfWrappedIndices = CGFloat(numberOfPages - numberOfWaypoints)
return try ParallaxInterval<CGFloat>(
from: leftEdgeInterval.to,
to: leftEdgeInterval.to + numberOfWrappedIndices)
}
.share(replay: 1)
/// The right edge interval starts where either the wrapping interval or the left edge interval stopped
/// and extends to the last page index.
///
/// The right edge interval may be `nil` in the following cases:
/// - The left edge interval is `nil`.
/// - The left edge interval extends to the last page index.
private lazy var rightEdgeInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
leftEdgeInterval,
wrappingInterval)
.map { numberOfPages, leftEdgeInterval, wrappingInterval -> ParallaxInterval<CGFloat>? in
guard let leftEdgeInterval = leftEdgeInterval else {
return nil
}
let lastPageIndex = CGFloat(numberOfPages - 1)
return try ParallaxInterval<CGFloat>(
from: wrappingInterval?.to ?? leftEdgeInterval.to,
to: lastPageIndex)
}
.share(replay: 1)
public override func awakeFromNib() {
super.awakeFromNib()
buildUI()
}
public override func layoutSubviews() {
super.layoutSubviews()
let circleRadius = waypointRadius
guard circleRadius.isFinite else {
return
}
let circleDiameter = 2 * circleRadius
let circleSize = CGSize(width: circleDiameter, height: circleDiameter)
let midY = bounds.midY
waypointViews.enumerated().forEach { i, circleView in
let waypointPosition = InfinitePageView.positionForWaypoint(at: i, radius: circleRadius)
circleView.center = CGPoint(x: waypointPosition, y: midY)
circleView.bounds.size = circleSize
circleView.bounds = circleView.bounds.integral
circleView.layer.cornerRadius = circleRadius
}
let cursorPosition = InfinitePageView.positionForWaypoint(at: 0, radius: circleRadius)
cursorView?.center = CGPoint(x: cursorPosition, y: midY)
cursorView?.bounds.size = circleSize
if let bounds = cursorView?.bounds.integral {
cursorView?.bounds = bounds
}
cursorView?.layer.cornerRadius = circleRadius
}
private func buildUI() {
cursorView?.removeFromSuperview()
waypointViews.forEach { $0.removeFromSuperview() }
waypointViews = (0 ..< numberOfWaypointsValue).map { _ in
InfinitePageView.createCircleView(isWaypoint: true)
}
waypointViews.forEach(addSubview)
let cursorView = InfinitePageView.createCircleView(isWaypoint: false)
addSubview(cursorView)
bringSubviewToFront(cursorView)
self.cursorView = cursorView
// Force immediate layout.
setNeedsLayout()
layoutIfNeeded()
}
private static func createCircleView(isWaypoint: Bool) -> CircleView {
let circleView = CircleView()
circleView.backgroundColor = isWaypoint ? UIColor.init(white: 1, alpha: 0.5) : UIColor.white
return circleView
}
}
extension InfinitePageView {
/// Bind the scrolling transform to the page view, allowing changes to the scrolling transform to drive
/// changes to state in the page view.
/// - Parameter scrollingTransform: The scrolling transform which should drive state changes in the page
/// view.
func bindScrollingTransform(_ scrollingTransform: Observable<ParallaxTransform<CGFloat>>) -> Disposable {
let leftEdgeTransform = self.leftEdgeTransform(from: scrollingTransform)
let rightEdgeTransform = self.rightEdgeTransform(from: scrollingTransform)
let wrappingTransform = self.wrappingTransform(from: scrollingTransform)
return Disposables.create([
bindCursorEffect(
with: scrollingTransform,
leftEdgeTransform: leftEdgeTransform,
rightEdgeTransform: rightEdgeTransform),
bindWrappingEffect(
with: scrollingTransform,
wrappingInterval: wrappingInterval,
wrappingTransform: wrappingTransform),
bindWaypointEffect(with: scrollingTransform)
])
}
private func leftEdgeTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: leftEdgeInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
private func wrappingTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: wrappingInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
private func rightEdgeTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: rightEdgeInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
}
extension InfinitePageView {
var waypointRadius: CGFloat {
let diameter = floor(bounds.width / CGFloat(numberOfWaypointsValue))
return floor(diameter / 2)
}
var numberOfWaypointsValue: Int {
return InfinitePageView.numberOfWaypoints(
numberOfPages: numberOfPagesRelay.value,
maxNumberOfWaypoints: maxNumberOfWaypointsRelay.value)
}
}
extension InfinitePageView {
var firstWaypointPosition: CGFloat {
let firstIndex = 0
return InfinitePageView.positionForWaypoint(at: firstIndex, radius: waypointRadius)
}
var centerWaypointPosition: CGFloat {
let centerIndex = InfinitePageView.indexOfCenterWaypoint(numberOfWaypoints: numberOfWaypointsValue)
return InfinitePageView.positionForWaypoint(at: centerIndex, radius: waypointRadius)
}
var lastWaypointPosition: CGFloat {
let lastIndex = numberOfWaypointsValue - 1
return InfinitePageView.positionForWaypoint(at: lastIndex, radius: waypointRadius)
}
static func numberOfWaypoints(numberOfPages: Int, maxNumberOfWaypoints: Int) -> Int {
return min(numberOfPages, maxNumberOfWaypoints)
}
private static func indexOfCenterWaypoint(numberOfWaypoints: Int) -> Int {
return numberOfWaypoints / 2
}
static func positionForWaypoint(at index: Int, radius: CGFloat) -> CGFloat {
let diameter = 2 * radius
return radius + (CGFloat(index) * (diameter))
}
}
| 715c2b9e89cb8cffe86c8b5735405304 | 35.952381 | 110 | 0.586679 | false | false | false | false |
IBM-Swift/Kitura | refs/heads/master | Sources/Kitura/staticFileServer/FileServer.swift | apache-2.0 | 1 | /*
* Copyright IBM Corporation 2016
*
* 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 LoggerAPI
import Foundation
extension StaticFileServer {
// MARK: FileServer
class FileServer {
/// Serve "index.html" files in response to a request on a directory.
private let serveIndexForDirectory: Bool
/// Redirect to trailing "/" when the pathname is a dir.
private let redirect: Bool
/// the path from where the files are served
private let servingFilesPath: String
/// If a file is not found, the given extensions will be added to the file name and searched for.
/// The first that exists will be served.
private let possibleExtensions: [String]
/// A setter for response headers.
private let responseHeadersSetter: ResponseHeadersSetter?
/// Whether accepts range requests or not
let acceptRanges: Bool
/// A default index to be served if the requested path is not found.
/// This is intended to be used by single page applications.
let defaultIndex: String?
init(servingFilesPath: String, options: StaticFileServer.Options,
responseHeadersSetter: ResponseHeadersSetter?) {
self.possibleExtensions = options.possibleExtensions
self.serveIndexForDirectory = options.serveIndexForDirectory
self.redirect = options.redirect
self.acceptRanges = options.acceptRanges
self.servingFilesPath = servingFilesPath
self.responseHeadersSetter = responseHeadersSetter
self.defaultIndex = options.defaultIndex
}
func getFilePath(from request: RouterRequest) -> String? {
var filePath = servingFilesPath
guard let requestPath = request.parsedURLPath.path else {
return nil
}
var matchedPath = request.matchedPath
if matchedPath.hasSuffix("*") {
matchedPath = String(matchedPath.dropLast())
}
if !matchedPath.hasSuffix("/") {
matchedPath += "/"
}
if requestPath.hasPrefix(matchedPath) {
filePath += "/"
let url = String(requestPath.dropFirst(matchedPath.count))
if let decodedURL = url.removingPercentEncoding {
filePath += decodedURL
} else {
Log.warning("unable to decode url \(url)")
filePath += url
}
}
if filePath.hasSuffix("/") {
if serveIndexForDirectory {
filePath += "index.html"
} else {
return nil
}
}
return filePath
}
func serveFile(_ filePath: String, requestPath: String, queryString: String, response: RouterResponse) {
let fileManager = FileManager()
var isDirectory = ObjCBool(false)
if fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
serveExistingFile(filePath, requestPath: requestPath, queryString: queryString,
isDirectory: isDirectoryBool, response: response)
return
}
if tryToServeWithExtensions(filePath, response: response) {
return
}
// We haven't been able to find the requested path. For single page applications,
// a default fallback index may be configured. Before we serve the default index
// we make sure that this is a not a direct file request. The best check we could
// run for that is if the requested file contains a '.'. This is inspired by:
// https://github.com/bripkens/connect-history-api-fallback
let isDirectFileAccess = filePath.split(separator: "/").last?.contains(".") ?? false
if isDirectFileAccess == false, let defaultIndex = self.defaultIndex {
serveDefaultIndex(defaultIndex: defaultIndex, response: response)
}
}
fileprivate func serveDefaultIndex(defaultIndex: String, response: RouterResponse) {
do {
try response.send(fileName: servingFilesPath + defaultIndex)
} catch {
response.error = Error.failedToRedirectRequest(path: servingFilesPath + "/", chainedError: error)
}
}
private func tryToServeWithExtensions(_ filePath: String, response: RouterResponse) -> Bool {
var served = false
let filePathWithPossibleExtensions = possibleExtensions.map { filePath + "." + $0 }
for filePathWithExtension in filePathWithPossibleExtensions {
served = served || serveIfNonDirectoryFile(atPath: filePathWithExtension, response: response)
}
return served
}
private func serveExistingFile(_ filePath: String, requestPath: String, queryString: String,
isDirectory: Bool, response: RouterResponse) {
if isDirectory {
if redirect {
do {
try response.redirect(requestPath + "/" + queryString)
} catch {
response.error = Error.failedToRedirectRequest(path: requestPath + "/", chainedError: error)
}
}
} else {
serveNonDirectoryFile(filePath, response: response)
}
}
@discardableResult
private func serveIfNonDirectoryFile(atPath path: String, response: RouterResponse) -> Bool {
var isDirectory = ObjCBool(false)
if FileManager().fileExists(atPath: path, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
if !isDirectoryBool {
serveNonDirectoryFile(path, response: response)
return true
}
}
return false
}
private func serveNonDirectoryFile(_ filePath: String, response: RouterResponse) {
if !isValidFilePath(filePath) {
return
}
do {
let fileAttributes = try FileManager().attributesOfItem(atPath: filePath)
// At this point only GET or HEAD are expected
let request = response.request
let method = request.serverRequest.method
response.headers["Accept-Ranges"] = acceptRanges ? "bytes" : "none"
responseHeadersSetter?.setCustomResponseHeaders(response: response,
filePath: filePath,
fileAttributes: fileAttributes)
// Check headers to see if it is a Range request
if acceptRanges,
method == "GET", // As per RFC, Only GET request can be Range Request
let rangeHeader = request.headers["Range"],
RangeHeader.isBytesRangeHeader(rangeHeader),
let fileSize = (fileAttributes[FileAttributeKey.size] as? NSNumber)?.uint64Value {
// At this point it looks like the client requested a Range Request
if let rangeHeaderValue = try? RangeHeader.parse(size: fileSize, headerValue: rangeHeader),
rangeHeaderValue.type == "bytes",
!rangeHeaderValue.ranges.isEmpty {
// At this point range is valid and server is able to serve it
if ifRangeHeaderShouldPreventPartialReponse(requestHeaders: request.headers, fileAttributes: fileAttributes) {
// If-Range header prevented a partial response. Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
} else {
// Send a partial response
serveNonDirectoryPartialFile(filePath, fileSize: fileSize, ranges: rangeHeaderValue.ranges, response: response)
}
} else {
// Send not satisfiable response
serveNotSatisfiable(filePath, fileSize: fileSize, response: response)
}
} else {
// Regular request OR Syntactically invalid range request OR fileSize was not available
if method == "HEAD" {
// Send only headers
_ = response.send(status: .OK)
} else {
if let etag = request.headers["If-None-Match"],
etag == CacheRelatedHeadersSetter.calculateETag(from: fileAttributes) {
response.statusCode = .notModified
} else {
// Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
}
}
}
} catch {
Log.error("serving file at path \(filePath), error: \(error)")
}
}
private func isValidFilePath(_ filePath: String) -> Bool {
guard let absoluteBasePath = NSURL(fileURLWithPath: servingFilesPath).standardizingPath?.absoluteString,
let standardisedPath = NSURL(fileURLWithPath: filePath).standardizingPath?.absoluteString else {
return false
}
return standardisedPath.hasPrefix(absoluteBasePath)
}
private func serveNotSatisfiable(_ filePath: String, fileSize: UInt64, response: RouterResponse) {
response.headers["Content-Range"] = "bytes */\(fileSize)"
_ = response.send(status: .requestedRangeNotSatisfiable)
}
private func serveNonDirectoryPartialFile(_ filePath: String, fileSize: UInt64, ranges: [Range<UInt64>], response: RouterResponse) {
let contentType = ContentType.sharedInstance.getContentType(forFileName: filePath)
if ranges.count == 1 {
let data = FileServer.read(contentsOfFile: filePath, inRange: ranges[0])
// Send a single part response
response.headers["Content-Type"] = contentType
response.headers["Content-Range"] = "bytes \(ranges[0].lowerBound)-\(ranges[0].upperBound)/\(fileSize)"
response.send(data: data ?? Data())
response.statusCode = .partialContent
} else {
// Send multi part response
let boundary = "KituraBoundary\(UUID().uuidString)" // Maybe a better boundary can be calculated in the future
response.headers["Content-Type"] = "multipart/byteranges; boundary=\(boundary)"
var data = Data()
ranges.forEach { range in
let fileData = FileServer.read(contentsOfFile: filePath, inRange: range) ?? Data()
var partHeader = "--\(boundary)\r\n"
partHeader += "Content-Range: bytes \(range.lowerBound)-\(range.upperBound)/\(fileSize)\r\n"
partHeader += (contentType == nil ? "" : "Content-Type: \(contentType!)\r\n")
partHeader += "\r\n"
data.append(Data(partHeader.utf8))
data.append(fileData)
data.append(Data("\r\n".utf8))
}
data.append(Data("--\(boundary)--".utf8))
response.send(data: data)
response.statusCode = .partialContent
}
}
private func ifRangeHeaderShouldPreventPartialReponse(requestHeaders headers: Headers, fileAttributes: [FileAttributeKey : Any]) -> Bool {
// If-Range is optional
guard let ifRange = headers["If-Range"], !ifRange.isEmpty else {
return false
}
// If-Range can be one of two values: ETag or Last-Modified but not both.
// If-Range as ETag
if (ifRange.contains("\"")) {
if let etag = CacheRelatedHeadersSetter.calculateETag(from: fileAttributes),
!etag.isEmpty,
ifRange.contains(etag) {
return false
}
return true
}
// If-Range as Last-Modified
if let ifRangeLastModified = FileServer.date(from: ifRange),
let lastModified = fileAttributes[FileAttributeKey.modificationDate] as? Date,
floor(lastModified.timeIntervalSince1970) > floor(ifRangeLastModified.timeIntervalSince1970) {
return true
}
return false
}
/// Helper function to convert http date Strings into Date
static func date(from httpDate: String) -> Date? {
let df = DateFormatter()
df.dateFormat = "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"
return df.date(from:httpDate)
}
/// Helper function to read bytes (of a given range) of a file into data
static func read(contentsOfFile filePath: String, inRange range: Range<UInt64>) -> Data? {
let file = FileHandle(forReadingAtPath: filePath)
file?.seek(toFileOffset: range.lowerBound)
// range is inclusive to make sure to increate upper bound by 1
let data = file?.readData(ofLength: range.count + 1)
file?.closeFile()
return data
}
}
}
| 73a0d59d8a5611ac0adfee37102c20e6 | 45.591195 | 146 | 0.560813 | false | false | false | false |
chenchangqing/CQTextField | refs/heads/master | Pod/Classes/CQPasswordTextField.swift | mit | 1 | //
// CQPasswordTextField.swift
// Pods
//
// Created by green on 15/12/17.
//
//
import UIKit
@IBDesignable public class CQPasswordTextField: CQCutLineTextField {
// 密码可见按钮
private let eyeButton = UIButton()
// 密码可见按钮选中颜色
@IBInspectable dynamic var eyeImageColor:UIColor = UIColor.magenta {
didSet {
updateOpenEyeImage()
}
}
// 闭眼图片
@IBInspectable dynamic var closeEyeImage:UIImage? {
didSet {
updateCloseEyeImage()
}
}
// 睁眼图片
@IBInspectable dynamic var eyeImage:UIImage? {
didSet {
updateOpenEyeImage()
}
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
eyeButton.frame = rightView.bounds
rightView.addSubview(eyeButton)
eyeButton.addTarget(self, action: #selector(CQPasswordTextField.eyeButtonClicked(_:)), for: .touchUpInside)
// 文本框
textField.isSecureTextEntry = true
}
func eyeButtonClicked(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
textField.isSecureTextEntry = false
} else {
textField.isSecureTextEntry = true
}
}
func updateOpenEyeImage() {
if let eyeImage = eyeImage {
eyeButton.tintColor = eyeImageColor
let tempImage = scaleImage(eyeImage, toScale: 0.5).withRenderingMode(.alwaysTemplate)
eyeButton.setImage(tempImage, for: .selected)
}
}
func updateCloseEyeImage() {
if let closeEyeImage = closeEyeImage {
let tempImage = scaleImage(closeEyeImage, toScale: 0.5)
eyeButton.setImage(tempImage, for: UIControlState())
}
}
}
| 681738248b0d1e91da1c8b4bf6654de7 | 23.487179 | 115 | 0.563351 | false | false | false | false |
jpsim/Yams | refs/heads/main | Sources/Yams/Tag.swift | mit | 1 | //
// Tag.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
/// Tags describe the the _type_ of a Node.
public final class Tag {
/// Tag name.
public struct Name: RawRepresentable, Hashable {
/// This `Tag.Name`'s raw string value.
public let rawValue: String
/// Create a `Tag.Name` with a raw string value.
public init(rawValue: String) {
self.rawValue = rawValue
}
}
/// Shorthand accessor for `Tag(.implicit)`.
public static var implicit: Tag {
return Tag(.implicit)
}
/// Create a `Tag` with the specified name, resolver and constructor.
///
/// - parameter name: Tag name.
/// - parameter resolver: `Resolver` this tag should use, `.default` if omitted.
/// - parameter constructor: `Constructor` this tag should use, `.default` if omitted.
public init(_ name: Name,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) {
self.resolver = resolver
self.constructor = constructor
self.name = name
}
/// Lens returning a copy of the current `Tag` with the specified overridden changes.
///
/// - note: Omitting or passing nil for a parameter will preserve the current `Tag`'s value in the copy.
///
/// - parameter name: Overridden tag name.
/// - parameter resolver: Overridden resolver.
/// - parameter constructor: Overridden constructor.
///
/// - returns: A copy of the current `Tag` with the specified overridden changes.
public func copy(with name: Name? = nil, resolver: Resolver? = nil, constructor: Constructor? = nil) -> Tag {
return .init(name ?? self.name, resolver ?? self.resolver, constructor ?? self.constructor)
}
// internal
let constructor: Constructor
var name: Name
fileprivate func resolved<T>(with value: T) -> Tag where T: TagResolvable {
if name == .implicit {
name = resolver.resolveTag(of: value)
} else if name == .nonSpecific {
name = T.defaultTagName
}
return self
}
// private
private let resolver: Resolver
}
extension Tag: CustomStringConvertible {
/// A textual representation of this tag.
public var description: String {
return name.rawValue
}
}
extension Tag: Hashable {
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
/// :nodoc:
public static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.name == rhs.name
}
}
extension Tag.Name: ExpressibleByStringLiteral {
/// :nodoc:
public init(stringLiteral value: String) {
self.rawValue = value
}
}
// http://www.yaml.org/spec/1.2/spec.html#Schema
extension Tag.Name {
// Special
/// Tag should be resolved by value.
public static let implicit: Tag.Name = ""
/// Tag should not be resolved by value, and be resolved as .str, .seq or .map.
public static let nonSpecific: Tag.Name = "!"
// Failsafe Schema
/// "tag:yaml.org,2002:str" <http://yaml.org/type/str.html>
public static let str: Tag.Name = "tag:yaml.org,2002:str"
/// "tag:yaml.org,2002:seq" <http://yaml.org/type/seq.html>
public static let seq: Tag.Name = "tag:yaml.org,2002:seq"
/// "tag:yaml.org,2002:map" <http://yaml.org/type/map.html>
public static let map: Tag.Name = "tag:yaml.org,2002:map"
// JSON Schema
/// "tag:yaml.org,2002:bool" <http://yaml.org/type/bool.html>
public static let bool: Tag.Name = "tag:yaml.org,2002:bool"
/// "tag:yaml.org,2002:float" <http://yaml.org/type/float.html>
public static let float: Tag.Name = "tag:yaml.org,2002:float"
/// "tag:yaml.org,2002:null" <http://yaml.org/type/null.html>
public static let null: Tag.Name = "tag:yaml.org,2002:null"
/// "tag:yaml.org,2002:int" <http://yaml.org/type/int.html>
public static let int: Tag.Name = "tag:yaml.org,2002:int"
// http://yaml.org/type/index.html
/// "tag:yaml.org,2002:binary" <http://yaml.org/type/binary.html>
public static let binary: Tag.Name = "tag:yaml.org,2002:binary"
/// "tag:yaml.org,2002:merge" <http://yaml.org/type/merge.html>
public static let merge: Tag.Name = "tag:yaml.org,2002:merge"
/// "tag:yaml.org,2002:omap" <http://yaml.org/type/omap.html>
public static let omap: Tag.Name = "tag:yaml.org,2002:omap"
/// "tag:yaml.org,2002:pairs" <http://yaml.org/type/pairs.html>
public static let pairs: Tag.Name = "tag:yaml.org,2002:pairs"
/// "tag:yaml.org,2002:set". <http://yaml.org/type/set.html>
public static let set: Tag.Name = "tag:yaml.org,2002:set"
/// "tag:yaml.org,2002:timestamp" <http://yaml.org/type/timestamp.html>
public static let timestamp: Tag.Name = "tag:yaml.org,2002:timestamp"
/// "tag:yaml.org,2002:value" <http://yaml.org/type/value.html>
public static let value: Tag.Name = "tag:yaml.org,2002:value"
/// "tag:yaml.org,2002:yaml" <http://yaml.org/type/yaml.html> We don't support this.
public static let yaml: Tag.Name = "tag:yaml.org,2002:yaml"
}
protocol TagResolvable {
var tag: Tag { get }
static var defaultTagName: Tag.Name { get }
func resolveTag(using resolver: Resolver) -> Tag.Name
}
extension TagResolvable {
var resolvedTag: Tag {
return tag.resolved(with: self)
}
func resolveTag(using resolver: Resolver) -> Tag.Name {
return tag.name == .implicit ? Self.defaultTagName : tag.name
}
}
| d96ce62f5ec368a11cf4accef08d0c47 | 35.967105 | 113 | 0.629293 | false | false | false | false |
zenghaojim33/BeautifulShop | refs/heads/master | BeautifulShop/BeautifulShop/Charts/Charts/BarLineChartViewBase.swift | apache-2.0 | 1 | //
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation;
import UIKit;
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values.
public var highlightIndicatorEnabled = true
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _doubleTapGestureRecognizer: UITapGestureRecognizer!
private var _pinchGestureRecognizer: UIPinchGestureRecognizer!
private var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
internal override func initialize()
{
super.initialize();
_leftAxis = ChartYAxis(position: .Left);
_rightAxis = ChartYAxis(position: .Right);
_xAxis = ChartXAxis();
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer);
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer);
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer);
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"));
_doubleTapGestureRecognizer.numberOfTapsRequired = 2;
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"));
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"));
_pinchGestureRecognizer.delegate = self;
_panGestureRecognizer.delegate = self;
self.addGestureRecognizer(_tapGestureRecognizer);
if (_doubleTapToZoomEnabled)
{
self.addGestureRecognizer(_doubleTapGestureRecognizer);
}
updateScaleGestureRecognizers();
if (_dragEnabled)
{
self.addGestureRecognizer(_panGestureRecognizer);
}
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect);
if (_dataNotSet)
{
return;
}
let context = UIGraphicsGetCurrentContext();
if (xAxis.isAdjustXLabelsEnabled)
{
calcModulus();
}
// execute all drawing commands
drawGridBackground(context: context);
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
}
_xAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_leftYAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_rightYAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_xAxisRenderer?.renderAxisLine(context: context);
_leftYAxisRenderer?.renderAxisLine(context: context);
_rightYAxisRenderer?.renderAxisLine(context: context);
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context);
CGContextClipToRect(context, _viewPortHandler.contentRect);
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
_xAxisRenderer?.renderGridLines(context: context);
_leftYAxisRenderer?.renderGridLines(context: context);
_rightYAxisRenderer?.renderGridLines(context: context);
renderer?.drawData(context: context);
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
// if highlighting is enabled
if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight);
}
// Removes clipping rectangle
CGContextRestoreGState(context);
renderer!.drawExtras(context: context);
_xAxisRenderer.renderAxisLabels(context: context);
_leftYAxisRenderer.renderAxisLabels(context: context);
_rightYAxisRenderer.renderAxisLabels(context: context);
renderer!.drawValues(context: context);
_legendRenderer.renderLegend(context: context);
// drawLegend();
drawMarkers(context: context);
drawDescription(context: context);
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum);
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum);
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted);
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
_leftAxis?._defaultValueFormatter = _defaultValueFormatter;
_rightAxis?._defaultValueFormatter = _defaultValueFormatter;
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals);
_legendRenderer?.computeLegend(_data);
calculateOffsets();
setNeedsDisplay();
}
internal override func calcMinMax()
{
var minLeft = _data.getYMin(.Left);
var maxLeft = _data.getYMax(.Left);
var minRight = _data.getYMin(.Right);
var maxRight = _data.getYMax(.Right);
var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft));
var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight));
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0;
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0;
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0;
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0;
}
}
var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop);
var topSpaceRight = rightRange * Float(_rightAxis.spaceTop);
var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom);
var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom);
_chartXMax = Float(_data.xVals.count - 1);
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft);
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight);
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft);
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight);
// consider starting at zero (0)
if (_leftAxis.isStartAtZeroEnabled)
{
_leftAxis.axisMinimum = 0.0;
}
if (_rightAxis.isStartAtZeroEnabled)
{
_rightAxis.axisMinimum = 0.0;
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum);
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum);
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0);
var offsetRight = CGFloat(0.0);
var offsetTop = CGFloat(0.0);
var offsetBottom = CGFloat(0.0);
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0;
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0;
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
offsetBottom += _legend.textHeightMax * 3.0;
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width;
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width;
}
var xlabelheight = xAxis.labelHeight * 2.0;
if (xAxis.isEnabled)
{
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight;
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight;
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight;
offsetTop += xlabelheight;
}
}
var min = CGFloat(10.0);
_viewPortHandler.restrainViewPort(
offsetLeft: max(min, offsetLeft),
offsetTop: max(min, offsetTop),
offsetRight: max(min*2, offsetRight),
offsetBottom: max(min, offsetBottom));
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil)
{
return;
}
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)));
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1;
}
}
public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
var xPos = CGFloat(entry.xIndex);
if (self.isKindOfClass(BarChartView))
{
var bd = _data as! BarChartData;
var space = bd.groupSpace;
var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true);
var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0;
xPos += x;
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY);
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt);
return pt;
}
/// draws the grid background
internal func drawGridBackground(#context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context);
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor);
CGContextFillRect(context, _viewPortHandler.contentRect);
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth);
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextStrokeRect(context, _viewPortHandler.contentRect);
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context);
}
}
/// Returns the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer;
}
else
{
return _rightAxisTransformer;
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false;
private var _isScaling = false;
private var _gestureScaleAxis = GestureScaleAxis.Both;
private var _closestDataSetToTouch: ChartDataSet!;
/// the last highlighted object
private var _lastHighlighted: ChartHighlight!;
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if (h === nil || h!.isEqual(_lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlighted = nil;
}
else
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom);
}
self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y);
}
}
}
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true;
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both;
}
else
{
var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x);
var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y);
if (x > y)
{
_gestureScaleAxis = .X;
}
else
{
_gestureScaleAxis = .Y;
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isScaling)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom);
}
var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0;
var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0;
var matrix = CGAffineTransformMakeTranslation(location.x, location.y);
matrix = CGAffineTransformScale(matrix, scaleX, scaleY);
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
recognizer.scale = 1.0;
}
}
}
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
if (!_dataNotSet && _dragEnabled && !self.hasNoDragOffset || !self.isFullyZoomedOut)
{
_isDragging = true;
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self));
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
_isDragging = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
var translation = recognizer.translationInView(self);
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x;
}
else
{
translation.y = -translation.y;
}
}
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
recognizer.setTranslation(CGPoint(x: 0.0, y: 0.0), inView: self);
}
}
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true;
}
return false;
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4f, into the charts center. center.
public func zoomIn()
{
var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms out by 0.7f, from the charts center. center.
public func zoomOut()
{
var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in
/// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in
/// :param: x
/// :param: y
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
var matrix = _viewPortHandler.fitScreen();
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX);
_viewPortHandler.setMinimumScaleY(scaleY);
}
/// Sets the size of the area (range on the x-axis) that should be maximum
/// visible at once. If this is e.g. set to 10, no more than 10 values on the
/// x-axis can be viewed at once without scrolling.
public func setVisibleXRange(xRange: CGFloat)
{
var xScale = _deltaX / (xRange);
_viewPortHandler.setMinimumScaleX(xScale);
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// :param: yRange
/// :param: axis - the axis for which this limit should apply
public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
var yScale = getDeltaY(axis) / yRange;
_viewPortHandler.setMinimumScaleY(yScale);
}
/// Moves the left side of the current viewport to the specified x-index.
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0);
getTransformer(.Left).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); });
}
}
/// Centers the viewport to the specified y-value on the y-axis.
///
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); });
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX;
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this.
public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true;
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom);
});
}
}
/// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false;
calculateOffsets();
}
// MARK: - Accessors
/// Returns the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange);
}
else
{
return CGFloat(rightAxis.axisRange);
}
}
/// Returns the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value));
getTransformer(axis).pointValueToPixel(&vals);
return vals;
}
/// the number of maximum visible drawn values on the chart
/// only active when setDrawValues() is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount;
}
set
{
_maxVisibleValueCount = newValue;
}
}
/// If set to true, the highlight indicators (cross of two lines for
/// LineChart and ScatterChart, dark bar overlay for BarChart) that give
/// visual indication that an Entry has been selected will be drawn upon
/// selecting values. This does not depend on the MarkerView.
/// :default: true
public var isHighlightIndicatorEnabled: Bool
{
return highlightIndicatorEnabled;
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled;
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue;
if (_dragEnabled)
{
self.addGestureRecognizer(_panGestureRecognizer);
}
else
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers?[i] === _panGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
}
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled;
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled;
_scaleYEnabled = enabled;
updateScaleGestureRecognizers();
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled;
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue;
if (_doubleTapToZoomEnabled)
{
self.addGestureRecognizer(_doubleTapGestureRecognizer);
}
else
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers?[i] === _doubleTapGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
}
}
}
}
/// :returns: true if zooming via double-tap is enabled false if not.
/// :default: true
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled;
}
/// :returns: true if drawing the grid background is enabled, false if not.
/// :default: true
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled;
}
/// :returns: true if drawing the borders rectangle is enabled, false if not.
/// :default: false
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled;
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.");
return nil;
}
var valPt = CGPoint();
valPt.x = pt.x;
valPt.y = 0.0;
// take any transformer to determine the x-axis value
_leftAxisTransformer.pixelToValue(&valPt);
var xTouchVal = valPt.x;
var base = floor(xTouchVal);
var touchOffset = _deltaX * 0.025;
// touch out of chart
if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset)
{
return nil;
}
if (base < 0.0)
{
base = 0.0;
}
if (base >= _deltaX)
{
base = _deltaX - 1.0;
}
var xIndex = Int(base);
// check if we are more than half of a x-value or not
if (xTouchVal - base > 0.5)
{
xIndex = Int(base + 1.0);
}
var valsAtIndex = getYValsAtIndex(xIndex);
var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left);
var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right);
if (_data!.getFirstRight() === nil)
{
rightdist = FLT_MAX;
}
if (_data!.getFirstLeft() === nil)
{
leftdist = FLT_MAX;
}
var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right;
var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis);
if (dataSetIndex == -1)
{
return nil;
}
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex);
}
/// Returns an array of SelInfo objects for the given x-index. The SelInfo
/// objects give information about the value at the selected index and the
/// DataSet it belongs to.
public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo]
{
var vals = [ChartSelInfo]();
var pt = CGPoint();
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
var dataSet = _data.getDataSetByIndex(i);
if (dataSet === nil)
{
continue;
}
// extract all y-values from all DataSets at the given x-index
var yVal = dataSet!.yValForXIndex(xIndex);
pt.y = CGFloat(yVal);
getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt);
if (!isnan(pt.y))
{
vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!));
}
}
return vals;
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// getPixelsForValues(...).
public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt);
return pt;
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to getValueByTouchPoint(...).
public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y));
getTransformer(axis).pointValueToPixel(&pt);
return pt;
}
/// returns the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y;
}
/// returns the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data!.getEntryForHighlight(h!);
}
return nil;
}
///returns the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!;
}
return nil;
}
/// Returns the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0);
}
/// Returns the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x);
}
/// returns the current x-scale factor
public var scaleX: CGFloat { return _viewPortHandler.scaleX; }
/// returns the current y-scale factor
public var scaleY: CGFloat { return _viewPortHandler.scaleY; }
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// Returns the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis;
}
/// Returns the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// Returns the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis;
}
else
{
return _rightAxis;
}
}
/// Returns the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis;
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled;
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
private func updateScaleGestureRecognizers()
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers![i] === _pinchGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
if (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)
{
self.addGestureRecognizer(_pinchGestureRecognizer);
}
}
/// returns true if pinch-zoom is enabled, false if not
/// :default: false
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset);
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset);
}
/// :returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; }
public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; }
public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; }
public override var chartYMax: Float
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum);
}
public override var chartYMin: Float
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum);
}
/// Returns true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted;
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!;
internal init(chart: BarLineChartViewBase)
{
_chart = chart;
}
internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat
{
var fillMin = CGFloat(0.0);
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0;
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Float, min: Float;
if (data.yMax > 0.0)
{
max = 0.0;
}
else
{
max = chartMaxY;
}
if (data.yMin < 0.0)
{
min = 0.0;
}
else
{
min = chartMinY;
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max);
}
else
{
fillMin = 0.0;
}
}
return fillMin;
}
} | d199cbedb9c8a5734e6c1a10457be0d6 | 33.386813 | 263 | 0.573215 | false | false | false | false |
collegboi/iOS-Sprite-Game | refs/heads/master | Minnion Maze/Minnion Maze/Player.swift | mit | 1 | //
// Player.swift
// Minnion Maze
//
// Created by Timothy Barnard on 13/12/2014.
// Copyright (c) 2014 Timothy Barnard. All rights reserved.
//
import SpriteKit
class Player : SKNode {
let sprite: SKSpriteNode
var velocity: CGVector!
let textureBk: SKTexture!
let textureFd: SKTexture!
let textureLt: SKTexture!
let textureRt: SKTexture!
let textureMad: SKTexture!
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override init() {
//character directions with own SKTexture variables
let atlas = SKTextureAtlas(named: "characters")
textureBk = atlas.textureNamed("minnion_back")
textureFd = atlas.textureNamed("minnion_front")
textureLt = atlas.textureNamed("minnion_left")
textureRt = atlas.textureNamed("minnion_right")
textureMad = atlas.textureNamed("madMinnion")
textureFd.filteringMode = .Nearest
textureBk.filteringMode = .Nearest
textureRt.filteringMode = .Nearest
textureLt.filteringMode = .Nearest
textureMad.filteringMode = .Nearest
sprite = SKSpriteNode(texture: textureBk)
//self.velocity = CGVector(angle: 0)
super.init()
addChild(sprite)
name = "player"
// min diameter for the physics body around the sprite
var minDiam = min(sprite.size.width, sprite.size.height)
minDiam = max(minDiam - 4.0, 1.0)
let physicsBody = SKPhysicsBody(circleOfRadius: minDiam / 8.0 )
//let physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
//
physicsBody.usesPreciseCollisionDetection = true
//
physicsBody.allowsRotation = false
physicsBody.restitution = 0
physicsBody.friction = 0
physicsBody.linearDamping = 0
physicsBody.categoryBitMask = PhysicsCategory.Player
physicsBody.contactTestBitMask = PhysicsCategory.All
physicsBody.collisionBitMask = PhysicsCategory.Boundary | PhysicsCategory.Wall
self.physicsBody = physicsBody
}
//taking in velocity form acceleromter to move the sprite
func moveSprite(velocity: CGVector) {
physicsBody?.applyImpulse(velocity)
self.velocity = velocity
playerDirection()
}
//detects which direction sprite is moving to change sprites direciton
func playerDirection() {
let direction = physicsBody!.velocity
if abs(direction.dy) > abs(direction.dx) {
if direction.dy < 0 {
sprite.texture = textureFd
} else {
sprite.texture = textureBk
}
} else {
if direction.dx > 0 {
sprite.texture = textureRt
} else {
sprite.texture = textureLt
}
}//if statement to see if sprite is moving direciton
}
//method to turn minnion mad due to loosing game
func playerLoose(score: Bool) {
sprite.texture = textureMad
let actionJump1 = SKAction.scaleTo(1.2, duration: 0.2)
let actionJump2 = SKAction.scaleTo(1, duration: 0.2)
let wait = SKAction.waitForDuration(0.25)
let sequence = SKAction.sequence([actionJump1, actionJump2])
sprite.runAction(sequence)
}
}
| 5b97d5a1d64001dd029754eba3fb8eda | 30.906542 | 86 | 0.621558 | false | false | false | false |
CaiMiao/CGSSGuide | refs/heads/master | DereGuide/Toolbox/MusicInfo/Model/CGSSSongFilter.swift | mit | 1 | //
// CGSSSongFilter.swift
// DereGuide
//
// Created by zzk on 11/09/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
struct CGSSSongFilter: CGSSFilter {
var liveTypes: CGSSLiveTypes
var eventTypes: CGSSLiveEventTypes
var centerTypes: CGSSCardTypes
var positionNumTypes: CGSSPositionNumberTypes
var favoriteTypes: CGSSFavoriteTypes
var searchText: String = ""
init(liveMask: UInt, eventMask: UInt, centerMask: UInt, positionNumMask: UInt, favoriteMask: UInt) {
liveTypes = CGSSLiveTypes.init(rawValue: liveMask)
eventTypes = CGSSLiveEventTypes.init(rawValue: eventMask)
centerTypes = CGSSCardTypes.init(rawValue: centerMask)
positionNumTypes = CGSSPositionNumberTypes.init(rawValue: positionNumMask)
favoriteTypes = CGSSFavoriteTypes.init(rawValue: favoriteMask)
}
func filter(_ list: [CGSSSong]) -> [CGSSSong] {
// let date1 = Date()
let result = list.filter { (v: CGSSSong) -> Bool in
let r1: Bool = searchText == "" ? true : {
let comps = searchText.components(separatedBy: " ")
for comp in comps {
if comp == "" { continue }
let b1 = { v.name.lowercased().contains(comp.lowercased()) }
let b2 = { v.detail.lowercased().contains(comp.lowercased())}
if b1() || b2() {
continue
} else {
return false
}
}
return true
}()
let r2: Bool = {
var b1 = false
if liveTypes == .all {
b1 = true
} else {
if liveTypes.contains(v.filterType) {
b1 = true
}
}
var b2 = false
if eventTypes == .all {
b2 = true
} else {
if eventTypes.contains(v.eventFilterType) {
b2 = true
}
}
var b3 = false
if centerTypes == .all {
b3 = true
} else {
if centerTypes.contains(v.centerType) {
b3 = true
}
}
var b4 = false
if positionNumTypes == .all {
b4 = true
} else {
if positionNumTypes.contains(v.positionNumType) {
b4 = true
}
}
var b7 = false
if favoriteTypes == .all {
b7 = true
} else {
if favoriteTypes.contains(v.favoriteType) {
b7 = true
}
}
if b1 && b2 && b3 && b4 && b7 {
return true
}
return false
}()
return r1 && r2
}
return result
}
func toDictionary() -> NSDictionary {
let dict = ["liveMask": liveTypes.rawValue, "eventMask": eventTypes.rawValue, "centerMask": centerTypes.rawValue, "favoriteMask": favoriteTypes.rawValue, "positionNumMask": positionNumTypes.rawValue] as NSDictionary
return dict
}
func save(to path: String) {
toDictionary().write(toFile: path, atomically: true)
}
init?(fromFile path: String) {
if let dict = NSDictionary.init(contentsOfFile: path) {
if let liveMask = dict.object(forKey: "liveMask") as? UInt, let eventMask = dict.object(forKey: "eventMask") as? UInt, let centerMask = dict.object(forKey: "centerMask") as? UInt, let favoriteMask = dict.object(forKey: "favoriteMask") as? UInt, let positionNumMask = dict.object(forKey: "positionNumMask") as? UInt {
self.init(liveMask: liveMask, eventMask: eventMask, centerMask: centerMask, positionNumMask: positionNumMask, favoriteMask: favoriteMask)
return
}
}
return nil
}
}
| e26b22019c5139c5178f8b03961207f8 | 34.04 | 328 | 0.477169 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift | mit | 1 | //
// TransformNodeOutput.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
import CoreGraphics
import QuartzCore
class GroupOutputNode: NodeOutput {
init(parent: NodeOutput?, rootNode: NodeOutput?) {
self.parent = parent
self.rootNode = rootNode
}
let parent: NodeOutput?
let rootNode: NodeOutput?
var isEnabled: Bool = true
private(set) var outputPath: CGPath? = nil
private(set) var transform: CATransform3D = CATransform3DIdentity
func setTransform(_ xform: CATransform3D, forFrame: CGFloat) {
transform = xform
outputPath = nil
}
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
guard isEnabled else {
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
outputPath = parent?.outputPath
return upstreamUpdates
}
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
if upstreamUpdates {
outputPath = nil
}
let rootUpdates = rootNode?.hasOutputUpdates(forFrame) ?? false
if rootUpdates {
outputPath = nil
}
var localUpdates: Bool = false
if outputPath == nil {
localUpdates = true
let newPath = CGMutablePath()
if let parentNode = parent, let parentPath = parentNode.outputPath {
/// First add parent path.
newPath.addPath(parentPath)
}
var xform = CATransform3DGetAffineTransform(transform)
if let rootNode = rootNode,
let rootPath = rootNode.outputPath,
let xformedPath = rootPath.copy(using: &xform) {
/// Now add root path. Note root path is transformed.
newPath.addPath(xformedPath)
}
outputPath = newPath
}
return upstreamUpdates || localUpdates
}
}
| ba7a8fdba9df085f8900bdf94d4613f5 | 24.557143 | 74 | 0.660704 | false | false | false | false |
ben-ng/swift | refs/heads/master | benchmark/single-source/SetTests.swift | apache-2.0 | 1 | //===--- SetTests.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
@inline(never)
public func run_SetIsSubsetOf(_ N: Int) {
let size = 200
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(_ s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var xor = Set<Int>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var or = Set<Int>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect(_ N: Int) {
let size = 400
SRand()
var set = Set<Int>(minimumCapacity: size)
var otherSet = Set<Int>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Int(truncatingBitPattern: Random()))
otherSet.insert(Int(truncatingBitPattern: Random()))
}
var and = Set<Int>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(_ N: Int) {
let size = 200
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var isSubset = false
for _ in 0 ..< N * 5000 {
isSubset = set.isSubset(of: otherSet)
if isSubset {
break
}
}
CheckResults(!isSubset, "Incorrect results in SetIsSubsetOf")
}
@inline(never)
func sink(_ s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var xor = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
xor = set.symmetricDifference(otherSet)
}
sink(&xor)
}
@inline(never)
public func run_SetUnion_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var or = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
or = set.union(otherSet)
}
sink(&or)
}
@inline(never)
public func run_SetIntersect_OfObjects(_ N: Int) {
let size = 400
SRand()
var set = Set<Box<Int>>(minimumCapacity: size)
var otherSet = Set<Box<Int>>(minimumCapacity: size)
for _ in 0 ..< size {
set.insert(Box(Int(truncatingBitPattern: Random())))
otherSet.insert(Box(Int(truncatingBitPattern: Random())))
}
var and = Set<Box<Int>>()
for _ in 0 ..< N * 100 {
and = set.intersection(otherSet)
}
sink(&and)
}
| a028e63196858e56c6bfd6d62c203448 | 20.615023 | 80 | 0.622068 | false | false | false | false |
pietro82/TransitApp | refs/heads/master | TransitApp/DirectionsDataManager.swift | mit | 1 | //
// DirectionsDataManager.swift
// TransitApp
//
// Created by Pietro Santececca on 24/01/17.
// Copyright © 2017 Tecnojam. All rights reserved.
//
import MapKit
class DirectionsDataManager {
static func retreiveDirectionsOptions(originLocation: CLLocationCoordinate2D,
arrivalLocation: CLLocationCoordinate2D,
timeType: TimeType,
time: Date) -> [DirectionsOption] {
guard let result = parseJsonData() else {
print("Error during JSON parsing: file is badly formatted")
return []
}
return result
}
static fileprivate func parseJsonData() -> [DirectionsOption]? {
var options = [DirectionsOption]()
guard let url = Bundle.main.url(forResource: "door2door", withExtension: "json") else {
return nil
}
do {
let data = try Data(contentsOf: url)
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let optionsJson = json["routes"] as? [[String: Any]] {
for optionJson in optionsJson {
// Directions mode
guard let mode = optionJson["type"] as? String else { return nil }
// Directions provider
guard let provider = optionJson["provider"] as? String else { return nil }
// Directions list
guard let directionsJson = optionJson["segments"] as? [[String: Any]] else { return nil }
// Directions price
var price: Price?
if let priceJson = optionJson["price"] as? [String: Any] {
guard let currency = priceJson["currency"] as? String else { return nil }
guard let amount = priceJson["amount"] as? Double else { return nil }
price = Price(currency: currency, amount: amount)
}
var directions = [Direction]()
for directionJson in directionsJson {
// Direction name
var name: String?
if let nameJson = directionJson["name"] as? String { name = nameJson }
// Direction num stops
guard let numStops = directionJson["num_stops"] as? Int else { return nil }
// Direction travel mode
guard let travelMode = directionJson["travel_mode"] as? String else { return nil }
// Direction description
var description: String?
if let descriptionJson = directionJson["description"] as? String { description = descriptionJson }
// Direction color
guard let color = directionJson["color"] as? String else { return nil }
// Direction icon url
guard let iconUrl = directionJson["icon_url"] as? String else { return nil }
// Direction polyline
var polyline: String?
if let polylineJson = directionJson["polyline"] as? String { polyline = polylineJson }
// Stops
guard let stopsJson = directionJson["stops"] as? [[String: Any]] else { return nil }
var stops = [Stop]()
for stopJson in stopsJson {
// Stop latitude
guard let latitude = stopJson["lat"] as? Double else { return nil }
// Stop longitude
guard let longitude = stopJson["lng"] as? Double else { return nil }
// Stop time
guard let timeString = stopJson["datetime"] as? String,
let timeDate = Utils.convertToDate(string: timeString) else { return nil }
// Stop name
var name: String?
if let nameJson = stopJson["name"] as? String { name = nameJson }
// Create a new stop
let stop = Stop(name: name, latitude: latitude, longitude: longitude, time: timeDate, color: color)
// Add stop to the stop list
stops.append(stop)
}
// Create a new direction
let direction = Direction(name: name, numStops: numStops, stops: stops, travelMode: travelMode, description: description, color: color, iconUrl: iconUrl, polyline: polyline)
// Add direction to the directions list
directions.append(direction)
}
// Create a new option
let option = DirectionsOption(mode: mode, provider: provider, price: price, directions: directions)
// Add option to the result list
options.append(option)
}
}
}
catch {
print("Error deserializing JSON: \(error)")
}
return options
}
}
| aa75737280ab5bcf8cf4cef2e14cd798 | 43.807407 | 197 | 0.440734 | false | false | false | false |
mark2b/l10n | refs/heads/master | Classes/l10n.swift | mit | 1 | //
// l10n.swift
//
// Created by Mark Berner on 19/01/2017.
// Copyright © 2017 Mark Berner. All rights reserved.
//
import Foundation
extension String {
public func l10n(_ resource: l10NResources.RawValue = l10NResources.default, locale:Locale? = nil, args:CVarArg...) -> String {
var bundle = Bundle.main
if let locale = locale {
let language = locale.languageCode
if let path = Bundle.main.path(forResource: language, ofType: "lproj"), let localizedBundle = Bundle(path: path) {
bundle = localizedBundle
}
}
var format:String
if resource == l10NResources.default {
format = bundle.localizedString(forKey: self, value: self, table: nil)
}
else {
format = bundle.localizedString(forKey: self, value: self, table: resource)
}
if args.count == 0 {
return format
}
else {
return NSString(format: format, arguments:getVaList(args)) as String
}
}
}
public struct l10NResources : RawRepresentable {
public typealias RawValue = String
public static let `default` = "default"
public init?(rawValue: l10NResources.RawValue) {
return nil
}
public var rawValue: String
}
| 2701f18ff4397eedede84a502968a93e | 26.291667 | 131 | 0.603817 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Source/Registration/UnregisteredUser+Payload.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
extension UnregisteredUser {
/**
* The dictionary payload that contains the resources to transmit to the backend
* when registering the user.
*/
var payload: ZMTransportData {
guard self.isComplete else {
fatalError("Attempt to register an incomplete user.")
}
var payload: [String: Any] = [:]
switch credentials! {
case .phone(let number):
payload["phone"] = number
payload["phone_code"] = verificationCode!
case .email(let address):
payload["email"] = address
payload["email_code"] = verificationCode!
}
payload["accent_id"] = accentColorValue!.rawValue
payload["name"] = name!
payload["locale"] = NSLocale.formattedLocaleIdentifier()
payload["label"] = CookieLabel.current.value
payload["password"] = password
return payload as ZMTransportData
}
}
| ea961882ee3a876dd6b13d8933d8c628 | 29.690909 | 84 | 0.662322 | false | false | false | false |
sharkspeed/dororis | refs/heads/dev | languages/swift/guide/8-enumerations.swift | bsd-2-clause | 1 | // 8 Enumerations
// 定义一种常见类型 由一组相关联的值组成 允许你以一种类型安全的方式操作它们。
// C 的枚举要赋值一组 整数值 Swift 要更灵活
// 提供给枚举的 raw value 可以是 string cahracter integer floating-point
// 枚举可以存储任何类型 类似 unions 或 variants
// 可以有计算属性 定义初始化函数 可以被 extended 可以实现 protocols
// 8.1 Enumeration Syntax
enum CompassPoint {
case north
case south
case east
case west
}
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created.
// Each enumeration definition defines a brand new type 每个枚举定义都生成一个新类型
// var directToEast = .east
var directToWest = CompassPoint.west
print(directToWest)
// 一旦 directToWest 被声明为 CompassPoint 就可以使用
directToWest = .east
print(directToWest)
// 8.2 Matching Enumeration Values with a Switch Statement
// 可以在 swich 中使用 枚举值
var directToWhere = CompassPoint.south
switch directToWhere {
case .north:
print("Go to north")
case .south:
print("Go to south")
case .west:
print("Go west")
case .east:
print("Go east")
}
// 如果不在 case 中列出全部枚举值的话就需要提供一个 default 语句
// 8.3 关联数值 Associated Values
// store UPC barcodes as a tuple of four integers, and QR code barcodes as a string of any length.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("JDSKFSJDLFJ")
// 一个时刻只能保存一个枚举值
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let productCode, let checkCode):
print("UPC: \(numberSystem) - \(manufacturer) - \(productCode) - \(checkCode)")
case .qrCode(let productCode):
print("QR code: \(productCode)")
}
// 类似上边都是 let 声明的常量的情况 可以将 let 提前
switch productBarcode {
case let .upc(numberSystem, manufacturer, productCode, checkCode):
print("UPC: \(numberSystem) - \(manufacturer) - \(productCode) - \(checkCode)")
case let .qrCode(productCode):
print("QR code: \(productCode)")
}
// 8.4 Raw Values
// As an alternative to associated values 预设值的枚举需要类型一致
enum ASCIIControl: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
// raw value define enumeration 时就赋值
// associated value 在基于枚举值创建变量/常量时
// 8.4.1 Implicitly Assigned Raw Values
// 在使用 raw values 时, 如果类型为 integer 或者 string 你可以不用为每个 case 赋值,Swift 会自动为你赋值。
enum PlanetEasy: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Planet.venus has an implicit raw value of 2, and so on.
enum CompassPointEasy: String {
case north, south, east, west
}
// int 的 raw values 从 0 开始 用户设置初始值可以修改这个默认值
// string 为 case 名的字面量
let earthsOrder = PlanetEasy.earth.rawValue
print(earthsOrder)
let sunsetDirection = CompassPointEasy.west.rawValue
print(sunsetDirection)
// 8.4.2 Initializing from a Raw Value
// 可以使用 枚举初始化 枚举实例
let aNewPlanet = PlanetEasy(rawValue: 7)
// aNewPlanet 类型为 Planet? 因为不是所有的 值都有对应的 case 找不到值就会返回 nil
let positionToFind = 11
if let somePlanet = PlanetEasy(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
// 8.4.3 Recursive Enumerations
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// 或者
indirect enum ArithmeticExpressionNew {
case number(Int)
case addition(ArithmeticExpressionNew, ArithmeticExpressionNew)
case multiplication(ArithmeticExpressionNew, ArithmeticExpressionNew)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
// 可以用于递归计算中 类似 模式匹配
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product))
// Prints "18" | 7fafc237590fd6a35f2160ccfc64ab0e | 24.255814 | 116 | 0.722312 | false | false | false | false |
lumenlunae/BusyNavigationBar | refs/heads/master | BusyNavigationBar/BusyNavigationBar/UINavigationBar+Animation.swift | mit | 1 | //
// UINavigationBar+Animation.swift
// BusyNavigationBar
//
// Created by Gunay Mert Karadogan on 22/7/15.
// Copyright (c) 2015 Gunay Mert Karadogan. All rights reserved.
//
import UIKit
private var BusyNavigationBarLoadingViewAssociationKey: UInt8 = 0
private var BusyNavigationBarOptionsAssociationKey: UInt8 = 1
private var alphaAnimationDurationOfLoadingView = 0.3
extension UINavigationBar {
private var busy_loadingView: UIView? {
get {
return objc_getAssociatedObject(self, &BusyNavigationBarLoadingViewAssociationKey) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self, &BusyNavigationBarLoadingViewAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
private var busy_options: BusyNavigationBarOptions {
get {
return objc_getAssociatedObject(self, &BusyNavigationBarOptionsAssociationKey) as! BusyNavigationBarOptions
}
set(newValue) {
objc_setAssociatedObject(self, &BusyNavigationBarOptionsAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
public override var bounds: CGRect {
didSet {
if oldValue != bounds {
// If busy_loadingView is in the view hierarchy
if let _ = busy_loadingView?.superview {
// Remove loadingView
busy_loadingView?.removeFromSuperview()
self.busy_loadingView = nil
// Restart
start(self.busy_options)
}
}
}
}
public func start(options: BusyNavigationBarOptions? = nil) {
if let loadingView = self.busy_loadingView {
loadingView.removeFromSuperview()
}
busy_options = options ?? BusyNavigationBarOptions()
insertLoadingView()
UIView.animateWithDuration(alphaAnimationDurationOfLoadingView, animations: { () -> Void in
self.busy_loadingView!.alpha = self.busy_options.alpha
})
let animationLayer = pickAnimationLayer()
animationLayer.masksToBounds = true
animationLayer.position = busy_loadingView!.center
if busy_options.transparentMaskEnabled {
animationLayer.mask = maskLayer()
}
busy_loadingView!.layer.addSublayer(animationLayer)
}
public func stop(){
if let loadingView = self.busy_loadingView {
UIView.animateWithDuration(alphaAnimationDurationOfLoadingView, animations: { () -> Void in
loadingView.alpha = 0.0
}) { (Completed) -> Void in
loadingView.removeFromSuperview()
}
}
}
func insertLoadingView() {
busy_loadingView = UIView(frame: bounds)
busy_loadingView!.center.x = bounds.size.width / 2
busy_loadingView!.alpha = 0.0
busy_loadingView!.layer.masksToBounds = true
busy_loadingView!.userInteractionEnabled = false
insertSubview(busy_loadingView!, atIndex: 1)
}
func pickAnimationLayer() -> CALayer {
var animationLayer: CALayer
switch busy_options.animationType {
case .Stripes:
animationLayer = AnimationLayerCreator.stripeAnimationLayer(bounds, options: busy_options)
case .Bars:
animationLayer = AnimationLayerCreator.barAnimation(bounds, options: busy_options)
case .CustomLayer(let layerCreator):
animationLayer = layerCreator()
}
return animationLayer
}
func maskLayer() -> CALayer {
let alphaLayer = CAGradientLayer()
alphaLayer.frame = bounds
alphaLayer.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0).CGColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).CGColor]
return alphaLayer
}
}
| d07406a5b1b49af804b80e0d9c0f1b0d | 32.181034 | 138 | 0.634191 | false | false | false | false |
22377832/swiftdemo | refs/heads/master | ImageButton/ImageButton/ViewController.swift | mit | 1 | //
// ViewController.swift
// ImageButton
//
// Created by adults on 2017/3/22.
// Copyright © 2017年 adults. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var featureView: UIView!
@IBOutlet weak var featureViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createFeatureView(8)
}
func createFeatureView(_ count: Int){
let images = [UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!]
let tiltes = ["title",
"title",
"title",
"title",
"title",
"title",
"title",
"title"]
let selectors = [#selector(pushToSomewhereOne),
#selector(pushToSomewhereTwo),
#selector(pushToSomewhereThree),
#selector(pushToSomewhereFour),
#selector(pushToSomewhereOne),
#selector(pushToSomewhereTwo),
#selector(pushToSomewhereThree),
#selector(pushToSomewhereFour)]
let space: CGFloat = 0
let numberOfLine = 4
// switch count {
// case 1, 2, 3, 5, 6:
// numberOfLine = 3
// case 4, 7, 8:
// numberOfLine = 4
//
// default:
// numberOfLine = 4
//
// }
let imageButtonWidth = (view.bounds.width - space * CGFloat(numberOfLine - 1)) / CGFloat(numberOfLine)
let imageButtonHeight = imageButtonWidth * 1.2
let imageSize = CGSize(width: imageButtonWidth * 0.6, height: imageButtonWidth * 0.6)
let number1 = count / numberOfLine
let number2 = count % numberOfLine == 0 ? 0 : 1
featureViewHeight.constant = (imageButtonHeight + space) * CGFloat(number1 + number2)
for index in 0..<count {
let imageButton = CYCImageButtonView(frame: CGRect(x: CGFloat(index % numberOfLine) * (imageButtonWidth + space), y: CGFloat(index / numberOfLine) * (imageButtonHeight + space) , width: imageButtonWidth, height: imageButtonHeight), image: images[index], imageSize: imageSize, title: tiltes[index], target: self, action: selectors[index])
self.featureView.addSubview(imageButton)
}
}
func pushToSomewhereOne(){
print("push 1")
}
func pushToSomewhereTwo(){
print("push 2")
}
func pushToSomewhereThree(){
print("push 3")
}
func pushToSomewhereFour(){
print("push 4")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| c3b84e65f5024be4ba1a33cb17940f54 | 32.606061 | 349 | 0.536519 | false | false | false | false |
gmilos/swift | refs/heads/master | test/SILGen/multi_file.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-LABEL: sil hidden @_TF10multi_file12rdar16016713
func rdar16016713(_ r: Range) {
// CHECK: [[LIMIT:%[0-9]+]] = function_ref @_TFV10multi_file5Rangeg5limitSi : $@convention(method) (Range) -> Int
// CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int
markUsed(r.limit)
}
// CHECK-LABEL: sil hidden @_TF10multi_file26lazyPropertiesAreNotStored
func lazyPropertiesAreNotStored(_ container: LazyContainer) {
var container = container
// CHECK: {{%[0-9]+}} = function_ref @_TFV10multi_file13LazyContainerg7lazyVarSi : $@convention(method) (@inout LazyContainer) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_TF10multi_file29lazyRefPropertiesAreNotStored
func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) {
// CHECK: {{%[0-9]+}} = class_method %0 : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int , $@convention(method) (@guaranteed LazyContainerClass) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_TF10multi_file25finalVarsAreDevirtualizedFCS_18FinalPropertyClassT_
func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) {
// CHECK: ref_element_addr %0 : $FinalPropertyClass, #FinalPropertyClass.foo
markUsed(obj.foo)
// CHECK: class_method %0 : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1
markUsed(obj.bar)
}
// rdar://18448869
// CHECK-LABEL: sil hidden @_TF10multi_file34finalVarsDontNeedMaterializeForSetFCS_27ObservingPropertyFinalClassT_
func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) {
obj.foo += 1
// CHECK: function_ref @_TFC10multi_file27ObservingPropertyFinalClassg3fooSi
// CHECK: function_ref @_TFC10multi_file27ObservingPropertyFinalClasss3fooSi
}
// rdar://18503960
// Ensure that we type-check the materializeForSet accessor from the protocol.
class HasComputedProperty: ProtocolWithProperty {
var foo: Int {
get { return 1 }
set {}
}
}
// CHECK-LABEL: sil hidden @_TFC10multi_file19HasComputedPropertym3fooSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC10multi_file19HasComputedPropertyS_20ProtocolWithPropertyS_FS1_m3fooSi : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
| 9b44f77a66cdb7e9e9ba6ce4a6cce4a6 | 52.26 | 295 | 0.755539 | false | false | false | false |
terietor/GTForms | refs/heads/master | Example/TestKeyboardTableViewController.swift | mit | 1 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import GTForms
class TestKeyboardTableViewController: FormTableViewController {
fileprivate lazy var hideKeyboardButton: UIBarButtonItem = {
let button = UIBarButtonItem(
title: "Hide Keyboard",
style: .done,
target: self,
action: #selector(didTapHideKeyboardButton)
)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.hideKeyboardButton
let selectionItems = [
SelectionFormItem(text: "Apple"),
SelectionFormItem(text: "Orange")
]
let selectionForm = SelectionForm(
items: selectionItems,
text: "Choose a fruit"
)
selectionForm.textColor = UIColor.red
selectionForm.textFont = UIFont
.preferredFont(forTextStyle: UIFontTextStyle.headline)
selectionForm.allowsMultipleSelection = true
let section = FormSection()
section.addRow(selectionForm)
section.addRow(FormDatePicker(text: "Date Picker"))
section.addRow(FormDoubleTextField(
text: "Double Form",
placeHolder: "Type a double")
)
self.formSections.append(section)
}
@objc fileprivate func didTapHideKeyboardButton() {
hideKeyboard()
}
}
| c18918e32f8a72b1ac0dccf1826562a0 | 33.945205 | 82 | 0.687574 | false | false | false | false |
vimeo/VIMVideoPlayer | refs/heads/v6.0.2 | Examples/VimeoPlayer-iOS-Example/VimeoPlayer-iOS-Example/ViewController.swift | mit | 1 | //
// ViewController.swift
// VIMVideoPlayer-iOS-Example
//
// Created by King, Gavin on 3/9/16.
// Copyright © 2016 Gavin King. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ViewController: UIViewController, VIMVideoPlayerViewDelegate
{
@IBOutlet weak var videoPlayerView: VIMVideoPlayerView!
@IBOutlet weak var slider: UISlider!
private var isScrubbing = false
override func viewDidLoad()
{
super.viewDidLoad()
self.setupVideoPlayerView()
self.setupSlider()
}
// MARK: Setup
private func setupVideoPlayerView()
{
self.videoPlayerView.player.looping = true
self.videoPlayerView.player.disableAirplay()
self.videoPlayerView.setVideoFillMode(AVLayerVideoGravityResizeAspectFill)
self.videoPlayerView.delegate = self
if let path = NSBundle.mainBundle().pathForResource("waterfall", ofType: "mp4")
{
self.videoPlayerView.player.setURL(NSURL(fileURLWithPath: path))
}
else
{
assertionFailure("Video file not found!")
}
}
private func setupSlider()
{
self.slider.addTarget(self, action: "scrubbingDidStart", forControlEvents: UIControlEvents.TouchDown)
self.slider.addTarget(self, action: "scrubbingDidChange", forControlEvents: UIControlEvents.ValueChanged)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpInside)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpOutside)
}
// MARK: Actions
@IBAction func didTapPlayPauseButton(sender: UIButton)
{
if self.videoPlayerView.player.playing
{
sender.selected = true
self.videoPlayerView.player.pause()
}
else
{
sender.selected = false
self.videoPlayerView.player.play()
}
}
// MARK: Scrubbing Actions
func scrubbingDidStart()
{
self.isScrubbing = true
self.videoPlayerView.player.startScrubbing()
}
func scrubbingDidChange()
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == true else
{
return
}
let time = Float(CMTimeGetSeconds(duration)) * self.slider.value
self.videoPlayerView.player.scrub(time)
}
func scrubbingDidEnd()
{
self.videoPlayerView.player.stopScrubbing()
self.isScrubbing = false
}
// MARK: VIMVideoPlayerViewDelegate
func videoPlayerViewIsReadyToPlayVideo(videoPlayerView: VIMVideoPlayerView?)
{
self.videoPlayerView.player.play()
}
func videoPlayerView(videoPlayerView: VIMVideoPlayerView!, timeDidChange cmTime: CMTime)
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == false else
{
return
}
let durationInSeconds = Float(CMTimeGetSeconds(duration))
let timeInSeconds = Float(CMTimeGetSeconds(cmTime))
self.slider.value = timeInSeconds / durationInSeconds
}
} | 509663bf583ff90f192833b204d365bf | 31.136691 | 113 | 0.659875 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/ChatSendAsMenuItem.swift | gpl-2.0 | 1 | //
// ChatSendAdMenuItem.swift
// Telegram
//
// Created by Mike Renoir on 18.01.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import Postbox
import SwiftSignalKit
import TelegramCore
class ContextSendAsMenuItem : ContextMenuItem {
private let peer: SendAsPeer
private let context: AccountContext
private let isSelected: Bool
init(peer: SendAsPeer, context: AccountContext, isSelected: Bool, handler: (() -> Void)? = nil) {
self.peer = peer
self.context = context
self.isSelected = isSelected
super.init(peer.peer.displayTitle.prefixWithDots(20), handler: handler)
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func rowItem(presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction) -> TableRowItem {
return ContextSendAsMenuRowItem(.zero, item: self, interaction: interaction, presentation: presentation, peer: peer, context: context, isSelected: isSelected)
}
}
private final class ContextSendAsMenuRowItem : AppMenuRowItem {
private let disposable = MetaDisposable()
fileprivate let context: AccountContext
fileprivate let statusLayout: TextViewLayout
fileprivate let peer: SendAsPeer
fileprivate let selected: Bool
init(_ initialSize: NSSize, item: ContextMenuItem, interaction: AppMenuBasicItem.Interaction, presentation: AppMenu.Presentation, peer: SendAsPeer, context: AccountContext, isSelected: Bool) {
self.peer = peer
self.context = context
self.selected = isSelected
let status: String
if peer.peer.isUser {
status = strings().chatSendAsPersonalAccount
} else {
if peer.peer.isGroup || peer.peer.isSupergroup {
status = strings().chatSendAsGroupCountable(Int(peer.subscribers ?? 0))
} else {
status = strings().chatSendAsChannelCountable(Int(peer.subscribers ?? 0))
}
}
self.statusLayout = .init(.initialize(string: status, color: presentation.disabledTextColor, font: .normal(.text)))
super.init(initialSize, item: item, interaction: interaction, presentation: presentation)
let signal:Signal<(CGImage?, Bool), NoError>
let peer = self.peer.peer
signal = peerAvatarImage(account: context.account, photo: .peer(peer, peer.smallProfileImage, peer.displayLetters, nil), displayDimensions: NSMakeSize(25 * System.backingScale, 25 * System.backingScale), font: .avatar(20), genCap: true, synchronousLoad: false) |> deliverOnMainQueue
disposable.set(signal.start(next: { [weak item] image, _ in
if let image = image {
item?.image = NSImage(cgImage: image, size: NSMakeSize(25, 25))
}
}))
}
override var imageSize: CGFloat {
return 25
}
deinit {
disposable.dispose()
}
override var textSize: CGFloat {
return max(text.layoutSize.width, statusLayout.layoutSize.width) + leftInset * 2 + innerInset * 2
}
override var effectiveSize: NSSize {
var size = super.effectiveSize
if peer.isPremiumRequired && !context.isPremium {
size.width += 15
}
return size
}
override var height: CGFloat {
return 35
}
override func makeSize(_ width: CGFloat = CGFloat.greatestFiniteMagnitude, oldWidth: CGFloat = 0) -> Bool {
_ = super.makeSize(width, oldWidth: oldWidth)
self.statusLayout.measure(width: width - leftInset * 2 - innerInset * 2)
return true
}
override func viewClass() -> AnyClass {
return ContextAccountMenuRowView.self
}
}
private final class ContextAccountMenuRowView : AppMenuRowView {
private let statusView: TextView = TextView()
private var borderView: View?
private var lockView: ImageView?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(statusView)
statusView.userInteractionEnabled = false
statusView.isSelectable = false
}
override func layout() {
super.layout()
guard let item = item as? ContextSendAsMenuRowItem else {
return
}
statusView.setFrameOrigin(NSMakePoint(textX, textY + 14))
if let borderView = borderView {
borderView.frame = imageFrame.insetBy(dx: -2, dy: -2)
}
if let lockView = lockView {
lockView.setFrameOrigin(textX + item.text.layoutSize.width, textY)
}
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? ContextSendAsMenuRowItem else {
return
}
statusView.update(item.statusLayout)
if item.peer.isPremiumRequired && !item.context.isPremium {
let current: ImageView
if let view = self.lockView {
current = view
} else {
current = ImageView()
addSubview(current)
self.lockView = current
}
current.image = NSImage(named: "Icon_EmojiLock")?.precomposed(item.presentation.disabledTextColor)
current.sizeToFit()
} else if let view = self.lockView {
performSubviewRemoval(view, animated: animated)
self.lockView = nil
}
if item.selected {
let current: View
if let view = borderView {
current = view
} else {
current = View()
self.borderView = current
addSubview(current)
}
current.setFrameSize(NSMakeSize(item.imageSize + 4, item.imageSize + 4))
current.layer?.cornerRadius = current.frame.height / 2
current.layer?.borderWidth = 1
current.layer?.borderColor = item.presentation.colors.accent.cgColor
} else if let view = borderView {
performSubviewRemoval(view, animated: animated)
}
}
override var textY: CGFloat {
return 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 497f7075df51f4f10653d0c3aa062fde | 33.315789 | 290 | 0.617485 | false | false | false | false |
yrchen/edx-app-ios | refs/heads/master | Source/JSONFormBuilderTextEditor.swift | apache-2.0 | 1 | //
// JSONFormBuilderTextEditor.swift
// edX
//
// Created by Michael Katz on 10/1/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
class JSONFormBuilderTextEditorViewController: UIViewController {
let textView = OEXPlaceholderTextView()
var text: String { return textView.text }
var doneEditing: ((value: String)->())?
init(text: String?, placeholder: String?) {
super.init(nibName: nil, bundle: nil)
self.view = UIView()
self.view.backgroundColor = UIColor.whiteColor()
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets
textView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes
textView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight()
textView.textColor = OEXStyles.sharedStyles().neutralBlackT()
textView.text = text ?? ""
if let placeholder = placeholder {
textView.placeholder = placeholder
}
textView.delegate = self
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
view.addSubview(textView)
textView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_topMargin)
make.leading.equalTo(view.snp_leadingMargin)
make.trailing.equalTo(view.snp_trailingMargin)
make.bottom.equalTo(view.snp_bottomMargin)
}
}
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil { //removing from the hierarchy
doneEditing?(value: textView.text)
}
}
}
extension JSONFormBuilderTextEditorViewController : UITextViewDelegate {
func textViewShouldEndEditing(textView: UITextView) -> Bool {
textView.resignFirstResponder()
return true
}
} | cbd2a088f561255a1b683b3093a91a0e | 29.043478 | 89 | 0.648649 | false | false | false | false |
hanzhuzi/XRVideoPlayer-master | refs/heads/master | XRPlayer/Source/XRPlayerMarcos.swift | mit | 1 | //
// XRPlayerMarcos.swift
// XRPlayer
//
// Created by 徐冉 on 2019/7/30.
// Copyright © 2019 QK. All rights reserved.
//
import UIKit
import Foundation
// MARK: - Print
#if DEBUG
func XRPlayerLog(_ items: Any...) {
print(items)
}
#else
func XRPlayerLog(_ items: Any...) {
}
#endif
//MARK: - 屏幕尺寸
// iPhone5, 5S,5C,SE
public func xrPlayer_iSiPhone5_5S_5C_SE() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 640, height: 1136)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1136, height: 640)) : false)
}
// iPhone6,6S,7,8
public func xrPlayer_iSiPhone6_6S_7_8() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 750, height: 1334)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1334, height: 750)) : false)
}
// iPhone6, 7, 8,Plus
public func xrPlayer_iSiPhone6_7_8Plus() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1242, height: 2208)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2208, height: 1242)) : false)
}
// iPhoneX, XS
public func xrPlayer_iSiPhoneX_XS() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1125, height: 2436)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2436, height: 1125)) : false)
}
// iPhoneXR
public func xrPlayer_iSiPhoneXR() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 828, height: 1792)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1792, height: 828)) : false)
}
// iPhoneXS_Max
public func xrPlayer_iSiPhoneXS_Max() -> Bool {
return (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 1242, height: 2688)) : false) || (UIScreen.instancesRespond(to: #selector(getter: UIScreen.currentMode)) ? __CGSizeEqualToSize(UIScreen.main.currentMode!.size, CGSize(width: 2688, height: 1242)) : false)
}
// 是否有齐刘海和虚拟指示器
public func xrPlayer_iSiPhoneXSerries() -> Bool {
var isiPhoneXSerries: Bool = false
if UIDevice.current.userInterfaceIdiom != .phone {
isiPhoneXSerries = false
}
if #available(iOS 11.0, *) {
if let mainWindow = UIApplication.shared.delegate?.window {
if mainWindow!.safeAreaInsets.bottom > 0 {
isiPhoneXSerries = true
}
}
}
isiPhoneXSerries = xrPlayer_iSiPhoneX_XS() || xrPlayer_iSiPhoneXR() || xrPlayer_iSiPhoneXS_Max()
return isiPhoneXSerries
}
// 加载XRPlayer Bundle中的图片
func xrplayer_imageForBundleResource(imageName: String, bundleClass: AnyClass) -> UIImage? {
let moduleBundle = Bundle(for: bundleClass)
if let resourceUrl = moduleBundle.resourceURL?.appendingPathComponent("XRPlayer.bundle") {
let resourceBundle = Bundle(url: resourceUrl)
let resImage = UIImage(named: imageName, in: resourceBundle, compatibleWith: nil)
return resImage
}
return nil
}
//MARK: - 颜色
// 颜色(RGB)
public func xrplayer_RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
public func xrplayer_RGBCOLOR(r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
}
//RGB颜色转换(16进制)
public func xrplayer_UIColorFromRGB(hexRGB: UInt32) -> UIColor
{
let redComponent = (hexRGB & 0xFF0000) >> 16
let greenComponent = (hexRGB & 0x00FF00) >> 8
let blueComponent = hexRGB & 0x0000FF
return xrplayer_RGBCOLOR(r: CGFloat(redComponent), g: CGFloat(greenComponent), b: CGFloat(blueComponent))
}
///延迟 afTime, 回调 block(in main 在主线程)
public func xrplayer_dispatch_after_in_main(_ afTime: TimeInterval,block: @escaping ()->()) {
let popTime = DispatchTime.now() + Double(Int64(afTime * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) // 1s * popTime
if popTime > DispatchTime(uptimeNanoseconds: 0) {
DispatchQueue.main.asyncAfter(deadline: popTime, execute: block)
}
}
| 8e8d31957a70137a8df78a52b16e2b56 | 39.08 | 355 | 0.7002 | false | false | false | false |
ZeldaIV/TDC2015-FP | refs/heads/master | Pods/RxBlocking/RxBlocking/Observable+Blocking.swift | mit | 12 | //
// Observable+Blocking.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 7/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension ObservableType {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: All elements of sequence.
*/
public func toArray() throws -> [E] {
let condition = NSCondition()
var elements = [E]()
var error: ErrorType?
var ended = false
self.subscribe { e in
switch e {
case .Next(let element):
elements.append(element)
case .Error(let e):
error = e
condition.lock()
ended = true
condition.signal()
condition.unlock()
case .Completed:
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
}
condition.lock()
while !ended {
condition.wait()
}
condition.unlock()
if let error = error {
throw error
}
return elements
}
}
extension ObservableType {
/**
Blocks current thread until sequence produces first element.
If sequence terminates with error before producing first element, terminating error will be thrown.
- returns: First element of sequence. If sequence is empty `nil` is returned.
*/
public func first() throws -> E? {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = self.subscribe { e in
switch e {
case .Next(let e):
if element == nil {
element = e
}
break
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
throw error
}
return element
}
}
extension ObservableType {
/**
Blocks current thread until sequence terminates.
If sequence terminates with error, terminating error will be thrown.
- returns: Last element in the sequence. If sequence is empty `nil` is returned.
*/
public func last() throws -> E? {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = self.subscribe { e in
switch e {
case .Next(let e):
element = e
return
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
throw error
}
return element
}
} | 037d1cba9ab56362734ea340c6168382 | 22.176829 | 103 | 0.474737 | false | false | false | false |
BrisyIOS/TodayNewsSwift3.0 | refs/heads/master | TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/View/HomeThreeImageCell.swift | apache-2.0 | 1 | //
// HomeThreeImageCell.swift
// TodayNews-Swift3.0
//
// Created by zhangxu on 2016/10/26.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class HomeThreeImageCell: HomeListCommonCell {
var homeListModel: HomeListModel? {
didSet {
// 取出可选类型中的数据
guard let homeListModel = homeListModel else {
return;
}
// 给titleLabel 赋值
if let title = homeListModel.title {
titleLabel.text = title;
homeListModel.titleLabelH = calculateLabelHeight(text: title, labelW: kScreenWidth - CGFloat(2) * 15, fontSize: 17);
}
// 时间
if let publish_time = homeListModel.publish_time {
timeLabel.text = changeTimestampToPublicTime(timestamp: publish_time);
homeListModel.timeLabelW = calculateWidth(title: timeLabel.text!, fontSize: 12);
}
// 头像
if let source_avatar = homeListModel.source_avatar {
if let source = homeListModel.source {
nameLabel.text = source;
homeListModel.nameLabelW = calculateWidth(title: source, fontSize: 12);
}
avatarImageView.zx_setImageWithURL(source_avatar);
}
if let mediaInfo = homeListModel.media_info {
nameLabel.text = mediaInfo.name;
avatarImageView.zx_setImageWithURL(mediaInfo.avatar_url);
}
// 评论
if let comment = homeListModel.comment_count {
commentLabel.text = (comment >= 10000) ? "\(comment/10000)万评论" : "\(comment)评论";
homeListModel.commentLabelW = calculateWidth(title: commentLabel.text!, fontSize: 12);
}
// 三张图
if let image_list = homeListModel.image_list {
if image_list.count != 0 {
for index in 0..<image_list.count {
let imageViewArray = [firstImage, secondImage, thirdImage];
let imageListModel = image_list[index];
var imageURL: String = "";
let url = imageListModel.url ?? "";
if url.hasSuffix(".webp") {
let range = url.range(of: ".webp")!;
imageURL = url.substring(to: range.lowerBound);
} else {
imageURL = url;
}
imageViewArray[index].zx_setImageWithURL(imageURL);
}
}
}
// 更新子控件的frame
layoutIfNeeded();
setNeedsLayout();
}
};
// 三张图
lazy var firstImage: UIImageView = UIImageView();
lazy var secondImage: UIImageView = UIImageView();
lazy var thirdImage: UIImageView = UIImageView();
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
// 添加第一张图品
contentView.addSubview(firstImage);
// 添加第二张图片
contentView.addSubview(secondImage);
// 添加第三张图片
contentView.addSubview(thirdImage);
}
// 更新子控件的frame
override func layoutSubviews() {
super.layoutSubviews();
guard let homeListModel = homeListModel else {
return;
}
let width = bounds.size.width;
// 设置titleLabel 的frame
let titleLabelX = realValue(15);
let titleLabelY = realValue(50/3);
let titleLabelW = width - titleLabelX * CGFloat(2);
let titleLabelH = homeListModel.titleLabelH;
titleLabel.frame = CGRect(x: titleLabelX, y: titleLabelY, width: titleLabelW, height: titleLabelH);
// 设置firstImage 的frame
let firstImageX = titleLabelX;
let firstImageY = titleLabel.frame.maxY + realValue(11);
let firstImageW = realValue(372/3);
let firstImageH = realValue(210/3);
firstImage.frame = CGRect(x: firstImageX, y: firstImageY, width: firstImageW, height: firstImageH);
// 设置secondImage 的frame
let secondImageX = firstImage.frame.maxX + realValue(20/3);
let secondImageY = firstImageY;
let secondImageW = firstImageW;
let secondImageH = firstImageH;
secondImage.frame = CGRect(x: secondImageX, y: secondImageY, width: secondImageW, height: secondImageH);
// 设置thirdImage 的frame
let thirdImageX = secondImage.frame.maxX + realValue(20/3);
let thirdImageY = firstImageY;
let thirdImageW = firstImageW;
let thirdImageH = firstImageH;
thirdImage.frame = CGRect(x: thirdImageX, y: thirdImageY, width: thirdImageW, height: thirdImageH);
// 设置avatarImageView 的frame
let avatarImageViewX = titleLabelX;
let avatarImageViewY = firstImage.frame.maxY + realValue(10);
let avatarImageViewW = realValue(49/3);
let avatarImageViewH = avatarImageViewW;
avatarImageView.frame = CGRect(x: avatarImageViewX, y: avatarImageViewY, width: avatarImageViewW, height: avatarImageViewH);
// 设置nameLabel 的frame
let nameLabelX = avatarImageView.frame.maxX + realValue(5);
let nameLabelY = firstImage.frame.maxY + realValue(36/3);
let nameLabelW = homeListModel.nameLabelW;
let nameLabelH = realValue(12);
nameLabel.frame = CGRect(x: nameLabelX, y: nameLabelY, width: nameLabelW, height: nameLabelH);
// 设置commentLabel 的frame
let commentLabelX = nameLabel.frame.maxX + realValue(5);
let commentLabelY = nameLabelY;
let commentLabelW = homeListModel.commentLabelW;
let commentLabelH = nameLabelH;
commentLabel.frame = CGRect(x: commentLabelX, y: commentLabelY, width: commentLabelW, height: commentLabelH);
// 设置timeLabel 的frame
let timeLabelX = commentLabel.frame.maxX + realValue(5);
let timeLabelY = nameLabelY;
let timeLabelW = homeListModel.timeLabelW;
let timeLabelH = nameLabelH;
timeLabel.frame = CGRect(x: timeLabelX, y: timeLabelY, width: timeLabelW, height: timeLabelH);
// 设置stickLabel 的frame
let stickLabelX = timeLabel.frame.maxX + realValue(5);
let stickLabelY = nameLabelY;
let stickLabelW = homeListModel.stickLabelW;
let stickLabelH = nameLabelH;
stickLabel.frame = CGRect(x: stickLabelX, y: stickLabelY, width: stickLabelW, height: stickLabelH);
// 设置圆角
let cornerRadii = CGSize(width: realValue(49/3/2), height: realValue(49/3/2));
setRoundCorner(currentView: avatarImageView, cornerRadii: cornerRadii);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| f4b714371e3aabfcfb5b0460a30ff3f4 | 38.617486 | 132 | 0.584414 | false | false | false | false |
eRGoon/RGPageViewController | refs/heads/master | RGPageViewController/RGPageViewController/Source/Extensions/RGPageViewController+UICollectionViewDelegate.swift | mit | 1 | //
// RGPageViewController+UICollectionViewDelegate.swift
// RGPageViewController
//
// Created by Ronny Gerasch on 23.01.17.
// Copyright © 2017 Ronny Gerasch. All rights reserved.
//
import Foundation
// MARK: - UICollectionViewDelegate
extension RGPageViewController: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if currentTabIndex != indexPath.row {
selectTabAtIndex(indexPath.row, updatePage: true)
}
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let tabView = cell.contentView.subviews.first as? RGTabView {
if indexPath.row == currentTabIndex {
tabView.selected = true
} else {
tabView.selected = false
}
}
}
}
| e01646be481ebcd969b30b6622c85850 | 30.142857 | 138 | 0.727064 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/PrintAsObjC/mixed-framework-fwd.swift | apache-2.0 | 10 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header.h
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=NO-IMPORT %s < %t/mixed-header.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -F %S/Inputs/ -module-name Mixed -import-underlying-module %s -typecheck -emit-objc-header-path %t/mixed-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=FRAMEWORK %s < %t/mixed-proto.h
// RUN: %check-in-clang -F %S/Inputs/ %t/mixed-proto.h
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name Mixed -import-objc-header %S/Inputs/Mixed.framework/Headers/Mixed.h %s -typecheck -emit-objc-header-path %t/mixed-header-proto.h -DREQUIRE
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=HEADER %s < %t/mixed-header-proto.h
// RUN: %check-in-clang -include %S/Inputs/Mixed.framework/Headers/Mixed.h %t/mixed-header-proto.h
// REQUIRES: objc_interop
// CHECK-LABEL: #if defined(__has_feature) && __has_feature(modules)
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: #endif
// NO-IMPORT-NOT: #import
// NO-IMPORT: @protocol CustomProto;
// FRAMEWORK-LABEL: #import <Mixed/Mixed.h>
// HEADER-NOT: __ObjC
// HEADER: #import "{{.*}}Mixed.h"
// HEADER-NOT: __ObjC
import Foundation
public class Dummy: NSNumber {
public func getProto() -> CustomProto? {
return nil
}
}
#if REQUIRE
extension Dummy: CustomProto {}
#endif
| 4a107a9e337dd3dfad5c9d2ca26a0901 | 45.333333 | 213 | 0.710175 | false | false | false | false |
dduan/swift | refs/heads/master | benchmark/single-source/NSError.swift | apache-2.0 | 2 | //===--- NSError.swift ----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
protocol P {
func buzz() throws -> Int
}
class K : P {
init() {}
func buzz() throws -> Int {
throw NSError(domain: "AnDomain", code: 42, userInfo: nil)
}
}
class G : K {
override init() {}
override func buzz() throws -> Int { return 0 }
}
func caller(x : P) throws {
try x.buzz()
}
@inline(never)
public func run_NSError(N: Int) {
for _ in 1...N*1000 {
let k = K()
let g = G()
do {
try caller(g)
try caller(k)
} catch _ {
continue
}
}
}
| 6b23a379f28c85d1fd96700dc4d00dd2 | 21.333333 | 80 | 0.534515 | false | false | false | false |
Glucosio/glucosio-ios | refs/heads/develop | Pods/Charts/Source/Charts/Renderers/BubbleChartRenderer.swift | apache-2.0 | 4 | //
// BubbleChartRenderer.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BubbleChartRenderer: BarLineScatterCandleBubbleRenderer
{
@objc open weak var dataProvider: BubbleChartDataProvider?
@objc public init(dataProvider: BubbleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData
else { return }
for set in bubbleData.dataSets as! [IBubbleChartDataSet] where set.isVisible
{
drawDataSet(context: context, dataSet: set)
}
}
private func getShapeSize(
entrySize: CGFloat,
maxSize: CGFloat,
reference: CGFloat,
normalizeSize: Bool) -> CGFloat
{
let factor: CGFloat = normalizeSize
? ((maxSize == 0.0) ? 1.0 : sqrt(entrySize / maxSize))
: entrySize
let shapeSize: CGFloat = reference * factor
return shapeSize
}
private var _pointBuffer = CGPoint()
private var _sizeBuffer = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawDataSet(context: CGContext, dataSet: IBubbleChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let valueToPixelMatrix = trans.valueToPixelMatrix
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
context.saveGState()
defer { context.restoreGState() }
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let entry = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { continue }
_pointBuffer.x = CGFloat(entry.x)
_pointBuffer.y = CGFloat(entry.y * phaseY)
_pointBuffer = _pointBuffer.applying(valueToPixelMatrix)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
guard
viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf),
viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf),
viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)
else { continue }
guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break }
let color = dataSet.color(atIndex: Int(entry.x))
let rect = CGRect(
x: _pointBuffer.x - shapeHalf,
y: _pointBuffer.y - shapeHalf,
width: shapeSize,
height: shapeSize
)
context.setFillColor(color.cgColor)
context.fillEllipse(in: rect)
}
}
open override func drawValues(context: CGContext)
{
guard let
dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData,
isDrawingValuesAllowed(dataProvider: dataProvider),
let dataSets = bubbleData.dataSets as? [IBubbleChartDataSet]
else { return }
let phaseX = max(0.0, min(1.0, animator.phaseX))
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0..<dataSets.count
{
let dataSet = dataSets[i]
guard
shouldDrawValues(forDataSet: dataSet),
let formatter = dataSet.valueFormatter
else { continue }
let alpha = phaseX == 1 ? phaseY : phaseX
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
for j in _xBounds.min..._xBounds.range + _xBounds.min
{
guard let e = dataSet.entryForIndex(j) as? BubbleChartDataEntry else { break }
let valueTextColor = dataSet.valueTextColorAt(j).withAlphaComponent(CGFloat(alpha))
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
guard viewPortHandler.isInBoundsRight(pt.x) else { break }
guard
viewPortHandler.isInBoundsLeft(pt.x),
viewPortHandler.isInBoundsY(pt.y)
else { continue }
let text = formatter.stringForValue(
Double(e.size),
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler)
// Larger font for larger bubbles?
let valueFont = dataSet.valueFont
let lineHeight = valueFont.lineHeight
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(
x: pt.x,
y: pt.y - (0.5 * lineHeight)),
align: .center,
attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: valueTextColor])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let bubbleData = dataProvider.bubbleData
else { return }
context.saveGState()
defer { context.restoreGState() }
let phaseY = animator.phaseY
for high in indices
{
guard
let dataSet = bubbleData.getDataSetByIndex(high.dataSetIndex) as? IBubbleChartDataSet,
dataSet.isHighlightEnabled,
let entry = dataSet.entryForXValue(high.x, closestToY: high.y) as? BubbleChartDataEntry,
isInBoundsX(entry: entry, dataSet: dataSet)
else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
_pointBuffer.x = CGFloat(entry.x)
_pointBuffer.y = CGFloat(entry.y * phaseY)
trans.pointValueToPixel(&_pointBuffer)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
guard
viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf),
viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf),
viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)
else { continue }
guard viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) else { break }
let originalColor = dataSet.color(atIndex: Int(entry.x))
var h: CGFloat = 0.0
var s: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
let color = NSUIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a)
let rect = CGRect(
x: _pointBuffer.x - shapeHalf,
y: _pointBuffer.y - shapeHalf,
width: shapeSize,
height: shapeSize)
context.setLineWidth(dataSet.highlightCircleWidth)
context.setStrokeColor(color.cgColor)
context.strokeEllipse(in: rect)
high.setDraw(x: _pointBuffer.x, y: _pointBuffer.y)
}
}
}
| ef687111410422d113cda01f88c48b21 | 34.940351 | 145 | 0.559992 | false | false | false | false |
Daltron/BigBoard | refs/heads/master | Example/BigBoard/ExampleView.swift | mit | 1 | //
// ExampleView.swift
// BigBoard
//
// Created by Dalton Hinterscher on 5/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SnapKit
protocol ExampleViewDelegate : class {
func numberOfStocks() -> Int
func stockAtIndex(_ index:Int) -> BigBoardStock
func stockSelectedAtIndex(_ index:Int)
func refreshControllPulled()
}
class ExampleView: UIView, UITableViewDataSource, UITableViewDelegate {
weak var delegate:ExampleViewDelegate?
var stocksTableView:UITableView!
var refreshControl:UIRefreshControl!
init(delegate:ExampleViewDelegate){
super.init(frame: CGRect.zero)
self.delegate = delegate
self.backgroundColor = UIColor.white
stocksTableView = UITableView(frame: CGRect.zero, style: .plain)
stocksTableView.dataSource = self
stocksTableView.delegate = self
stocksTableView.rowHeight = 50.0
addSubview(stocksTableView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshControllerPulled), for: .valueChanged)
stocksTableView.addSubview(refreshControl)
stocksTableView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func refreshControllerPulled(){
delegate!.refreshControllPulled()
}
// MARK: UITableViewDataSource and UITableViewDataSource Implementation
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return delegate!.numberOfStocks()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseIdentifier = "ExampleCell"
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: reuseIdentifier)
let currentPriceLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 25))
currentPriceLabel.textAlignment = .right
cell?.accessoryView = currentPriceLabel
}
return cell!
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let stock = delegate!.stockAtIndex((indexPath as NSIndexPath).row)
cell.textLabel?.text = stock.name!
cell.detailTextLabel?.text = stock.symbol!
let currentPriceLabel = cell.accessoryView as! UILabel!
currentPriceLabel?.text = "$\(stock.lastTradePriceOnly!)"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
delegate!.stockSelectedAtIndex((indexPath as NSIndexPath).row)
}
}
| 8ca11853c0462582f910f08a4edafddd | 32.793478 | 112 | 0.670634 | false | false | false | false |
invoy/CoreDataQueryInterface | refs/heads/master | CoreDataQueryInterface/Util.swift | mit | 1 | //
// Util.swift
// CoreDataQueryInterface
//
// Created by Gregory Higley on 10/5/16.
// Copyright © 2016 Prosumma LLC. All rights reserved.
//
import Foundation
var debug: Bool = {
for arg in ProcessInfo.processInfo.arguments {
if arg == "-com.prosumma.CoreDataQueryInterface.Debug" {
return true
}
}
return false
}()
infix operator ??= : AssignmentPrecedence
func ??=<T>(lhs: inout T?, rhs: @autoclosure () -> T?) {
if lhs != nil { return }
lhs = rhs()
}
| aec342850e3911274408f48ebfed55e7 | 18.807692 | 64 | 0.609709 | false | false | false | false |
spamproject/spam | refs/heads/master | spam/spam.swift | mit | 1 | import Foundation
private let fileManager = NSFileManager()
private let spamDirectory = ".spam"
private let swiftc = "xcrun -sdk macosx swiftc"
private extension Module {
var installPath: String {
get {
return spamDirectory + "/src/" + username + "/" + repo
}
}
}
// MARK: helper functions
func findModules(path: String) -> [Module] {
var modules = [Module]()
if let streamReader = StreamReader(path: path) {
var line: String?
while let line = streamReader.nextLine() {
if let module = Module(importStatement: line) {
modules.append(module)
}
}
} else {
error("could not read \(path)")
}
return modules
}
func compile(modules: [Module]) -> String {
let s = spamDirectory
mkdir("\(s)/lib")
var command = "\(swiftc) -I \(s)/lib -L \(s)/lib "
for module in modules {
let modulePath = "\(spamDirectory)/lib/\(module.moduleName).swiftmodule"
if !fileManager.fileExistsAtPath(modulePath) {
compile(module)
}
command += "-l\(module.moduleName.lowercaseString) "
}
if let sourceFiles = filesOfType("swift", atPath: ".") {
return "\(command)\(sourceFiles)"
} else {
error("could not find any Swift files in the current directory")
}
}
func compile(module: Module) {
log("Compiling \(module.moduleName)…")
let s = spamDirectory
let u = module.username
let r = module.repo
let M = module.moduleName
let m = module.moduleName.lowercaseString
let path = "\(s)/src/\(u)/\(r)"
var sourceFiles = filesOfType("swift", atPath: "\(path)/\(r)")
?? filesOfType("swift", atPath: "\(path)/\(m)")
?? filesOfType("swift", atPath: "\(path)/Source")
?? filesOfType("swift", atPath: "\(path)/src")
?? filesOfType("swift", atPath: "\(path)")
if sourceFiles != nil {
call("\(swiftc) -emit-library -emit-object " +
"\(sourceFiles!) -module-name \(M)")
if let objectFiles = filesOfType("o", atPath: ".") {
call("ar rcs lib\(m).a \(objectFiles)")
call("rm \(objectFiles)")
call("mv lib\(m).a \(s)/lib/")
call("\(swiftc) -parse-as-library -emit-module \(sourceFiles!) " +
"-module-name \(M) -o \(s)/lib/")
} else {
error("could not find object files")
}
} else {
error("could not find any Swift files in \(path)")
}
}
// MARK: subcommands
func install() {
func install(module: Module) {
mkdir("\(spamDirectory)/src")
call("git clone \(module.path) \(module.installPath)")
if let version = module.version {
call("git --git-dir=\(module.installPath)/.git " +
"--work-tree=\(module.installPath) checkout \(version) -q")
}
}
if let sourceFiles = filesOfType("swift", atPath: ".") {
for file in split(sourceFiles, isSeparator: { $0 == " " }) {
let modules = findModules(file)
for module in modules {
if !fileManager.fileExistsAtPath(module.installPath) {
install(module)
}
}
}
} else {
error("could not find any Swift files in the current directory")
}
}
func uninstall() {
log("Removing .spam/ and its contents…")
call("rm -rf \(spamDirectory)")
}
func compile(#outputFile: String?) {
if let sourceFiles = filesOfType("swift", atPath: ".") {
var modules = [Module]()
for file in split(sourceFiles, isSeparator: { $0 == " " }) {
modules += findModules(file)
}
let finalCompilationCommand = compile(modules)
if let outputFile = outputFile {
log("Compiling \(outputFile)…")
call("\(finalCompilationCommand) -o \(outputFile)")
} else {
log("Compiling project…")
call(finalCompilationCommand)
}
} else {
error("could not find any Swift files in the current directory")
}
}
func build(#outputFile: String?) {
install()
compile(outputFile: outputFile)
}
| ec561891929fae45ce14c58160342e3c | 29.948148 | 80 | 0.561273 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/IRGen/lazy_globals.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8
// CHECK: @_T012lazy_globals1xSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1ySiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1zSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: define internal swiftcc void @globalinit_[[T]]_func0() {{.*}} {
// CHECK: entry:
// CHECK: store i64 1, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1xSiv, i32 0, i32 0), align 8
// CHECK: store i64 2, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1ySiv, i32 0, i32 0), align 8
// CHECK: store i64 3, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1zSiv, i32 0, i32 0), align 8
// CHECK: ret void
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1xSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1xSiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1ySifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1ySiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1zSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*), i8* undef)
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1zSiv to i8*)
// CHECK: }
var (x, y, z) = (1, 2, 3)
// CHECK: define hidden swiftcc i64 @_T012lazy_globals4getXSiyF() {{.*}} {
// CHECK: entry:
// CHECK: %0 = call swiftcc i8* @_T012lazy_globals1xSifau()
// CHECK: %1 = bitcast i8* %0 to %TSi*
// CHECK: %._value = getelementptr inbounds %TSi, %TSi* %1, i32 0, i32 0
// CHECK: %2 = load i64, i64* %._value, align 8
// CHECK: ret i64 %2
// CHECK: }
func getX() -> Int { return x }
| e96406a9946b9bd5d00ab3dc5dcb9adc | 48.021739 | 132 | 0.647007 | false | false | false | false |
CNKCQ/oschina | refs/heads/master | Carthage/Checkouts/SnapKit/Source/ConstraintInsetTarget.swift | mit | 3 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol ConstraintInsetTarget: ConstraintConstantTarget {
}
extension Int: ConstraintInsetTarget {
}
extension UInt: ConstraintInsetTarget {
}
extension Float: ConstraintInsetTarget {
}
extension Double: ConstraintInsetTarget {
}
extension CGFloat: ConstraintInsetTarget {
}
extension ConstraintInsets: ConstraintInsetTarget {
}
extension ConstraintInsetTarget {
internal var constraintInsetTargetValue: ConstraintInsets {
if let amount = self as? ConstraintInsets {
return amount
} else if let amount = self as? Float {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? Double {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? CGFloat {
return ConstraintInsets(top: amount, left: amount, bottom: amount, right: amount)
} else if let amount = self as? Int {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else if let amount = self as? UInt {
return ConstraintInsets(top: CGFloat(amount), left: CGFloat(amount), bottom: CGFloat(amount), right: CGFloat(amount))
} else {
return ConstraintInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
}
| 5e5e5a21d155bad4ff1b411727aec2ad | 38.128571 | 129 | 0.711574 | false | false | false | false |
BrantSteven/SinaProject | refs/heads/master | BSweibo/BSweibo/class/newFeature/WelcomeVC.swift | mit | 1 | //
// WelcomeVC.swift
// BSweibo
//
// Created by 上海旅徒电子商务有限公司 on 16/9/27.
// Copyright © 2016年 白霜. All rights reserved.
//
import UIKit
class WelcomeVC: UIViewController {
/// 图像底部约束
private var iconBottomCons: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
//1.初始化UI
createUI()
//2.设置用户信息
if let iconUrlStr = UserAccount.readAccount()?.avatar_large {
bsLog(message: iconUrlStr)
iconView.sd_setImage(with: NSURL(string: iconUrlStr) as URL!)
}
}
override func viewDidAppear(_ animated: Bool) {//头像从底部滑上去
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
self.iconView.frame = CGRect(x: BSWidth/2-50, y: 100, width: 100, height: 100)
self.message.frame = CGRect(x: self.iconView.left, y: self.iconView.bottom+10, width: 100, height: 39)
}) { (_) -> Void in
self.message.alpha = 1.0//完成头像的滑动 label展示
//去主页 注意点: 企业开发中如果要切换根控制器 最好都在appdelegate中切换
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ChangeRootViewControllerNotifacationtion), object: true)
}
}
//初始化UI
func createUI(){
view.addSubview(imageView)
view.addSubview(iconView)
view.addSubview(message)
imageView.frame = view.bounds
iconView.frame = CGRect(x: BSWidth/2-50, y: BSHeight - 100, width: 100, height: 100)
// message.frame = CGRect(x: iconView.left, y: iconView.bottom+10, width: 100, height: 39)
}
//MARK:懒加载控件
//背景图片
lazy var imageView:UIImageView = {
let imageV = UIImageView.init(image: UIImage.init(named: "ad_background"))
return imageV
}()
///头像
lazy var iconView:UIImageView = {
let iconV = UIImageView(image: UIImage(named: "avatar_default_big"))
iconV.layer.masksToBounds = true
iconV.layer.cornerRadius = 50
return iconV
}()
///消息文字
lazy var message:UILabel = {
let messageLabel = UILabel.init()
messageLabel.text = "欢迎归来"
messageLabel.textAlignment = NSTextAlignment.center
messageLabel.alpha = 0//隐藏label
return messageLabel
}()
}
| ab1eed7dc6018f0822f7aefdd778c3e8 | 36.40625 | 180 | 0.630744 | false | false | false | false |
github/codeql | refs/heads/main | swift/ql/test/query-tests/Security/CWE-311/testCoreData.swift | mit | 1 |
// --- stubs ---
class NSObject
{
}
class NSManagedObject : NSObject
{
func value(forKey key: String) -> Any? { return "" }
func setValue(_ value: Any?, forKey key: String) {}
func primitiveValue(forKey key: String) -> Any? { return "" }
func setPrimitiveValue(_ value: Any?, forKey key: String) {}
}
class MyManagedObject : NSManagedObject
{
func setIndirect(value: String) {
setValue(value, forKey: "myKey")
}
var myValue: String {
get {
if let v = value(forKey: "myKey") as? String
{
return v
} else {
return ""
}
}
set {
setValue(newValue, forKey: "myKey")
}
}
}
func encrypt(_ data: String) -> String { return data }
func hash(data: inout String) { }
func getPassword() -> String { return "" }
func doSomething(password: String) { }
// --- tests ---
func test1(obj : NSManagedObject, password : String, password_hash : String) {
// NSManagedObject methods...
obj.setValue(password, forKey: "myKey") // BAD
obj.setValue(password_hash, forKey: "myKey") // GOOD (not sensitive)
obj.setPrimitiveValue(password, forKey: "myKey") // BAD
obj.setPrimitiveValue(password_hash, forKey: "myKey") // GOOD (not sensitive)
}
func test2(obj : MyManagedObject, password : String, password_file : String) {
// MyManagedObject methods...
obj.setValue(password, forKey: "myKey") // BAD
obj.setValue(password_file, forKey: "myKey") // GOOD (not sensitive)
obj.setIndirect(value: password) // BAD [reported on line 19]
obj.setIndirect(value: password_file) // GOOD (not sensitive)
obj.myValue = password // BAD [reported on line 32]
obj.myValue = password_file // GOOD (not sensitive)
}
class MyClass {
var harmless = "abc"
var password = "123"
}
func test3(obj : NSManagedObject, x : String) {
// alternative evidence of sensitivity...
obj.setValue(x, forKey: "myKey") // BAD [NOT REPORTED]
doSomething(password: x);
obj.setValue(x, forKey: "myKey") // BAD
var y = getPassword();
obj.setValue(y, forKey: "myKey") // BAD
var z = MyClass()
obj.setValue(z.harmless, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(z.password, forKey: "myKey") // BAD
}
func test4(obj : NSManagedObject, passwd : String) {
// sanitizers...
var x = passwd;
var y = passwd;
var z = passwd;
obj.setValue(x, forKey: "myKey") // BAD
obj.setValue(y, forKey: "myKey") // BAD
obj.setValue(z, forKey: "myKey") // BAD
x = encrypt(x);
hash(data: &y);
z = "";
obj.setValue(x, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(y, forKey: "myKey") // GOOD (not sensitive)
obj.setValue(z, forKey: "myKey") // GOOD (not sensitive)
}
| b0a1b00efb679f6077c112221d1ce7ef | 23.462264 | 78 | 0.66101 | false | false | false | false |
Keanyuan/SwiftContact | refs/heads/master | SwiftContent/SwiftContent/Classes/ContentView/shareView/YMShareButtonView.swift | mit | 1 | //
// YMShareButtonView.swift
// DanTang
//
// Created by 杨蒙 on 16/7/23.
// Copyright © 2016年 hrscy. All rights reserved.
//
import UIKit
typealias sendValueClosure = (_ shareButtonType: Int) -> Void
enum YMShareButtonType: Int {
/// 微信朋友圈
case WeChatTimeline = 0
/// 微信好友
case WeChatSession = 1
/// 微博
case Weibo = 2
/// QQ 空间
case QZone = 3
/// QQ 好友
case QQFriends = 4
/// 复制链接
case CopyLink = 5
}
class YMShareButtonView: UIView {
//声明一个闭包
var shareButtonBlock:sendValueClosure?
// 图片数组
let images = ["Share_WeChatTimelineIcon_70x70_", "Share_WeChatSessionIcon_70x70_", "Share_WeiboIcon_70x70_", "Share_QzoneIcon_70x70_", "Share_QQIcon_70x70_", "Share_CopyLinkIcon_70x70_"]
// 标题数组
let titles = ["微信朋友圈", "微信好友", "微博", "QQ 空间", "QQ 好友", "复制链接"]
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI() {
let maxCols = 3
let buttonW: CGFloat = 70
let buttonH: CGFloat = buttonW + 30
let buttonStartX: CGFloat = 20
let xMargin: CGFloat = (SCREENW - 20 - 2 * buttonStartX - CGFloat(maxCols) * buttonW) / CGFloat(maxCols - 1)
// 创建按钮
for index in 0..<images.count {
let button = YMVerticalButton()
button.tag = index
button.setImage(UIImage(named: images[index]), for: .normal)
button.setTitle(titles[index], for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.width = buttonW
button.height = buttonH
button.addTarget(self, action: #selector(shareButtonClick), for: .touchUpInside)
// 计算 X、Y
let row = Int(index / maxCols)
let col = index % maxCols
let buttonX: CGFloat = CGFloat(col) * (xMargin + buttonW) + buttonStartX
let buttonMaxY: CGFloat = CGFloat(row) * buttonH
let buttonY = buttonMaxY
button.frame = CGRect(x: buttonX, y: buttonY, width: buttonW, height: buttonH)
addSubview(button)
}
}
func shareButtonClick(button: UIButton) {
if let shareButtonType = YMShareButtonType(rawValue: button.tag) {
switch shareButtonType {
case .WeChatTimeline:
break
case .WeChatSession:
break
case .Weibo:
break
case .QZone:
break
case .QQFriends:
break
case .CopyLink:
break
}
}
print(button.titleLabel!.text!)
if (shareButtonBlock != nil){
shareButtonBlock!(button.tag)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| a6e98c9fa6499a7baf40a299b2004369 | 27.218182 | 190 | 0.535116 | false | false | false | false |
Kawoou/FlexibleImage | refs/heads/master | Sources/Filter/GammaFilter.swift | mit | 1 | //
// GammaFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(watchOS)
import Metal
#endif
internal class GammaFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "GammaFilter"
}
}
internal var gamma: Float = 1.0
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [self.gamma]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
let memoryPool = device.memoryPool!
let width = Int(device.drawRect!.width)
let height = Int(device.drawRect!.height)
var index = 0
for _ in 0..<height {
for _ in 0..<width {
let r = Float(memoryPool[index + 0]) / 255.0
let g = Float(memoryPool[index + 1]) / 255.0
let b = Float(memoryPool[index + 2]) / 255.0
memoryPool[index + 0] = UInt8(powf(r, self.gamma) * 255.0)
memoryPool[index + 1] = UInt8(powf(g, self.gamma) * 255.0)
memoryPool[index + 2] = UInt8(powf(b, self.gamma) * 255.0)
index += 4
}
}
return super.processNone(device)
}
}
| 54b36369cbf6ad559aa64a8e63388485 | 29.710843 | 160 | 0.488035 | false | false | false | false |
DSanzh/GuideMe-iOS | refs/heads/master | Pavers/Sources/FRP/Sugar/OptionalComparison.swift | mit | 7 | import Foundation
precedencegroup Comparison {
associativity: left
higherThan: LogicalConjunctionPrecedence
}
infix operator ?= : Comparison
public func ?=<T>(left: inout T, right: T?) {
guard let value = right else { return }
left = value
}
public func ?=<T>(left: inout T?, right: T?) {
guard let value = right else { return }
left = value
}
| 55e265b3bd404c5915a45e61b91bdfc7 | 19 | 46 | 0.686111 | false | false | false | false |
alskipp/Monoid | refs/heads/master | MonoidTests/AllMonoidTests.swift | mit | 1 | // Copyright © 2016 Al Skipp. All rights reserved.
import XCTest
import Monoid
class AllMonoidTests: XCTestCase {
func testMempty() {
XCTAssertTrue(All.mempty.value == true)
}
func testMappend() {
XCTAssertTrue(All(true) <> All(true) <> All(true) == All(true))
XCTAssertTrue(All(true) <> All(true) <> All(false) == All(false))
}
func testMconcat() {
XCTAssertTrue(.mconcat([All(true), All(true), All(true)]) == All(true))
XCTAssertTrue(.mconcat([All(true), All(false), All(true)]) == All(false))
}
func testComparable() {
XCTAssertTrue(All(false) < All(true))
}
func testDescription() {
XCTAssertTrue(All(true).description == "All(true)")
}
}
| 6f5ba6a7b3b06db3233e43b9084c3188 | 22.333333 | 77 | 0.642857 | false | true | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/PeersListController.swift | gpl-2.0 | 1 | //
// PeersListController.swift
// TelegramMac
//
// Created by keepcoder on 29/12/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import Postbox
import TelegramCore
import Reactions
import SwiftSignalKit
private final class Arguments {
let context: AccountContext
let joinGroupCall:(ChatActiveGroupCallInfo)->Void
let joinGroup:(PeerId)->Void
let openPendingRequests:()->Void
let dismissPendingRequests:([PeerId])->Void
init(context: AccountContext, joinGroupCall:@escaping(ChatActiveGroupCallInfo)->Void, joinGroup:@escaping(PeerId)->Void, openPendingRequests:@escaping()->Void, dismissPendingRequests: @escaping([PeerId])->Void) {
self.context = context
self.joinGroupCall = joinGroupCall
self.joinGroup = joinGroup
self.openPendingRequests = openPendingRequests
self.dismissPendingRequests = dismissPendingRequests
}
}
final class RevealAllChatsView : Control {
let textView: TextView = TextView()
var layoutState: SplitViewState = .dual {
didSet {
needsLayout = true
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
textView.userInteractionEnabled = false
textView.isSelectable = false
addSubview(textView)
let layout = TextViewLayout(.initialize(string: strings().chatListCloseFilter, color: .white, font: .medium(.title)))
layout.measure(width: max(280, frame.width))
textView.update(layout)
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowColor = NSColor.black.withAlphaComponent(0.1)
shadow.shadowOffset = NSMakeSize(0, 2)
self.shadow = shadow
set(background: theme.colors.accent, for: .Normal)
}
override func cursorUpdate(with event: NSEvent) {
NSCursor.pointingHand.set()
}
override var backgroundColor: NSColor {
didSet {
textView.backgroundColor = backgroundColor
}
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
needsLayout = true
}
override func layout() {
super.layout()
textView.center()
layer?.cornerRadius = frame.height / 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class FilterTabsView : View {
let tabs: ScrollableSegmentView = ScrollableSegmentView(frame: NSZeroRect)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(tabs)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
tabs.frame = bounds
}
}
struct PeerListState : Equatable {
struct InputActivities : Equatable {
struct Activity : Equatable {
let peer: PeerEquatable
let activity: PeerInputActivity
init(_ peer: Peer, _ activity: PeerInputActivity) {
self.peer = PeerEquatable(peer)
self.activity = activity
}
}
var activities: [PeerActivitySpace: [Activity]]
}
struct ForumData : Equatable {
static func == (lhs: PeerListState.ForumData, rhs: PeerListState.ForumData) -> Bool {
if lhs.peer != rhs.peer {
return false
}
if let lhsCached = lhs.peerView.cachedData, let rhsCached = rhs.peerView.cachedData {
if !lhsCached.isEqual(to: rhsCached) {
return false
}
} else if (lhs.peerView.cachedData != nil) != (rhs.peerView.cachedData != nil) {
return false
}
if lhs.call != rhs.call {
return false
}
if lhs.online != rhs.online {
return false
}
if lhs.invitationState != rhs.invitationState {
return false
}
return true
}
var peer: TelegramChannel
var peerView: PeerView
var online: Int32
var call: ChatActiveGroupCallInfo?
var invitationState: PeerInvitationImportersState?
}
var proxySettings: ProxySettings
var connectionStatus: ConnectionStatus
var splitState: SplitViewState
var searchState: SearchFieldState = .None
var peer: PeerEquatable?
var forumPeer: ForumData?
var mode: PeerListMode
var activities: InputActivities
}
class PeerListContainerView : View {
private final class ProxyView : Control {
fileprivate let button:ImageButton = ImageButton()
private var connecting: ProgressIndicator?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(button)
button.userInteractionEnabled = false
button.isEventLess = true
}
func update(_ pref: ProxySettings, connection: ConnectionStatus, animated: Bool) {
switch connection {
case .connecting, .waitingForNetwork:
if pref.enabled {
let current: ProgressIndicator
if let view = self.connecting {
current = view
} else {
current = ProgressIndicator(frame: focus(NSMakeSize(11, 11)))
self.connecting = current
addSubview(current)
}
current.userInteractionEnabled = false
current.isEventLess = true
current.progressColor = theme.colors.accentIcon
} else if let view = connecting {
performSubviewRemoval(view, animated: animated)
self.connecting = nil
}
button.set(image: pref.enabled ? theme.icons.proxyState : theme.icons.proxyEnable, for: .Normal)
case .online, .updating:
if let view = connecting {
performSubviewRemoval(view, animated: animated)
self.connecting = nil
}
if pref.enabled {
button.set(image: theme.icons.proxyEnabled, for: .Normal)
} else {
button.set(image: theme.icons.proxyEnable, for: .Normal)
}
}
button.sizeToFit()
needsLayout = true
}
override func layout() {
super.layout()
button.center()
if let connecting = connecting {
var rect = connecting.centerFrame()
if backingScaleFactor == 2.0 {
rect.origin.x -= 0.5
rect.origin.y -= 0.5
}
connecting.frame = rect
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
connecting?.progressColor = theme.colors.accentIcon
}
}
private final class StatusView : Control {
fileprivate var button:PremiumStatusControl?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
private var peer: Peer?
private weak var effectPanel: Window?
func update(_ peer: Peer, context: AccountContext, animated: Bool) {
var interactiveStatus: Reactions.InteractiveStatus? = nil
if visibleRect != .zero, window != nil, let interactive = context.reactions.interactiveStatus {
interactiveStatus = interactive
}
if let view = self.button, interactiveStatus != nil, interactiveStatus?.fileId != nil {
performSubviewRemoval(view, animated: animated, duration: 0.3)
self.button = nil
}
let control = PremiumStatusControl.control(peer, account: context.account, inlinePacksContext: context.inlinePacksContext, isSelected: false, isBig: true, playTwice: true, cached: self.button, animated: animated)
if let control = control {
self.button = control
addSubview(control)
control.center()
} else {
self.button?.removeFromSuperview()
self.button = nil
}
self.peer = peer
if let interactive = interactiveStatus {
self.playAnimation(interactive, context: context)
}
}
private func playAnimation(_ status: Reactions.InteractiveStatus, context: AccountContext) {
guard let control = self.button, let window = self.window else {
return
}
guard let fileId = status.fileId else {
return
}
control.isHidden = true
let play:(StatusView)->Void = { [weak control] superview in
guard let control = control else {
return
}
control.isHidden = false
let panel = Window(contentRect: NSMakeRect(0, 0, 160, 120), styleMask: [.fullSizeContentView], backing: .buffered, defer: false)
panel._canBecomeMain = false
panel._canBecomeKey = false
panel.ignoresMouseEvents = true
panel.level = .popUpMenu
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = false
let player = CustomReactionEffectView(frame: NSMakeSize(160, 120).bounds, context: context, fileId: fileId)
player.isEventLess = true
player.triggerOnFinish = { [weak panel] in
if let panel = panel {
panel.parent?.removeChildWindow(panel)
panel.orderOut(nil)
}
}
superview.effectPanel = panel
let controlRect = superview.convert(control.frame, to: nil)
var rect = CGRect(origin: CGPoint(x: controlRect.midX - player.frame.width / 2, y: controlRect.midY - player.frame.height / 2), size: player.frame.size)
rect = window.convertToScreen(rect)
panel.setFrame(rect, display: true)
panel.contentView?.addSubview(player)
window.addChildWindow(panel, ordered: .above)
}
if let fromRect = status.rect {
let layer = InlineStickerItemLayer(account: context.account, inlinePacksContext: context.inlinePacksContext, emoji: .init(fileId: fileId, file: nil, emoji: ""), size: control.frame.size)
let toRect = control.convert(control.frame.size.bounds, to: nil)
let from = fromRect.origin.offsetBy(dx: fromRect.width / 2, dy: fromRect.height / 2)
let to = toRect.origin.offsetBy(dx: toRect.width / 2, dy: toRect.height / 2)
let completed: (Bool)->Void = { [weak self] _ in
DispatchQueue.main.async {
if let container = self {
play(container)
NSHapticFeedbackManager.defaultPerformer.perform(.levelChange, performanceTime: .default)
}
}
}
parabollicReactionAnimation(layer, fromPoint: from, toPoint: to, window: context.window, completion: completed)
} else {
play(self)
}
}
override func layout() {
super.layout()
button?.center()
}
deinit {
if let panel = effectPanel {
panel.parent?.removeChildWindow(panel)
panel.orderOut(nil)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
}
}
private final class ActionView : Control {
private let textView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
textView.userInteractionEnabled = false
textView.isSelectable = false
border = [.Top, .Right]
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
textView.backgroundColor = theme.colors.background
}
func update(action: @escaping(PeerId)->Void, peerId: PeerId, title: String) {
let layout = TextViewLayout(.initialize(string: title, color: theme.colors.accent, font: .normal(.text)))
layout.measure(width: .greatestFiniteMagnitude)
textView.update(layout)
self.set(background: theme.colors.background, for: .Normal)
self.set(background: theme.colors.grayBackground, for: .Highlight)
self.removeAllHandlers()
self.set(handler: { _ in
action(peerId)
}, for: .Click)
needsLayout = true
}
override func layout() {
super.layout()
textView.center()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private var callView: ChatGroupCallView?
private var header: NSView?
private let backgroundView = BackgroundView(frame: NSZeroRect)
let tableView = TableView(frame:NSZeroRect, drawBorder: true)
private let containerView: View = View()
let searchView:SearchView = SearchView(frame:NSMakeRect(10, 0, 0, 0))
let compose:ImageButton = ImageButton()
private var premiumStatus: StatusView?
private var downloads: DownloadsControl?
private var proxy: ProxyView?
private var actionView: ActionView?
fileprivate var showDownloads:(()->Void)? = nil
fileprivate var hideDownloads:(()->Void)? = nil
var mode: PeerListMode = .plain {
didSet {
switch mode {
case .folder:
compose.isHidden = true
case .plain:
compose.isHidden = false
case .filter:
compose.isHidden = true
case .forum:
compose.isHidden = true
}
updateLayout(self.frame.size, transition: .immediate)
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.border = [.Right]
compose.autohighlight = false
autoresizesSubviews = false
addSubview(containerView)
addSubview(tableView)
containerView.addSubview(compose)
containerView.addSubview(searchView)
addSubview(backgroundView)
backgroundView.isHidden = true
tableView.getBackgroundColor = {
.clear
}
updateLocalizationAndTheme(theme: theme)
}
private var state: PeerListState?
var openProxy:((Control)->Void)? = nil
var openStatus:((Control)->Void)? = nil
fileprivate func updateState(_ state: PeerListState, arguments: Arguments, animated: Bool) {
let animated = animated && self.state?.splitState == state.splitState && self.state != nil
self.state = state
var voiceChat: ChatActiveGroupCallInfo?
if state.forumPeer?.call?.data?.groupCall == nil {
if let data = state.forumPeer?.call?.data, data.participantCount == 0 && state.forumPeer?.call?.activeCall.scheduleTimestamp == nil {
voiceChat = nil
} else {
voiceChat = state.forumPeer?.call
}
} else {
voiceChat = nil
}
self.updateAdditionHeader(state, size: frame.size, arguments: arguments, animated: animated)
if let info = voiceChat, state.splitState != .minimisize {
let current: ChatGroupCallView
var offset: CGFloat = -44
if let header = header {
offset += header.frame.height
}
let rect = NSMakeRect(0, offset, frame.width, 44)
if let view = self.callView {
current = view
} else {
current = .init({ _, _ in
arguments.joinGroupCall(info)
}, context: arguments.context, state: .none(info), frame: rect)
self.callView = current
containerView.addSubview(current, positioned: .below, relativeTo: header)
}
current.border = [.Right, .Bottom]
current.update(info, animated: animated)
} else if let view = self.callView {
performSubviewRemoval(view, animated: animated)
self.callView = nil
}
if let peer = state.forumPeer?.peer, peer.participationStatus == .left, state.splitState != .minimisize {
let current: ActionView
if let view = self.actionView {
current = view
} else {
current = ActionView(frame: NSMakeRect(0, frame.height - 50, frame.width, 50))
self.actionView = current
addSubview(current)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
}
current.update(action: arguments.joinGroup, peerId: peer.id, title: strings().chatInputJoin)
} else if let view = self.actionView {
performSubviewRemoval(view, animated: animated)
self.actionView = nil
}
self.searchView.isHidden = state.splitState == .minimisize
let componentSize = NSMakeSize(40, 30)
var controlPoint = NSMakePoint(frame.width - 12 - compose.frame.width, floorToScreenPixels(backingScaleFactor, (containerView.frame.height - componentSize.height)/2.0))
let hasControls = state.splitState != .minimisize && state.searchState != .Focus && mode.isPlain
let hasProxy = (!state.proxySettings.servers.isEmpty || state.proxySettings.effectiveActiveServer != nil) && hasControls
let hasStatus = state.peer?.peer.isPremium ?? false && hasControls
if hasProxy {
controlPoint.x -= componentSize.width
let current: ProxyView
if let view = self.proxy {
current = view
} else {
current = ProxyView(frame: CGRect(origin: controlPoint, size: componentSize))
self.proxy = current
self.containerView.addSubview(current, positioned: .below, relativeTo: searchView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
current.set(handler: { [weak self] control in
self?.openProxy?(control)
}, for: .Click)
}
current.update(state.proxySettings, connection: state.connectionStatus, animated: animated)
} else if let view = self.proxy {
performSubviewRemoval(view, animated: animated)
self.proxy = nil
}
if hasStatus, let peer = state.peer?.peer {
controlPoint.x -= componentSize.width
let current: StatusView
if let view = self.premiumStatus {
current = view
} else {
current = StatusView(frame: CGRect(origin: controlPoint, size: componentSize))
self.premiumStatus = current
self.containerView.addSubview(current, positioned: .below, relativeTo: searchView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
current.set(handler: { [weak self] control in
self?.openStatus?(control)
}, for: .Click)
}
current.update(peer, context: arguments.context, animated: animated)
} else if let view = self.premiumStatus {
performSubviewRemoval(view, animated: animated)
self.premiumStatus = nil
}
let transition: ContainedViewLayoutTransition
if animated {
transition = .animated(duration: 0.2, curve: .easeOut)
} else {
transition = .immediate
}
self.updateLayout(self.frame.size, transition: transition)
}
private func updateAdditionHeader(_ state: PeerListState, size: NSSize, arguments: Arguments, animated: Bool) {
let inviteRequestsPending = state.forumPeer?.invitationState?.waitingCount ?? 0
let hasInvites: Bool = state.forumPeer != nil && inviteRequestsPending > 0 && state.splitState != .minimisize
if let state = state.forumPeer?.invitationState, hasInvites {
self.updatePendingRequests(state, arguments: arguments, animated: animated)
} else {
self.updatePendingRequests(nil, arguments: arguments, animated: animated)
}
}
private func updatePendingRequests(_ state: PeerInvitationImportersState?, arguments: Arguments, animated: Bool) {
if let state = state {
let current: ChatPendingRequests
let headerState: ChatHeaderState = .pendingRequests(nil, Int(state.count), state.importers)
if let view = self.header as? ChatPendingRequests {
current = view
} else {
if let view = self.header {
performSubviewRemoval(view, animated: animated)
self.header = nil
}
current = .init(context: arguments.context, openAction: arguments.openPendingRequests, dismissAction: arguments.dismissPendingRequests, state: headerState, frame: NSMakeRect(0, 0, frame.width, 44))
current.border = [.Right, .Bottom]
self.header = current
containerView.addSubview(current)
}
current.update(with: headerState, animated: animated)
} else {
if let view = self.header {
performSubviewRemoval(view, animated: animated)
self.header = nil
}
}
}
private func updateTags(_ state: PeerListState,updateSearchTags: @escaping(SearchTags)->Void, updatePeerTag:@escaping(@escaping(Peer?)->Void)->Void, updateMessageTags: @escaping(@escaping(MessageTags?)->Void)->Void) {
var currentTag: MessageTags?
var currentPeerTag: Peer?
let tags:[(MessageTags?, String, CGImage)] = [(nil, strings().searchFilterClearFilter, theme.icons.search_filter),
(.photo, strings().searchFilterPhotos, theme.icons.search_filter_media),
(.video, strings().searchFilterVideos, theme.icons.search_filter_media),
(.webPage, strings().searchFilterLinks, theme.icons.search_filter_links),
(.music, strings().searchFilterMusic, theme.icons.search_filter_music),
(.voiceOrInstantVideo, strings().searchFilterVoice, theme.icons.search_filter_music),
(.gif, strings().searchFilterGIFs, theme.icons.search_filter_media),
(.file, strings().searchFilterFiles, theme.icons.search_filter_files)]
let collectTags: ()-> ([String], CGImage) = {
var values: [String] = []
let image: CGImage
if let tag = currentPeerTag {
values.append(tag.compactDisplayTitle.prefix(10))
}
if let tag = currentTag {
if let found = tags.first(where: { $0.0 == tag }) {
values.append(found.1)
image = found.2
} else {
image = theme.icons.search_filter
}
} else {
image = theme.icons.search_filter
}
return (values, image)
}
switch state.searchState {
case .Focus:
if searchView.customSearchControl == nil {
searchView.customSearchControl = CustomSearchController(clickHandler: { [weak self] control, updateTitle in
var items: [ContextMenuItem] = []
if state.forumPeer == nil {
items.append(ContextMenuItem(strings().chatListDownloadsTag, handler: { [weak self] in
updateSearchTags(SearchTags(messageTags: nil, peerTag: nil))
self?.showDownloads?()
}, itemImage: MenuAnimation.menu_save_as.value))
}
for tag in tags {
var append: Bool = false
if currentTag != tag.0 {
append = true
}
if append {
if let messagetag = tag.0 {
let itemImage: MenuAnimation?
switch messagetag {
case .photo:
itemImage = .menu_shared_media
case .video:
itemImage = .menu_video
case .webPage:
itemImage = .menu_copy_link
case .voiceOrInstantVideo:
itemImage = .menu_voice
case .gif:
itemImage = .menu_add_gif
case .file:
itemImage = .menu_file
default:
itemImage = nil
}
if let itemImage = itemImage {
items.append(ContextMenuItem(tag.1, handler: { [weak self] in
currentTag = tag.0
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
let collected = collectTags()
updateTitle(collected.0, collected.1)
self?.hideDownloads?()
}, itemImage: itemImage.value))
}
}
}
}
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
let value = AppMenu(menu: menu)
if let event = NSApp.currentEvent {
value.show(event: event, view: control)
}
}, deleteTag: { [weak self] index in
var count: Int = 0
if currentTag != nil {
count += 1
}
if currentPeerTag != nil {
count += 1
}
if index == 1 || count == 1 {
currentTag = nil
}
if index == 0 {
currentPeerTag = nil
}
let collected = collectTags()
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
self?.searchView.updateTags(collected.0, collected.1)
self?.hideDownloads?()
}, icon: theme.icons.search_filter)
}
updatePeerTag( { [weak self] updatedPeerTag in
guard let `self` = self else {
return
}
currentPeerTag = updatedPeerTag
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
self.searchView.setString("")
let collected = collectTags()
self.searchView.updateTags(collected.0, collected.1)
})
updateMessageTags( { [weak self] updatedMessageTags in
guard let `self` = self else {
return
}
currentTag = updatedMessageTags
updateSearchTags(SearchTags(messageTags: currentTag, peerTag: currentPeerTag?.id))
let collected = collectTags()
self.searchView.updateTags(collected.0, collected.1)
})
case .None:
searchView.customSearchControl = nil
}
}
fileprivate func searchStateChanged(_ state: PeerListState, arguments: Arguments, animated: Bool, updateSearchTags: @escaping(SearchTags)->Void, updatePeerTag:@escaping(@escaping(Peer?)->Void)->Void, updateMessageTags: @escaping(@escaping(MessageTags?)->Void)->Void) {
self.updateTags(state, updateSearchTags: updateSearchTags, updatePeerTag: updatePeerTag, updateMessageTags: updateMessageTags)
self.updateState(state, arguments: arguments, animated: animated)
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
let theme = (theme as! TelegramPresentationTheme)
self.backgroundColor = theme.colors.background
compose.set(background: .clear, for: .Normal)
compose.set(background: .clear, for: .Hover)
compose.set(background: theme.colors.accent, for: .Highlight)
compose.set(image: theme.icons.composeNewChat, for: .Normal)
compose.set(image: theme.icons.composeNewChat, for: .Hover)
compose.set(image: theme.icons.composeNewChatActive, for: .Highlight)
compose.layer?.cornerRadius = .cornerRadius
super.updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
self.updateLayout(frame.size, transition: .immediate)
}
func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) {
guard let state = self.state else {
return
}
var offset: CGFloat
switch theme.controllerBackgroundMode {
case .background:
offset = 50
case .tiled:
offset = 50
default:
offset = 50
}
if state.splitState == .minimisize {
switch self.mode {
case .folder, .forum:
offset = 0
default:
break
}
}
var inset: CGFloat = 0
if let header = self.header {
offset += header.frame.height
transition.updateFrame(view: header, frame: NSMakeRect(0, inset, size.width, header.frame.height))
inset += header.frame.height
}
if let callView = self.callView {
offset += callView.frame.height
transition.updateFrame(view: callView, frame: NSMakeRect(0, inset, size.width, callView.frame.height))
inset += callView.frame.height
}
let componentSize = NSMakeSize(40, 30)
transition.updateFrame(view: self.containerView, frame: NSMakeRect(0, 0, size.width, offset))
var searchWidth = (size.width - 10 * 2)
if state.searchState != .Focus && state.mode.isPlain {
searchWidth -= (componentSize.width + 12)
}
if let _ = self.proxy {
searchWidth -= componentSize.width
}
if let _ = self.premiumStatus {
searchWidth -= componentSize.width
}
let searchRect = NSMakeRect(10, floorToScreenPixels(backingScaleFactor, inset + (offset - inset - componentSize.height)/2.0), searchWidth, componentSize.height)
transition.updateFrame(view: searchView, frame: searchRect)
transition.updateFrame(view: tableView, frame: NSMakeRect(0, offset, size.width, size.height - offset))
transition.updateFrame(view: backgroundView, frame: size.bounds)
if let downloads = downloads {
let rect = NSMakeRect(0, size.height - downloads.frame.height, size.width - .borderSize, downloads.frame.height)
transition.updateFrame(view: downloads, frame: rect)
}
if state.splitState == .minimisize {
transition.updateFrame(view: compose, frame: compose.centerFrame())
} else {
var controlPoint = NSMakePoint(size.width - 12, floorToScreenPixels(backingScaleFactor, (offset - componentSize.height)/2.0))
controlPoint.x -= componentSize.width
transition.updateFrame(view: compose, frame: CGRect(origin: controlPoint, size: componentSize))
if let view = proxy {
controlPoint.x -= componentSize.width
transition.updateFrame(view: view, frame: CGRect(origin: controlPoint, size: componentSize))
}
if let view = premiumStatus {
controlPoint.x -= componentSize.width
transition.updateFrame(view: view, frame: CGRect(origin: controlPoint, size: componentSize))
}
}
if let actionView = self.actionView {
transition.updateFrame(view: actionView, frame: CGRect(origin: CGPoint(x: 0, y: size.height - actionView.frame.height), size: actionView.frame.size))
}
}
func updateDownloads(_ state: DownloadsSummary.State, context: AccountContext, arguments: DownloadsControlArguments, animated: Bool) {
if !state.isEmpty {
let current: DownloadsControl
if let view = self.downloads {
current = view
} else {
current = DownloadsControl(frame: NSMakeRect(0, frame.height - 30, frame.width - .borderSize, 30))
self.downloads = current
addSubview(current, positioned: .above, relativeTo: self.tableView)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
current.layer?.animatePosition(from: NSMakePoint(current.frame.minX, current.frame.maxY), to: current.frame.origin)
}
}
current.update(state, context: context, arguments: arguments, animated: animated)
current.removeAllHandlers()
current.set(handler: { _ in
arguments.open()
}, for: .Click)
} else if let view = self.downloads {
self.downloads = nil
performSubviewPosRemoval(view, pos: NSMakePoint(0, frame.maxY), animated: true)
}
}
}
enum PeerListMode : Equatable {
case plain
case folder(EngineChatList.Group)
case filter(Int32)
case forum(PeerId)
var isPlain:Bool {
switch self {
case .plain:
return true
default:
return false
}
}
var groupId: EngineChatList.Group {
switch self {
case let .folder(groupId):
return groupId
default:
return .root
}
}
var filterId: Int32? {
switch self {
case let .filter(id):
return id
default:
return nil
}
}
var location: ChatListControllerLocation {
switch self {
case .plain:
return .chatList(groupId: .root)
case let .folder(group):
return .chatList(groupId: group._asGroup())
case let .forum(peerId):
return .forum(peerId: peerId)
case let .filter(filterId):
return .chatList(groupId: .group(filterId))
}
}
}
class PeersListController: TelegramGenericViewController<PeerListContainerView>, TableViewDelegate {
func findGroupStableId(for stableId: AnyHashable) -> AnyHashable? {
return nil
}
private let stateValue: Atomic<PeerListState?> = Atomic(value: nil)
private let stateSignal: ValuePromise<PeerListState?> = ValuePromise(nil, ignoreRepeated: true)
var stateUpdater: Signal<PeerListState?, NoError> {
return stateSignal.get()
}
private let progressDisposable = MetaDisposable()
private let createSecretChatDisposable = MetaDisposable()
private let actionsDisposable = DisposableSet()
private let followGlobal:Bool
private let searchOptions: AppSearchOptions
private var downloadsController: ViewController?
private var tempImportersContext: PeerInvitationImportersContext? = nil
let mode:PeerListMode
private(set) var searchController:SearchController? {
didSet {
if let controller = searchController {
genericView.customHandler.size = { [weak controller, weak self] size in
let frame = self?.genericView.tableView.frame ?? size.bounds
controller?.view.frame = frame
}
progressDisposable.set((controller.isLoading.get() |> deliverOnMainQueue).start(next: { [weak self] isLoading in
self?.genericView.searchView.isLoading = isLoading
}))
}
}
}
let topics: ForumChannelTopics?
init(_ context: AccountContext, followGlobal:Bool = true, mode: PeerListMode = .plain, searchOptions: AppSearchOptions = [.chats, .messages]) {
self.followGlobal = followGlobal
self.mode = mode
self.searchOptions = searchOptions
switch mode {
case let .forum(peerId):
self.topics = ForumChannelTopics(account: context.account, peerId: peerId)
default:
self.topics = nil
}
super.init(context)
self.bar = .init(height: !mode.isPlain ? 50 : 0)
}
override var redirectUserInterfaceCalls: Bool {
return true
}
override var responderPriority: HandlerPriority {
return .low
}
deinit {
progressDisposable.dispose()
createSecretChatDisposable.dispose()
actionsDisposable.dispose()
}
override func viewDidResized(_ size: NSSize) {
super.viewDidResized(size)
}
func showDownloads(animated: Bool) {
self.genericView.searchView.change(state: .Focus, true)
let context = self.context
if let controller = self.searchController {
let ready = controller.ready.get()
|> filter { $0 }
|> take(1)
_ = ready.start(next: { [weak self] _ in
guard let `self` = self else {
return
}
let controller: ViewController
if let current = self.downloadsController {
controller = current
} else {
controller = DownloadsController(context: context, searchValue: self.genericView.searchView.searchValue |> map { $0.request })
self.downloadsController = controller
controller.frame = self.genericView.tableView.frame
self.addSubview(controller.view)
if animated {
controller.view.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
controller.view.layer?.animateScaleSpring(from: 1.1, to: 1, duration: 0.2)
}
}
self.genericView.searchView.updateTags([strings().chatListDownloadsTag], theme.icons.search_filter_downloads)
})
}
}
private func hideDownloads(animated: Bool) {
if let downloadsController = downloadsController {
downloadsController.viewWillDisappear(animated)
self.downloadsController = nil
downloadsController.viewDidDisappear(animated)
let view = downloadsController.view
downloadsController.view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in
view?.removeFromSuperview()
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
let context = self.context
let mode = self.mode
genericView.showDownloads = { [weak self] in
self?.showDownloads(animated: true)
}
genericView.hideDownloads = { [weak self] in
self?.hideDownloads(animated: true)
}
let actionsDisposable = self.actionsDisposable
actionsDisposable.add((context.cancelGlobalSearch.get() |> deliverOnMainQueue).start(next: { [weak self] animated in
self?.genericView.searchView.cancel(animated)
}))
genericView.mode = mode
if followGlobal {
actionsDisposable.add((context.globalPeerHandler.get() |> deliverOnMainQueue).start(next: { [weak self] location in
guard let `self` = self else {return}
self.changeSelection(location)
if location == nil {
if !self.genericView.searchView.isEmpty {
_ = self.window?.makeFirstResponder(self.genericView.searchView.input)
}
}
}))
}
if self.navigationController?.modalAction is FWDNavigationAction {
self.setCenterTitle(strings().chatForwardActionHeader)
}
if self.navigationController?.modalAction is ShareInlineResultNavigationAction {
self.setCenterTitle(strings().chatShareInlineResultActionHeader)
}
genericView.tableView.delegate = self
let state = self.stateSignal
let stateValue = self.stateValue
let updateState:((PeerListState?)->PeerListState?) -> Void = { f in
state.set(stateValue.modify(f))
}
let layoutSignal = context.layoutValue
let proxy = proxySettings(accountManager: context.sharedContext.accountManager) |> mapToSignal { ps -> Signal<(ProxySettings, ConnectionStatus), NoError> in
return context.account.network.connectionStatus |> map { status -> (ProxySettings, ConnectionStatus) in
return (ps, status)
}
}
let peer: Signal<PeerEquatable?, NoError> = context.account.postbox.peerView(id: context.peerId) |> map { view in
if let peer = peerViewMainPeer(view) {
return PeerEquatable(peer)
} else {
return nil
}
}
let forumPeer: Signal<PeerListState.ForumData?, NoError>
if case let .forum(peerId) = self.mode {
let tempImportersContext = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .requests(query: nil))
self.tempImportersContext = tempImportersContext
let signal = combineLatest(context.account.postbox.peerView(id: peerId), getGroupCallPanelData(context: context, peerId: peerId), tempImportersContext.state)
forumPeer = signal |> mapToSignal { view, call, invitationState in
if let peer = peerViewMainPeer(view) as? TelegramChannel, let cachedData = view.cachedData as? CachedChannelData, peer.isForum {
let info: ChatActiveGroupCallInfo?
if let activeCall = cachedData.activeCall {
info = .init(activeCall: activeCall, data: call, callJoinPeerId: cachedData.callJoinPeerId, joinHash: nil, isLive: peer.isChannel || peer.isGigagroup)
} else {
info = nil
}
let membersCount = cachedData.participantsSummary.memberCount ?? 0
let online: Signal<Int32, NoError>
if membersCount < 200 {
online = context.peerChannelMemberCategoriesContextsManager.recentOnlineSmall(peerId: peerId)
} else {
online = context.peerChannelMemberCategoriesContextsManager.recentOnline(peerId: peerId)
}
return online |> map {
return .init(peer: peer, peerView: view, online: $0, call: info, invitationState: invitationState)
}
} else {
return .single(nil)
}
}
} else {
forumPeer = .single(nil)
}
let postbox = context.account.postbox
let previousPeerCache = Atomic<[PeerId: Peer]>(value: [:])
let previousActivities = Atomic<PeerListState.InputActivities?>(value: nil)
let inputActivities = context.account.allPeerInputActivities()
|> mapToSignal { activitiesByPeerId -> Signal<[PeerActivitySpace: [PeerListState.InputActivities.Activity]], NoError> in
var foundAllPeers = true
var cachedResult: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = [:]
previousPeerCache.with { dict -> Void in
for (chatPeerId, activities) in activitiesByPeerId {
var cachedChatResult: [PeerListState.InputActivities.Activity] = []
for (peerId, activity) in activities {
if let peer = dict[peerId] {
cachedChatResult.append(PeerListState.InputActivities.Activity(peer, activity))
} else {
foundAllPeers = false
break
}
cachedResult[chatPeerId] = cachedChatResult
}
}
}
if foundAllPeers {
return .single(cachedResult)
} else {
return postbox.transaction { transaction -> [PeerActivitySpace: [PeerListState.InputActivities.Activity]] in
var result: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = [:]
var peerCache: [PeerId: Peer] = [:]
for (chatPeerId, activities) in activitiesByPeerId {
var chatResult: [PeerListState.InputActivities.Activity] = []
for (peerId, activity) in activities {
if let peer = transaction.getPeer(peerId) {
chatResult.append(PeerListState.InputActivities.Activity(peer, activity))
peerCache[peerId] = peer
}
}
result[chatPeerId] = chatResult
}
let _ = previousPeerCache.swap(peerCache)
return result
}
}
}
|> map { activities -> PeerListState.InputActivities in
return previousActivities.modify { current in
var updated = false
let currentList: [PeerActivitySpace: [PeerListState.InputActivities.Activity]] = current?.activities ?? [:]
if currentList.count != activities.count {
updated = true
} else {
outer: for (space, currentValue) in currentList {
if let value = activities[space] {
if currentValue.count != value.count {
updated = true
break outer
} else {
for i in 0 ..< currentValue.count {
if currentValue[i] != value[i] {
updated = true
break outer
}
}
}
} else {
updated = true
break outer
}
}
}
if updated {
if activities.isEmpty {
return .init(activities: [:])
} else {
return .init(activities: activities)
}
} else {
return current
}
} ?? .init(activities: [:])
}
actionsDisposable.add(combineLatest(queue: .mainQueue(), proxy, layoutSignal, peer, forumPeer, inputActivities, appearanceSignal).start(next: { pref, layout, peer, forumPeer, inputActivities, _ in
updateState { state in
let state: PeerListState = .init(proxySettings: pref.0, connectionStatus: pref.1, splitState: layout, searchState: state?.searchState ?? .None, peer: peer, forumPeer: forumPeer, mode: mode, activities: inputActivities)
return state
}
}))
let pushController:(ViewController)->Void = { [weak self] c in
self?.context.bindings.rootNavigation().push(c)
}
let openProxySettings:()->Void = { [weak self] in
if let controller = self?.context.bindings.rootNavigation().controller as? InputDataController {
if controller.identifier == "proxy" {
return
}
}
let controller = proxyListController(accountManager: context.sharedContext.accountManager, network: context.account.network, share: { servers in
var message: String = ""
for server in servers {
message += server.link + "\n\n"
}
message = message.trimmed
showModal(with: ShareModalController(ShareLinkObject(context, link: message)), for: context.window)
}, pushController: { controller in
pushController(controller)
})
pushController(controller)
}
genericView.openProxy = { _ in
openProxySettings()
}
genericView.openStatus = { control in
let peer = stateValue.with { $0?.peer?.peer }
if let peer = peer as? TelegramUser {
let callback:(TelegramMediaFile, Int32?, CGRect?)->Void = { file, timeout, fromRect in
context.reactions.setStatus(file, peer: peer, timestamp: context.timestamp, timeout: timeout, fromRect: fromRect)
}
if control.popover == nil {
showPopover(for: control, with: PremiumStatusController(context, callback: callback, peer: peer), edge: .maxY, inset: NSMakePoint(-80, -35), static: true, animationMode: .reveal)
}
}
}
genericView.compose.contextMenu = { [weak self] in
let items = [ContextMenuItem(strings().composePopoverNewGroup, handler: { [weak self] in
self?.context.composeCreateGroup()
}, itemImage: MenuAnimation.menu_create_group.value),
ContextMenuItem(strings().composePopoverNewSecretChat, handler: { [weak self] in
self?.context.composeCreateSecretChat()
}, itemImage: MenuAnimation.menu_lock.value),
ContextMenuItem(strings().composePopoverNewChannel, handler: { [weak self] in
self?.context.composeCreateChannel()
}, itemImage: MenuAnimation.menu_channel.value)];
let menu = ContextMenu()
for item in items {
menu.addItem(item)
}
return menu
}
genericView.searchView.searchInteractions = SearchInteractions({ [weak self] state, animated in
switch state.state {
case .Focus:
assert(self?.searchController == nil)
self?.showSearchController(animated: animated)
case .None:
self?.hideSearchController(animated: animated)
}
updateState { current in
var current = current
current?.searchState = state.state
return current
}
}, { [weak self] state in
updateState { current in
var current = current
current?.searchState = state.state
return current
}
self?.searchController?.request(with: state.request)
}, responderModified: { [weak self] state in
self?.context.isInGlobalSearch = state.responder
})
let stateSignal = state.get()
|> filter { $0 != nil }
|> map { $0! }
let previousState: Atomic<PeerListState?> = Atomic(value: nil)
let arguments = Arguments(context: context, joinGroupCall: { info in
if case let .forum(peerId) = mode {
let join:(PeerId, Date?, Bool)->Void = { joinAs, _, _ in
_ = showModalProgress(signal: requestOrJoinGroupCall(context: context, peerId: peerId, joinAs: joinAs, initialCall: info.activeCall, initialInfo: info.data?.info, joinHash: nil), for: context.window).start(next: { result in
switch result {
case let .samePeer(callContext):
applyGroupCallResult(context.sharedContext, callContext)
case let .success(callContext):
applyGroupCallResult(context.sharedContext, callContext)
default:
alert(for: context.window, info: strings().errorAnError)
}
})
}
if let callJoinPeerId = info.callJoinPeerId {
join(callJoinPeerId, nil, false)
} else {
selectGroupCallJoiner(context: context, peerId: peerId, completion: join)
}
}
}, joinGroup: { peerId in
joinChannel(context: context, peerId: peerId)
}, openPendingRequests: { [weak self] in
if let importersContext = self?.tempImportersContext, case let .forum(peerId) = mode {
let navigation = context.bindings.rootNavigation()
navigation.push(RequestJoinMemberListController(context: context, peerId: peerId, manager: importersContext, openInviteLinks: { [weak navigation] in
navigation?.push(InviteLinksController(context: context, peerId: peerId, manager: nil))
}))
}
}, dismissPendingRequests: { peerIds in
if case let .forum(peerId) = mode {
FastSettings.dismissPendingRequests(peerIds, for: peerId)
updateState { current in
var current = current
current?.forumPeer?.invitationState = nil
return current
}
}
})
self.takeArguments = { [weak arguments] in
return arguments
}
actionsDisposable.add(stateSignal.start(next: { [weak self] state in
self?.updateState(state, previous: previousState.swap(state), arguments: arguments)
}))
centerBarView.set(handler: { _ in
switch mode {
case let .forum(peerId):
ForumUI.openInfo(peerId, context: context)
default:
break
}
}, for: .Click)
}
private var state: PeerListState? {
return self.stateValue.with { $0 }
}
private func updateState(_ state: PeerListState, previous: PeerListState?, arguments: Arguments) {
if previous?.forumPeer != state.forumPeer {
if state.forumPeer == nil {
switch self.mode {
case let .forum(peerId):
if state.splitState == .single {
let controller = ChatController(context: context, chatLocation: .peer(peerId))
self.navigationController?.push(controller)
self.navigationController?.removeImmediately(self, depencyReady: controller)
} else {
self.navigationController?.back()
}
default:
break
}
return
}
}
if previous?.splitState != state.splitState {
if case .minimisize = state.splitState {
if self.genericView.searchView.state == .Focus {
self.genericView.searchView.change(state: .None, false)
}
}
self.checkSearchMedia()
self.genericView.tableView.alwaysOpenRowsOnMouseUp = state.splitState == .single
self.genericView.tableView.reloadData()
self.requestUpdateBackBar()
}
setCenterTitle(self.defaultBarTitle)
if let forum = state.forumPeer {
let title = stringStatus(for: forum.peerView, context: context, onlineMemberCount: forum.online, expanded: true)
setCenterStatus(title.status.string)
} else {
setCenterStatus(nil)
}
self.genericView.searchStateChanged(state, arguments: arguments, animated: true, updateSearchTags: { [weak self] tags in
self?.searchController?.updateSearchTags(tags)
self?.sharedMediaWithToken(tags)
}, updatePeerTag: { [weak self] f in
self?.searchController?.setPeerAsTag = f
}, updateMessageTags: { [weak self] f in
self?.updateSearchMessageTags = f
})
if let forum = state.forumPeer {
if forum.peer.participationStatus == .left && previous?.forumPeer?.peer.participationStatus == .member {
self.navigationController?.back()
}
}
}
private var topicRightBar: ImageButton?
override func requestUpdateRightBar() {
super.requestUpdateRightBar()
topicRightBar?.style = navigationButtonStyle
topicRightBar?.set(image: theme.icons.chatActions, for: .Normal)
topicRightBar?.set(image: theme.icons.chatActionsActive, for: .Highlight)
topicRightBar?.setFrameSize(70, 50)
topicRightBar?.center()
}
private var takeArguments:()->Arguments? = {
return nil
}
override func getRightBarViewOnce() -> BarView {
switch self.mode {
case .forum:
let bar = BarView(70, controller: self)
let button = ImageButton()
bar.addSubview(button)
let context = self.context
self.topicRightBar = button
button.contextMenu = { [weak self] in
let menu = ContextMenu()
if let peer = self?.state?.forumPeer {
var items: [ContextMenuItem] = []
let chatController = context.bindings.rootNavigation().controller as? ChatController
let infoController = context.bindings.rootNavigation().controller as? PeerInfoController
let topicController = context.bindings.rootNavigation().controller as? InputDataController
if infoController == nil || (infoController?.peerId != peer.peer.id || infoController?.threadInfo != nil) {
items.append(ContextMenuItem(strings().forumTopicContextInfo, handler: {
ForumUI.openInfo(peer.peer.id, context: context)
}, itemImage: MenuAnimation.menu_show_info.value))
}
if chatController == nil || (chatController?.chatInteraction.chatLocation != .peer(peer.peer.id)) {
items.append(ContextMenuItem(strings().forumTopicContextShowAsMessages, handler: { [weak self] in
self?.open(with: .chatId(.chatList(peer.peer.id), peer.peer.id, -1), forceAnimated: true)
}, itemImage: MenuAnimation.menu_read.value))
}
if let call = self?.state?.forumPeer?.call {
if call.data?.groupCall == nil {
if let data = call.data, data.participantCount == 0 && call.activeCall.scheduleTimestamp == nil {
items.append(ContextMenuItem(strings().peerInfoActionVoiceChat, handler: { [weak self] in
self?.takeArguments()?.joinGroupCall(call)
}, itemImage: MenuAnimation.menu_video_chat.value))
}
}
}
if peer.peer.isAdmin && peer.peer.hasPermission(.manageTopics) {
if topicController?.identifier != "ForumTopic" {
if !items.isEmpty {
items.append(ContextSeparatorItem())
}
items.append(ContextMenuItem(strings().forumTopicContextNew, handler: {
ForumUI.createTopic(peer.peer.id, context: context)
}, itemImage: MenuAnimation.menu_edit.value))
}
}
if !items.isEmpty {
for item in items {
menu.addItem(item)
}
}
}
return menu
}
return bar
default:
break
}
return super.getRightBarViewOnce()
}
override var defaultBarTitle: String {
switch self.mode {
case .folder:
return strings().chatListArchivedChats
case .forum:
return state?.forumPeer?.peer.displayTitle ?? super.defaultBarTitle
default:
return super.defaultBarTitle
}
}
private func checkSearchMedia() {
let destroy:()->Void = { [weak self] in
if let previous = self?.mediaSearchController {
self?.context.bindings.rootNavigation().removeImmediately(previous)
}
}
guard context.layout == .dual else {
destroy()
return
}
guard let _ = self.searchController else {
destroy()
return
}
}
private weak var mediaSearchController: PeerMediaController?
private var updateSearchMessageTags: ((MessageTags?)->Void)? = nil
private func sharedMediaWithToken(_ tags: SearchTags) -> Void {
let destroy:()->Void = { [weak self] in
if let previous = self?.mediaSearchController {
self?.context.bindings.rootNavigation().removeImmediately(previous)
}
}
guard context.layout == .dual else {
destroy()
return
}
guard let searchController = self.searchController else {
destroy()
return
}
guard let messageTags = tags.messageTags else {
destroy()
return
}
if let peerId = tags.peerTag {
let onDeinit: ()->Void = { [weak self] in
self?.updateSearchMessageTags?(nil)
}
let navigation = context.bindings.rootNavigation()
let signal = searchController.externalSearchMessages
|> filter { $0 != nil && $0?.tags == messageTags }
let controller = PeerMediaController(context: context, peerId: peerId, isProfileIntended: false, externalSearchData: PeerMediaExternalSearchData(initialTags: messageTags, searchResult: signal, loadMore: { }))
controller.onDeinit = onDeinit
navigation.push(controller, false, style: nil)
if let previous = self.mediaSearchController {
previous.onDeinit = nil
navigation.removeImmediately(previous, depencyReady: controller)
}
self.mediaSearchController = controller
}
}
override func requestUpdateBackBar() {
self.leftBarView.minWidth = 70
super.requestUpdateBackBar()
}
override func getLeftBarViewOnce() -> BarView {
let view = BackNavigationBar(self, canBeEmpty: true)
view.minWidth = 70
return view
}
override func backSettings() -> (String, CGImage?) {
return context.layout == .minimisize ? ("", theme.icons.instantViewBack) : super.backSettings()
}
func changeSelection(_ location: ChatLocation?) {
if let location = location {
var id: UIChatListEntryId
switch location {
case .peer:
id = .chatId(.chatList(location.peerId), location.peerId, -1)
case let .thread(data):
let threadId = makeMessageThreadId(data.messageId)
switch self.mode {
case .plain, .filter, .folder:
id = .forum(location.peerId)
case .forum:
id = .chatId(.forum(threadId), location.peerId, -1)
}
}
if self.genericView.tableView.item(stableId: id) == nil {
let fId = UIChatListEntryId.forum(location.peerId)
if self.genericView.tableView.item(stableId: fId) != nil {
id = fId
}
}
self.genericView.tableView.changeSelection(stableId: id)
} else {
self.genericView.tableView.changeSelection(stableId: nil)
}
}
private func showSearchController(animated: Bool) {
if searchController == nil {
let initialTags: SearchTags
let target: SearchController.Target
switch self.mode {
case let .forum(peerId):
initialTags = .init(messageTags: nil, peerTag: nil)
target = .forum(peerId)
default:
initialTags = .init(messageTags: nil, peerTag: nil)
target = .common(.root)
}
let rect = self.genericView.tableView.frame
let frame = rect
let searchController = SearchController(context: self.context, open: { [weak self] (id, messageId, close) in
if let id = id {
self?.open(with: id, messageId: messageId, close: close)
} else {
self?.genericView.searchView.cancel(true)
}
}, options: self.searchOptions, frame: frame, target: target, tags: initialTags)
searchController.pinnedItems = self.collectPinnedItems
self.searchController = searchController
searchController.defaultQuery = self.genericView.searchView.query
searchController.navigationController = self.navigationController
searchController.viewWillAppear(true)
searchController.loadViewIfNeeded()
let signal = searchController.ready.get() |> take(1)
_ = signal.start(next: { [weak searchController, weak self] _ in
if let searchController = searchController {
if animated {
searchController.view.layer?.animateAlpha(from: 0.0, to: 1.0, duration: 0.25, completion:{ [weak self] complete in
if complete {
self?.searchController?.viewDidAppear(animated)
}
})
searchController.view.layer?.animateScaleSpring(from: 1.05, to: 1.0, duration: 0.4, bounce: false)
searchController.view.layer?.animatePosition(from: NSMakePoint(rect.minX, rect.minY + 15), to: rect.origin, duration: 0.4, timingFunction: .spring)
} else {
searchController.viewDidAppear(animated)
}
self?.addSubview(searchController.view)
}
})
}
}
private func hideSearchController(animated: Bool) {
if let downloadsController = downloadsController {
downloadsController.viewWillDisappear(animated)
self.downloadsController = nil
downloadsController.viewDidDisappear(animated)
let view = downloadsController.view
downloadsController.view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in
view?.removeFromSuperview()
})
}
if let searchController = self.searchController {
let animated = animated && searchController.didSetReady
searchController.viewWillDisappear(animated)
searchController.view.layer?.opacity = animated ? 1.0 : 0.0
searchController.viewDidDisappear(true)
self.searchController = nil
self.genericView.tableView.isHidden = false
self.genericView.tableView.change(opacity: 1, animated: animated)
let view = searchController.view
searchController.view._change(opacity: 0, animated: animated, duration: 0.25, timingFunction: CAMediaTimingFunctionName.spring, completion: { [weak view] completed in
view?.removeFromSuperview()
})
if animated {
searchController.view.layer?.animateScaleSpring(from: 1.0, to: 1.05, duration: 0.4, removeOnCompletion: false, bounce: false)
genericView.tableView.layer?.animateScaleSpring(from: 0.95, to: 1.00, duration: 0.4, removeOnCompletion: false, bounce: false)
}
}
if let controller = mediaSearchController {
context.bindings.rootNavigation().removeImmediately(controller, upNext: false)
}
}
override func focusSearch(animated: Bool, text: String? = nil) {
genericView.searchView.change(state: .Focus, animated)
if let text = text {
genericView.searchView.setString(text)
}
}
var collectPinnedItems:[PinnedItemId] {
return []
}
public override func escapeKeyAction() -> KeyHandlerResult {
guard context.layout != .minimisize else {
return .invoked
}
if genericView.tableView.highlightedItem() != nil {
genericView.tableView.cancelHighlight()
return .invoked
}
if genericView.searchView.state == .None {
return genericView.searchView.changeResponder() ? .invoked : .rejected
} else if genericView.searchView.state == .Focus && genericView.searchView.query.length > 0 {
genericView.searchView.change(state: .None, true)
return .invoked
}
return .rejected
}
public override func returnKeyAction() -> KeyHandlerResult {
if let highlighted = genericView.tableView.highlightedItem() {
_ = genericView.tableView.select(item: highlighted)
return .invoked
}
return .rejected
}
func open(with entryId: UIChatListEntryId, messageId:MessageId? = nil, initialAction: ChatInitialAction? = nil, close:Bool = true, addition: Bool = false, forceAnimated: Bool = false) ->Void {
let navigation = context.bindings.rootNavigation()
var addition = addition
var close = close
if let searchTags = self.searchController?.searchTags {
if searchTags.peerTag != nil && searchTags.messageTags != nil {
addition = true
}
if !searchTags.isEmpty {
close = false
}
}
switch entryId {
case let .chatId(type, peerId, _):
switch type {
case let .chatList(peerId):
if let modalAction = navigation.modalAction as? FWDNavigationAction, peerId == context.peerId {
_ = Sender.forwardMessages(messageIds: modalAction.messages.map{$0.id}, context: context, peerId: context.peerId, replyId: nil).start()
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.0).start()
modalAction.afterInvoke()
navigation.removeModalAction()
} else {
if let current = navigation.controller as? ChatController, peerId == current.chatInteraction.peerId, let messageId = messageId, current.mode == .history {
current.chatInteraction.focusMessageId(nil, messageId, .center(id: 0, innerId: nil, animated: false, focus: .init(focus: true), inset: 0))
} else {
let chatLocation: ChatLocation = .peer(peerId)
let chat: ChatController
if addition {
chat = ChatAdditionController(context: context, chatLocation: chatLocation, messageId: messageId)
} else {
chat = ChatController(context: self.context, chatLocation: chatLocation, messageId: messageId, initialAction: initialAction)
}
let animated = context.layout == .single || forceAnimated
navigation.push(chat, context.layout == .single || forceAnimated, style: animated ? .push : ViewControllerStyle.none)
}
}
case let .forum(threadId):
_ = ForumUI.openTopic(threadId, peerId: peerId, context: context, messageId: messageId).start()
}
case let .groupId(groupId):
self.navigationController?.push(ChatListController(context, modal: false, mode: .folder(groupId)))
case let .forum(peerId):
ForumUI.open(peerId, context: context)
case .reveal:
break
case .empty:
break
case .loading:
break
}
if close {
self.genericView.searchView.cancel(true)
}
}
func longSelect(row: Int, item: TableRowItem) {
}
func selectionWillChange(row:Int, item:TableRowItem, byClick: Bool) -> Bool {
return true
}
func selectionDidChange(row:Int, item:TableRowItem, byClick:Bool, isNew:Bool) -> Void {
}
func isSelectable(row:Int, item:TableRowItem) -> Bool {
return true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
}
private var effectiveTableView: TableView {
switch genericView.searchView.state {
case .Focus:
return searchController?.genericView ?? genericView.tableView
case .None:
return genericView.tableView
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if context.layout == .single && animated {
context.globalPeerHandler.set(.single(nil))
}
context.window.set(handler: { [weak self] _ in
if let strongSelf = self {
return strongSelf.escapeKeyAction()
}
return .invokeNext
}, with: self, for: .Escape, priority:.low)
context.window.set(handler: { [weak self] _ in
if let strongSelf = self {
return strongSelf.returnKeyAction()
}
return .invokeNext
}, with: self, for: .Return, priority:.low)
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
if let item = self?.effectiveTableView.selectedItem(), item.index > 0 {
self?.effectiveTableView.selectPrev()
}
return .invoked
}, with: self, for: .UpArrow, priority: .medium, modifierFlags: [.option])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectNext()
return .invoked
}, with: self, for: .DownArrow, priority:.medium, modifierFlags: [.option])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectNext(turnDirection: false)
return .invoked
}, with: self, for: .Tab, priority: .modal, modifierFlags: [.control])
context.window.set(handler: { [weak self] _ -> KeyHandlerResult in
self?.effectiveTableView.selectPrev(turnDirection: false)
return .invoked
}, with: self, for: .Tab, priority: .modal, modifierFlags: [.control, .shift])
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
context.window.removeAllHandlers(for: self)
}
}
| 50a021e0dd652ab7dbc97cfe34eada9f | 39.722503 | 272 | 0.539213 | false | false | false | false |
yashvyas29/YVSwiftTableForms | refs/heads/master | YVSwiftTableFormsExample/Resources/YVSwiftTableForms/YVSubClasses/YVTextFieldValidator.swift | gpl-3.0 | 1 | //
// YVTextFieldValidator.swift
// YVSwiftTableForms
//
// Created by Yash on 10/05/16.
// Copyright © 2016 Yash. All rights reserved.
//
import UIKit
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let alphabetCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let specialSymbolsCharacterSet : NSCharacterSet = NSCharacterSet(charactersInString: "!~`@#$%^&*-+();:=_{}[],.<>?\\/|\"\'")
class YVTextFieldValidator: UITextField, UITextFieldDelegate {
//** properties which will decide which kind of validation user wants
var ParentDelegate : AnyObject?
var checkForEmptyTextField : Bool = false
var allowOnlyNumbers : Bool = false
var allowOnlyAlphabets : Bool = false
var restrictSpecialSymbolsOnly : Bool = false
var checkForValidEmailAddress : Bool = false
var restrictTextFieldToLimitedCharecters : Bool = false
var setNumberOfCharectersToBeRestricted : Int = 0
var allowToShowAlertView : Bool = false
var alertControllerForNumberOnly = UIAlertController()
var alertControllerForAlphabetsOnly = UIAlertController()
var alertControllerForSpecialSymbols = UIAlertController()
var alertControllerForInvalidEmailAddress = UIAlertController()
//MARK: awakeFromNib
// Setting the delegate to Class's instance
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
//MARK: validation methods
// 01. This method will check if there are any blank textFields in class
class func checkIfAllFieldsAreFilled(view:UIView) -> Bool{
let subviews : NSArray = view.subviews
if(subviews.count == 0){
return false
}
for currentObject in subviews{
if let currentObject = currentObject as? UITextField {
if((currentObject.text?.isEmpty) != nil){
YVTextFieldValidator.shaketextField(currentObject)
}
}
self.checkIfAllFieldsAreFilled(currentObject as! UIView)
}
return true
}
// 02. This method will check if there are any white space in the textField.
class func checkForWhiteSpaceInTextField(inputString : String) -> String{
let trimmedString = inputString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmedString
}
// 03. This method will allow only numbers in the textField.
func allowOnlyNumbersInTextField(string : String)->Bool{
let numberCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let inputString = string
let range = inputString.rangeOfCharacterFromSet(numberCharacterSet)
print(inputString)
// range will be nil if no numbers are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 04. This method will allow only alphabets in the textField.
func allowOnlyAlphabetsInTextField(string : String)->Bool{
let inputString = string
let range = inputString.rangeOfCharacterFromSet(alphabetCharacterSet)
print(inputString)
// range will be nil if no alphabet are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
// 05. This method will restrict only special symbols in the textField.
func restrictSpecialSymbols(string : String) -> Bool
{
let range = string.rangeOfCharacterFromSet(specialSymbolsCharacterSet.invertedSet)
print(string)
// range will be nil if no specialSymbol are found
if range != nil {
return true
}
else {
return false
// do your stuff
}
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
if(checkForValidEmailAddress){
let emailReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let range = textField.text!.rangeOfString(emailReg, options:.RegularExpressionSearch)
let result = range != nil ? true : false
print(result)
if(result){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForInvalidEmailAddress, animated: true, completion: nil)
return false
}
}
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(allowOnlyNumbers){
if(string == ""){
return true
}
let flag : Bool = self.allowOnlyNumbersInTextField(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForNumberOnly, animated: true, completion: nil)
return false
}
}
}
else if(allowOnlyAlphabets){
if(string == "") {
return true
}
let flag : Bool = self.allowOnlyAlphabetsInTextField(string)
if(flag) {
return true
}
else {
if(allowToShowAlertView) {
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForAlphabetsOnly, animated: true, completion: nil)
return false
}
}
}
else if(restrictSpecialSymbolsOnly){
if(string == ""){
return true
}
let flag : Bool = self.restrictSpecialSymbols(string)
if(flag){
return true
}
else{
if(allowToShowAlertView){
ParentDelegate as! UIViewController
ParentDelegate!.presentViewController(alertControllerForSpecialSymbols, animated: true, completion: nil)
return false
}
}
}
else if(restrictTextFieldToLimitedCharecters){
let newLength = textField.text!.characters.count + string.characters.count - range.length
return newLength <= setNumberOfCharectersToBeRestricted
}
else{
return true
}
return false
}
//MARK: Setter methods
func setFlagForAllowNumbersOnly(flagForNumbersOnly : Bool){
allowOnlyNumbers = flagForNumbersOnly
}
func setFlagForAllowAlphabetsOnly(flagForAlphabetsOnly : Bool){
allowOnlyAlphabets = flagForAlphabetsOnly
}
func setFlagForRestrictSpecialSymbolsOnly(RestrictSpecialSymbols : Bool){
restrictSpecialSymbolsOnly = RestrictSpecialSymbols
}
func setFlagForcheckForValidEmailAddressOnly(flagForValidEmailAddress : Bool){
checkForValidEmailAddress = flagForValidEmailAddress
}
func setFlagForLimitedNumbersOFCharecters(numberOfCharacters : Int,flagForLimitedNumbersOfCharacters : Bool){
restrictTextFieldToLimitedCharecters = flagForLimitedNumbersOfCharacters
setNumberOfCharectersToBeRestricted = numberOfCharacters
}
//MARK: show alert methods
func showAlertForNumberOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForNumberOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForNumberOnly.addAction(buttonAction)
}
}
func showAlertForAlphabetsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForAlphabetsOnly = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForAlphabetsOnly.addAction(buttonAction)
}
}
func showAlertForSpecialSymbolsOnly(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForSpecialSymbols = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForSpecialSymbols.addAction(buttonAction)
}
}
func showAlertForinvalidEmailAddrress(title: String, message: String, buttonTitles : NSArray, buttonActions: NSArray){
alertControllerForInvalidEmailAddress = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
for i in 0 ..< buttonActions.count {
let count = i
let buttonAction = UIAlertAction(title: buttonTitles[count] as? String, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
if(buttonActions.count > 0){
let methodName = buttonActions[count] as! String
print(methodName)
NSTimer.scheduledTimerWithTimeInterval(0, target: self.ParentDelegate as! UIViewController, selector: Selector(methodName), userInfo: nil, repeats: false)
}
})
alertControllerForInvalidEmailAddress.addAction(buttonAction)
}
}
//MARK: Shake TextField
class func shaketextField(textfield : UITextField) {
let shake:CABasicAnimation = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let from_point:CGPoint = CGPointMake(textfield.center.x - 5, textfield.center.y)
let from_value:NSValue = NSValue(CGPoint: from_point)
let to_point:CGPoint = CGPointMake(textfield.center.x + 5, textfield.center.y)
let to_value:NSValue = NSValue(CGPoint: to_point)
shake.fromValue = from_value
shake.toValue = to_value
textfield.layer.addAnimation(shake, forKey: "position")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| 0722126da92eb8679acb3b7308b1fd56 | 33.516971 | 174 | 0.593116 | false | false | false | false |
marsal-silveira/Tonight | refs/heads/master | Tonight/src/Utils/Logger.swift | mit | 1 | //
// Logger.swift
// Tonight
//
// Created by Marsal on 29/02/16.
// Copyright © 2016 Marsal Silveira. All rights reserved.
//
class Logger
{
static func log(logMessage: String = "", file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__)
{
// __FILE__ : String - The name of the file in which it appears.
// __FUNCTION__ : String - The name of the declaration in which it appears.
// __LINE__ : Int - The line number on which it appears.
let fileURL = NSURL(fileURLWithPath: file)
let className = fileURL.lastPathComponent!.stringByReplacingOccurrencesOfString(fileURL.pathExtension!, withString: "")
print("[\(className)\(function)][\(line)] \(logMessage)")
}
} | 7d0b576e6a4ebb2743497567270962f1 | 35.333333 | 127 | 0.62336 | false | false | false | false |
zpz1237/NirTableHeaderView | refs/heads/master | TableHeaderViewAlbum/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// TableHeaderViewAlbum
//
// Created by Nirvana on 10/28/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
//你想要展示的tableHeaderView
let imgView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 64))
imgView.contentMode = .ScaleAspectFill
imgView.image = UIImage(named: "header")
//若含有navigationController
//一、取消ScrollViewInsets自动调整
self.automaticallyAdjustsScrollViewInsets = false
//二、隐藏NavBar
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
//类型零
//let headerView = NirTableHeaderView(subview: imgView, andType: 0)
//类型一
//let headerView = NirTableHeaderView(subview: imgView, andType: 1)
//类型二
//let headerView = NirTableHeaderView(subview: imgView, andType: 2)
//类型三
//let headerView = NirTableHeaderView(subview: imgView, andType: 3)
//headerView.tableView = self.tableView
//headerView.maximumOffsetY = -90
//类型四
let headerView = NirTableHeaderView(subview: imgView, andType: 4)
self.tableView.tableHeaderView = headerView
self.tableView.delegate = self
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view delegate
override func scrollViewDidScroll(scrollView: UIScrollView) {
let headerView = self.tableView.tableHeaderView as! NirTableHeaderView
headerView.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 20
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nirCell", forIndexPath: indexPath)
cell.textLabel?.text = "Just Try"
return cell
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
extension UINavigationController {
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
return self.topViewController
}
}
| ba1548140446cf04b9f3e552e632b713 | 33.483516 | 118 | 0.678776 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Exercise2.playgroundpage/Sources/Assessments.swift | mit | 1 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution = "```swift\nmoveForward()\n\nif isOnClosedSwitch {\n toggleSwitch()\n} else if isOnGem {\n collectGem()\n}\n\nmoveForward()\nif isOnClosedSwitch {\n toggleSwitch()\n} else if isOnGem {\n collectGem()\n}\n```"
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
let success = "### Impressive! \nYou now know how to write your own `else if` statements.\n\n[**Next Page**](@next)"
var hints = [
"Start by moving Byte to the first tile and use an `if` statement to check whether Byte is on a closed switch.",
"Add an `if` statement and use the condition `isOnClosedSwitch` to check whether you should toggle a switch. Then add an `else if` block by tapping the word `if` in your code area and tapping \"Add 'else if' Statement\".",
"If Byte is on a closed switch, toggle it. Otherwise (the “else” part), if Byte is on a gem, collect it.",
]
if !checker.didUseConditionalStatement("if") {
hints[0] = "After you've added an `if` statement, tap the word `if` in your code and use the \"Add 'else if' Statement\" option."
hints.remove(at: 1)
} else if !checker.didUseConditionalStatement("else if") {
hints[0] = "To add an `else if` statement, tap the word `if` in your code and then tap \"Add else if statement\"."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| e2c950d4a2a7fa398b2a9dcfa972d2f7 | 49.84375 | 234 | 0.668101 | false | false | false | false |
takeotsuchida/Watch-Connectivity | refs/heads/master | Connectivity WatchKit Extension/GlanceController.swift | gpl-2.0 | 1 | //
// GlanceController.swift
// Connectivity WatchKit Extension
//
// Created by Takeo Tsuchida on 2015/07/31.
// Copyright © 2015年 MUMPK Limited Partnership. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class GlanceController: WKInterfaceController {
@IBOutlet var transferredImage: WKInterfaceImage!
@IBOutlet var contextLabel: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if let context = WCSession.defaultSession().receivedApplicationContext as? [String:String],
message = context[dataId] {
contextLabel.setText(message)
}
let url = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let urls = try! NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles)
for url in urls {
if let data = NSData(contentsOfURL: url), image = UIImage(data: data) {
self.transferredImage.setImage(image)
break
}
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| 8d4af349b00b54a62454a4cfb37733be | 32.4375 | 145 | 0.672897 | false | false | false | false |
jshultz/ios9-swift2-shake-app-random-sounds | refs/heads/master | shake-that-app/ViewController.swift | mit | 1 | //
// ViewController.swift
// shake-that-app
//
// Created by Jason Shultz on 10/22/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player:AVAudioPlayer = AVAudioPlayer() // Create a player
var tune:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeUp.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeUp)
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if event?.subtype == UIEventSubtype.MotionShake {
print("device was shaken, not stirred")
}
}
func playSound(tune:String) {
let audioPath = NSBundle.mainBundle().pathForResource(tune, ofType: "mp3")! // path to audio file
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
} catch {
print("siomething went wrong")
}
}
func swiped(gesture:UIGestureRecognizer){
if let swipegesture = gesture as? UISwipeGestureRecognizer {
switch swipegesture.direction {
case UISwipeGestureRecognizerDirection.Right:
print("swipe right")
case UISwipeGestureRecognizerDirection.Up:
let audioPath = NSBundle.mainBundle().pathForResource("mozart-k311-3-sasaki", ofType: "mp3")! // path to audio file
print("swipe up")
default:
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 02101d2e15c42eb11686ca68c3e70f12 | 27.746835 | 131 | 0.598855 | false | false | false | false |
searchs/grobox | refs/heads/master | learn.swift | mit | 1 | //Getting to know Swift Programming Language enough to build Mobile Automated Test Framework
import UIKit
var str = "Look what I can do"
2+2
var myVar: String = "Mobo Robots"
var myInt: Int = 18
var hungry: Bool = true
var costOfCandy: Double = 1.325
myVar = "Bad Robots"
let life: Int = 42
let pi: Double = 3.142
let canTouchThis: Bool = false
let captain: String = "Kirk"
//captain = "Hook" //immutable: gives an error
let favoriteNumber = 33
var dullNumber = 7
let batmanCoolness = 10
var supermanCoolness = 9
var aquamanCoolness = 1
batmanCoolness < aquamanCoolness
supermanCoolness >= 8
batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness > aquamanCoolness && batmanCoolness == (aquamanCoolness + supermanCoolness)
batmanCoolness < supermanCoolness || aquamanCoolness < supermanCoolness
var spidermanCoolness = 6
if (batmanCoolness > spidermanCoolness) {
spidermanCoolness = spidermanCoolness - 1
} else if (batmanCoolness >= spidermanCoolness) {
spidermanCoolness = spidermanCoolness - 1
} else {
spidermanCoolness = spidermanCoolness + 1
}
print("Getting Swift into fingers!")
var apples = 5
print("Sally has \(apples) apples ")
var secondsLeft = 3
while (secondsLeft > 0) {
print(secondsLeft)
secondsLeft = secondsLeft - 1
}
print("Blast off!")
var cokesLeft = 7
var fantasLeft = 4
while(cokesLeft > 0) {
print("You have \(cokesLeft) Cokes left.")
cokesLeft = cokesLeft - 1
if(cokesLeft <= fantasLeft) {
break
}
}
print("You stop drinking Cokes.")
var numbers = 0
while(numbers <= 10) {
if(numbers == 9) {
numbers = numbers + 1
continue
}
print(numbers)
numbers = numbers + 1
}
var optionalNumber: Int? = 5
optionalNumber = nil
if let number = optionalNumber {
print(number)
}
else {
print("Nothing here")
}
var languagesLearned: String = "3"
var languagesLearnedNum: Int? = Int(languagesLearned)
print("\(languagesLearnedNum.dynamicType)")
var isDone = false
var statement: string = isDone ? ""Job done and we are ready" : "Time running out"
| fada97eb402639d1bb1eeaba16fa8e42 | 18.650943 | 92 | 0.704753 | false | false | false | false |
HTWDD/htwcampus | refs/heads/develop | HTWDD/Main Categories/General/Models/Semester.swift | mit | 1 | //
// Semester.swift
// HTWDD
//
// Created by Benjamin Herzog on 05/01/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import Marshal
enum Semester: Hashable, CustomStringConvertible, Comparable {
case summer(year: Int)
case winter(year: Int)
var year: Int {
switch self {
case .summer(let year):
return year
case .winter(let year):
return year
}
}
var localized: String {
switch self {
case .summer(let year):
return Loca.summerSemester + " \(year)"
case .winter(let year):
return Loca.winterSemester + " \(year)"
}
}
var description: String {
switch self {
case .summer(let year):
return "SS_\(year)"
case .winter(let year):
return "WS_\(year)"
}
}
var hashValue: Int {
return description.hashValue
}
static func <(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 < year2
case (.winter(let year1), .winter(let year2)):
return year1 < year2
case (.summer(let year1), .winter(let year2)):
if year1 == year2 {
return true
} else {
return year1 < year2
}
case (.winter(let year1), .summer(let year2)):
if year1 == year2 {
return false
} else {
return year1 < year2
}
}
}
static func ==(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 == year2
case (.winter(let year1), .winter(let year2)):
return year1 == year2
default:
return false
}
}
}
extension Semester: ValueType {
static func value(from object: Any) throws -> Semester {
guard let number = object as? Int else {
throw MarshalError.typeMismatch(expected: Int.self, actual: type(of: object))
}
let rawValue = "\(number)"
guard rawValue.count == 5 else {
throw MarshalError.typeMismatch(expected: 5, actual: rawValue.count)
}
var raw = rawValue
let rawType = raw.removeLast()
guard let year = Int(raw) else {
throw MarshalError.typeMismatch(expected: Int.self, actual: raw)
}
if rawType == "1" {
return .summer(year: year)
} else if rawType == "2" {
return .winter(year: year)
} else {
throw MarshalError.typeMismatch(expected: "1 or 2", actual: rawType)
}
}
}
extension Semester: Codable {
func encode(to encoder: Encoder) throws {
let semesterNumber: Int
switch self {
case .summer(_): semesterNumber = 1
case .winter(_): semesterNumber = 2
}
var container = encoder.singleValueContainer()
try container.encode(self.year*10 + semesterNumber)
}
init(from decoder: Decoder) throws {
let number = try decoder.singleValueContainer().decode(Int.self)
self = try Semester.value(from: number)
}
}
| db48635b70948be0e5f1637f7c202355 | 25.140625 | 89 | 0.537956 | false | false | false | false |
v2panda/DaysofSwift | refs/heads/master | swift2.3/My-CollectionViewAnimation/My-CollectionViewAnimation/AnimationCollectionViewCell.swift | mit | 1 | //
// AnimationCollectionViewCell.swift
// My-CollectionViewAnimation
//
// Created by Panda on 16/3/7.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class AnimationCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var button: UIButton!
var backButtonTapped: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func prepareCell(viewModel:AnimationCellModel) {
imageView.image = UIImage(named: viewModel.imagePath)
textView.scrollEnabled = false
button.hidden = true
button.addTarget(self, action: Selector("backButtonDidTouch"), forControlEvents: .TouchUpInside)
}
func backButtonDidTouch() {
backButtonTapped?()
}
func handleCellSelected() {
textView.scrollEnabled = false
button.hidden = false
self.superview?.bringSubviewToFront(self)
}
}
| 53cc3f456116cba3a0794c916644c41e | 25.425 | 104 | 0.666036 | false | false | false | false |
jad6/CV | refs/heads/master | Swift/Jad's CV/Models/ExperienceObject.swift | bsd-3-clause | 1 | //
// ExperienceObject.swift
// Jad's CV
//
// Created by Jad Osseiran on 17/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
class ExperienceObject: ExtractedObject {
let startDate: NSDate
let endDate: NSDate
let organisationImage: UIImage?
let organisation: String
let position: String
let detailedDescription: String
class func sortedExperiences() -> [ExperienceObject] {
var error = NSError?()
var objects = self.extractObjects(&error)
error?.handle()
if var experiences = objects as? [ExperienceObject] {
experiences.sort() {
return ($0.startDate.compare($1.startDate) != .OrderedAscending) &&
($0.endDate.compare($1.endDate) != .OrderedAscending)
}
return experiences
} else {
return [ExperienceObject]()
}
}
required init(dictionary: NSDictionary) {
self.startDate = dictionary["startDate"] as NSDate
self.endDate = dictionary["endDate"] as NSDate
self.organisation = dictionary["organisation"] as String
self.position = dictionary["position"] as String
self.detailedDescription = dictionary["description"] as String
if let imageName = dictionary["imageName"] as? String {
self.organisationImage = UIImage(named: imageName)
}
super.init(dictionary: dictionary)
}
func timeSpentString(separator: String) -> String {
return startDate.combinedCondensedStringWithEndDate(endDate, withSeparator: separator)
}
}
class ExtraCurricularActivity: ExperienceObject {
class func extraCurricularActivitiesListData() -> ListData<ExtraCurricularActivity> {
var extraCurricularActivitiesListData = ListData<ExtraCurricularActivity>()
extraCurricularActivitiesListData.sections += [ListSection(rowObjects: ExtraCurricularActivity.extraCurricularActivities(), name: "Extra Curricular")]
return extraCurricularActivitiesListData
}
class func extraCurricularActivities() -> [ExtraCurricularActivity] {
return self.sortedExperiences() as [ExtraCurricularActivity]
}
override class func filePathForResource() -> String? {
return NSBundle.mainBundle().pathForResource("Extra Curricular", ofType: "plist")
}
required init(dictionary: NSDictionary) {
super.init(dictionary: dictionary)
}
}
class TimelineEvent: ExperienceObject {
enum Importance: Int, IntegerLiteralConvertible {
case None = 0, Major, Minor
static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Importance {
if value == 1 {
return .Major
} else if value == 2 {
return .Minor
} else {
return .None
}
}
}
let color: UIColor
let importance: Importance
class func timelineEventsListData() -> ListData<TimelineEvent> {
var timelineEventsListData = ListData<TimelineEvent>()
timelineEventsListData.sections += [ListSection(rowObjects: TimelineEvent.timelineEvents(), name: "Timeline")]
return timelineEventsListData
}
class func timelineEvents() -> [TimelineEvent] {
return self.sortedExperiences() as [TimelineEvent]
}
override class func filePathForResource() -> String? {
return NSBundle.mainBundle().pathForResource("Experience", ofType: "plist")
}
required init(dictionary: NSDictionary) {
self.color = UIColor.colorFromRGBString(dictionary["color"] as String)
let importance = dictionary["importance"] as Int
self.importance = Importance.convertFromIntegerLiteral(importance)
super.init(dictionary: dictionary)
}
} | 42345b373d4d071040f882a4107387c4 | 31.677686 | 158 | 0.64002 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Views/Chat/New Chat/Cells/ThreadReplyCollapsedCell.swift | mit | 1 | //
// ThreadReplyCollapsedCell.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import UIKit
import RocketChatViewController
final class ThreadReplyCollapsedCell: BaseMessageCell, SizingCell {
static let identifier = String(describing: ThreadReplyCollapsedCell.self)
static let sizingCell: UICollectionViewCell & ChatCell = {
guard let cell = ThreadReplyCollapsedCell.instantiateFromNib() else {
return ThreadReplyCollapsedCell()
}
return cell
}()
@IBOutlet weak var iconThread: UIImageView!
@IBOutlet weak var avatarContainerView: UIView! {
didSet {
avatarContainerView.layer.cornerRadius = 4
avatarView.frame = avatarContainerView.bounds
avatarContainerView.addSubview(avatarView)
}
}
@IBOutlet weak var labelThreadTitle: UILabel!
@IBOutlet weak var labelThreadReply: UILabel!
@IBOutlet weak var avatarWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var avatarLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var labelTextTopConstraint: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
let gesture = UITapGestureRecognizer(target: self, action: #selector(didTapContainerView))
gesture.delegate = self
contentView.addGestureRecognizer(gesture)
}
override func configure(completeRendering: Bool) {
configure(
with: avatarView,
date: nil,
status: nil,
and: nil,
completeRendering: completeRendering
)
guard
let model = viewModel?.base as? MessageReplyThreadChatItem
else {
return
}
let threadName = model.threadName
// If thread name is empty, it means we don't have the
// main message cell yet or it's not a valid title, so we
// can hide the entire header.
if model.isSequential || threadName == nil {
iconThread.isHidden = true
labelThreadTitle.text = nil
labelTextTopConstraint.constant = 0
} else {
iconThread.isHidden = false
labelThreadTitle.text = threadName
labelTextTopConstraint.constant = 4
}
updateText()
}
func updateText() {
guard
let viewModel = viewModel?.base as? MessageReplyThreadChatItem,
let message = viewModel.message
else {
return
}
labelThreadReply.text = message.threadReplyCompressedMessage
}
@objc func didTapContainerView() {
guard
let viewModel = viewModel,
let model = viewModel.base as? MessageReplyThreadChatItem,
let threadIdentifier = model.message?.threadMessageId
else {
return
}
delegate?.openThread(identifier: threadIdentifier)
}
}
extension ThreadReplyCollapsedCell {
override func applyTheme() {
super.applyTheme()
let theme = self.theme ?? .light
labelThreadTitle.textColor = theme.actionTintColor
updateText()
}
}
| b4ccc791788bc1d5049fbe4b2881556e | 27.226087 | 98 | 0.638016 | false | false | false | false |
AlDrago/SwiftyJSON | refs/heads/master | Tests/PrintableTests.swift | mit | 1 | // PrintableTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 XCTest
import SwiftyJSON3
class PrintableTests: XCTestCase {
func testNumber() {
let json:JSON = 1234567890.876623
XCTAssertEqual(json.description, "1234567890.876623")
XCTAssertEqual(json.debugDescription, "1234567890.876623")
}
func testBool() {
let jsonTrue:JSON = true
XCTAssertEqual(jsonTrue.description, "true")
XCTAssertEqual(jsonTrue.debugDescription, "true")
let jsonFalse:JSON = false
XCTAssertEqual(jsonFalse.description, "false")
XCTAssertEqual(jsonFalse.debugDescription, "false")
}
func testString() {
let json:JSON = "abcd efg, HIJK;LMn"
XCTAssertEqual(json.description, "abcd efg, HIJK;LMn")
XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn")
}
func testNil() {
let jsonNil_1:JSON = nil
XCTAssertEqual(jsonNil_1.description, "null")
XCTAssertEqual(jsonNil_1.debugDescription, "null")
let jsonNil_2:JSON = JSON(NSNull())
XCTAssertEqual(jsonNil_2.description, "null")
XCTAssertEqual(jsonNil_2.debugDescription, "null")
}
func testArray() {
let json:JSON = [1,2,"4",5,"6"]
var description = json.description.replacingOccurrences(of: "\n", with: "")
description = description.replacingOccurrences(of: " ", with: "")
XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]")
XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0)
XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0)
}
func testDictionary() {
let json:JSON = ["1":2,"2":"two", "3":3]
var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "")
debugDescription = debugDescription.replacingOccurrences(of: " ", with: "")
XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0)
XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil)
XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil)
XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: NSString.CompareOptions.caseInsensitive) != nil)
}
}
| e48054a0f331c749973e238a617837a1 | 45.44 | 123 | 0.689348 | false | true | false | false |
davidbutz/ChristmasFamDuels | refs/heads/master | iOS/Boat Aware/LoadingView.swift | mit | 1 | //
// LoadingView.swift
// ThriveIOSPrototype
//
// Created by Dave Butz on 1/11/16.
// Copyright © 2016 Dave Butz. All rights reserved.
//
import Foundation
import UIKit
public class LoadingOverlay{
var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()
var captionLabel = UILabel()
class var shared: LoadingOverlay {
struct Static {
static let instance: LoadingOverlay = LoadingOverlay()
}
return Static.instance
}
func setCaption(caption: String) {
captionLabel.text = caption
}
public func showOverlay(view: UIView) {
overlayView.frame = CGRectMake(0, 0, 300, 300)
overlayView.center = view.center
overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
overlayView.clipsToBounds = true
overlayView.layer.cornerRadius = 10
activityIndicator.frame = CGRectMake(0, 0, 40, 40)
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.center = CGPointMake(overlayView.bounds.width / 2, overlayView.bounds.height / 2)
captionLabel.frame = CGRectMake(10, 200, 290, 40);
// captionLabel.backgroundColor = UIColor.blackColor()
captionLabel.textColor = UIColor.whiteColor()
captionLabel.adjustsFontSizeToFitWidth = true
captionLabel.textAlignment = NSTextAlignment.Center
//captionLabel!.text = "Loading..."
overlayView.addSubview(captionLabel);
overlayView.addSubview(activityIndicator);
view.addSubview(overlayView)
activityIndicator.startAnimating()
}
public func hideOverlayView() {
activityIndicator.stopAnimating()
captionLabel.removeFromSuperview();
activityIndicator.removeFromSuperview();
overlayView.removeFromSuperview()
}
}
class LoadingView : UIView {
var captionLabel : UILabel?
func setCaption(caption: String) {
captionLabel!.text = caption
}
func done() {
self.removeFromSuperview()
}
override init(frame aRect: CGRect) {
super.init(frame: aRect)
let hudView = UIView(frame: CGRectMake(aRect.width/2.0 - (170/2.0), aRect.height/2.0 - (170/2.0), 170, 170))
hudView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
hudView.clipsToBounds = true
hudView.layer.cornerRadius = 10.0
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicatorView.frame = CGRectMake(65, 40, activityIndicatorView.bounds.size.width, activityIndicatorView.bounds.size.width)
hudView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
captionLabel = UILabel(frame: CGRectMake(20, 115, 130, 22))
// captionLabel.backgroundColor = UIColor.blackColor()
captionLabel!.textColor = UIColor.whiteColor()
captionLabel!.adjustsFontSizeToFitWidth = true
captionLabel!.textAlignment = NSTextAlignment.Center
//captionLabel!.text = "Loading..."
hudView.addSubview(captionLabel!)
self.addSubview(hudView)
}
// convenience override init() {
// self.init(frame:CGRectZero)
// }
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
| e8ccfc6606fee3c5286747371bf43165 | 32.761905 | 138 | 0.653315 | false | false | false | false |
gontovnik/DGElasticBounceTutorial | refs/heads/master | DGElasticBounceTutorial/ViewController.swift | mit | 1 | //
// ViewController.swift
// DGElasticBounceTutorial
//
// Created by Danil Gontovnik on 10/13/15.
// Copyright © 2015 Danil Gontovnik. All rights reserved.
//
import UIKit
// MARK: -
// MARK: (UIView) Extension
extension UIView {
func dg_center(usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentationLayer() as? CALayer {
return presentationLayer.position
}
return center
}
}
// MARK: -
// MARK: ViewController
class ViewController: UIViewController {
// MARK: -
// MARK: Vars
private let minimalHeight: CGFloat = 50.0
private let maxWaveHeight: CGFloat = 100.0
private let shapeLayer = CAShapeLayer()
private var displayLink: CADisplayLink!
private var animating = false {
didSet {
view.userInteractionEnabled = !animating
displayLink.paused = !animating
}
}
private let l3ControlPointView = UIView()
private let l2ControlPointView = UIView()
private let l1ControlPointView = UIView()
private let cControlPointView = UIView()
private let r1ControlPointView = UIView()
private let r2ControlPointView = UIView()
private let r3ControlPointView = UIView()
// MARK: -
override func loadView() {
super.loadView()
shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: minimalHeight)
shapeLayer.fillColor = UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0).CGColor
shapeLayer.actions = ["position" : NSNull(), "bounds" : NSNull(), "path" : NSNull()]
view.layer.addSublayer(shapeLayer)
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "panGestureDidMove:"))
view.addSubview(l3ControlPointView)
view.addSubview(l2ControlPointView)
view.addSubview(l1ControlPointView)
view.addSubview(cControlPointView)
view.addSubview(r1ControlPointView)
view.addSubview(r2ControlPointView)
view.addSubview(r3ControlPointView)
layoutControlPoints(baseHeight: minimalHeight, waveHeight: 0.0, locationX: view.bounds.width / 2.0)
updateShapeLayer()
displayLink = CADisplayLink(target: self, selector: Selector("updateShapeLayer"))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
displayLink.paused = true
}
// MARK: -
// MARK: Methods
func panGestureDidMove(gesture: UIPanGestureRecognizer) {
if gesture.state == .Ended || gesture.state == .Failed || gesture.state == .Cancelled {
let centerY = minimalHeight
animating = true
UIView.animateWithDuration(0.9, delay: 0.0, usingSpringWithDamping: 0.57, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
self.l3ControlPointView.center.y = centerY
self.l2ControlPointView.center.y = centerY
self.l1ControlPointView.center.y = centerY
self.cControlPointView.center.y = centerY
self.r1ControlPointView.center.y = centerY
self.r2ControlPointView.center.y = centerY
self.r3ControlPointView.center.y = centerY
}, completion: { _ in
self.animating = false
})
} else {
let additionalHeight = max(gesture.translationInView(view).y, 0)
let waveHeight = min(additionalHeight * 0.6, maxWaveHeight)
let baseHeight = minimalHeight + additionalHeight - waveHeight
let locationX = gesture.locationInView(gesture.view).x
layoutControlPoints(baseHeight: baseHeight, waveHeight: waveHeight, locationX: locationX)
updateShapeLayer()
}
}
private func layoutControlPoints(baseHeight baseHeight: CGFloat, waveHeight: CGFloat, locationX: CGFloat) {
let width = view.bounds.width
let minLeftX = min((locationX - width / 2.0) * 0.28, 0.0)
let maxRightX = max(width + (locationX - width / 2.0) * 0.28, width)
let leftPartWidth = locationX - minLeftX
let rightPartWidth = maxRightX - locationX
l3ControlPointView.center = CGPoint(x: minLeftX, y: baseHeight)
l2ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.44, y: baseHeight)
l1ControlPointView.center = CGPoint(x: minLeftX + leftPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
cControlPointView.center = CGPoint(x: locationX , y: baseHeight + waveHeight * 1.36)
r1ControlPointView.center = CGPoint(x: maxRightX - rightPartWidth * 0.71, y: baseHeight + waveHeight * 0.64)
r2ControlPointView.center = CGPoint(x: maxRightX - (rightPartWidth * 0.44), y: baseHeight)
r3ControlPointView.center = CGPoint(x: maxRightX, y: baseHeight)
}
func updateShapeLayer() {
shapeLayer.path = currentPath()
}
private func currentPath() -> CGPath {
let width = view.bounds.width
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 0.0, y: 0.0))
bezierPath.addLineToPoint(CGPoint(x: 0.0, y: l3ControlPointView.dg_center(animating).y))
bezierPath.addCurveToPoint(l1ControlPointView.dg_center(animating), controlPoint1: l3ControlPointView.dg_center(animating), controlPoint2: l2ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r1ControlPointView.dg_center(animating), controlPoint1: cControlPointView.dg_center(animating), controlPoint2: r1ControlPointView.dg_center(animating))
bezierPath.addCurveToPoint(r3ControlPointView.dg_center(animating), controlPoint1: r1ControlPointView.dg_center(animating), controlPoint2: r2ControlPointView.dg_center(animating))
bezierPath.addLineToPoint(CGPoint(x: width, y: 0.0))
bezierPath.closePath()
return bezierPath.CGPath
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
| 4138711be15ef7c36b724b207cbf9d11 | 39.335484 | 187 | 0.654511 | false | false | false | false |
SwiftFS/Swift-FS-China | refs/heads/master | Sources/SwiftFSChina/server/CollectServer.swift | mit | 1 | //
// CollectServer.swift
// PerfectChina
//
// Created by mubin on 2017/7/28.
//
//
import PerfectLib
import MySQL
struct CollectServer {
public static func cancel_collect(user_id:Int,topic_id:Int) throws -> Bool {
return try pool.execute{
try $0.query("delete from collect where user_id=? and topic_id=?",[user_id,topic_id])
}.affectedRows > 0
}
public static func collect(user_id:Int,topic_id:Int) throws -> Bool {
return try pool.execute{
try $0.query("insert into collect (user_id,topic_id) values(?,?) ON DUPLICATE KEY UPDATE create_time=CURRENT_TIMESTAMP ",[user_id,topic_id])
}.insertedID > 0
}
public static func get_all_of_user(user_id:Int,page_no:Int,page_size:Int) throws -> [CollectEntity] {
return try pool.execute{
try $0.query("select t.*, u.avatar as avatar, cc.name as category_name from collect c " +
" right join topic t on c.topic_id=t.id " +
" left join user u on t.user_id=u.id " +
" left join category cc on t.category_id=cc.id " +
" where c.user_id=? order by c.id desc limit ?,? "
,[user_id,(page_no - 1) * page_size,page_size])
}
}
public static func is_collect(current_userid:Int,topic_id:String) throws -> Bool {
let row:[Count] = try pool.execute{
try $0.query("select count(c.id) as count from collect c " +
" where c.user_id=? and c.topic_id=?",[current_userid,topic_id])
}
return !(row.count > 0 && row[0].count < 1)
}
}
| 50df2a5467e0ea708b8aef36c5690416 | 31.509804 | 152 | 0.568758 | false | false | false | false |
CanyFrog/HCComponent | refs/heads/master | HCSource/HCBaseRefreshView.swift | mit | 1 | //
// HCBaseRefreshView.swift
// HCComponents
//
// Created by Magee Huang on 6/13/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
/// base on https://github.com/CoderMJLee/MJRefresh
import UIKit
public enum HCRefreshState {
case normal, draging, trigger, refreshing, empty
}
fileprivate let HCRefreshContentOffsetKey = "HCRefreshContentOffsetKey"
fileprivate let HCRefreshContentSizeKey = "HCRefreshContentSizeKey"
fileprivate let HCRefreshPanStateKey = "HCRefreshPanStateKey"
public class HCBaseRefreshView: UIView {
/// super scrollview infomation
public weak var scrollView: UIScrollView!
public var originInset: UIEdgeInsets!
/// state information
public var state: HCRefreshState = .normal {
didSet {
if state != oldValue {
changeState(oldState: oldValue, to: state)
}
}
}
public var isRefreshing: Bool {
return state == .refreshing || state == .trigger
}
public var isAutoChangeAlpha: Bool = false {
didSet {
guard !isRefreshing else { return }
alpha = isAutoChangeAlpha ? dragingRatio : 1.0
}
}
public var dragingRatio: CGFloat = 0.0 {
didSet {
guard !isRefreshing else { return }
if isAutoChangeAlpha {
alpha = dragingRatio
}
}
}
public var aniDuration: TimeInterval = 0.3
/// callback
internal var refreshHandler: EmptyExecute?
internal var beiginRefreshHandler: EmptyExecute?
internal var stopRefreshHandler: EmptyExecute?
internal var panGesture: UIPanGestureRecognizer {
return scrollView.panGestureRecognizer
}
public convenience init(refresh: @escaping EmptyExecute) {
self.init(frame: .zero)
refreshHandler = refresh
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
if state == .trigger {
state = .refreshing // handler view not didapper when beigin refreshing
}
}
public override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
guard let newS = newSuperview else {
removeScrollViewObserver()
return
}
if let s = (newS as? UIScrollView) {
removeScrollViewObserver()
left = 0
width = s.width
s.alwaysBounceVertical = true
originInset = s.contentInset // recording origin contentInset
addScrollViewObserver()
}
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if !isUserInteractionEnabled { return }
if keyPath == HCRefreshContentSizeKey { // Must be change size even througn isHidden
scrollViewDidChanged(size: change)
}
if isHidden { return }
if keyPath == HCRefreshContentOffsetKey {
scrollViewDidChanged(offset: change)
}
else if keyPath == HCRefreshPanStateKey {
scrollViewDidCahnged(panState: change)
}
}
fileprivate func removeScrollViewObserver() {
let options: NSKeyValueObservingOptions = [.new, .old]
scrollView.addObserver(self, forKeyPath: HCRefreshContentOffsetKey, options: options, context: nil)
scrollView.addObserver(self, forKeyPath: HCRefreshContentSizeKey, options: options, context: nil)
panGesture.addObserver(self, forKeyPath: HCRefreshPanStateKey, options: options, context: nil)
}
fileprivate func addScrollViewObserver() {
scrollView.removeObserver(self, forKeyPath: HCRefreshContentOffsetKey)
scrollView.removeObserver(self, forKeyPath: HCRefreshContentSizeKey)
scrollView.removeObserver(self, forKeyPath: HCRefreshPanStateKey)
}
public func scrollViewDidChanged(size: [NSKeyValueChangeKey : Any]?) {
}
public func scrollViewDidChanged(offset: [NSKeyValueChangeKey : Any]?) {
}
public func scrollViewDidCahnged(panState: [NSKeyValueChangeKey : Any]?) {
}
public func changeState(oldState: HCRefreshState ,to newState: HCRefreshState) {
DispatchQueue.main.async {
self.setNeedsLayout()
}
}
public func beginRefreshing(_ completion: EmptyExecute? = nil) {
beiginRefreshHandler = completion
UIView.animate(withDuration: aniDuration) {
self.alpha = 1.0
}
dragingRatio = 1.0
if let _ = window {
state = .refreshing
}
else {
// 预防正在刷新中时,调用本方法使得header inset回置失败
if state != .refreshing {
state = .trigger
setNeedsDisplay() // 预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下
}
}
}
public func stopRefreshing(_ completion: EmptyExecute? = nil) {
stopRefreshHandler = completion
DispatchQueue.main.async {
self.state = .normal
}
}
public func execRefreshing() {
DispatchQueue.main.async {
self.refreshHandler?()
}
}
}
| a7f38ee7ce44c15721e5b567f0b23dcd | 30.511905 | 158 | 0.625614 | false | false | false | false |
asurinsaka/swift_examples_2.1 | refs/heads/master | CarolCamera/CarolCamera/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// CarolCamera
//
// Created by larryhou on 29/11/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import UIKit
import CoreData
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication)
{
print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume)
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
let captureController = window?.rootViewController as! CaptureViewController
captureController.restoreVolume()
}
func applicationDidEnterBackground(application: UIApplication)
{
print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume)
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication)
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume)
}
func applicationDidBecomeActive(application: UIApplication)
{
print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume)
// 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)
{
print(__FUNCTION__, AVAudioSession.sharedInstance().outputVolume)
let captureController = window?.rootViewController as! CaptureViewController
captureController.restoreVolume()
// 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 applicationDocumentsDirectory: NSURL =
{
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.larryhou.samples.CarolCamera" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel =
{
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CarolCamera", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator =
{
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do
{
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch
{
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext =
{
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext ()
{
if managedObjectContext.hasChanges
{
do
{
try managedObjectContext.save()
}
catch
{
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 34431cd9b93c02c149ec2f58fc95fadf | 47.680851 | 291 | 0.708042 | false | false | false | false |
slavapestov/swift | refs/heads/master | test/SILGen/address_only_types.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | FileCheck %s
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden @_TF18address_only_types21address_only_argument
func address_only_argument(let x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types29address_only_ignored_argument
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: destroy_addr [[XARG]]
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_return
func address_only_return(let x: Unloadable, let y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64):
// CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x"
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [take] [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden @_TF18address_only_types27address_only_missing_return
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_TF18address_only_types39address_only_conditional_missing_return
func address_only_conditional_missing_return(let x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr [take] %1 to [initialization] %0 : $*Unloadable
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_TF18address_only_types41address_only_conditional_missing_return
func address_only_conditional_missing_return_2(x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_call_1_ignore_returnFT_T_
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call_2
func address_only_call_2(let x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]] : $*Unloadable
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2
// CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]]
// CHECK: apply [[FUNC]]([[X_CALL_ARG]])
// CHECK: dealloc_stack [[X_CALL_ARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_call_1_in_2
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_materialize
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP_PROJ]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_assignment_from_temp
func address_only_assignment_from_temp(inout dest: Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable):
// CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable
// CHECK: [[PB:%.*]] = project_box [[DEST_LOCAL]]
// CHECK: copy_addr [[DEST]] to [initialization] [[PB]]
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [take] [[TEMP]] to [[PB]] :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: copy_addr [[PB]] to [[DEST]]
// CHECK: release [[DEST_LOCAL]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types31address_only_assignment_from_lv
func address_only_assignment_from_lv(inout dest: Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable
// CHECK: [[PB:%.*]] = project_box [[DEST_LOCAL]]
// CHECK: copy_addr [[DEST]] to [initialization] [[PB]]
// CHECK: [[VBOX:%.*]] = alloc_box $Unloadable
// CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable
dest = v
// FIXME: emit into?
// CHECK: copy_addr [[PBOX]] to [[PB]] :
// CHECK: release [[VBOX]]
// CHECK: copy_addr [[PB]] to [[DEST]]
// CHECK: release [[DEST_LOCAL]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden @_TF18address_only_types45address_only_assignment_from_temp_to_property
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_TF18address_only_types43address_only_assignment_from_lv_to_property
func address_only_assignment_from_lv_to_property(let v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[VARG]] : $*Unloadable
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden @_TF18address_only_types16address_only_varFT_PS_10Unloadable_
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box $Unloadable
// CHECK: [[XPB:%.*]] = project_box [[XBOX]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: copy_addr [[XPB]] to [initialization] [[RET]]
// CHECK: release [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden @_TF18address_only_types39call_address_only_nontuple_arg_function
func call_address_only_nontuple_arg_function(x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
| cd9bf315228e7c2b629df9589ff2ee6c | 38.686441 | 127 | 0.636237 | false | false | false | false |
Bouke/HAP | refs/heads/master | Sources/VaporHTTP/Body/HTTPBody.swift | mit | 1 | import Foundation
/// Represents an `HTTPMessage`'s body.
///
/// let body = HTTPBody(string: "Hello, world!")
///
/// This can contain any data (streaming or static) and should match the message's `"Content-Type"` header.
public struct HTTPBody: LosslessHTTPBodyRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// An empty `HTTPBody`.
public static let empty: HTTPBody = .init()
/// Returns the body's contents as `Data`. `nil` if the body is streaming.
public var data: Data? {
storage.data
}
/// The size of the body's contents. `nil` if the body is streaming.
public var count: Int? {
storage.count
}
/// See `CustomStringConvertible`.
public var description: String {
switch storage {
case .data, .buffer, .dispatchData, .staticString, .string, .none: return debugDescription
}
}
/// See `CustomDebugStringConvertible`.
public var debugDescription: String {
switch storage {
case .none: return "<no body>"
case .buffer(let buffer): return buffer.getString(at: 0, length: buffer.readableBytes) ?? "n/a"
case .data(let data): return String(data: data, encoding: .ascii) ?? "n/a"
case .dispatchData(let data): return String(data: Data(data), encoding: .ascii) ?? "n/a"
case .staticString(let string): return string.description
case .string(let string): return string
}
}
/// Internal storage.
var storage: HTTPBodyStorage
/// Creates an empty body. Useful for `GET` requests where HTTP bodies are forbidden.
public init() {
self.storage = .none
}
/// Create a new body wrapping `Data`.
public init(data: Data) {
storage = .data(data)
}
/// Create a new body wrapping `DispatchData`.
public init(dispatchData: DispatchData) {
storage = .dispatchData(dispatchData)
}
/// Create a new body from the UTF8 representation of a `StaticString`.
public init(staticString: StaticString) {
storage = .staticString(staticString)
}
/// Create a new body from the UTF8 representation of a `String`.
public init(string: String) {
self.storage = .string(string)
}
/// Create a new body from a Swift NIO `ByteBuffer`.
public init(buffer: ByteBuffer) {
self.storage = .buffer(buffer)
}
/// Internal init.
internal init(storage: HTTPBodyStorage) {
self.storage = storage
}
/// See `LosslessHTTPBodyRepresentable`.
public func convertToHTTPBody() -> HTTPBody {
self
}
}
/// Maximum streaming body size to use for `debugPrint(_:)`.
private let maxDebugStreamingBodySize: Int = 1_000_000
| c309c9ee33a9379dda76219e65bbaccc | 30.837209 | 110 | 0.642075 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS Tests/AudioMessageViewTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
extension MockMessage: AudioTrack {
public var title: String? {
return .none
}
public var author: String? {
return .none
}
public var duration: TimeInterval {
return 9999
}
public var streamURL: URL? {
return .none
}
public var previewStreamURL: URL? {
return .none
}
public var failedToLoad: Bool {
get {
return false
}
set {
// no-op
}
}
}
final class AudioMessageViewTests: XCTestCase {
var sut: AudioMessageView!
var mediaPlaybackManager: MediaPlaybackManager!
override func setUp() {
super.setUp()
let url = Bundle(for: type(of: self)).url(forResource: "audio_sample", withExtension: "m4a")!
let audioMessage = MockMessageFactory.audioMessage(config: {
$0.backingFileMessageData?.transferState = .uploaded
$0.backingFileMessageData?.downloadState = .downloaded
$0.backingFileMessageData.fileURL = url
})
mediaPlaybackManager = MediaPlaybackManager(name: "conversationMedia")
sut = AudioMessageView(mediaPlaybackManager: mediaPlaybackManager)
sut.audioTrackPlayer?.load(audioMessage, sourceMessage: audioMessage)
sut.configure(for: audioMessage, isInitial: true)
}
override func tearDown() {
sut = nil
mediaPlaybackManager = nil
super.tearDown()
}
func testThatAudioMessageIsResumedAfterIncomingCallIsTerminated() {
// GIVEN & WHEN
// play
sut.playButton.sendActions(for: .touchUpInside)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
// THEN
let incomingState = CallState.incoming(video: false, shouldRing: true, degraded: false)
sut.callCenterDidChange(callState: incomingState, conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: nil)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
sut.callCenterDidChange(callState: .terminating(reason: WireSyncEngine.CallClosedReason.normal), conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: incomingState)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
}
func testThatAudioMessageIsNotResumedIfItIsPausedAfterIncomingCallIsTerminated() {
// GIVEN & WHEN
// play
sut.playButton.sendActions(for: .touchUpInside)
XCTAssert((sut.audioTrackPlayer?.isPlaying)!)
// pause
sut.playButton.sendActions(for: .touchUpInside)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
// THEN
let incomingState = CallState.incoming(video: false, shouldRing: true, degraded: false)
sut.callCenterDidChange(callState: incomingState, conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: nil)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
sut.callCenterDidChange(callState: .terminating(reason: WireSyncEngine.CallClosedReason.normal), conversation: ZMConversation(), caller: ZMUser(), timestamp: nil, previousCallState: incomingState)
XCTAssertFalse((sut.audioTrackPlayer?.isPlaying)!)
}
}
| fad5a5e04ecfae195ceff3fa52acfa9f | 31.300813 | 204 | 0.684621 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | Client/Frontend/Browser/LocalRequestHelper.swift | mpl-2.0 | 6 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
class LocalRequestHelper: TabContentScript {
func scriptMessageHandlerName() -> String? {
return "localRequestHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard message.frameInfo.request.url?.isLocal ?? false else { return }
let params = message.body as! [String: String]
if params["type"] == "load",
let urlString = params["url"],
let url = URL(string: urlString) {
_ = message.webView?.load(PrivilegedRequest(url: url) as URLRequest)
} else if params["type"] == "reload" {
_ = message.webView?.reload()
} else {
assertionFailure("Invalid message: \(message.body)")
}
}
class func name() -> String {
return "LocalRequestHelper"
}
}
| e256df649608e43bde92b6547f1ebd11 | 33.875 | 132 | 0.640681 | false | false | false | false |
garygriswold/Bible.js | refs/heads/master | Plugins/AudioPlayer/src/ios/AudioPlayer_TestHarness/AudioPlayer_TestHarness/ViewController.swift | mit | 1 | //
// ViewController.swift
// AudioPlayer
//
// Created by Gary Griswold on 7/31/17.
// Copyright © 2017 ShortSands. All rights reserved.
//
import UIKit
import AudioPlayer
class ViewController: UIViewController {
let audioController = AudioBibleController.shared
override func viewDidLoad() {
super.viewDidLoad()
let readVersion = "KJVPD"//WEB"//KJVPD"//
let readLang = "eng"
let readBook = "JHN"
let readChapter = 2
self.audioController.findAudioVersion(version: readVersion, silLang: readLang,
complete: { bookIdList in
print("BOOKS: \(bookIdList)")
self.audioController.present(view: self.view, book: readBook,
chapterNum: readChapter, complete: { error in
print("ViewController.present did finish error: \(String(describing: error))")
})
})
// let readBook2 = "MAT"
// self.audioController.present(view: self.view, book: readBook2, chapterNum: readChapter,
// complete: { error in }
// )
//
// let readBook3 = "EPH"
// self.audioController.present(view: self.view, book: readBook3, chapterNum: readChapter,
// complete: { error in }
// )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("****** viewWillDisappear *****")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("****** viewDidDisappear *****")
}
}
| 0f58a4d57a80b7a288a9115e025c60ec | 33.224138 | 118 | 0.532997 | false | false | false | false |
zmian/xcore.swift | refs/heads/main | Sources/Xcore/Cocoa/Components/UIImage/ImageFetcher/ImageDownloader.swift | mit | 1 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
import SDWebImage
extension ImageSourceType.CacheType {
fileprivate init(_ type: SDImageCacheType) {
switch type {
case .none:
self = .none
case .disk:
self = .disk
case .memory:
self = .memory
default:
fatalError(because: .unknownCaseDetected(type))
}
}
}
/// An internal class to download remote images.
///
/// Currently, it uses `SDWebImage` for download requests.
enum ImageDownloader {
typealias CancelToken = () -> Void
/// Downloads the image at the given URL, if not present in cache or return the
/// cached version otherwise.
static func load(
url: URL,
completion: @escaping (
_ image: UIImage?,
_ data: Data?,
_ error: Error?,
_ finished: Bool,
_ cacheType: ImageSourceType.CacheType
) -> Void
) -> CancelToken? {
let token = SDWebImageManager.shared.loadImage(
with: url,
options: [.avoidAutoSetImage],
progress: nil
) { image, data, error, cacheType, finished, _ in
completion(image, data, error, finished, .init(cacheType))
}
return token?.cancel
}
/// Downloads the image from the given url.
static func download(
url: URL,
completion: @escaping (
_ image: UIImage?,
_ data: Data?,
_ error: Error?,
_ finished: Bool
) -> Void
) {
SDWebImageDownloader.shared.downloadImage(
with: url,
options: [],
progress: nil
) { image, data, error, finished in
completion(image, data, error, finished)
}
}
static func removeCache() {
SDImageCache.shared.apply {
$0.clearMemory()
$0.clearDisk()
$0.deleteOldFiles()
}
}
}
| 5aa3b4fbc4ee62b3c2ff69380fa3041c | 24.9125 | 83 | 0.527255 | false | false | false | false |
tbergmen/TableViewModel | refs/heads/master | Example/Tests/ViewControllerTestingHelper.swift | mit | 1 | /*
Copyright (c) 2016 Tunca Bergmen <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import UIKit
public class ViewControllerTestingHelper {
class func wait() {
NSRunLoop.mainRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.01))
}
class func emptyViewController() -> UIViewController {
let viewController = UIViewController()
viewController.view = UIView()
return viewController
}
class func prepareWindowWithRootViewController(viewController: UIViewController) -> UIWindow {
let window: UIWindow = UIWindow(frame: CGRect())
window.makeKeyAndVisible()
window.rootViewController = viewController
wait()
return window
}
class func presentViewController(viewController: UIViewController) {
let window: UIWindow = prepareWindowWithRootViewController(emptyViewController())
window.rootViewController?.presentViewController(viewController, animated: false, completion: nil)
wait()
}
class func dismissViewController(viewController: UIViewController) {
viewController.dismissViewControllerAnimated(false, completion: nil)
wait()
}
class func presentAndDismissViewController(viewController: UIViewController) {
presentViewController(viewController)
dismissViewController(viewController)
}
class func pushViewController(viewController: UIViewController) -> UINavigationController {
let navigationController: UINavigationController = UINavigationController(rootViewController: emptyViewController())
_ = prepareWindowWithRootViewController(navigationController)
navigationController.pushViewController(viewController, animated: false)
wait()
return navigationController
}
} | 816314495a98593209a12c93d0f08ef1 | 39.271429 | 124 | 0.759404 | false | false | false | false |
kfix/MacPin | refs/heads/main | modules/Linenoise/History.swift | gpl-3.0 | 1 | /*
Copyright (c) 2017, Andy Best <andybest.net at gmail dot com>
Copyright (c) 2010-2014, Salvatore Sanfilippo <antirez at gmail dot com>
Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
internal class History {
public enum HistoryDirection: Int {
case previous = -1
case next = 1
}
var maxLength: UInt = 0 {
didSet {
if history.count > maxLength && maxLength > 0 {
history.removeFirst(history.count - Int(maxLength))
}
}
}
private var index: Int = 0
var currentIndex: Int {
return index
}
private var hasTempItem: Bool = false
private var history: [String] = [String]()
var historyItems: [String] {
return history
}
public func add(_ item: String) {
// Don't add a duplicate if the last item is equal to this one
if let lastItem = history.last {
if lastItem == item {
// Reset the history pointer to the end index
index = history.endIndex
return
}
}
// Remove an item if we have reached maximum length
if maxLength > 0 && history.count >= maxLength {
_ = history.removeFirst()
}
history.append(item)
// Reset the history pointer to the end index
index = history.endIndex
}
func replaceCurrent(_ item: String) {
history[index] = item
}
// MARK: - History Navigation
internal func navigateHistory(direction: HistoryDirection) -> String? {
if history.count == 0 {
return nil
}
switch direction {
case .next:
index += HistoryDirection.next.rawValue
case .previous:
index += HistoryDirection.previous.rawValue
}
// Stop at the beginning and end of history
if index < 0 {
index = 0
return nil
} else if index >= history.count {
index = history.count
return nil
}
return history[index]
}
// MARK: - Saving and loading
internal func save(toFile path: String) throws {
let output = history.joined(separator: "\n")
try output.write(toFile: path, atomically: true, encoding: .utf8)
}
internal func load(fromFile path: String) throws {
let input = try String(contentsOfFile: path, encoding: .utf8)
input.split(separator: "\n").forEach {
add(String($0))
}
}
}
| aeff0f713deecefcc7512d5ab5849cba | 30.76 | 80 | 0.625189 | false | false | false | false |
PlutoMa/Swift-LeetCode | refs/heads/master | Code/Problem009.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
class Solution {
func isPalindrome(_ x: Int) -> Bool {
if x < 0 {
return false
}
let xString = String(x)
if xString.characters.count == 1 {
return true
}
let count = xString.characters.count / 2
for i in 1...count {
let startString = xString.substring(to: xString.index(xString.startIndex, offsetBy: i))
let startChar = startString.substring(from: startString.index(before: startString.endIndex))
let endString = xString.substring(from: xString.index(xString.endIndex, offsetBy: -i))
let endChar = endString.substring(to: endString.index(after: endString.startIndex))
if startChar != endChar {
return false
}
}
return true
}
}
print(Solution().isPalindrome(123))
print(Solution().isPalindrome(1221))
print(Solution().isPalindrome(-123)) | 331ad6bf93f95f8f02175c5eebd04bc8 | 31 | 104 | 0.589443 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/DIKit.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import DIKit
import WalletPayloadKit
extension DependencyContainer {
// MARK: - FeatureAuthenticationDomain Module
public static var featureAuthenticationDomain = module {
// MARK: - Services
factory { JWTService() as JWTServiceAPI }
factory { AccountRecoveryService() as AccountRecoveryServiceAPI }
factory { MobileAuthSyncService() as MobileAuthSyncServiceAPI }
factory { ResetPasswordService() as ResetPasswordServiceAPI }
single { PasswordValidator() as PasswordValidatorAPI }
single { SeedPhraseValidator() as SeedPhraseValidatorAPI }
single { SharedKeyParsingService() }
// MARK: - NabuAuthentication
single { NabuAuthenticationExecutor() as NabuAuthenticationExecutorAPI }
single { NabuAuthenticationErrorBroadcaster() }
factory { () -> WalletRepositoryAPI in
let walletRepositoryProvider: WalletRepositoryProvider = DIKit.resolve()
return walletRepositoryProvider.repository as WalletRepositoryAPI
}
factory { () -> WalletRecoveryService in
WalletRecoveryService.live(
walletManager: DIKit.resolve(),
walletRecovery: DIKit.resolve(),
nativeWalletEnabled: { nativeWalletFlagEnabled() }
)
}
factory { () -> WalletCreationService in
let app: AppProtocol = DIKit.resolve()
let settingsClient: UpdateSettingsClientAPI = DIKit.resolve()
return WalletCreationService.live(
walletManager: DIKit.resolve(),
walletCreator: DIKit.resolve(),
nabuRepository: DIKit.resolve(),
updateCurrencyService: provideUpdateCurrencyForWallets(app: app, client: settingsClient),
nativeWalletCreationEnabled: { nativeWalletCreationFlagEnabled() }
)
}
factory { () -> WalletFetcherService in
WalletFetcherService.live(
walletManager: DIKit.resolve(),
accountRecoveryService: DIKit.resolve(),
walletFetcher: DIKit.resolve(),
nativeWalletEnabled: { nativeWalletFlagEnabled() }
)
}
factory { () -> NabuAuthenticationErrorReceiverAPI in
let broadcaster: NabuAuthenticationErrorBroadcaster = DIKit.resolve()
return broadcaster as NabuAuthenticationErrorReceiverAPI
}
factory { () -> UserAlreadyRestoredHandlerAPI in
let broadcaster: NabuAuthenticationErrorBroadcaster = DIKit.resolve()
return broadcaster as UserAlreadyRestoredHandlerAPI
}
factory { () -> NabuAuthenticationExecutorProvider in
{ () -> NabuAuthenticationExecutorAPI in
DIKit.resolve()
} as NabuAuthenticationExecutorProvider
}
}
}
| 0089525ed512b6c827af03614446aabe | 34.247059 | 105 | 0.644192 | false | false | false | false |
tinyfool/GoodMorning | refs/heads/master | GoodMorning/GoodMorning/GoodMorning/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// GoodMorning
//
// Created by pei hao on 3/16/15.
// Copyright (c) 2015 pei hao. All rights reserved.
//
import UIKit
import AVFoundation
class BaseViewController: UIViewController,AVSpeechSynthesizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func speak(words:String) {
var synthesizer = AVSpeechSynthesizer();
var utterance = AVSpeechUtterance(string: "");
utterance = AVSpeechUtterance(string:words);
utterance.voice = AVSpeechSynthesisVoice(language:"zh-CN");
utterance.rate = 0.1;
synthesizer.delegate = self
synthesizer.speakUtterance(utterance);
}
func speechSynthesizer(synthesizer: AVSpeechSynthesizer!, didFinishSpeechUtterance utterance: AVSpeechUtterance!) {
//self.parentViewController
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 42920cff4e19899c5c6963c6578869c5 | 27.442308 | 119 | 0.676133 | false | false | false | false |
cwaffles/Soulcast | refs/heads/master | Soulcast/IncomingQueue.swift | mit | 1 |
import Foundation
import UIKit
let soloQueue = IncomingQueue()
protocol IncomingQueueDelegate: class {
func didEnqueue()
func didDequeue()
func didBecomeEmpty()
}
class IncomingQueue: NSObject, UICollectionViewDataSource {
let cellIdentifier:String = NSStringFromClass(IncomingCollectionCell)
var count:Int {return soulQueue.count}
fileprivate let soulQueue = Queue<Soul>()
weak var delegate:IncomingQueueDelegate?
func enqueue(_ someSoul:Soul) {
soulQueue.append(someSoul)
delegate?.didEnqueue()
}
var isEmpty:Bool { return count == 0 }
func peek() -> Soul? {
return soulQueue.head?.value
}
func purge() {
for _ in 0...count {
soulQueue.dequeue()
}
}
func dequeue() -> Soul? {
let tempSoul = soulQueue.dequeue()
if tempSoul != nil {
delegate?.didDequeue()
}
if soulQueue.count == 0 {
self.delegate?.didBecomeEmpty()
}
return tempSoul
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return soulQueue.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! IncomingCollectionCell
var someNode = soulQueue.head
if indexPath.row != 0 {
for _ in 1 ... indexPath.row {
someNode = someNode?.next
}
}
let theSoul = someNode!.value
cell.radius = Float(theSoul.radius!)
cell.epoch = theSoul.epoch!
return cell
}
}
// singly rather than doubly linked list implementation
// private, as users of Queue never use this directly
private final class QueueNode<T> {
// note, not optional – every node has a value
var value: T
// but the last node doesn't have a next
var next: QueueNode<T>? = nil
init(value: T) { self.value = value }
}
// Ideally, Queue would be a struct with value semantics but
// I'll leave that for now
public final class Queue<T> {
// note, these are both optionals, to handle
// an empty queue
fileprivate var head: QueueNode<T>? = nil
fileprivate var tail: QueueNode<T>? = nil
public init() { }
}
extension Queue {
// append is the standard name in Swift for this operation
public func append(_ newElement: T) {
let oldTail = tail
self.tail = QueueNode(value: newElement)
if head == nil { head = tail }
else { oldTail?.next = self.tail }
}
public func dequeue() -> T? {
if let head = self.head {
self.head = head.next
if head.next == nil { tail = nil }
return head.value
}
else {
return nil
}
}
}
public struct QueueIndex<T>: Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func <(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool {
return lhs.node === rhs.node
}
fileprivate let node: QueueNode<T>?
public func successor() -> QueueIndex<T> {
return QueueIndex(node: node?.next)
}
}
public func ==<T>(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool {
return lhs.node === rhs.node
}
extension Queue: MutableCollection {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: QueueIndex<T>) -> QueueIndex<T> {
return i
}
public typealias Index = QueueIndex<T>
public var startIndex: Index { return Index(node: head) }
public var endIndex: Index { return Index(node: nil) }
public subscript(idx: Index) -> T {
get {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
return idx.node!.value
}
set(newValue) {
precondition(idx.node != nil, "Attempt to subscript out of bounds")
idx.node!.value = newValue
}
}
public typealias Iterator = IndexingIterator<Queue>
public func makeIterator() -> Iterator {
return Iterator(_elements: self)
}
}
| 11e5078c34ef4ed5b94c29c6cdadfab3 | 25.436782 | 129 | 0.66413 | false | false | false | false |
eoger/firefox-ios | refs/heads/master | Shared/GeneralUtils.swift | mpl-2.0 | 2 | /* 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
/**
Assertion for checking that the call is being made on the main thread.
- parameter message: Message to display in case of assertion.
*/
public func assertIsMainThread(_ message: String) {
assert(Thread.isMainThread, message)
}
// Simple timer for manual profiling. Not for production use.
// Prints only if timing is longer than a threshold (to reduce noisy output).
open class PerformanceTimer {
let startTime: CFAbsoluteTime
var endTime: CFAbsoluteTime?
let threshold: Double
let label: String
public init(thresholdSeconds: Double = 0.001, label: String = "") {
self.threshold = thresholdSeconds
self.label = label
startTime = CFAbsoluteTimeGetCurrent()
}
public func stopAndPrint() {
if let t = stop() {
print("Ran for \(t) seconds. [\(label)]")
}
}
public func stop() -> String? {
endTime = CFAbsoluteTimeGetCurrent()
if let duration = duration {
return "\(duration)"
}
return nil
}
public var duration: CFAbsoluteTime? {
if let endTime = endTime {
let time = endTime - startTime
return time > threshold ? time : nil
} else {
return nil
}
}
}
| ba1c65ccbfb3bbc4448eddfba0ac4b36 | 27.711538 | 77 | 0.628935 | false | false | false | false |
dbart01/Rigid | refs/heads/master | Rigid/IfElseWritable.swift | bsd-2-clause | 1 | //
// IfElseWritable.swift
// Rigid
//
// Copyright (c) 2015 Dima Bart
// 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.
//
// 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 OWNER 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.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
import Foundation
struct IfElseWritable: Writable {
typealias IfElsePair = (ifBlock: Writable, elseBlock: Writable)
var indent: Int = 0
let condition: String
let pair: IfElsePair
let useLineBreaks: Bool
// ----------------------------------
// MARK: - Init -
//
init(condition: String, pair: IfElsePair, useLineBreaks: Bool = false) {
self.condition = condition
self.pair = pair
self.useLineBreaks = useLineBreaks
}
// ----------------------------------
// MARK: - Writable -
//
func content() -> String {
var content = "\n"
content += "#if \(self.condition)"
if self.useLineBreaks {
content += "\n"
}
content += pair.ifBlock.content()
content += "#else"
if self.useLineBreaks {
content += "\n"
}
content += pair.elseBlock.content()
content += "#endif\n"
return content
}
} | 15740605b967f052ca5004a1c0394182 | 35.418919 | 83 | 0.648478 | false | false | false | false |
pendowski/PopcornTimeIOS | refs/heads/master | Popcorn Time/API/AirPlayManager.swift | gpl-3.0 | 1 |
import Foundation
import MediaPlayer
enum TableViewUpdates {
case Reload
case Insert
case Delete
}
protocol ConnectDevicesProtocol: class {
func updateTableView(dataSource newDataSource: [AnyObject], updateType: TableViewUpdates, indexPaths: [NSIndexPath]?)
func didConnectToDevice(deviceIsChromecast chromecast: Bool)
}
class AirPlayManager: NSObject {
var dataSourceArray = [MPAVRouteProtocol]()
weak var delegate: ConnectDevicesProtocol?
let MPAudioDeviceControllerClass: NSObject.Type = NSClassFromString("MPAudioDeviceController") as! NSObject.Type
let MPAVRoutingControllerClass: NSObject.Type = NSClassFromString("MPAVRoutingController") as! NSObject.Type
var routingController: MPAVRoutingControllerProtocol
var audioDeviceController: MPAudioDeviceControllerProtocol
override init() {
routingController = MPAVRoutingControllerClass.init() as MPAVRoutingControllerProtocol
audioDeviceController = MPAudioDeviceControllerClass.init() as MPAudioDeviceControllerProtocol
super.init()
audioDeviceController.setRouteDiscoveryEnabled!(true)
routingController.setDelegate!(self)
updateAirPlayDevices()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateAirPlayDevices), name: MPVolumeViewWirelessRouteActiveDidChangeNotification, object: nil)
}
func mirrorChanged(sender: UISwitch, selectedRoute: MPAVRouteProtocol) {
if sender.on {
routingController.pickRoute!(selectedRoute.wirelessDisplayRoute!())
} else {
routingController.pickRoute!(selectedRoute)
}
}
func updateAirPlayDevices() {
routingController.fetchAvailableRoutesWithCompletionHandler! { (routes) in
if routes.count > self.dataSourceArray.count {
var indexPaths = [NSIndexPath]()
for index in self.dataSourceArray.count..<routes.count {
indexPaths.append(NSIndexPath(forRow: index, inSection: 0))
}
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Insert, indexPaths: indexPaths)
} else if routes.count < self.dataSourceArray.count {
var indexPaths = [NSIndexPath]()
for (index, route) in self.dataSourceArray.enumerate() {
if !routes.contains({ $0.routeUID!() == route.routeUID!() }) // If the new array doesn't contain an object in the old array it must have been removed
{
indexPaths.append(NSIndexPath(forRow: index, inSection: 0))
}
}
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Delete, indexPaths: indexPaths)
} else {
self.dataSourceArray = routes
self.delegate?.updateTableView(dataSource: self.dataSourceArray, updateType: .Reload, indexPaths: nil)
}
}
}
func airPlayItemImage(row: Int) -> UIImage {
if let routeType = self.audioDeviceController.routeDescriptionAtIndex!(row)["AirPlayPortExtendedInfo"]?["model"] as? String {
if routeType.containsString("AppleTV") {
return UIImage(named: "AirTV")!
} else {
return UIImage(named: "AirSpeaker")!
}
} else {
return UIImage(named: "AirAudio")!
}
}
func didSelectRoute(selectedRoute: MPAVRouteProtocol) {
self.routingController.pickRoute!(selectedRoute)
}
// MARK: - MPAVRoutingControllerDelegate
func routingControllerAvailableRoutesDidChange(controller: MPAVRoutingControllerProtocol) {
updateAirPlayDevices()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
audioDeviceController.setRouteDiscoveryEnabled!(false)
}
}
// MARK: - MPProtocols
@objc protocol MPAVRoutingControllerProtocol {
optional func availableRoutes() -> NSArray
optional func discoveryMode() -> Int
optional func fetchAvailableRoutesWithCompletionHandler(completion: (routes: [MPAVRouteProtocol]) -> Void)
optional func name() -> AnyObject
optional func pickRoute(route: MPAVRouteProtocol) -> Bool
optional func pickRoute(route: MPAVRouteProtocol, withPassword: String) -> Bool
optional func videoRouteForRoute(route: MPAVRouteProtocol) -> MPAVRouteProtocol
optional func clearCachedRoutes()
optional func setDelegate(delegate: NSObject)
}
@objc protocol MPAVRouteProtocol {
optional func routeName() -> String
optional func routeSubtype() -> Int
optional func routeType() -> Int
optional func requiresPassword() -> Bool
optional func routeUID() -> String
optional func isPicked() -> Bool
optional func passwordType() -> Int
optional func wirelessDisplayRoute() -> MPAVRouteProtocol
}
@objc protocol MPAudioDeviceControllerProtocol {
optional func setRouteDiscoveryEnabled(enabled: Bool)
optional func routeDescriptionAtIndex(index: Int) -> [String: AnyObject]
}
extension NSObject : MPAVRoutingControllerProtocol, MPAVRouteProtocol, MPAudioDeviceControllerProtocol {
} | 5634991026eda311b64a6ddcdfadc87e | 39.75 | 178 | 0.687988 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/PearlFX/FilterUI/BrightnessFilterViewController.swift | bsd-3-clause | 2 | //
// BrightnessFilterViewController.swift
// PearlCam
//
// Created by Tiangong You on 6/10/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class BrightnessFilterViewController: AdjustmentUIViewController {
@IBOutlet weak var brightnessSlider: FXSlider!
@IBOutlet weak var contrastSlider: FXSlider!
@IBOutlet weak var vibranceSlider: FXSlider!
override func viewDidLoad() {
super.viewDidLoad()
brightnessSlider.value = filterManager.exposure!
contrastSlider.value = filterManager.contrast!
vibranceSlider.value = filterManager.vibrance!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func brightnessValueDidChange(_ sender: Any) {
filterManager.exposure = brightnessSlider.value
}
@IBAction func contrastValueDidChange(_ sender: Any) {
filterManager.contrast = contrastSlider.value
}
@IBAction func vibranceValueDidChange(_ sender: Any) {
filterManager.vibrance = vibranceSlider.value
}
}
| d04a9971579385d8ea993e61c255f8bf | 27.25641 | 66 | 0.701452 | false | false | false | false |
xiaomudegithub/viossvc | refs/heads/master | viossvc/General/Base/BaseCustomTableViewController.swift | apache-2.0 | 1 | //
// BaseCustomTableViewController.swift
// viossvc
//
// Created by yaowang on 2016/10/29.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
class BaseCustomTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,TableViewHelperProtocol {
@IBOutlet weak var tableView: UITableView!
var tableViewHelper:TableViewHelper = TableViewHelper();
override func viewDidLoad() {
super.viewDidLoad()
initTableView();
}
//友盟页面统计
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView(NSStringFromClass(self.classForCoder))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView(NSStringFromClass(self.classForCoder))
}
final func initTableView() {
if tableView == nil {
for view:UIView in self.view.subviews {
if view.isKindOfClass(UITableView) {
tableView = view as? UITableView;
break;
}
}
}
if tableView.tableFooterView == nil {
tableView.tableFooterView = UIView(frame:CGRectMake(0,0,0,0.5));
}
tableView.delegate = self;
tableView.dataSource = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:TableViewHelperProtocol
func isSections() ->Bool {
return false;
}
func isCacheCellHeight() -> Bool {
return false;
}
func isCalculateCellHeight() ->Bool {
return isCacheCellHeight();
}
func tableView(tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: NSIndexPath) -> String? {
return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView:UITableView ,cellDataForRowAtIndexPath indexPath: NSIndexPath) -> AnyObject? {
return nil;
}
//MARK: -UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self);
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if( isCalculateCellHeight() ) {
let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self);
if( cellHeight != CGFloat.max ) {
return cellHeight;
}
}
return tableView.rowHeight;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0;
}
}
class BaseCustomRefreshTableViewController :BaseCustomTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
self.setupRefreshControl();
}
internal func didRequestComplete(data:AnyObject?) {
endRefreshing();
self.tableView.reloadData();
}
func completeBlockFunc()->CompleteBlock {
return { [weak self] (obj) in
self?.didRequestComplete(obj)
}
}
override func didRequestError(error:NSError) {
self.endRefreshing()
super.didRequestError(error)
}
deinit {
performSelectorRemoveRefreshControl();
}
}
class BaseCustomListTableViewController :BaseCustomRefreshTableViewController {
internal var dataSource:Array<AnyObject>?;
override func didRequestComplete(data: AnyObject?) {
dataSource = data as? Array<AnyObject>;
super.didRequestComplete(dataSource);
}
//MARK: -UITableViewDelegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var count:Int = dataSource != nil ? 1 : 0;
if isSections() && count != 0 {
count = dataSource!.count;
}
return count;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![section] as? Array<AnyObject>;
}
return datas == nil ? 0 : datas!.count;
}
//MARK:TableViewHelperProtocol
override func tableView(tableView:UITableView ,cellDataForRowAtIndexPath indexPath: NSIndexPath) -> AnyObject? {
var datas:Array<AnyObject>? = dataSource;
if dataSource != nil && isSections() {
datas = dataSource![indexPath.section] as? Array<AnyObject>;
}
return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil;
}
}
class BaseCustomPageListTableViewController :BaseCustomListTableViewController {
override func viewDidLoad() {
super.viewDidLoad();
setupLoadMore();
}
override func didRequestComplete(data: AnyObject?) {
tableViewHelper.didRequestComplete(&self.dataSource,
pageDatas: data as? Array<AnyObject>, controller: self);
super.didRequestComplete(self.dataSource);
}
override func didRequestError(error:NSError) {
if (!(self.pageIndex == 1) ) {
self.errorLoadMore()
}
self.setIsLoadData(true)
super.didRequestError(error)
}
deinit {
removeLoadMore();
}
}
| 949839950e2a8b86e87d00219fff5527 | 29.756345 | 128 | 0.636244 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/1_stdlib/OptionalRenames.swift | apache-2.0 | 6 | // RUN: %target-parse-verify-swift
func getInt(x: Int) -> Int? {
if x == 0 {
return .None // expected-error {{'None' has been renamed to 'none'}} {{13-17=none}}
}
return .Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{11-15=some}}
}
let x = Optional.Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{18-22=some}}
switch x {
case .None: break // expected-error {{'None' has been renamed to 'none'}} {{9-13=none}}
case .Some(let x): print(x) // expected-error {{'Some' has been renamed to 'some'}} {{9-13=some}}
}
let optionals: (Int?, Int?) = (Optional.Some(1), .None)
// expected-error@-1 {{'Some' has been renamed to 'some'}} {{41-45=some}}
// expected-error@-2 {{'None' has been renamed to 'none'}} {{51-55=none}}
switch optionals {
case (.None, .none): break // expected-error {{'None' has been renamed to 'none'}} {{10-14=none}}
case (.Some(let left), .some(let right)): break // expected-error {{'Some' has been renamed to 'some'}} {{10-14=some}}
default: break
}
| 4f0d233f4f2784a140206829889c97a4 | 38.615385 | 120 | 0.619417 | false | false | false | false |
ZhangMingNan/MNMeiTuan | refs/heads/master | 15-MeiTuan/Kingfisher-master/Kingfisher/ImageCache.swift | apache-2.0 | 8 | //
// ImageCache.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
*/
public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification"
/**
Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
*/
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
private let defaultCacheName = "default"
private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache."
private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue."
private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue."
private let defaultCacheInstance = ImageCache(name: defaultCacheName)
private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
public typealias RetrieveImageDiskTask = dispatch_block_t
/**
Cache type of a cached image.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case None, Memory, Disk, Watch
}
/**
* `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher.
*/
public class ImageCache {
//Memory
private let memoryCache = NSCache()
/// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory.
public var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
private let ioQueue: dispatch_queue_t
private let diskCachePath: String
private var fileManager: NSFileManager!
/// The longest time duration of the cache being stored in disk. Default is 1 week.
public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
/// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit.
public var maxDiskCacheSize: UInt = 0
private let processQueue: dispatch_queue_t
/// The default cache.
public class var defaultCache: ImageCache {
return defaultCacheInstance
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
:param: name Name of the cache. It will be used as the memory cache name and the disk cache folder name. This value should not be an empty string.
:returns: The cache object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = cacheReverseDNS + name
memoryCache.name = cacheName
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
diskCachePath = paths.first!.stringByAppendingPathComponent(cacheName)
ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL)
processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT)
dispatch_sync(ioQueue, { () -> Void in
self.fileManager = NSFileManager()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK: - Store & Remove
public extension ImageCache {
/**
Store an image to cache. It will be saved to both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
instead.
:param: image The image will be stored.
:param: key Key for the image.
*/
public func storeImage(image: UIImage, forKey key: String) {
storeImage(image, forKey: key, toDisk: true, completionHandler: nil)
}
/**
Store an image to cache. It is an async operation.
:param: image The image will be stored.
:param: key Key for the image.
:param: toDisk Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
:param: completionHandler Called when stroe operation completes.
*/
public func storeImage(image: UIImage, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
if toDisk {
dispatch_async(ioQueue, { () -> Void in
if let data = UIImagePNGRepresentation(image) {
if !self.fileManager.fileExistsAtPath(self.diskCachePath) {
self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil, error: nil)
}
self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil)
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
} else {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
})
} else {
if let handler = completionHandler {
handler()
}
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
instead.
:param: key Key for the image.
*/
public func removeImageForKey(key: String) {
removeImageForKey(key, fromDisk: true, completionHandler: nil)
}
/**
Remove the image for key for the cache. It is an async operation.
:param: key Key for the image.
:param: fromDisk Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
:param: completionHandler Called when removal operation completes.
*/
public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.removeObjectForKey(key)
if fromDisk {
dispatch_async(ioQueue, { () -> Void in
self.fileManager.removeItemAtPath(self.cachePathForKey(key), error: nil)
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
})
} else {
if let handler = completionHandler {
handler()
}
}
}
}
// MARK: - Get data from cache
extension ImageCache {
/**
Get an image for a key from memory or disk.
:param: key Key for the image.
:param: options Options of retriving image.
:param: completionHandler Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`.
:returns: The retriving task.
*/
public func retrieveImageForKey(key: String, options:KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
// No completion handler. Not start working and early return.
if (completionHandler == nil) {
return dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {}
}
let block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
if let image = self.retrieveImageInMemoryCacheForKey(key) {
//Found image in memory cache.
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
dispatch_async(options.queue, { () -> Void in
completionHandler?(result, .Memory)
return
})
})
} else {
completionHandler?(image, .Memory)
}
} else {
//Begin to load image from disk
dispatch_async(self.ioQueue, { () -> Void in
if let image = self.retrieveImageInDiskCacheForKey(key, scale: options.scale) {
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
self.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler?(result, .Memory)
return
})
})
} else {
self.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
if let completionHandler = completionHandler {
completionHandler(image, .Disk)
}
})
}
} else {
// No image found from either memory or disk
dispatch_async(options.queue, { () -> Void in
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
})
}
})
}
}
dispatch_async(options.queue, block)
return block
}
/**
Get an image for a key from memory.
:param: key Key for the image.
:returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? {
return memoryCache.objectForKey(key) as? UIImage
}
/**
Get an image for a key from disk.
:param: key Key for the image.
:param: scale The scale factor to assume when interpreting the image data.
:returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? {
return diskImageForKey(key, scale: scale)
}
}
// MARK: - Clear & Clean
extension ImageCache {
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is an async operation.
*/
public func clearDiskCache() {
clearDiskCacheWithCompletionHandler(nil)
}
/**
Clear disk cache. This is an async operation.
:param: completionHander Called after the operation completes.
*/
public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
dispatch_async(ioQueue, { () -> Void in
self.fileManager.removeItemAtPath(self.diskCachePath, error: nil)
self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil, error: nil)
if let completionHander = completionHander {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHander()
})
}
})
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCacheWithCompletionHander(nil)
}
/**
Clean expired disk cache. This is an async operation.
:param: completionHandler Called after the operation completes.
*/
public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
// Do things in cocurrent io queue
dispatch_async(ioQueue, { () -> Void in
if let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) {
let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
var cachedFiles = [NSURL: [NSObject: AnyObject]]()
var URLsToDelete = [NSURL]()
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
if let resourceValues = fileURL.resourceValuesForKeys(resourceKeys, error: nil) {
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
// If this file is expired, add it to URLsToDelete
if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
if modificationDate.laterDate(expiredDate) == expiredDate {
URLsToDelete.append(fileURL)
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
cachedFiles[fileURL] = resourceValues
}
}
}
}
for fileURL in URLsToDelete {
self.fileManager.removeItemAtURL(fileURL, error: nil)
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in
if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate {
if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
return date1.compare(date2) == .OrderedAscending
}
}
// Not valid date information. This should not happen. Just in case.
return true
})
for fileURL in sortedFiles {
if (self.fileManager.removeItemAtURL(fileURL, error: nil)) {
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize -= fileSize.unsignedLongValue
}
if diskCacheSize < targetSize {
break
}
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map({ (url) -> String in
return url.lastPathComponent!
})
NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
if let completionHandler = completionHandler {
completionHandler()
}
})
} else {
println("Bad disk cache path. \(self.diskCachePath) is not a valid local directory path.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler()
}
})
}
})
}
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCacheWithCompletionHander { () -> () in
endBackgroundTask(&backgroundTask!)
}
}
}
// MARK: - Check cache status
public extension ImageCache {
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
:param: key Key for the image.
:returns: The check result.
*/
public func isImageCachedForKey(key: String) -> CacheCheckResult {
if memoryCache.objectForKey(key) != nil {
return CacheCheckResult(cached: true, cacheType: .Memory)
}
let filePath = cachePathForKey(key)
if fileManager.fileExistsAtPath(filePath) {
return CacheCheckResult(cached: true, cacheType: .Disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
:param: key The key which is used for caching.
:returns: Corresponding hash.
*/
public func hashForKey(key: String) -> String {
return cacheFileNameForKey(key)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
:param: completionHandler Called with the calculated size when finishes.
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) {
dispatch_async(ioQueue, { () -> Void in
if let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) {
let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL,
includingPropertiesForKeys: resourceKeys,
options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,
errorHandler: nil) {
for fileURL in fileEnumerator.allObjects as! [NSURL] {
if let resourceValues = fileURL.resourceValuesForKeys(resourceKeys, error: nil) {
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
}
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: diskCacheSize)
}
})
} else {
println("Bad disk cache path. \(self.diskCachePath) is not a valid local directory path.")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: 0)
}
})
}
})
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImageForKey(key: String, scale: CGFloat) -> UIImage? {
if let data = diskImageDataForKey(key) {
if let image = UIImage(data: data, scale: scale) {
return image
} else {
return nil
}
} else {
return nil
}
}
func diskImageDataForKey(key: String) -> NSData? {
let filePath = cachePathForKey(key)
return NSData(contentsOfFile: filePath)
}
func cachePathForKey(key: String) -> String {
let fileName = cacheFileNameForKey(key)
return diskCachePath.stringByAppendingPathComponent(fileName)
}
func cacheFileNameForKey(key: String) -> String {
return key.kf_MD5()
}
}
extension UIImage {
var kf_imageCost: Int {
return Int(size.height * size.width * scale * scale)
}
}
extension Dictionary {
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
var array = Array(self)
sort(&array) {
let (lk, lv) = $0
let (rk, rv) = $1
return isOrderedBefore(lv, rv)
}
return array.map {
let (k, v) = $0
return k
}
}
}
| c21f26a8a603d1202f928414c2dabbbb | 39.781734 | 335 | 0.563029 | false | false | false | false |
bara86/BSImagePicker | refs/heads/master | Pod/Classes/Model/AssetCollectionDataSource.swift | mit | 6 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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 Photos
final class AssetCollectionDataSource : NSObject, SelectableDataSource {
private var assetCollection: PHAssetCollection
var selections: [PHObject] = []
var delegate: SelectableDataDelegate?
var allowsMultipleSelection: Bool = false
var maxNumberOfSelections: Int = 1
var selectedIndexPaths: [NSIndexPath] {
get {
if selections.count > 0 {
return [NSIndexPath(forItem: 0, inSection: 0)]
} else {
return []
}
}
}
required init(assetCollection: PHAssetCollection) {
self.assetCollection = assetCollection
super.init()
}
// MARK: SelectableDataSource
var sections: Int {
get {
return 1
}
}
func numberOfObjectsInSection(section: Int) -> Int {
return 1
}
func objectAtIndexPath(indexPath: NSIndexPath) -> PHObject {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
return assetCollection
}
func selectObjectAtIndexPath(indexPath: NSIndexPath) {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
selections = [assetCollection]
}
func deselectObjectAtIndexPath(indexPath: NSIndexPath) {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
selections = []
}
func isObjectAtIndexPathSelected(indexPath: NSIndexPath) -> Bool {
assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row")
return selections.count > 0
}
}
| e1d73580a6dccde4454badf1e5dbcf05 | 36.443038 | 122 | 0.682894 | false | false | false | false |
onemonth/TakePhotos | refs/heads/master | TakePhotos/ViewController.swift | mit | 1 | //
// ViewController.swift
// TakePictures
//
// Created by Alfred Hanssen on 3/1/16.
// Copyright © 2016 One Month. All rights reserved.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
// MARK: Actions
@IBAction func presentCamera()
{
let sourceType = UIImagePickerControllerSourceType.Camera
self.presentImagePicker(sourceType: sourceType)
}
@IBAction func presentPhotoLibrary()
{
let sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentImagePicker(sourceType: sourceType)
}
@IBAction func presentSavedPhotosAlbum()
{
let sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
self.presentImagePicker(sourceType: sourceType)
}
// MARK: Private API
private func presentImagePicker(sourceType sourceType: UIImagePickerControllerSourceType)
{
if UIImagePickerController.isSourceTypeAvailable(sourceType) == false
{
// The sourceType is not available
return
}
let viewController = UIImagePickerController()
viewController.sourceType = sourceType
viewController.delegate = self
self.presentViewController(viewController, animated: true, completion: nil)
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
// Do something with the image
}
else if let URL = info[UIImagePickerControllerMediaURL] as? NSURL
{
// Do something with the URL
print(URL.absoluteString)
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
| cf22f8a298857b269c07793fbe7c3c19 | 33.354839 | 121 | 0.709546 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Plans/FeatureItemRow.swift | gpl-2.0 | 2 | import UIKit
import WordPressShared
struct FeatureItemRow: ImmuTableRow {
static let cell = ImmuTableCell.class(FeatureItemCell.self)
let title: String
let description: String
let iconURL: URL?
let action: ImmuTableAction? = nil
func configureCell(_ cell: UITableViewCell) {
guard let cell = cell as? FeatureItemCell else { return }
cell.featureTitleLabel?.text = title
if let featureDescriptionLabel = cell.featureDescriptionLabel {
cell.featureDescriptionLabel?.attributedText = attributedDescriptionText(description, font: featureDescriptionLabel.font)
}
if let iconURL = iconURL {
cell.featureIconImageView?.setImageWith(iconURL, placeholderImage: nil)
}
cell.featureTitleLabel.textColor = WPStyleGuide.darkGrey()
cell.featureDescriptionLabel.textColor = WPStyleGuide.grey()
WPStyleGuide.configureTableViewCell(cell)
}
fileprivate func attributedDescriptionText(_ text: String, font: UIFont) -> NSAttributedString {
let lineHeight: CGFloat = 18
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.minimumLineHeight = lineHeight
let attributedText = NSMutableAttributedString(string: text, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font])
return attributedText
}
}
| 9aa17ab57982f984188d1fbf5b98dd79 | 35.325 | 156 | 0.723331 | false | false | false | false |
qutheory/vapor | refs/heads/master | Sources/Vapor/Utilities/Storage.swift | mit | 1 | public struct Storage {
var storage: [ObjectIdentifier: AnyStorageValue]
struct Value<T>: AnyStorageValue {
var value: T
var onShutdown: ((T) throws -> ())?
func shutdown(logger: Logger) {
do {
try self.onShutdown?(self.value)
} catch {
logger.error("Could not shutdown \(T.self): \(error)")
}
}
}
let logger: Logger
public init(logger: Logger = .init(label: "codes.vapor.storage")) {
self.storage = [:]
self.logger = logger
}
public mutating func clear() {
self.storage = [:]
}
public subscript<Key>(_ key: Key.Type) -> Key.Value?
where Key: StorageKey
{
get {
self.get(Key.self)
}
set {
self.set(Key.self, to: newValue)
}
}
public func contains<Key>(_ key: Key.Type) -> Bool {
self.storage.keys.contains(ObjectIdentifier(Key.self))
}
public func get<Key>(_ key: Key.Type) -> Key.Value?
where Key: StorageKey
{
guard let value = self.storage[ObjectIdentifier(Key.self)] as? Value<Key.Value> else {
return nil
}
return value.value
}
public mutating func set<Key>(
_ key: Key.Type,
to value: Key.Value?,
onShutdown: ((Key.Value) throws -> ())? = nil
)
where Key: StorageKey
{
let key = ObjectIdentifier(Key.self)
if let value = value {
self.storage[key] = Value(value: value, onShutdown: onShutdown)
} else if let existing = self.storage[key] {
self.storage[key] = nil
existing.shutdown(logger: self.logger)
}
}
public func shutdown() {
self.storage.values.forEach {
$0.shutdown(logger: self.logger)
}
}
}
protocol AnyStorageValue {
func shutdown(logger: Logger)
}
public protocol StorageKey {
associatedtype Value
}
| 4b3642b4b518c8186b4a3fd478063a46 | 23.8875 | 94 | 0.542441 | false | false | false | false |
malaonline/iOS | refs/heads/master | mala-ios/View/Course/SingleCourseView.swift | mit | 1 | //
// SingleCourseView.swift
// mala-ios
//
// Created by 王新宇 on 16/6/15.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class SingleCourseView: UIView {
// MARK: - Property
/// 单次课程数据模型
var model: StudentCourseModel? {
didSet {
DispatchQueue.main.async {
self.changeDisplayMode()
self.setupCourseInfo()
}
}
}
// MARK: - Components
/// 信息背景视图
private lazy var headerBackground: UIView = {
let view = UIView(UIColor(named: .Disabled))
view.layer.cornerRadius = 2
view.layer.masksToBounds = true
return view
}()
/// 学科年级信息标签
private lazy var subjectLabel: UILabel = {
let label = UILabel(
text: "学科",
fontSize: 14,
textColor: UIColor(named: .WhiteTranslucent9)
)
return label
}()
/// 直播课程图标
private lazy var liveCourseIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_courseIcon")
return imageView
}()
/// 老师姓名图标
private lazy var teacherIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_teacher")
return imageView
}()
/// 老师姓名标签
private lazy var teacherLabel: UILabel = {
let label = UILabel(
text: "老师姓名",
fontSize: 14,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 助教老师姓名
private lazy var assistantLabel: UILabel = {
let label = UILabel(
text: "助教老师姓名",
fontSize: 13,
textColor: UIColor(named: .HeaderTitle)
)
return label
}()
/// 上课时间图标
private lazy var timeSlotIcon: UIImageView = {
let imageView = UIImageView(imageName: "comment_time")
return imageView
}()
/// 上课时间信息
private lazy var timeSlotLabel: UILabel = {
let label = UILabel(
text: "上课时间",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 上课地点图标
private lazy var schoolIcon: UIImageView = {
let imageView = UIImageView(imageName: "comment_location")
return imageView
}()
/// 上课地点
private lazy var schoolLabel: UILabel = {
let label = UILabel(
text: "上课地点",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
label.numberOfLines = 0
return label
}()
/// 评论按钮
private lazy var commentButton: UIButton = {
let button = UIButton()
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
button.layer.masksToBounds = true
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
button.isHidden = true
return button
}()
// MARK: - Instance Method
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private
private func setupUserInterface() {
backgroundColor = UIColor.white
// SubView
addSubview(headerBackground)
headerBackground.addSubview(subjectLabel)
headerBackground.addSubview(liveCourseIcon)
addSubview(teacherIcon)
addSubview(teacherLabel)
addSubview(assistantLabel)
addSubview(timeSlotIcon)
addSubview(timeSlotLabel)
addSubview(schoolIcon)
addSubview(schoolLabel)
addSubview(commentButton)
// AutoLayout
headerBackground.snp.makeConstraints { (maker) in
maker.top.equalTo(self)
maker.height.equalTo(32)
maker.left.equalTo(self)
maker.right.equalTo(self)
}
subjectLabel.snp.makeConstraints { (maker) in
maker.height.equalTo(14)
maker.left.equalTo(headerBackground).offset(10)
maker.centerY.equalTo(headerBackground)
}
liveCourseIcon.snp.makeConstraints { (maker) in
maker.height.equalTo(21)
maker.right.equalTo(headerBackground).offset(-10)
maker.centerY.equalTo(headerBackground)
}
teacherIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(headerBackground.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(13)
}
teacherLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon)
maker.left.equalTo(teacherIcon.snp.right).offset(5)
maker.height.equalTo(13)
}
assistantLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon)
maker.left.equalTo(teacherLabel.snp.right).offset(27.5)
maker.height.equalTo(13)
}
timeSlotIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(13)
}
timeSlotLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(timeSlotIcon)
maker.left.equalTo(timeSlotIcon.snp.right).offset(5)
maker.height.equalTo(13)
}
schoolIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(timeSlotIcon.snp.bottom).offset(10)
maker.left.equalTo(headerBackground)
maker.width.equalTo(13)
maker.height.equalTo(15)
}
schoolLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(schoolIcon)
maker.left.equalTo(schoolIcon.snp.right).offset(5)
maker.right.equalTo(self)
maker.bottom.equalTo(self).offset(-20)
}
commentButton.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherLabel)
maker.right.equalTo(headerBackground)
maker.height.equalTo(24)
}
}
/// 加载课程数据
private func setupCourseInfo() {
guard let course = model else { return }
// 课程类型
if course.isLiveCourse == true {
liveCourseIcon.isHidden = false
assistantLabel.isHidden = false
teacherLabel.text = course.lecturer?.name
assistantLabel.text = String(format: "助教:%@", course.teacher?.name ?? "")
}else {
liveCourseIcon.isHidden = true
assistantLabel.isHidden = true
teacherLabel.text = course.teacher?.name
}
// 课程信息
subjectLabel.text = String(format: "%@%@", course.grade, course.subject)
timeSlotLabel.text = String(format: "%@-%@", getDateString(course.start, format: "HH:mm"), getDateString(course.end, format: "HH:mm"))
schoolLabel.attributedText = model?.attrAddressString
// 课程状态
switch course.status {
case .Past:
headerBackground.backgroundColor = UIColor(named: .Disabled)
commentButton.isHidden = false
break
case .Today:
headerBackground.backgroundColor = UIColor(named: .ThemeDeepBlue)
commentButton.isHidden = true
break
case .Future:
headerBackground.backgroundColor = UIColor(named: .ThemeDeepBlue)
commentButton.isHidden = true
break
}
}
/// 根据当前课程评价状态,渲染对应UI样式
private func changeDisplayMode() {
// 课程评价状态
if model?.comment != nil {
setStyleCommented()
}else if model?.isExpired == true {
setStyleExpired()
}else {
setStyleNoComments()
}
}
/// 设置过期样式
private func setStyleExpired() {
commentButton.layer.borderColor = UIColor(named: .HeaderTitle).cgColor
commentButton.setTitle("评价已过期", for: .normal)
commentButton.setTitleColor(UIColor(named: .HeaderTitle), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .HeaderTitle)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.isEnabled = false
}
/// 设置待评论样式
private func setStyleNoComments() {
commentButton.layer.borderColor = UIColor(named: .ThemeRed).cgColor
commentButton.setTitle("去评价", for: .normal)
commentButton.setTitleColor(UIColor(named: .ThemeRed), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .ThemeRedHighlight)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.addTarget(self, action: #selector(SingleCourseView.toComment), for: .touchUpInside)
}
/// 设置已评论样式
private func setStyleCommented() {
commentButton.layer.borderColor = UIColor(named: .commentBlue).cgColor
commentButton.setTitle("查看评价", for: .normal)
commentButton.setTitleColor(UIColor(named: .commentBlue), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor.white), for: .normal)
commentButton.setBackgroundImage(UIImage.withColor(UIColor(named: .CommitHighlightBlue)), for: .highlighted)
commentButton.titleLabel?.font = FontFamily.PingFangSC.Regular.font(12)
commentButton.addTarget(self, action: #selector(SingleCourseView.showComment), for: .touchUpInside)
}
// MARK: - Event Response
/// 去评价
@objc private func toComment() {
let commentWindow = CommentViewWindow(contentView: UIView())
commentWindow.finishedAction = { [weak self] in
self?.commentButton.removeTarget(self, action: #selector(SingleCourseView.toComment), for: .touchUpInside)
self?.setStyleCommented()
}
commentWindow.model = self.model ?? StudentCourseModel()
commentWindow.isJustShow = false
commentWindow.show()
}
/// 查看评价
@objc private func showComment() {
let commentWindow = CommentViewWindow(contentView: UIView())
commentWindow.model = self.model ?? StudentCourseModel()
commentWindow.isJustShow = true
commentWindow.show()
}
}
| edccf4c0cdf171fd7a3d3d42f2053502 | 33.483974 | 142 | 0.603588 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | examples/uiKit/uiKitCatalog/UIKitCatalog/CustomToolbarViewController.swift | mit | 3 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to customize a UIToolbar.
*/
import UIKit
class CustomToolbarViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var toolbar: UIToolbar!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
}
// MARK: - Configuration
func configureToolbar() {
let toolbarBackgroundImage = UIImage(named: "toolbar_background")
toolbar.setBackgroundImage(toolbarBackgroundImage, forToolbarPosition: .bottom, barMetrics: .default)
let toolbarButtonItems = [
customImageBarButtonItem,
flexibleSpaceBarButtonItem,
customBarButtonItem
]
toolbar.setItems(toolbarButtonItems, animated: true)
}
// MARK: - UIBarButtonItem Creation and Configuration
var customImageBarButtonItem: UIBarButtonItem {
let customBarButtonItemImage = UIImage(named: "tools_icon")
let customImageBarButtonItem = UIBarButtonItem(image: customBarButtonItemImage, style: .plain, target: self, action: #selector(CustomToolbarViewController.barButtonItemClicked(_:)))
customImageBarButtonItem.tintColor = UIColor.applicationPurpleColor
return customImageBarButtonItem
}
var flexibleSpaceBarButtonItem: UIBarButtonItem {
// Note that there's no target/action since this represents empty space.
return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
var customBarButtonItem: UIBarButtonItem {
let barButtonItem = UIBarButtonItem(title: NSLocalizedString("Button", comment: ""), style: .plain, target: self, action: #selector(CustomToolbarViewController.barButtonItemClicked(_:)))
let backgroundImage = UIImage(named: "WhiteButton")
barButtonItem.setBackgroundImage(backgroundImage, for: UIControlState(), barMetrics: .default)
let attributes = [
NSForegroundColorAttributeName: UIColor.applicationPurpleColor
]
barButtonItem.setTitleTextAttributes(attributes, for: UIControlState())
return barButtonItem
}
// MARK: - Actions
func barButtonItemClicked(_ barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the custom toolbar was clicked: \(barButtonItem).")
}
}
| 81aa8a88e23b688f19abb92810eccb3d | 32.506667 | 194 | 0.70394 | false | true | false | false |
mortorqrobotics/morscout-ios | refs/heads/master | MorScout/Models/Dropdown.swift | mit | 1 | //
// Dropdown.swift
// MorScout
//
// Created by Farbod Rafezy on 3/1/16.
// Copyright © 2016 MorTorq. All rights reserved.
//
import Foundation
import SwiftyJSON
class Dropdown: DataPoint {
let name: String
var options: [String]
init(json: JSON) {
name = json["name"].stringValue
options = []
for (_, subJson):(String, JSON) in json["options"] {
options.append(subJson.stringValue)
}
}
init(name: String, options: [String]){
self.name = name
self.options = options
}
required convenience init(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: "name") as! String
let options = aDecoder.decodeObject(forKey: "options") as! [String]
self.init(name: name, options: options)
}
func encodeWithCoder(_ aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(options, forKey: "options")
}
}
| 32d1a9f57c352a28b3373a17e0e3d3a0 | 24.605263 | 75 | 0.606372 | false | false | false | false |
TeamDeverse/BC-Agora | refs/heads/master | BC-Agora/background.swift | mit | 1 | //
// background.swift
// BC-Agora
//
// Created by William Bowditch on 11/16/15.
// Copyright © 2015 William Bowditch. All rights reserved.
//
import Foundation
//import UIView
extension UIViewController {
func addBackground() {
// screen width and height:
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill
self.addSubview(imageViewBackground)
self.sendSubviewToBack(imageViewBackground)
}}
| 71e92d7b52fff29ff236389d4f64daa9 | 29.222222 | 85 | 0.676471 | false | false | false | false |
armadsen/CocoaHeads-SLC-Presentations | refs/heads/master | IntroToConcurrentProgramming/GCD.playground/Pages/Untitled Page 4.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import Foundation
let queue = OperationQueue()
queue.name = "MySerialOperationQueue"
queue.maxConcurrentOperationCount = 1
let op1 = BlockOperation {
print("Do this first")
}
let op2 = BlockOperation {
print("Do this second")
}
let op3 = BlockOperation {
print("Do this third")
}
queue.waitUntilAllOperationsAreFinished()
print("Done!")
//: [Next](@next)
| 89a2d82ace1fab647a78995454fa4f43 | 15.04 | 41 | 0.703242 | false | false | false | false |
northwoodspd/FluentConstraints | refs/heads/master | FluentConstraints/FluentConstraintSet.swift | mit | 1 | //
// FluentConstraintSet.swift
// FluentConstraints
//
// Created by Steve Madsen on 6/26/15.
// Copyright (c) 2015 Northwoods Consulting Partners. All rights reserved.
//
import Foundation
open class FluentConstraintSet {
var firstView: UIView
var constraints: [FluentConstraint] = []
public init(_ view: UIView) {
self.firstView = view
}
open func build() -> [NSLayoutConstraint] {
return constraints.map { $0.build() }
}
open func activate() -> [NSLayoutConstraint] {
let constraints = build()
NSLayoutConstraint.activate(constraints)
return constraints
}
// MARK: relationship to view
open var inSuperview: FluentConstraintSet {
precondition(self.firstView.superview != nil, "View does not have a superview")
self.constraints.forEach { $0.secondView = self.firstView.superview! }
return self
}
open func onView(_ view: UIView) -> FluentConstraintSet {
self.constraints.forEach { $0.secondView = view }
return self
}
open func asView(_ view: UIView) -> FluentConstraintSet {
return onView(view)
}
// MARK: internal helpers
func fluentConstraintForView(_ view: UIView, attribute: NSLayoutConstraint.Attribute, constant: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> FluentConstraint {
let constraint = FluentConstraint(view)
constraint.firstAttribute = attribute
constraint.relation = relation
constraint.secondAttribute = attribute
constraint.constant = constant
return constraint
}
// MARK: builds collections of fluent constraints
open var centered: FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .centerX))
constraints.append(fluentConstraintForView(self.firstView, attribute: .centerY))
return self
}
open var sameSize: FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .width))
constraints.append(fluentConstraintForView(self.firstView, attribute: .height))
return self
}
open func inset(_ insets: UIEdgeInsets) -> FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left))
constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right))
constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top))
constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom))
return self
}
open func inset(_ constant: CGFloat) -> FluentConstraintSet {
return inset(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant))
}
open func insetAtLeast(_ insets: UIEdgeInsets) -> FluentConstraintSet {
constraints.append(fluentConstraintForView(self.firstView, attribute: .left, constant: insets.left, relation: .greaterThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .right, constant: -insets.right, relation: .lessThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .top, constant: insets.top, relation: .greaterThanOrEqual))
constraints.append(fluentConstraintForView(self.firstView, attribute: .bottom, constant: -insets.bottom, relation: .lessThanOrEqual))
return self
}
open func insetAtLeast(_ constant: CGFloat) -> FluentConstraintSet {
return insetAtLeast(UIEdgeInsets(top: constant, left: constant, bottom: constant, right: constant))
}
}
| 4e57659e8d9902e1b044430721e7e063 | 37.639175 | 182 | 0.705977 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Constraints/gather_all_adjacencies.swift | apache-2.0 | 47 | // RUN: %target-swift-frontend -typecheck %s
// SR-5120 / rdar://problem/32618740
protocol InitCollection: Collection {
init(_ array: [Iterator.Element])
}
protocol InitAny {
init()
}
extension Array: InitCollection {
init(_ array: [Iterator.Element]) {
self = array
}
}
extension String: InitAny {
init() {
self = "bar"
}
}
class Foo {
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T
where T.Iterator.Element == U
{
return T.init([U.init()])
}
func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T?
where T.Iterator.Element == U
{
return T.init([U.init()])
}
}
let _: [String] = Foo().foo(of: String.self)
| 236f0564cdbbfa9d67aee1f58262f325 | 16.894737 | 64 | 0.619118 | false | false | false | false |
Rochester-Ting/DouyuTVDemo | refs/heads/master | RRDouyuTV/RRDouyuTV/Classes/Tools(工具)/Common.swift | mit | 1 | //
// Common.swift
// RRDouyuTV
//
// Created by 丁瑞瑞 on 11/10/16.
// Copyright © 2016年 Rochester. All rights reserved.
//
import Foundation
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationH : CGFloat = 44
let kTitleViewH : CGFloat = 40
let kTabBarH : CGFloat = 44
let kScreenW : CGFloat = UIScreen.main.bounds.size.width
let kScreenH : CGFloat = UIScreen.main.bounds.size.height
let kClycleH : CGFloat = 150
let kGameViewH : CGFloat = 80
| f2575afe6db437e8fac255d6f0a6a675 | 21.8 | 57 | 0.725877 | false | false | false | false |
daaavid/TIY-Assignments | refs/heads/master | 37--Venue-Menu/Venue-Menu/Venue-Menu/SearchTableViewController.swift | cc0-1.0 | 1 | //
// SearchTableViewController.swift
// Venue-Menu
//
// Created by david on 11/26/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import QuartzCore
import CoreData
protocol APIControllerProtocol
{
func venuesWereFound(venues: [NSDictionary])
}
class SearchTableViewController: UITableViewController, APIControllerProtocol, UISearchBarDelegate
{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var searchResults = [NSManagedObject]()
var location: Location!
let locationManager = LocationManager()
var apiController: APIController!
override func viewDidLoad()
{
super.viewDidLoad()
segmentedControl.hidden = true
searchBar.delegate = self
location = USER_LOCATION
// locationManager.delegate = self
// locationManager.configureLocationManager()
apiController = APIController(delegate: self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return searchResults.count
}
func locationWasFound(location: Location)
{
self.location = location
}
@IBAction func segmentedControlValueChanged(sender: UISegmentedControl)
{
search()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
search()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
searchBar.resignFirstResponder()
}
func search()
{
if let _ = location
{
print("searching")
print(location)
if let term = searchBar.text
{
switch segmentedControl.selectedSegmentIndex
{
case 0: apiController.search(term, location: location, searchOption: "explore")
case 1: apiController.search(term, location: location, searchOption: "search")
default: print("segmentedControl unknown segmentIndex")
}
}
searchBar.resignFirstResponder()
}
}
func venuesWereFound(venues: [NSDictionary])
{
print(venues.count)
dispatch_async(dispatch_get_main_queue(), {
for eachVenueDict in venues
{
if let venue = Venue.venueWithJSON(eachVenueDict)
{
self.searchResults.append(venue)
}
}
self.apiController.cancelSearch()
self.tableView.reloadData()
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath) as! VenueCell
let venue = searchResults[indexPath.row]
cell.venueLabel.text = venue.valueForKey("name") as? String
cell.typeLabel.text = venue.valueForKey("type") as? String
cell.addressLabel.text = venue.valueForKey("address") as? String
if let imageURL = venue.valueForKey("icon") as? String
{
let imageView = makeCellImage(imageURL)
cell.addSubview(imageView)
}
return cell
}
func makeCellImage(iconURL: String) -> UIImageView
{
let imageView = UIImageView()
imageView.frame = CGRect(x: 8, y: 8, width: 64, height: 64)
imageView.downloadedFrom(iconURL, contentMode: .ScaleToFill)
imageView.round()
imageView.backgroundColor = UIColor(hue:0.625, saturation:0.8, brightness:0.886, alpha:1)
return imageView
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let mainVC = navigationController?.viewControllers[0] as! MainViewController
let detailVC = storyboard?.instantiateViewControllerWithIdentifier("detailVC") as! DetailViewController
let chosenVenue = searchResults[indexPath.row]
detailVC.venue = chosenVenue
detailVC.location = USER_LOCATION
detailVC.delegate = mainVC
navigationController?.pushViewController(detailVC, animated: true)
}
// override func viewDidDisappear(animated: Bool)
// {
// let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// for venue in searchResults
// {
// managedObjectContext.deleteObject(venue)
// }
// }
}
| a10c267a2025bf3645e8ff34411f2aaa | 29.402516 | 118 | 0.628051 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | refs/heads/master | Pod/Classes/Sources.Api/AppResourceData.swift | apache-2.0 | 1 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli-
-cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
This class represents a resource provided by the platform from the application's secure payload.
@author Carlos Lozano Diez
@since v2.1.3
@version 1.0
*/
public class AppResourceData {
/**
Marker to indicate whether the resource is cooked in some way (compressed, encrypted, etc.) If true, the
implementation must uncompress/unencrypt following the cookedType recipe specified by the payload.
*/
var cooked : Bool?
/**
This is the length of the payload after cooking. In general, this length indicates the amount
of space saved with regard to the rawLength of the payload.
*/
var cookedLength : Int64?
/**
If the data is cooked, this field should contain the recipe to return the cooked data to its original
uncompressed/unencrypted/etc format.
*/
var cookedType : String?
/**
The payload data of the resource in ready to consume format.
*/
var data : [UInt8]?
/**
The id or path identifier of the resource.
*/
var id : String?
/**
The raw length of the payload before any cooking occurred. This is equivalent to the size of the resource
after uncompressing and unencrypting.
*/
var rawLength : Int64?
/**
The raw type of the payload - this is equivalent to the mimetype of the content.
*/
var rawType : String?
/**
Default constructor.
@since v2.1.3
*/
public init() {
}
/**
Convenience constructor.
@param id The id or path of the resource retrieved.
@param data The payload data of the resource (uncooked).
@param rawType The raw type/mimetype of the resource.
@param rawLength The raw length/original length in bytes of the resource.
@param cooked True if the resource is cooked.
@param cookedType Type of recipe used for cooking.
@param cookedLength The cooked length in bytes of the resource.
@since v2.1.3
*/
public init(id: String, data: [UInt8], rawType: String, rawLength: Int64, cooked: Bool, cookedType: String, cookedLength: Int64) {
self.id = id
self.data = data
self.rawType = rawType
self.rawLength = rawLength
self.cooked = cooked
self.cookedType = cookedType
self.cookedLength = cookedLength
}
/**
Attribute to denote whether the payload of the resource is cooked.
@return True if the resource is cooked, false otherwise.
@since v2.1.3
*/
public func getCooked() -> Bool? {
return self.cooked
}
/**
Attribute to denote whether the payload of the resource is cooked.
@param cooked True if the resource is cooked, false otherwise.
@since v2.1.3
*/
public func setCooked(cooked: Bool) {
self.cooked = cooked
}
/**
The length in bytes of the payload after cooking.
@return Length in bytes of cooked payload.
@since v2.1.3
*/
public func getCookedLength() -> Int64? {
return self.cookedLength
}
/**
The length in bytes of the payload after cooking.
@param cookedLength Length in bytes of cooked payload.
@since v2.1.3
*/
public func setCookedLength(cookedLength: Int64) {
self.cookedLength = cookedLength
}
/**
If the resource is cooked, this will return the recipe used during cooking.
@return The cooking recipe to reverse the cooking process.
@since v2.1.3
*/
public func getCookedType() -> String? {
return self.cookedType
}
/**
If the resource is cooked, the type of recipe used during cooking.
@param cookedType The cooking recipe used during cooking.
@since v2.1.3
*/
public func setCookedType(cookedType: String) {
self.cookedType = cookedType
}
/**
Returns the payload of the resource.
@return Binary payload of the resource.
@since v2.1.3
*/
public func getData() -> [UInt8]? {
return self.data
}
/**
Sets the payload of the resource.
@param data Binary payload of the resource.
@since v2.1.3
*/
public func setData(data: [UInt8]) {
self.data = data
}
/**
Gets The id or path identifier of the resource.
@return id The id or path identifier of the resource.
*/
public func getId() -> String? {
return self.id
}
/**
Sets the id or path of the resource.
@param id The id or path of the resource.
@since v2.1.3
*/
public func setId(id: String) {
self.id = id
}
/**
Gets the resource payload's original length.
@return Original length of the resource in bytes before cooking.
@since v2.1.3
*/
public func getRawLength() -> Int64? {
return self.rawLength
}
/**
Sets the resource payload's original length.
@param rawLength Original length of the resource in bytes before cooking.
@since v2.1.3
*/
public func setRawLength(rawLength: Int64) {
self.rawLength = rawLength
}
/**
Gets the resource's raw type or mimetype.
@return Resource's type or mimetype.
@since v2.1.3
*/
public func getRawType() -> String? {
return self.rawType
}
/**
Sets the resource's raw type or mimetype.
@param rawType Resource's type or mimetype.
@since v2.1.3
*/
public func setRawType(rawType: String) {
self.rawType = rawType
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> AppResourceData {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> AppResourceData {
let resultObject : AppResourceData = AppResourceData()
if let value : AnyObject = dict.objectForKey("cooked") {
if "\(value)" as NSString != "<null>" {
resultObject.cooked = (value as! Bool)
}
}
if let value : AnyObject = dict.objectForKey("cookedLength") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.cookedLength = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("cookedType") {
if "\(value)" as NSString != "<null>" {
resultObject.cookedType = (value as! String)
}
}
if let value : AnyObject = dict.objectForKey("data") {
if "\(value)" as NSString != "<null>" {
var data : [UInt8] = [UInt8](count: (value as! NSArray).count, repeatedValue: 0)
let dataData : NSData = (value as! NSData)
dataData.getBytes(&data, length: (value as! NSArray).count * sizeof(UInt8))
resultObject.data = data
}
}
if let value : AnyObject = dict.objectForKey("id") {
if "\(value)" as NSString != "<null>" {
resultObject.id = (value as! String)
}
}
if let value : AnyObject = dict.objectForKey("rawLength") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.rawLength = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("rawType") {
if "\(value)" as NSString != "<null>" {
resultObject.rawType = (value as! String)
}
}
return resultObject
}
public static func toJSON(object: AppResourceData) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.cooked != nil ? jsonString.appendString("\"cooked\": \(object.cooked!), ") : jsonString.appendString("\"cooked\": null, ")
object.cookedLength != nil ? jsonString.appendString("\"cookedLength\": \(object.cookedLength!), ") : jsonString.appendString("\"cookedLength\": null, ")
object.cookedType != nil ? jsonString.appendString("\"cookedType\": \"\(JSONUtil.escapeString(object.cookedType!))\", ") : jsonString.appendString("\"cookedType\": null, ")
if (object.data != nil) {
// Start array of objects.
jsonString.appendString("\"data\": [")
for var i = 0; i < object.data!.count; i++ {
jsonString.appendString("\(object.data![i])")
if (i < object.data!.count-1) {
jsonString.appendString(", ");
}
}
// End array of objects.
jsonString.appendString("], ");
} else {
jsonString.appendString("\"data\": null, ")
}
object.id != nil ? jsonString.appendString("\"id\": \"\(JSONUtil.escapeString(object.id!))\", ") : jsonString.appendString("\"id\": null, ")
object.rawLength != nil ? jsonString.appendString("\"rawLength\": \(object.rawLength!), ") : jsonString.appendString("\"rawLength\": null, ")
object.rawType != nil ? jsonString.appendString("\"rawType\": \"\(JSONUtil.escapeString(object.rawType!))\"") : jsonString.appendString("\"rawType\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| cb454e8c6f7d6a5ad9241430020e2982 | 31.988571 | 184 | 0.573705 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Pods/LeanCloud/Sources/Storage/DataType/Number.swift | gpl-3.0 | 1 | //
// LCNumber.swift
// LeanCloud
//
// Created by Tang Tianyong on 2/27/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
LeanCloud number type.
It is a wrapper of `Swift.Double` type, used to store a number value.
*/
public final class LCNumber: NSObject, LCValue, LCValueExtension, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public private(set) var value: Double = 0
public override init() {
super.init()
}
public convenience init(_ value: Double) {
self.init()
self.value = value
}
public convenience required init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
public convenience required init(integerLiteral value: IntegerLiteralType) {
self.init(Double(value))
}
public required init?(coder aDecoder: NSCoder) {
value = aDecoder.decodeDouble(forKey: "value")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(value, forKey: "value")
}
public func copy(with zone: NSZone?) -> Any {
return LCNumber(value)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? LCNumber {
return object === self || object.value == value
} else {
return false
}
}
public var jsonValue: Any {
return value
}
func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String {
return String(format: "%g", value)
}
public var jsonString: String {
return formattedJSONString(indentLevel: 0)
}
public var rawValue: LCValueConvertible {
return value
}
var lconValue: Any? {
return jsonValue
}
static func instance() -> LCValue {
return LCNumber()
}
func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows {
/* Nothing to do. */
}
func add(_ other: LCValue) throws -> LCValue {
let result = LCNumber(value)
result.addInPlace((other as! LCNumber).value)
return result
}
func addInPlace(_ amount: Double) {
value += amount
}
func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be concatenated.")
}
func differ(_ other: LCValue) throws -> LCValue {
throw LCError(code: .invalidType, reason: "Object cannot be differed.")
}
}
| e99121ed4a6681909962fcdc39de1fee | 23.436893 | 122 | 0.62058 | false | false | false | false |
shahmishal/swift | refs/heads/master | test/Constraints/function_builder.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
enum Either<T,U> {
case first(T)
case second(U)
}
@_functionBuilder
struct TupleBuilder {
static func buildBlock<T1, T2>(_ t1: T1, _ t2: T2) -> (T1, T2) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: T1, _ t2: T2, _ t3: T3)
-> (T1, T2, T3) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4)
-> (T1, T2, T3, T4) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: T1, _ t2: T2, _ t3: T3, _ t4: T4, _ t5: T5
) -> (T1, T2, T3, T4, T5) {
return (t1, t2, t3, t4, t5)
}
static func buildDo<T>(_ value: T) -> T { return value }
static func buildIf<T>(_ value: T?) -> T? { return value }
static func buildEither<T,U>(first value: T) -> Either<T,U> {
return .first(value)
}
static func buildEither<T,U>(second value: U) -> Either<T,U> {
return .second(value)
}
}
func tuplify<T>(_ cond: Bool, @TupleBuilder body: (Bool) -> T) {
print(body(cond))
}
// CHECK: (17, 3.14159, "Hello, DSL", (["nested", "do"], 6), Optional((2.71828, ["if", "stmt"])))
let name = "dsl"
tuplify(true) {
17
3.14159
"Hello, \(name.map { $0.uppercased() }.joined())"
do {
["nested", "do"]
1 + 2 + 3
}
if $0 {
2.71828
["if", "stmt"]
}
}
// CHECK: ("Empty optional", nil)
tuplify(false) {
"Empty optional"
if $0 {
2.71828
["if", "stmt"]
}
}
// CHECK: ("chain0", main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.second(2.8, "capable"))
tuplify(false) {
"chain0"
if $0 {
"marginal"
2.9
} else {
2.8
"capable"
}
}
// CHECK: ("chain1", nil)
tuplify(false) {
"chain1"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain2", Optional(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain2"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
}
}
// CHECK: ("chain3", main.Either<main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>, main.Either<(Swift.Double, Swift.Double), (Swift.String, Swift.String)>>.first(main.Either<(Swift.String, Swift.Double), (Swift.Double, Swift.String)>.first("marginal", 2.9)))
tuplify(true) {
"chain3"
if $0 {
"marginal"
2.9
} else if $0 {
2.8
"capable"
} else if $0 {
2.8
1.0
} else {
"wild"
"broken"
}
}
// CHECK: ("chain4", main.Either<main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>>, main.Either<main.Either<(Swift.String, Swift.Int), (Swift.String, Swift.Int)>, (Swift.String, Swift.Int)>>.first
tuplify(true) {
"chain4"
if $0 {
"0"
0
} else if $0 {
"1"
1
} else if $0 {
"2"
2
} else if $0 {
"3"
3
} else if $0 {
"4"
4
} else if $0 {
"5"
5
} else {
"6"
6
}
}
// rdar://50710698
// CHECK: ("chain5", 8, 9)
tuplify(true) {
"chain5"
#if false
6
$0
#else
8
9
#endif
}
// CHECK: ("getterBuilder", 0, 4, 12)
@TupleBuilder
var globalBuilder: (String, Int, Int, Int) {
"getterBuilder"
0
4
12
}
print(globalBuilder)
// CHECK: ("funcBuilder", 13, 45.0)
@TupleBuilder
func funcBuilder(d: Double) -> (String, Int, Double) {
"funcBuilder"
13
d
}
print(funcBuilder(d: 45))
struct MemberBuilders {
@TupleBuilder
func methodBuilder(_ i: Int) -> (String, Int) {
"methodBuilder"
i
}
@TupleBuilder
static func staticMethodBuilder(_ i: Int) -> (String, Int) {
"staticMethodBuilder"
i + 14
}
@TupleBuilder
var propertyBuilder: (String, Int) {
"propertyBuilder"
12
}
}
// CHECK: ("staticMethodBuilder", 27)
print(MemberBuilders.staticMethodBuilder(13))
let mbuilders = MemberBuilders()
// CHECK: ("methodBuilder", 13)
print(mbuilders.methodBuilder(13))
// CHECK: ("propertyBuilder", 12)
print(mbuilders.propertyBuilder)
struct Tagged<Tag, Entity> {
let tag: Tag
let entity: Entity
}
protocol Taggable {
}
extension Taggable {
func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> {
return Tagged(tag: tag, entity: self)
}
}
extension Int: Taggable { }
extension String: Taggable { }
extension Double: Taggable { }
@_functionBuilder
struct TaggedBuilder<Tag> {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> {
return t1
}
static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) {
return (t1, t2, t3)
}
static func buildBlock<T1, T2, T3, T4>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>)
-> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>) {
return (t1, t2, t3, t4)
}
static func buildBlock<T1, T2, T3, T4, T5>(
_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t3: Tagged<Tag, T3>, _ t4: Tagged<Tag, T4>, _ t5: Tagged<Tag, T5>
) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>, Tagged<Tag, T4>, Tagged<Tag, T5>) {
return (t1, t2, t3, t4, t5)
}
static func buildIf<T>(_ value: Tagged<Tag, T>?) -> Tagged<Tag, T>? { return value }
}
enum Color {
case red, green, blue
}
func acceptColorTagged<Result>(@TaggedBuilder<Color> body: () -> Result) {
print(body())
}
struct TagAccepter<Tag> {
static func acceptTagged<Result>(@TaggedBuilder<Tag> body: () -> Result) {
print(body())
}
}
func testAcceptColorTagged(b: Bool, i: Int, s: String, d: Double) {
// CHECK: Tagged<
acceptColorTagged {
i.tag(.red)
s.tag(.green)
d.tag(.blue)
}
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged {
i.tag(.red)
s.tag(.green)
d.tag(.blue)
}
// CHECK: Tagged<
TagAccepter<Color>.acceptTagged { () -> Tagged<Color, Int> in
if b {
return i.tag(Color.green)
} else {
return i.tag(Color.blue)
}
}
}
testAcceptColorTagged(b: true, i: 17, s: "Hello", d: 3.14159)
// rdar://53325810
// Test that we don't have problems with expression pre-checking when
// type-checking an overloaded function-builder call. In particular,
// we need to make sure that expressions in the closure are pre-checked
// before we build constraints for them. Note that top-level expressions
// that need to be rewritten by expression prechecking (such as the operator
// sequences in the boolean conditions and statements below) won't be
// rewritten in the original closure body if we just precheck the
// expressions produced by the function-builder transformation.
struct ForEach1<Data : RandomAccessCollection, Content> {
var data: Data
var content: (Data.Element) -> Content
func show() {
print(content(data.first!))
print(content(data.last!))
}
}
extension ForEach1 where Data.Element: StringProtocol {
// Checking this overload shouldn't trigger inappropriate caching that
// affects checking the next overload.
init(_ data: Data,
@TupleBuilder content: @escaping (Data.Element) -> Content) {
self.init(data: data, content: content)
}
}
extension ForEach1 where Data == Range<Int> {
// This is the overload we actually want.
init(_ data: Data,
@TupleBuilder content: @escaping (Int) -> Content) {
self.init(data: data, content: content)
}
}
let testForEach1 = ForEach1(-10 ..< 10) { i in
"testForEach1"
if i < 0 {
"begin"
i < -5
} else {
i > 5
"end"
}
}
testForEach1.show()
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.first("begin", true))
// CHECK: ("testForEach1", main.Either<(Swift.String, Swift.Bool), (Swift.Bool, Swift.String)>.second(true, "end"))
| aedae8ea9a6bf005fbe181a7cf655a04 | 21.880682 | 292 | 0.606407 | false | false | false | false |
halo/LinkLiar | refs/heads/master | LinkLiar/Classes/MACPrefixQuestion.swift | mit | 1 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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 Cocoa
class MACPrefixQuestion {
let title: String
let description: String
let alert = NSAlert()
let textField: CopyPastableNSTextField = {
let field = CopyPastableNSTextField(frame: NSMakeRect(0, 0, 150, 24))
field.formatter = MACPrefixFormatter()
field.stringValue = "aa:bb:cc"
field.placeholderString = "aa:bb:cc"
return field
}()
init(title: String, description: String) {
self.title = title
self.description = description
alert.messageText = title
alert.informativeText = description
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.accessoryView = textField
}
func ask() -> String? {
let button = alert.runModal()
if (button == NSApplication.ModalResponse.alertFirstButtonReturn) {
textField.validateEditing()
return textField.stringValue
} else {
return nil
}
}
}
| 9e1c71542e1f04e3fc8a73d75042bea0 | 35.535714 | 133 | 0.73216 | false | false | false | false |
codepgq/WeiBoDemo | refs/heads/master | PQWeiboDemo/PQWeiboDemo/classes/Index 首页/model/PQUserInfoModel.swift | mit | 1 | //
// PQUserInfoModel.swift
// PQWeiboDemo
//
// Created by ios on 16/10/8.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class PQUserInfoModel: NSObject {
/// 用户ID
var id: Int = 0
/// 用户昵称
var name :String?
/// 用户头像地址
var profile_image_url : String?
{
didSet{
if let urlStr = profile_image_url
{
imageURL = NSURL(string: urlStr)
}
}
}
/// 用户头像地址
var imageURL : NSURL?
/// 用户是否认证
var verified :Bool = false
/// 用户认证类型, -1 没有认证 0,认证用户 2 3 5企业认证 220 达人
var verified_type : Int = -1{
didSet{
switch verified_type {
case 0:
verified_image = UIImage(named: "avatar_vip")
case 2,3,5:
verified_image = UIImage(named: "avatar_enterprise_vip")
case 220:
verified_image = UIImage(named: "avatar_grassroot")
default:
verified_image = nil
}
}
}
/// 认证头像
var verified_image : UIImage?
/// 有没有钻石💎
var followers_count : Int = 0{
didSet{
if followers_count >= 1000000{
isHiddenDiamond = false
}
}
}
var isHiddenDiamond :Bool = true
var mbrank : Int = 0{
didSet{
if mbrank > 0 && mbrank < 7 {
mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
}
}
var mbrankImage :UIImage?
init(dict : [String : AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| 33062cd39cf1d7c03fe924f89976244d | 20.876543 | 85 | 0.485892 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceKit/Sources/XCTAsyncAssertions/XCTAssertEventuallyThrowsSpecificError.swift | mit | 1 | import XCTest
public func XCTAssertThrowsSpecificError<E, T>(
_ expected: E,
_ block: @autoclosure () throws -> T,
file: StaticString = #file,
line: UInt = #line
) where E: Error & Equatable {
do {
_ = try block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch let error as E {
XCTAssertEqual(expected, error, file: file, line: line)
} catch {
XCTFail("Unexpected error thrown: \(error)", file: file, line: line)
}
}
public func XCTAssertEventuallyThrowsSpecificError<E>(
_ expected: E,
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async where E: Error & Equatable {
do {
try await block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch let error as E {
XCTAssertEqual(expected, error, file: file, line: line)
} catch {
XCTFail("Unexpected error thrown: \(error)", file: file, line: line)
}
}
public func XCTAssertEventuallyThrowsError(
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async {
do {
try await block()
XCTFail("Expected to throw an error.", file: file, line: line)
} catch {
// 👍
}
}
public func XCTAssertEventuallyNoThrows(
_ block: () async throws -> Void,
file: StaticString = #file,
line: UInt = #line
) async {
do {
try await block()
// 👍
} catch {
XCTFail("Unexpected error raised: \(error)", file: file, line: line)
}
}
| 4c02a8816021d18cd45936688b1e4218 | 25.949153 | 76 | 0.589308 | false | false | false | false |
chrislzm/TimeAnalytics | refs/heads/master | Time Analytics/TAActivityTableViewController.swift | mit | 1 | //
// TAActivityTableViewController.swift
// Time Analytics
//
// Displays all Time Analytics Activity data (TAActivitySegment managed objects) and allows user to tap into a detail view for each one.
//
// Created by Chris Leung on 5/23/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import CoreData
import UIKit
class TAActivityTableViewController: TATableViewController {
@IBOutlet weak var activityTableView: UITableView!
let viewTitle = "Activities"
// MARK: Lifecycle
override func viewDidLoad() {
// Set tableview for superclass before calling super method so that it can setup the table's properties (style, etc.)
super.tableView = activityTableView
super.viewDidLoad()
navigationItem.title = viewTitle
// Get the context
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.stack.context
// Create a fetchrequest
let fr = NSFetchRequest<NSFetchRequestResult>(entityName: "TAActivitySegment")
fr.sortDescriptors = [NSSortDescriptor(key: "startTime", ascending: false)]
// Create the FetchedResultsController
fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context, sectionNameKeyPath: "daySectionIdentifier", cacheName: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// If no data, let the user know
if fetchedResultsController?.sections?.count == 0 {
createTableEmptyMessageIn(tableView, "No activities recorded yet.\n\nPlease ensure that your sleep and\nworkout activities are being written\nto Apple Health data and that\nTime Analytics is authorized to\nread your Health data.")
} else {
removeTableEmptyMessageFrom(tableView)
// Deselect row if we selected one that caused a segue
if let selectedRowIndexPath = activityTableView.indexPathForSelectedRow {
activityTableView.deselectRow(at: selectedRowIndexPath, animated: true)
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment
let cell = tableView.dequeueReusableCell(withIdentifier: "TAActivityTableViewCell", for: indexPath) as! TAActivityTableViewCell
// Get label values
let start = activity.startTime! as Date
let end = activity.endTime! as Date
// Set label values
cell.timeLabel.text = generateTimeInOutStringWithDate(start, end)
cell.lengthLabel.text = generateLengthString(start, end)
cell.nameLabel.text = "\(activity.type!): \(activity.name!)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment
showActivityDetailViewController(activity)
}
}
| 126f4f9d2137176374fa707e02c64847 | 39.858974 | 242 | 0.68748 | false | false | false | false |
Pacific3/PFoundation | refs/heads/master | PFoundation/Operations/Conditions/ExclusivityController.swift | mit | 1 | //
// RBExclusivityController.swift
// reserbus-ios
//
// Created by Swanros on 8/14/15.
// Copyright © 2015 Reserbus S. de R.L. de C.V. All rights reserved.
//
private let ExclusivityControllerSerialQueueLabel = "Operations.ExclusivityController"
class RBExclusivityController {
static let sharedInstance = RBExclusivityController()
private let serialQueue = dispatch_queue_create(ExclusivityControllerSerialQueueLabel, DISPATCH_QUEUE_SERIAL)
private var operations: [String: [Operation]] = [:]
private init() {}
func addOperation(operation: Operation, categories: [String]) {
dispatch_sync(serialQueue) {
for category in categories {
self.noqueue_addOperation(operation, category: category)
}
}
}
func removeOperation(operation: Operation, categories: [String]) {
dispatch_async(serialQueue) {
for category in categories {
self.noqueue_removeOperation(operation, category: category)
}
}
}
private func noqueue_addOperation(operation: Operation, category: String) {
var operationsWithThisCategory = operations[category] ?? []
if let last = operationsWithThisCategory.last {
operation.addDependency(last)
}
operationsWithThisCategory.append(operation)
operations[category] = operationsWithThisCategory
}
private func noqueue_removeOperation(operation: Operation, category: String) {
let matchingOperations = operations[category]
if var operationsWithThisCategory = matchingOperations,
let index = operationsWithThisCategory.indexOf(operation) {
operationsWithThisCategory.removeAtIndex(index)
operations[category] = operationsWithThisCategory
}
}
}
| 4dd7d3e041225e1a31d07cefd6cb5b52 | 33.4 | 113 | 0.659619 | false | false | false | false |
yellowChao/beverly | refs/heads/master | DTMaster/Pods/Alamofire/Source/MultipartFormData.swift | mit | 1 | //
// MultipartFormData.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- https://www.ietf.org/rfc/rfc2388.txt
- https://www.ietf.org/rfc/rfc2045.txt
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: NSError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
- returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String) {
let headers = contentHeaders(name: name)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
let headers = contentHeaders(name: name, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
if let
fileName = fileURL.lastPathComponent,
pathExtension = fileURL.pathExtension {
let mimeType = mimeTypeForPathExtension(pathExtension)
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
}
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(OSX 10.10, *) {
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
}
guard isReachable else {
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
guard let
path = fileURL.path
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else {
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
var bodyContentLength: UInt64?
do {
if let
path = fileURL.path,
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber {
bodyContentLength = fileSize.unsignedLongLongValue
}
} catch {
// No-op
}
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
return
}
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(
stream stream: NSInputStream,
length: UInt64,
name: String,
fileName: String,
mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- HTTP headers
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter headers: The HTTP headers for the body part.
*/
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.
- returns: The encoded `NSData` if encoding is successful.
*/
public func encode() throws -> NSData {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
let encoded = NSMutableData()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encodeBodyPart(bodyPart)
encoded.appendData(encodedData)
}
return encoded
}
/**
Writes the appended body parts into the given file URL.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
- parameter fileURL: The file URL to write the multipart form data into.
- throws: An `NSError` if encoding encounters an error.
*/
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
}
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
try writeBodyPart(bodyPart, toOutputStream: outputStream)
}
outputStream.close()
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
encoded.appendData(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return encoded
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
if let error = error {
throw error
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
}
private func writeInitialBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws {
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return try writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw streamError
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
}
private func writeFinalBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws {
if bodyPart.hasFinalBoundary {
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return try writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let streamError = outputStream.streamError {
throw streamError
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if let streamError = outputStream.streamError {
throw streamError
}
}
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
if let
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(name name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"",
"Content-Type": "\(mimeType)"
]
}
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(code code: Int, failureReason: String) {
guard bodyPartError == nil else { return }
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
}
| 103b710f53d4b55bd7b4d56ce53f5aef | 39.302147 | 128 | 0.637858 | false | false | false | false |
RubyNative/RubyKit | refs/heads/master | String.swift | mit | 2 | //
// String.swift
// SwiftRuby
//
// Created by John Holdsworth on 26/09/2015.
// Copyright © 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/SwiftRuby/String.swift#13 $
//
// Repo: https://github.com/RubyNative/SwiftRuby
//
// See: http://ruby-doc.org/core-2.2.3/String.html
//
import Foundation
public var STRING_ENCODING = String.Encoding.utf8
public let FALLBACK_INPUT_ENCODING = String.Encoding.isoLatin1
public let FALLBACK_OUTPUT_ENCODING = String.Encoding.utf8
public enum StringIndexDisposition {
case warnAndFail, truncate
}
public var STRING_INDEX_DISPOSITION: StringIndexDisposition = .warnAndFail
public protocol string_like: array_like {
var to_s: String { get }
}
public protocol char_like {
var to_c: [CChar] { get }
}
extension String: string_like, array_like, data_like, char_like {
public subscript (i: Int) -> String {
return slice(i)
}
public subscript (start: Int, len: Int) -> String {
return slice(start, len: len)
}
public subscript (r: Range<Int>) -> String {
return String(self[index(startIndex, offsetBy: r.lowerBound) ..<
index(startIndex, offsetBy: r.upperBound)])
}
public var to_s: String {
return self
}
public var to_a: [String] {
// ??? self.characters.count
return [self]
}
public var to_c: [CChar] {
if let chars = cString(using: STRING_ENCODING) {
return chars
}
SRLog("String.to_c, unable to encode string for output")
return U(cString(using: FALLBACK_OUTPUT_ENCODING))
}
public var to_d: Data {
return Data(array: self.to_c)
}
public var to_i: Int {
if let val = Int(self) {
return val
}
let dummy = -99999999
SRLog("Unable to convert \(self) to Int. Returning \(dummy)")
return dummy
}
public var to_f: Double {
if let val = Double(self) {
return val
}
let dummy = -99999999.0
SRLog("Unable to convert \(self) to Doubleb. Returning \(dummy)")
return dummy
}
public func characterAtIndex(_ i: Int) -> Int {
if let char = self[i].unicodeScalars.first {
return Int(char.value)
}
SRLog("No character available in string '\(self)' returning nul char")
return 0
}
public var downcase: String {
return self.lowercased()
}
public func each_byte(_ block: (UInt8) -> ()) {
for char in utf8 {
block(char)
}
}
public func each_char(_ block: (UInt16) -> ()) {
for char in utf16 {
block(char)
}
}
public func each_codepoint(_ block: (String) -> ()) {
for char in self {
block(String(char ))
}
}
public func each_line(_ block: (String) -> ()) {
StringIO(self).each_line(LINE_SEPARATOR, nil, block)
}
public var length: Int {
return count
}
public var ord: Int {
return characterAtIndex(0)
}
public func slice(_ start: Int, len: Int = 1) -> String {
var vstart = start, vlen = len
let length = self.length
if start < 0 {
vstart = length + start
}
if vstart < 0 {
SRLog("String.str(\(start), \(len)) start before front of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vstart = 0
}
}
else if vstart > length {
SRLog("String.str(\(start), \(len)) start after end of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vstart = length
}
}
if len < 0 {
vlen = length + len - vstart
}
else if len == NSNotFound {
vlen = length - vstart
}
if vlen < 0 {
SRLog("String.str(\(start), \(len)) start + len before start of substring '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vlen = 0
}
}
else if vstart + vlen > length {
SRLog("String.str(\(start), \(len)) start + len after end of string '\(self)', length \(length)")
if STRING_INDEX_DISPOSITION == .truncate {
vlen = length - vstart
}
}
return self[vstart..<vstart+vlen]
}
public func split(_ delimiter: String) -> [String] {
return components(separatedBy: delimiter)
}
public var upcase: String {
return self.uppercased()
}
}
| 2cf435bdc725ffe007742df6d75e0eba | 24.192513 | 115 | 0.545532 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.