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
seanwoodward/IBAnimatable
refs/heads/master
IBAnimatable/ActivityIndicatorAnimationBallZigZag.swift
mit
1
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallZigZag: ActivityIndicatorAnimating { // MARK: Properties private let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = .infinity animation.removedOnCompletion = false circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(CATransform3D: CATransform3DMakeTranslation(0, 0, 0))] circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallZigZag { func circleAt(frame frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) { let circle = ActivityIndicatorShape.Circle.createLayerWith(size: size, color: color) circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } }
91c5f4b9181a4553d334f41e701cdbd8
42.928571
156
0.702033
false
false
false
false
HipHipArr/PocketCheck
refs/heads/master
Cheapify 2.0/CVCalendarMenuView.swift
mit
1
// // CVCalendarMenuView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarMenuView: UIView { var symbols = [String]() var symbolViews: [UILabel]? var firstWeekday: Weekday? = .Sunday var dayOfWeekTextColor: UIColor? = .darkGrayColor() //sets the day of the week labels to dark Gray color var dayOfWeekTextUppercase: Bool? = true //The day of week labels are all uppercase var dayOfWeekFont: UIFont? = UIFont(name: "Avenir", size: 10) //Font for the day of week labels ("Mon," "Tues," etc.) @IBOutlet weak var menuViewDelegate: AnyObject? { set { if let delegate = newValue as? MenuViewDelegate { self.delegate = delegate } } get { return delegate as? AnyObject } } var delegate: MenuViewDelegate? { didSet { setupAppearance() setupWeekdaySymbols() createDaySymbols() } } init() { super.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setupAppearance() { if let delegate = delegate { firstWeekday~>delegate.firstWeekday?() dayOfWeekTextColor~>delegate.dayOfWeekTextColor?() dayOfWeekTextUppercase~>delegate.dayOfWeekTextUppercase?() dayOfWeekFont~>delegate.dayOfWeekFont?() } } func setupWeekdaySymbols() { let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)! calendar.components(NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: NSDate()) calendar.firstWeekday = firstWeekday!.rawValue symbols = calendar.weekdaySymbols as! [String] } func createDaySymbols() { // Change symbols with their places if needed. let dateFormatter = NSDateFormatter() var weekdays = dateFormatter.shortWeekdaySymbols as NSArray let firstWeekdayIndex = firstWeekday!.rawValue - 1 if (firstWeekdayIndex > 0) { let copy = weekdays weekdays = (weekdays.subarrayWithRange(NSMakeRange(firstWeekdayIndex, 7 - firstWeekdayIndex))) weekdays = weekdays.arrayByAddingObjectsFromArray(copy.subarrayWithRange(NSMakeRange(0, firstWeekdayIndex))) } self.symbols = weekdays as! [String] // Add symbols. self.symbolViews = [UILabel]() let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 var y: CGFloat = 0 for i in 0..<7 { x = CGFloat(i) * width + space let symbol = UILabel(frame: CGRectMake(x, y, width, height)) symbol.textAlignment = .Center symbol.text = self.symbols[i] if (dayOfWeekTextUppercase!) { symbol.text = (self.symbols[i]).uppercaseString } symbol.font = dayOfWeekFont symbol.textColor = dayOfWeekTextColor self.symbolViews?.append(symbol) self.addSubview(symbol) } } func commitMenuViewUpdate() { if let delegate = delegate { let space = 0 as CGFloat let width = self.frame.width / 7 - space let height = self.frame.height var x: CGFloat = 0 var y: CGFloat = 0 for i in 0..<self.symbolViews!.count { x = CGFloat(i) * width + space let frame = CGRectMake(x, y, width, height) let symbol = self.symbolViews![i] symbol.frame = frame } } } }
ce727165edf6a7597dfc7aeceafc5f57
29.968992
123
0.576471
false
false
false
false
TEDxBerkeley/iOSapp
refs/heads/master
iOSApp/MainTabBarController.swift
apache-2.0
1
// // MainTabBarController.swift // TEDxBerkeley // // Created by alvinwan on 1/4/16. // Copyright (c) 2016 TExBerkeley. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { self.tabBar.tintColor = UIColor.whiteColor() // change default text color UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)], forState: .Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected) // change default image tint for item in self.tabBar.items! { if let image = item.image { item.image = image.imageWithColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)).imageWithRenderingMode(.AlwaysOriginal) } } } } extension UIImage { // written by "gotnull" on StackOverflow // http://stackoverflow.com/questions/19274789/how-can-i-change-image-tintcolor-in-ios-and-watchkit/24545102#24545102 func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, CGBlendMode.Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } }
c9a220e2ef784181aa496e1523eb5129
36
157
0.672853
false
false
false
false
jengelsma/cis657-summer2016-class-demos
refs/heads/master
Lecture08-PuppyFlixDemo/Lecture08-PuppyFlixDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // Lecture08-PuppyFlixDemo // // Created by Jonathan Engelsma on 5/31/16. // Copyright © 2016 Jonathan Engelsma. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? var count: Int? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self self.count = 0 return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } func incrementNetworkActivity() { self.count! += 1 UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func decrementNetworkActivity() { if self.count! > 0 { self.count! -= 1 } if self.count! == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } func resetNetworkActivity() { self.count! = 0 UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
9d4238691f8b113e5fb0ed6e0c8dcc9f
45.517647
285
0.739251
false
false
false
false
alessandroorru/SimpleSwiftLogger
refs/heads/master
Log.swift
mit
1
public enum Log : Int { case Trace, Debug, Info, Warning, Error, None public typealias PrintFunction = (items: Any..., separator: String, terminator: String) -> Void public typealias SimpleFormatter = (object: Any) -> String public typealias ExtendedFormatter = (object: Any, file: String, line: Int, function: String) -> String public typealias ColorForLevel = (level: Log) -> UIColor public static var Level : Log = Log.Error public static var printFunction : PrintFunction = Swift.print public static var simpleFormatter : SimpleFormatter = Log.format public static var extendedFormatter : ExtendedFormatter = Log.format public static var colorForLevel : ColorForLevel = Log.colorForLevel public static var dateFormatter : NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .NoStyle dateFormatter.timeStyle = .MediumStyle dateFormatter.locale = NSLocale.systemLocale() return dateFormatter }() public func print(object:Any, extended: Bool = true, file: String = __FILE__, line: Int = __LINE__, function: String = __FUNCTION__) { guard rawValue >= Log.Level.rawValue else { return } let color = colorString() var formattedString : String switch extended { case false: formattedString = Log.simpleFormatter(object: object) case true: formattedString = Log.extendedFormatter(object: object, file: file, line: line, function: function) } if Log.colorsEnabled { formattedString = "\(Log.ESCAPE)\(color)\(formattedString)\(Log.RESET)" } Log.printFunction(items: formattedString, separator: ",", terminator: "\n") } // MARK: - Private private func colorString() -> String { let color = Log.colorForLevel(self) var r : CGFloat = 0 var g : CGFloat = 0 var b : CGFloat = 0 var a : CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) return String(format: "fg%.0f,%.0f,%.0f;", arguments: [round(r*255), round(g*255), round(b*255)]) } private static func colorForLevel(level: Log) -> UIColor { switch level { case .Trace: return UIColor.whiteColor() case .Debug: return UIColor.darkGrayColor() case .Info: return UIColor.yellowColor() case .Warning: return UIColor.orangeColor() case .Error: return UIColor.redColor() default: return UIColor.whiteColor() } } private static func format(object: Any) -> String { return "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" } private static func format(object: Any, file: String, line: Int, function: String) -> String { let file = file.componentsSeparatedByString("/").last! var logString = "\n\n[\(file):\(line)] \(function) | \n" logString += "\(Log.dateFormatter.stringFromDate(NSDate())): \(object)" logString += "\n" return logString } private static var colorsEnabled: Bool = { let xcodeColors = NSProcessInfo().environment["XcodeColors"] let xcodeColorsAvailable = xcodeColors != nil && xcodeColors == "YES" return xcodeColorsAvailable }() private static let ESCAPE = "\u{001b}[" private static let RESET_FG = "\(ESCAPE) fg;" // Clear any foreground color private static let RESET_BG = "\(ESCAPE) bg;" // Clear any background color private static let RESET = "\(ESCAPE);" // Clear any foreground or background color } infix operator => {} public func =>(lhs: Any, rhs: Log) { rhs.print(lhs, extended: false) }
e147d44da64adabe5110c6d763fdb8e1
36.201923
138
0.609359
false
false
false
false
cikelengfeng/Jude
refs/heads/master
Jude/Antlr4/BufferedTokenStream.swift
mit
2
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// This implementation of {@link org.antlr.v4.runtime.TokenStream} loads tokens from a /// {@link org.antlr.v4.runtime.TokenSource} on-demand, and places the tokens in a buffer to provide /// access to any previous token by index. /// /// <p> /// This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your /// parser requires the token stream filter tokens to only those on a particular /// channel, such as {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL} or /// {@link org.antlr.v4.runtime.Token#HIDDEN_CHANNEL}, use a filtering token stream such a /// {@link org.antlr.v4.runtime.CommonTokenStream}.</p> public class BufferedTokenStream: TokenStream { /// The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched. internal var tokenSource: TokenSource /// A collection of all tokens fetched from the token source. The list is /// considered a complete view of the input once {@link #fetchedEOF} is set /// to {@code true}. internal var tokens: Array<Token> = Array<Token>() // Array<Token>(100 /// The index into {@link #tokens} of the current token (next token to /// {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be /// {@link #LT LT(1)}. /// /// <p>This field is set to -1 when the stream is first constructed or when /// {@link #setTokenSource} is called, indicating that the first token has /// not yet been fetched from the token source. For additional information, /// see the documentation of {@link org.antlr.v4.runtime.IntStream} for a description of /// Initializing Methods.</p> internal var p: Int = -1 /// Indicates whether the {@link org.antlr.v4.runtime.Token#EOF} token has been fetched from /// {@link #tokenSource} and added to {@link #tokens}. This field improves /// performance for the following cases: /// /// <ul> /// <li>{@link #consume}: The lookahead check in {@link #consume} to prevent /// consuming the EOF symbol is optimized by checking the values of /// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> /// <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into /// {@link #tokens} is trivial with this field.</li> /// <ul> internal var fetchedEOF: Bool = false public init(_ tokenSource: TokenSource) { self.tokenSource = tokenSource } public func getTokenSource() -> TokenSource { return tokenSource } public func index() -> Int { return p } public func mark() -> Int { return 0 } public func release(_ marker: Int) { // no resources to release } public func reset() throws { try seek(0) } public func seek(_ index: Int) throws { try lazyInit() p = try adjustSeekIndex(index) } public func size() -> Int { return tokens.count } public func consume() throws { var skipEofCheck: Bool if p >= 0 { if fetchedEOF { // the last token in tokens is EOF. skip check if p indexes any // fetched token except the last. skipEofCheck = p < tokens.count - 1 } else { // no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = p < tokens.count } } else { // not yet initialized skipEofCheck = false } if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF { throw ANTLRError.illegalState(msg: "cannot consume EOF") //RuntimeException("cannot consume EOF") //throw ANTLRError.IllegalState /* throw IllegalStateException("cannot consume EOF"); */ } if try sync(p + 1) { p = try adjustSeekIndex(p + 1) } } /// Make sure index {@code i} in tokens has a token. /// /// - returns: {@code true} if a token is located at index {@code i}, otherwise /// {@code false}. /// - seealso: #get(int i) @discardableResult internal func sync(_ i: Int) throws -> Bool { assert(i >= 0, "Expected: i>=0") let n: Int = i - tokens.count + 1 // how many more elements we need? //print("sync("+i+") needs "+n); if n > 0 { let fetched: Int = try fetch(n) return fetched >= n } return true } /// Add {@code n} elements to buffer. /// /// - returns: The actual number of elements added to the buffer. internal func fetch(_ n: Int) throws -> Int { if fetchedEOF { return 0 } for i in 0..<n { let t: Token = try tokenSource.nextToken() if t is WritableToken { (t as! WritableToken).setTokenIndex(tokens.count) } tokens.append(t) //add if t.getType() == BufferedTokenStream.EOF { fetchedEOF = true return i + 1 } } return n } public func get(_ i: Int) throws -> Token { if i < 0 || i >= tokens.count { let index = tokens.count - 1 throw ANTLRError.indexOutOfBounds(msg: "token index \(i) out of range 0..\(index)") } return tokens[i] //tokens[i] } /// Get all tokens from start..stop inclusively public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? { var stop = stop if start < 0 || stop < 0 { return nil } try lazyInit() var subset: Array<Token> = Array<Token>() if stop >= tokens.count { stop = tokens.count - 1 } for i in start...stop { let t: Token = tokens[i] if t.getType() == BufferedTokenStream.EOF { break } subset.append(t) } return subset } //TODO: LT(i)!.getType(); public func LA(_ i: Int) throws -> Int { return try LT(i)!.getType() } internal func LB(_ k: Int) throws -> Token? { if (p - k) < 0 { return nil } return tokens[p - k] } public func LT(_ k: Int) throws -> Token? { try lazyInit() if k == 0 { return nil } if k < 0 { return try LB(-k) } let i: Int = p + k - 1 try sync(i) if i >= tokens.count { // return EOF token // EOF must be last token return tokens[tokens.count - 1] } // if ( i>range ) range = i; return tokens[i] } /// Allowed derived classes to modify the behavior of operations which change /// the current stream position by adjusting the target token index of a seek /// operation. The default implementation simply returns {@code i}. If an /// exception is thrown in this method, the current stream index should not be /// changed. /// /// <p>For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that /// the seek target is always an on-channel token.</p> /// /// - parameter i: The target token index. /// - returns: The adjusted target token index. internal func adjustSeekIndex(_ i: Int) throws -> Int { return i } internal final func lazyInit() throws { if p == -1 { try setup() } } internal func setup() throws { try sync(0) p = try adjustSeekIndex(0) } /// Reset this token stream by setting its token source. public func setTokenSource(_ tokenSource: TokenSource) { self.tokenSource = tokenSource tokens.removeAll() p = -1 fetchedEOF = false } public func getTokens() -> Array<Token> { return tokens } public func getTokens(_ start: Int, _ stop: Int) throws -> Array<Token>? { return try getTokens(start, stop, nil) } /// Given a start and stop index, return a List of all tokens in /// the token type BitSet. Return null if no tokens were found. This /// method looks at both on and off channel tokens. public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> Array<Token>? { try lazyInit() if start < 0 || stop >= tokens.count || stop < 0 || start >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "start \(start) or stop \(stop) not in 0..\(tokens.count - 1)") } if start > stop { return nil } var filteredTokens: Array<Token> = Array<Token>() for i in start...stop { let t: Token = tokens[i] if let types = types , !types.contains(t.getType()) { }else { filteredTokens.append(t) } } if filteredTokens.isEmpty { return nil //filteredTokens = nil; } return filteredTokens } public func getTokens(_ start: Int, _ stop: Int, _ ttype: Int) throws -> Array<Token>? { //TODO Set<Int> initialCapacity var s: Set<Int> = Set<Int>() s.insert(ttype) //s.append(ttype); return try getTokens(start, stop, s) } /// Given a starting index, return the index of the next token on channel. /// Return {@code i} if {@code tokens[i]} is on channel. Return the index of /// the EOF token if there are no tokens on channel between {@code i} and /// EOF. internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) if i >= size() { return size() - 1 } var token: Token = tokens[i] while token.getChannel() != channel { if token.getType() == BufferedTokenStream.EOF { return i } i += 1 try sync(i) token = tokens[i] } return i } /// Given a starting index, return the index of the previous token on /// channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1 /// if there are no tokens on channel between {@code i} and 0. /// /// <p> /// If {@code i} specifies an index at or after the EOF token, the EOF token /// index is returned. This is due to the fact that the EOF token is treated /// as though it were on every channel.</p> internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) if i >= size() { // the EOF token is on every channel return size() - 1 } while i >= 0 { let token: Token = tokens[i] if token.getType() == BufferedTokenStream.EOF || token.getChannel() == channel { return i } i -= 1 } return i } /// Collect all tokens on specified channel to the right of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or /// EOF. If channel is -1, find any non default channel token. public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)") } let nextOnChannel: Int = try nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) var to: Int let from: Int = tokenIndex + 1 // if none onchannel to right, nextOnChannel=-1 so set to = last token if nextOnChannel == -1 { to = size() - 1 } else { to = nextOnChannel } return filterForChannel(from, to, channel) } /// Collect all hidden tokens (any off-default channel) to the right of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL /// or EOF. public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array<Token>? { return try getHiddenTokensToRight(tokenIndex, -1) } /// Collect all tokens on specified channel to the left of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. /// If channel is -1, find any non default channel token. public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)") //RuntimeException("\(tokenIndex) not in 0..\(tokens.count-1)") //throw ANTLRError.IndexOutOfBounds /* throw IndexOutOfBoundsException(tokenIndex+" not in 0.."+(tokens.count-1)); */ } if tokenIndex == 0 { // obviously no tokens can appear before the first token return nil } let prevOnChannel: Int = try previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1 { return nil } // if none onchannel to left, prevOnChannel=-1 then from=0 let from: Int = prevOnChannel + 1 let to: Int = tokenIndex - 1 return filterForChannel(from, to, channel) } /// Collect all hidden tokens (any off-default channel) to the left of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array<Token>? { return try getHiddenTokensToLeft(tokenIndex, -1) } internal func filterForChannel(_ from: Int, _ to: Int, _ channel: Int) -> Array<Token>? { var hidden: Array<Token> = Array<Token>() for i in from...to { let t: Token = tokens[i] if channel == -1 { if t.getChannel() != Lexer.DEFAULT_TOKEN_CHANNEL { hidden.append(t) } } else { if t.getChannel() == channel { hidden.append(t) } } } if hidden.count == 0 { return nil } return hidden } public func getSourceName() -> String { return tokenSource.getSourceName() } /// Get the text of all tokens in this buffer. public func getText() throws -> String { return try getText(Interval.of(0, size() - 1)) } public func getText(_ interval: Interval) throws -> String { let start: Int = interval.a var stop: Int = interval.b if start < 0 || stop < 0 { return "" } try fill() if stop >= tokens.count { stop = tokens.count - 1 } let buf: StringBuilder = StringBuilder() for i in start...stop { let t: Token = tokens[i] if t.getType() == BufferedTokenStream.EOF { break } buf.append(t.getText()!) } return buf.toString() } public func getText(_ ctx: RuleContext) throws -> String { return try getText(ctx.getSourceInterval()) } public func getText(_ start: Token?, _ stop: Token?) throws -> String { if let start = start, let stop = stop { return try getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex())) } return "" } /// Get all tokens from lexer until EOF public func fill() throws { try lazyInit() let blockSize: Int = 1000 while true { let fetched: Int = try fetch(blockSize) if fetched < blockSize { return } } } }
ea74c686432bc8dea9dc642b207eb7b5
31.021825
129
0.56032
false
false
false
false
satoshin21/Anima
refs/heads/master
Sources/Anima.swift
mit
1
// // Anima.swift // Pods // // Created by Satoshi Nagasaka on 2017/03/09. // // import UIKit public typealias AnimaCompletion = () -> Void public class Anima: NSObject { public enum Status: Equatable { case notFired case active case willPaused case paused(AnimaCompletion?) case completed public static func ==(left: Status, right: Status) -> Bool { switch (left, right) { case (.notFired, .notFired): fallthrough case (.active, .active): fallthrough case (.willPaused, .willPaused): fallthrough case (.paused, .paused): fallthrough case (.completed, .completed): return true default: return false } } } // MARK: - Properties public private(set) var status: Status = .notFired /** If you don't add any duration option 'AnimaOption.duration()', `defaultDuration` is applied. Default value is one. */ public static var defaultDuration: TimeInterval = 1 /** If you don't add any TimingFunction option 'AnimaOption.timingFunction()', `defaultTimingFunction` is applied. Default value is 'easeInCubic'. */ public static var defaultTimingFunction = TimingFunction.easeInCubic /// animation stack. internal var stack = [AnimaNode]() /// Animation target Layer. weak private var layer: CALayer? public var isActive: Bool { return status == .active } // MARK: - Initializer /// Anima needs target layer of animation in initializer. init(_ layer: CALayer) { self.layer = layer super.init() } // MARK: - Set Animations /// call this method to define next (or first) animation. /// /// - Parameters: /// - animationType: Animation that you want to perform (moveX, size, rotation, ... etc) /// - options: Animation option that you want to apply (duration, timingFunction, completion, ... etc) /// - Returns: itself (Anima object) public func then(_ animationType: AnimaType, options: [AnimaOption] = []) -> Self { return next(animaNode: AnimaNode(nodeType: .single(animationType), options: options)) } /// call this method to define next (or first) grouped animation. /// each animations will run concurrently in the same time. /// /// - Parameters: /// - animationType: Animation that you want to perform (moveX, size, rotation, ... etc) /// - options: Animation option that you want to apply (duration, timingFunction, completion, ... etc) /// - Returns: itself (Anima object) public func then(group animations: [AnimaType], options: [AnimaOption] = []) -> Self { return next(animaNode: AnimaNode(nodeType: .group(animations), options: options)) } /// call this method to delay next animation. /// /// - Parameter t: TimeInterval. time of waiting next action /// - Returns: itself public func then(waitFor t: TimeInterval) -> Self { return next(animaNode: AnimaNode(nodeType: .wait(t))) } /// Set the CALayer.anchorPoint value with enum of "AnchorPoint". /// Usualy, updating CALayer.anchorPoint directly, it will change layer's frame. /// but this method do not affect layer's frame, it update layer's anchorPoint only. /// - Parameter anchorPoint: AnchorPoint /// - Returns: itself public func then(setAnchor anchorPoint: AnimaAnchorPoint) -> Self { return next(animaNode: AnimaNode(nodeType: .anchor(anchorPoint))) } /// perform series of animation you defined. /// /// - Parameter completion: all of animation is finished, it will be called. public func fire(completion: AnimaCompletion? = nil) { status = .active guard stack.count > 0 else { onCompletion(completion) return } fireNext(completion) } public func pause() { switch status { case .willPaused, .active: status = .willPaused default: break; } } public func resume() { switch status { case .willPaused: status = .active case .paused(let completion): status = .active fireNext(completion) default: break; } } /// perform animation at top of stack. private func fireNext(_ completion: AnimaCompletion?) { guard case .active = status else { status = .paused(completion) return } guard let layer = layer, !stack.isEmpty else { onCompletion(completion) return } stack.removeFirst().addAnimation(to: layer) {[weak self] (finished) in self?.fireNext(completion) } } private func next(animaNode: AnimaNode) -> Self { stack.append(animaNode) return self } private func onCompletion(_ completion: AnimaCompletion?) { status = .completed completion?() } }
5e4df121d2fe5647d058ca71bf16a82d
27.818182
108
0.571535
false
false
false
false
WaterReporter/WaterReporter-iOS
refs/heads/master
WaterReporter/WaterReporter/GroupsTableView.swift
agpl-3.0
1
// // GroupsTableView.swift // Water-Reporter // // Created by Joshua Powell on 9/13/17. // Copyright © 2017 Viable Industries, L.L.C. All rights reserved. // import Foundation import SwiftyJSON import UIKit class GroupsTableView: UITableView, UITableViewDelegate, UITableViewDataSource { var groups: JSON? func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { print("GroupsTableView::tableView::cellForRowAtIndexPath \(groups!)"); let cell = tableView.dequeueReusableCellWithIdentifier("reportGroupTableViewCell", forIndexPath: indexPath) as! ReportGroupTableViewCell // // Assign the organization logo to the UIImageView // cell.imageViewGroupLogo.tag = indexPath.row var organizationImageUrl:NSURL! if let thisOrganizationImageUrl: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["picture"].string { organizationImageUrl = NSURL(string: thisOrganizationImageUrl) } cell.imageViewGroupLogo.kf_indicatorType = .Activity cell.imageViewGroupLogo.kf_showIndicatorWhenLoading = true cell.imageViewGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in cell.imageViewGroupLogo.image = image cell.imageViewGroupLogo.layer.cornerRadius = cell.imageViewGroupLogo.frame.size.width / 2 cell.imageViewGroupLogo.clipsToBounds = true }) // // Assign the organization name to the UILabel // if let thisOrganizationName: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["name"].string { cell.labelGroupName.text = thisOrganizationName } // Assign existing groups to the group field cell.switchSelectGroup.tag = indexPath.row // if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] { // //// if self.tempGroups.contains("\(_organization_id_number)") { //// cell.switchSelectGroup.on = true //// } //// else { //// cell.switchSelectGroup.on = false //// } // // } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 72.0 } // func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // print("GroupsTableView::tableView::numberOfSectionsInTableView") // // return 1 // } func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int { if self.groups == nil { print("Showing 0 group cells") return 0 } print("Showing \((self.groups?.count)!) group cells") return (self.groups?.count)! } }
68cf2996cac1b83ede2bd5ec509064f2
33.472527
154
0.635958
false
false
false
false
sjtu-meow/iOS
refs/heads/master
Meow/RichTextEditor.swift
apache-2.0
1
// // RichTextEditor.swift // Meow // // Created by 林武威 on 2017/7/6. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit import RxSwift protocol RichTextEditorDelegate { func didTapAddImage() } class RichTextEditor: UIView { @IBOutlet weak var webview: UIWebView! var delegate: RichTextEditorDelegate? override func awakeFromNib() { loadEditor() } @IBAction func addImage(_ sender: Any) { delegate?.didTapAddImage() } var htmlString: String { get { return webview.stringByEvaluatingJavaScript(from: "document.getElementById('content').innerHTML")! } } func insertImage(id: String, url: String) { let script = "window.insertImage('\(id)', '\(url)')" let _ = webview.stringByEvaluatingJavaScript(from: script) } func loadEditor() { let editorURL = Bundle.main.url(forResource: "editor", withExtension: "html")! webview.loadRequest(URLRequest(url: editorURL)) } func updateImagePath(id: String, url: String ) { let scripts = "window.setImagePath('\(id )', '\(url)')" let _ = webview.stringByEvaluatingJavaScript(from: scripts) } }
7f06c32b435adee366eca0c0540e05a0
23.352941
110
0.622383
false
false
false
false
IntrepidPursuits/swift-wisdom
refs/heads/master
SwiftWisdomTests/StandardLibrary/Date/TimeOfDayTests.swift
mit
1
// // TimeOfDayTests.swift // SwiftWisdom // // Created by Patrick Butkiewicz on 3/1/17. // Copyright © 2017 Intrepid. All rights reserved. // import Foundation import XCTest import SwiftWisdom final class TimeOfDayTests: XCTestCase { // Corresponds to Jan 1st, 2017, 3:16 AM GMT private var testSingleHourDigitEpochTime: TimeInterval = 1483240560 // Corresponds to Jan 1st, 2017, 11:00 AM GMT private var testDoubleHourDigitEpochTime: TimeInterval = 1483268400 override func setUp() { let offset = TimeZone.autoupdatingCurrent.secondsFromGMT(for: Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) // Was breaking on Daylight savings time. testSingleHourDigitEpochTime -= TimeInterval(offset) testDoubleHourDigitEpochTime -= TimeInterval(offset) } func testTimeFromDate() { let td1 = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) XCTAssert(td1?.displayString.compare("3:16 AM") == .orderedSame) XCTAssert(td1?.stringRepresentation.compare("03:16") == .orderedSame) let td2 = TimeOfDay(Date(timeIntervalSince1970: testDoubleHourDigitEpochTime)) XCTAssert(td2?.displayString.compare("11:00 AM") == .orderedSame) XCTAssert(td2?.stringRepresentation.compare("11:00") == .orderedSame) } func testTimeFromString() { let td = TimeOfDay("3:16") XCTAssert(td?.displayString.compare("3:16 AM") == .orderedSame) XCTAssert(td?.stringRepresentation.compare("03:16") == .orderedSame) let td2 = TimeOfDay("11:00") XCTAssert(td2?.displayString.compare("11:00 AM") == .orderedSame) XCTAssert(td2?.stringRepresentation.compare("11:00") == .orderedSame) let td3 = TimeOfDay("16:21") XCTAssert(td3?.displayString.compare("4:21 PM") == .orderedSame) XCTAssert(td3?.stringRepresentation.compare("16:21") == .orderedSame) } func testNilTimeFromInvalidString() { XCTAssertNil(TimeOfDay("")) } func testApplyingTimeToDate() { let timeToApply = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) let receivingDate = Date(timeIntervalSince1970: testDoubleHourDigitEpochTime) let newDate = timeToApply?.timeOnDate(receivingDate) let newTime = TimeOfDay(newDate!) XCTAssert(timeToApply?.minutes == newTime?.minutes) XCTAssert(timeToApply?.hours == newTime?.hours) } func testApplyingTimeToToday() { let timeToApply = TimeOfDay(Date(timeIntervalSince1970: testSingleHourDigitEpochTime)) let newDate = timeToApply?.timeToday() let newTime = TimeOfDay(newDate!) XCTAssert(timeToApply?.minutes == newTime?.minutes) XCTAssert(timeToApply?.hours == newTime?.hours) } }
71ee0d6fc9377ecb7f9299ef0f631d36
39.8
170
0.686625
false
true
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKitDemo/SwiftMKitDemo/UI/Data/Audio/AudioViewController.swift
mit
1
// // AudioViewController.swift // SwiftMKitDemo // // Created by wei.mao on 2018/7/13. // Copyright © 2018年 cdts. All rights reserved. // import UIKit import AudioKit import AudioKitUI import SwiftMKit class AudioViewController: UIViewController, AKKeyboardDelegate { let bank = AKOscillatorBank() var keyboardView: AKKeyboardView? override func viewDidLoad() { super.viewDidLoad() AudioKit.output = bank try? AudioKit.start() keyboardView = AKKeyboardView(width: 440, height: 100) keyboardView?.delegate = self // keyboard.polyphonicMode = true self.view.addSubview(keyboardView!) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { keyboardView?.frame = CGRect(x: 0, y: 100, w: 440, h: 100) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func noteOn(note: MIDINoteNumber) { bank.play(noteNumber: note, velocity: 80) } func noteOff(note: MIDINoteNumber) { bank.stop(noteNumber: note) } }
19369d1ebd8c96fbd47605660943b476
24.125
66
0.646766
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/Solutions/Easy/Easy_019_Remove_Nth_Node_From_End_Of_List.swift
mit
1
/* https://github.com/diwu/LeetCode-Solutions-in-Swift #19 Remove Nth Node From End of List Level: easy Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. Inspired by @i at https://leetcode.com/discuss/1656/is-there-a-solution-with-one-pass-and-o-1-space */ class Easy_019_Remove_Nth_Node_From_End_Of_List { class Node { var value: Int var next: Node? init(value: Int, next: Node?) { self.value = value self.next = next } } class func removeNthFromEnd(_ head: Node?, n: Int) -> Node? { let dummyHead: Node = Node(value: 0, next: head) var fast: Node? = dummyHead, slow: Node? = dummyHead var localN = n while localN > 0 { fast = fast?.next localN -= 1 } while fast?.next != nil { fast = fast?.next slow = slow?.next } slow?.next = slow?.next?.next return dummyHead.next } }
69db4675a360c77abef7d930f97484b1
22.384615
99
0.583059
false
false
false
false
arsonik/AKTrakt
refs/heads/master
Source/shared/Requests/Search.swift
mit
1
// // Search.swift // Pods // // Created by Florian Morello on 27/05/16. // // import Foundation import Alamofire /// Represents trakt search object type private enum TraktSearchType: String { /// Movie case Movie = "movie" /// Show case Show = "show" /// Season case Season = "season" /// Episode case Episode = "episode" /// Person case Person = "person" /// Associated TraktObject type public var classType: TraktObject.Type? { switch self { case .Movie: return TraktMovie.self case .Show: return TraktShow.self case .Season: return TraktSeason.self case .Person: return TraktPerson.self case .Episode: return TraktEpisode.self } } } /// Serarch request public class TraktRequestSearch<T: TraktObject where T: protocol<Searchable>>: TraktRequest { /** Init - parameter query: search query string - parameter type: optional trakt type - parameter year: optional year - parameter pagination: optional pagination */ public init(query: String, type: T.Type? = nil, year: UInt? = nil, pagination: TraktPagination? = nil) { var params: JSONHash = [ "query": query ] if year != nil { params["year"] = year! } if type != nil { params["type"] = type!.objectName } if pagination != nil { params += pagination!.value() } super.init(path: "/search", params: params) } /** Execute request - parameter trakt: trakt client - parameter completion: closure [TraktObject]?, NSError? - returns: Alamofire.Request */ public func request(trakt: Trakt, completion: ([TraktObject]?, NSError?) -> Void) -> Request? { return trakt.request(self) { response in guard let entries = response.result.value as? [JSONHash] else { return completion(nil, response.result.error) } completion(entries.flatMap { guard let type = TraktSearchType(rawValue: $0["type"] as? String ?? "") else { return nil } return type.classType?.init(data: $0[type.rawValue] as? JSONHash) }, nil) } } }
5800956822e394689bbd5608335b30f1
25.655556
108
0.554815
false
false
false
false
mikelikespie/swiftled
refs/heads/master
src/main/swift/SwiftledMobile/RootSplitViewController.swift
mit
1
// // ViewController.swift // SwiftledMobile // // Created by Michael Lewis on 12/29/15. // Copyright © 2015 Lolrus Industries. All rights reserved. // import UIKit import RxSwift import OPC //import RxCocoa import Foundation import Visualizations import Cleanse import yoga_YogaKit import Views private let segmentLength = 18 private let segmentCount = 30 private let ledCount = segmentLength * segmentCount class ViewController: UIViewController, UISplitViewControllerDelegate { let disposeBag = DisposeBag() private var typedView: ContentView { return scrollView.container } private lazy var scrollView: YogaScrollView = YogaScrollView() override func loadView() { self.view = scrollView } override func viewDidLoad() { super.viewDidLoad() typedView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) scrollView.addSubview(typedView) self.splitViewController?.delegate = self let root = try! ComponentFactory .of(SwiftLedComponent.self) .build(LedConfiguration( segmentLength: segmentLength, segmentCount: segmentCount )) root .entryPoint .start() .addDisposableTo(disposeBag) root.rootVisualization .controls .map { Array($0.map { $0.cells }.joined()) } .subscribe(onNext: { [unowned self] cells in self.scrollView.cells = cells }) .addDisposableTo(disposeBag) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } }
786015823d0b4c56365b1c62a7ddbef0
23.757143
71
0.613387
false
false
false
false
carabina/DDMathParser
refs/heads/master
MathParser/RewriteRule.swift
mit
2
// // RewriteRule.swift // DDMathParser // // Created by Dave DeLong on 8/25/15. // // import Foundation public struct RuleTemplate { public static let AnyExpression = "__exp" public static let AnyNumber = "__num" public static let AnyVariable = "__var" public static let AnyFunction = "__func" private init() { } } public struct RewriteRule { public let predicate: Expression public let condition: Expression? public let template: Expression public init(predicate: Expression, condition: Expression? = nil, template: Expression) { self.predicate = predicate self.condition = condition self.template = template } public init(predicate: String, condition: String? = nil, template: String) throws { self.predicate = try Expression(string: predicate) self.template = try Expression(string: template) if let condition = condition { self.condition = try Expression(string: condition) } else { self.condition = nil } } public func rewrite(expression: Expression, substitutions: Substitutions, evaluator: Evaluator) -> Expression { guard let replacements = matchWithCondition(expression, substitutions: substitutions, evaluator: evaluator) else { return expression } return applyReplacements(replacements, toExpression: template) } private func matchWithCondition(expression: Expression, substitutions: Substitutions = [:], evaluator: Evaluator, replacementsSoFar: Dictionary<String, Expression> = [:]) -> Dictionary<String, Expression>? { guard let replacements = match(expression, toExpression: predicate, replacementsSoFar: replacementsSoFar) else { return nil } // we replaced, and we don't have a condition => we match guard let condition = condition else { return replacements } // see if the expression matches the condition let matchingCondition = applyReplacements(replacements, toExpression: condition) // if there's an error evaluating the condition, then we don't match guard let result = try? evaluator.evaluate(matchingCondition, substitutions: substitutions) else { return nil } // non-zero => we match return (result != 0) ? replacements : nil } private func match(expression: Expression, toExpression target: Expression, replacementsSoFar: Dictionary<String, Expression>) -> Dictionary<String, Expression>? { var replacements = replacementsSoFar switch target.kind { // we're looking for a specific number; return the replacements if we match that number case .Number(_): return expression == target ? replacements : nil // we're looking for a specific variable; return the replacements if we match case .Variable(_): return expression == target ? replacements : nil // we're looking for something else case .Function(let f, let args): // we're looking for anything if f.hasPrefix(RuleTemplate.AnyExpression) { // is this a matcher ("__exp42") we've seen before? // if it is, only return replacements if it's the same expression // as what has already been matched if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } // otherwise remember this one and return the new replacements replacements[f] = expression return replacements } // we're looking for any number if f.hasPrefix(RuleTemplate.AnyNumber) && expression.kind.isNumber { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // we're looking for any variable if f.hasPrefix(RuleTemplate.AnyVariable) && expression.kind.isVariable { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // we're looking for any function if f.hasPrefix(RuleTemplate.AnyFunction) && expression.kind.isFunction { if let seenBefore = replacements[f] { return seenBefore == expression ? replacements : nil } replacements[f] = expression return replacements } // if we make it this far, we're looking for a specific function // make sure the expression we're matching against is also a function guard case let .Function(expressionF, expressionArgs) = expression.kind else { return nil } // make sure the functions have the same name guard expressionF == f else { return nil } // make sure the functions have the same number of arguments guard expressionArgs.count == args.count else { return nil } // make sure each argument matches for (expressionArg, targetArg) in zip(expressionArgs, args) { // if this argument doesn't match, return nil guard let argReplacements = match(expressionArg, toExpression: targetArg, replacementsSoFar: replacements) else { return nil } replacements = argReplacements } return replacements } } private func applyReplacements(replacements: Dictionary<String, Expression>, toExpression expression: Expression) -> Expression { switch expression.kind { case .Function(let f, let args): if let replacement = replacements[f] { return Expression(kind: replacement.kind, range: replacement.range) } let newArgs = args.map { applyReplacements(replacements, toExpression: $0) } return Expression(kind: .Function(f, newArgs), range: expression.range) default: return Expression(kind: expression.kind, range: expression.range) } } }
48271ebb175238357144a1ac21a3e6ec
43.135484
211
0.578424
false
false
false
false
pirishd/InstantMock
refs/heads/dev
Sources/InstantMock/Verifications/Verifier.swift
mit
1
// // Verifier.swift // InstantMock // // Created by Patrick on 08/05/2017. // Copyright © 2017 pirishd. All rights reserved. // /** Protoocl dedicated to verify equality between values */ public protocol Verifier { func equal(_ arg: Any?, to value: Any?) -> Bool } /** Main verifier implementation */ final class VerifierImpl: Verifier { /// Singleton static let instance = VerifierImpl() /** Make sure two optional values are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equal(_ arg: Any?, to value: Any?) -> Bool { // compare nil values if arg == nil && value == nil { return true } if arg != nil && value == nil { return false } if arg == nil && value != nil { return false } // otherwise, perform advanced verifications return self.equal(arg!, to: value!) } /** Make sure two non-nil values are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equal(_ arg: Any, to value: Any) -> Bool { // MockUsable values if let mockArg = arg as? MockUsable, let mockValue = value as? MockUsable { return mockArg.equal(to: mockValue) } // try to compare by reference if (arg as AnyObject) === (value as AnyObject) { return true } // compare Void types if arg is Void && value is Void { return true } // arguments can be types if let argType = arg as? Any.Type, let valueType = value as? Any.Type { return argType == valueType } // arguments can be tuples if self.equalTuples(arg, to: value) { return true } // default case return false } /** Make sure two values that are tuples are equal (up to five arguments in the tuple) - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ private func equalTuples(_ arg: Any?, to value: Any?) -> Bool { return self.equalTuple2(arg, to: value) || self.equalTuple3(arg, to: value) || self.equalTuple4(arg, to: value) || self.equalTuple5(arg, to: value) } private func equalTuple2(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2) = arg as? (Any?, Any?), let (val1, val2) = value as? (Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) } return false } private func equalTuple3(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3) = arg as? (Any?, Any?, Any?), let (val1, val2, val3) = value as? (Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) } return false } private func equalTuple4(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3, arg4) = arg as? (Any?, Any?, Any?, Any?), let (val1, val2, val3, val4) = value as? (Any?, Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) && self.equal(arg4, to: val4) } return false } private func equalTuple5(_ arg: Any?, to value: Any?) -> Bool { if let (arg1, arg2, arg3, arg4, arg5) = arg as? (Any?, Any?, Any?, Any?, Any?), let (val1, val2, val3, val4, val5) = value as? (Any?, Any?, Any?, Any?, Any?) { return self.equal(arg1, to: val1) && self.equal(arg2, to: val2) && self.equal(arg3, to: val3) && self.equal(arg4, to: val4) && self.equal(arg5, to: val5) } return false } /** Make sure two arrays are equal - parameter arg: first argument - paramater value: second argument - returs: true if two values are equal */ func equalArray(_ arg: [Any?], to value: [Any?]) -> Bool { // make sure the two arrays have the same number of elements if arg.count != value.count { return false } // verify equality between array elements if arg.count > 0 { for i in 0...arg.count-1 { if !self.equal(arg[i], to: value[i]) { return false } } } return true } }
415c07433c475349c0e060999988438d
28.738562
119
0.55011
false
false
false
false
danielgindi/Charts
refs/heads/master
Source/Charts/Components/Legend.swift
apache-2.0
2
// // Legend.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartLegend) open class Legend: ComponentBase { @objc(ChartLegendForm) public enum Form: Int { /// Avoid drawing a form case none /// Do not draw the a form, but leave space for it case empty /// Use default (default dataset's form to the legend's form) case `default` /// Draw a square case square /// Draw a circle case circle /// Draw a horizontal line case line } @objc(ChartLegendHorizontalAlignment) public enum HorizontalAlignment: Int { case left case center case right } @objc(ChartLegendVerticalAlignment) public enum VerticalAlignment: Int { case top case center case bottom } @objc(ChartLegendOrientation) public enum Orientation: Int { case horizontal case vertical } @objc(ChartLegendDirection) public enum Direction: Int { case leftToRight case rightToLeft } /// The legend entries array @objc open var entries = [LegendEntry]() /// Entries that will be appended to the end of the auto calculated entries after calculating the legend. /// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect) @objc open var extraEntries = [LegendEntry]() /// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic legend) private var _isLegendCustom = false /// The horizontal alignment of the legend @objc open var horizontalAlignment: HorizontalAlignment = HorizontalAlignment.left /// The vertical alignment of the legend @objc open var verticalAlignment: VerticalAlignment = VerticalAlignment.bottom /// The orientation of the legend @objc open var orientation: Orientation = Orientation.horizontal /// Flag indicating whether the legend will draw inside the chart or outside @objc open var drawInside: Bool = false /// Flag indicating whether the legend will draw inside the chart or outside @objc open var isDrawInsideEnabled: Bool { return drawInside } /// The text direction of the legend @objc open var direction: Direction = Direction.leftToRight @objc open var font: NSUIFont = NSUIFont.systemFont(ofSize: 10.0) @objc open var textColor = NSUIColor.labelOrBlack /// The form/shape of the legend forms @objc open var form = Form.square /// The size of the legend forms @objc open var formSize = CGFloat(8.0) /// The line width for forms that consist of lines @objc open var formLineWidth = CGFloat(3.0) /// Line dash configuration for shapes that consist of lines. /// /// This is how much (in pixels) into the dash pattern are we starting from. @objc open var formLineDashPhase: CGFloat = 0.0 /// Line dash configuration for shapes that consist of lines. /// /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] @objc open var formLineDashLengths: [CGFloat]? @objc open var xEntrySpace = CGFloat(6.0) @objc open var yEntrySpace = CGFloat(0.0) @objc open var formToTextSpace = CGFloat(5.0) @objc open var stackSpace = CGFloat(3.0) @objc open var calculatedLabelSizes = [CGSize]() @objc open var calculatedLabelBreakPoints = [Bool]() @objc open var calculatedLineSizes = [CGSize]() public override init() { super.init() self.xOffset = 5.0 self.yOffset = 3.0 } @objc public init(entries: [LegendEntry]) { super.init() self.entries = entries } @objc open func getMaximumEntrySize(withFont font: NSUIFont) -> CGSize { var maxW = CGFloat(0.0) var maxH = CGFloat(0.0) var maxFormSize: CGFloat = 0.0 for entry in entries { let formSize = entry.formSize.isNaN ? self.formSize : entry.formSize if formSize > maxFormSize { maxFormSize = formSize } guard let label = entry.label else { continue } let size = (label as NSString).size(withAttributes: [.font: font]) if size.width > maxW { maxW = size.width } if size.height > maxH { maxH = size.height } } return CGSize( width: maxW + maxFormSize + formToTextSpace, height: maxH ) } @objc open var neededWidth = CGFloat(0.0) @objc open var neededHeight = CGFloat(0.0) @objc open var textWidthMax = CGFloat(0.0) @objc open var textHeightMax = CGFloat(0.0) /// flag that indicates if word wrapping is enabled /// this is currently supported only for `orientation == Horizontal`. /// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps. /// /// **default**: true @objc open var wordWrapEnabled = true /// if this is set, then word wrapping the legend is enabled. @objc open var isWordWrapEnabled: Bool { return wordWrapEnabled } /// The maximum relative size out of the whole chart view in percent. /// If the legend is to the right/left of the chart, then this affects the width of the legend. /// If the legend is to the top/bottom of the chart, then this affects the height of the legend. /// /// **default**: 0.95 (95%) @objc open var maxSizePercent: CGFloat = 0.95 @objc open func calculateDimensions(labelFont: NSUIFont, viewPortHandler: ViewPortHandler) { let maxEntrySize = getMaximumEntrySize(withFont: labelFont) let defaultFormSize = self.formSize let stackSpace = self.stackSpace let formToTextSpace = self.formToTextSpace let xEntrySpace = self.xEntrySpace let yEntrySpace = self.yEntrySpace let wordWrapEnabled = self.wordWrapEnabled let entries = self.entries let entryCount = entries.count textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height switch orientation { case .vertical: var maxWidth = CGFloat(0.0) var width = CGFloat(0.0) var maxHeight = CGFloat(0.0) let labelLineHeight = labelFont.lineHeight var wasStacked = false for i in entries.indices { let e = entries[i] let drawingForm = e.form != .none let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize if !wasStacked { width = 0.0 } if drawingForm { if wasStacked { width += stackSpace } width += formSize } if let label = e.label { let size = (label as NSString).size(withAttributes: [.font: labelFont]) if drawingForm && !wasStacked { width += formToTextSpace } else if wasStacked { maxWidth = max(maxWidth, width) maxHeight += labelLineHeight + yEntrySpace width = 0.0 wasStacked = false } width += size.width maxHeight += labelLineHeight + yEntrySpace } else { wasStacked = true width += formSize if i < entryCount - 1 { width += stackSpace } } maxWidth = max(maxWidth, width) } neededWidth = maxWidth neededHeight = maxHeight case .horizontal: let labelLineHeight = labelFont.lineHeight let contentWidth: CGFloat = viewPortHandler.contentWidth * maxSizePercent // Prepare arrays for calculated layout if calculatedLabelSizes.count != entryCount { calculatedLabelSizes = [CGSize](repeating: CGSize(), count: entryCount) } if calculatedLabelBreakPoints.count != entryCount { calculatedLabelBreakPoints = [Bool](repeating: false, count: entryCount) } calculatedLineSizes.removeAll(keepingCapacity: true) // Start calculating layout var maxLineWidth: CGFloat = 0.0 var currentLineWidth: CGFloat = 0.0 var requiredWidth: CGFloat = 0.0 var stackedStartIndex: Int = -1 for i in entries.indices { let e = entries[i] let drawingForm = e.form != .none let label = e.label calculatedLabelBreakPoints[i] = false if stackedStartIndex == -1 { // we are not stacking, so required width is for this label only requiredWidth = 0.0 } else { // add the spacing appropriate for stacked labels/forms requiredWidth += stackSpace } // grouped forms have null labels if let label = label { calculatedLabelSizes[i] = (label as NSString).size(withAttributes: [.font: labelFont]) requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0 requiredWidth += calculatedLabelSizes[i].width } else { calculatedLabelSizes[i] = CGSize() requiredWidth += drawingForm ? formSize : 0.0 if stackedStartIndex == -1 { // mark this index as we might want to break here later stackedStartIndex = i } } if label != nil || i == entryCount - 1 { let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace if (!wordWrapEnabled || // No word wrapping, it must fit. currentLineWidth == 0.0 || // The line is empty, it must fit. (contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits { // Expand current line currentLineWidth += requiredSpacing + requiredWidth } else { // It doesn't fit, we need to wrap a line // Add current line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) // Start a new line calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true currentLineWidth = requiredWidth } if i == entryCount - 1 { // Add last line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) } } stackedStartIndex = label != nil ? -1 : stackedStartIndex } neededWidth = maxLineWidth neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) + yEntrySpace * CGFloat(calculatedLineSizes.isEmpty ? 0 : (calculatedLineSizes.count - 1)) } neededWidth += xOffset neededHeight += yOffset } /// MARK: - Custom legend /// Sets a custom legend's entries array. /// * A nil label will start a group. /// This will disable the feature that automatically calculates the legend entries from the datasets. /// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed). @objc open func setCustom(entries: [LegendEntry]) { self.entries = entries _isLegendCustom = true } /// Calling this will disable the custom legend entries (set by `setLegend(...)`). Instead, the entries will again be calculated automatically (after `notifyDataSetChanged()` is called). @objc open func resetCustom() { _isLegendCustom = false } /// **default**: false (automatic legend) /// `true` if a custom legend entries has been set @objc open var isLegendCustom: Bool { return _isLegendCustom } }
d4c43f73782313c391ed044c106dd5e1
33.090909
190
0.528491
false
false
false
false
ppraveentr/MobileCore
refs/heads/master
Sources/CoreComponents/Contollers/ViewControllerProtocol.swift
mit
1
// // ViewControllerProtocol.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 15/06/17. // Copyright © 2017 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import UIKit public protocol ViewControllerProtocol where Self: UIViewController { var modelStack: AnyObject? { get set } // Setup View func setupCoreView() // MARK: Navigation Bar // Bydefalut leftButton action is set to 'leftButtonAction' func setupNavigationbar(title: String, leftButton: UIBarButtonItem?, rightButton: UIBarButtonItem?) // invokes's 'popViewController' if not rootViewController or-else invokes 'dismiss' func dismissSelf(_ animated: Bool) // Navigation bar defalut Actions func leftButtonAction() func rightButtonAction() // MARK: Keyboard notification. func registerKeyboardNotifications() // Notifications will be unregistered in 'deinit' func unregisterKeyboardNotifications() // MARK: Alert ViewController func showAlert(title: String?, message: String?, action: UIAlertAction?, actions: [UIAlertAction]?) // MARK: Activity indicator func showActivityIndicator() func hideActivityIndicator(_ completionBlock: LoadingIndicator.CompletionBlock?) // MARK: Layout Guide func topSafeAreaLayoutGuide() -> Bool func horizontalSafeAreaLayoutGuide() -> Bool func shouldDissmissKeyboardOnTap() -> Bool } private extension AssociatedKey { static var baseView = "baseView" static var screenIdentifier = "screenIdentifier" static var modelStack = "modelStack" static var completionBlock = "completionBlock" } extension UIViewController: ViewControllerProtocol { @IBOutlet public var baseView: FTView? { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.baseView) { FTView() } } set { AssociatedObject<FTView>.setAssociated(self, value: newValue, key: &AssociatedKey.baseView) } } @IBOutlet public var topPinnedView: UIView? { get { self.baseView?.topPinnedView } set { self.baseView?.topPinnedView = newValue } } @IBOutlet public var bottomPinnedView: UIView? { get { self.baseView?.bottomPinnedView } set { self.baseView?.bottomPinnedView = newValue } } // Unquie Identifier for eachScreen public var screenIdentifier: String? { get { AssociatedObject<String>.getAssociated(self, key: &AssociatedKey.screenIdentifier) } set { AssociatedObject<String>.setAssociated(self, value: newValue, key: &AssociatedKey.screenIdentifier) } } // modelData that can be passed from previous controller public var modelStack: AnyObject? { get { AssociatedObject<AnyObject>.getAssociated(self, key: &AssociatedKey.modelStack) } set { AssociatedObject<AnyObject>.setAssociated(self, value: newValue, key: &AssociatedKey.modelStack) } } // Setup baseView's topLayoutGuide by sending true in subControllers if needed @objc open func topSafeAreaLayoutGuide() -> Bool { true } @objc open func horizontalSafeAreaLayoutGuide() -> Bool { true } // Will dismiss Keyboard by tapping on any non-interative part of the view. @objc open func shouldDissmissKeyboardOnTap() -> Bool { true } public func setupCoreView() { if self.view == self.baseView { return } guard let rootView = self.view else { return } var isValidBaseView = false // Make it as Views RooView, if forget to map it in IB. if self.baseView != rootView, (rootView as? FTView) != nil { self.baseView = rootView as? FTView isValidBaseView = true } self.view = self.baseView // Setup baseView's topLayoutGuide & bottomLayoutGuide setupLayoutGuide() // To Dismiss keyboard on tap in view setupKeyboardTapRecognizer() // Reset rootView if !isValidBaseView { rootView.removeFromSuperview() self.mainView?.pin(view: rootView, edgeOffsets: .zero) } } } extension UIViewController { // MARK: Navigation Bar public func setupNavigationbar(title: String, leftButton: UIBarButtonItem? = nil, rightButton: UIBarButtonItem? = nil) { self.title = title configureBarButton(button: leftButton, defaultAction: kleftButtonAction) configureBarButton(button: rightButton, defaultAction: kRightButtonAction) self.navigationItem.leftBarButtonItem = leftButton self.navigationItem.rightBarButtonItem = rightButton } // MARK: Dissmiss Self model public func dismissSelf(_ animated: Bool = true) { self_dismissSelf(animated) } // MARK: default Nav-bar button actions @IBAction open func leftButtonAction() { dismissSelf() } @IBAction open func rightButtonAction() { // Optional Protocol implementation: intentionally empty } } // MARK: Layout Guide for rootView private extension UIViewController { func setupLayoutGuide() { // Update: topPinnedButtonView if let topView = self.topPinnedView { self.baseView?.topPinnedView = topView } // Update: bottomPinnedButtonView if let bottomView = self.bottomPinnedView { self.baseView?.bottomPinnedView = bottomView } // Pin: rootView let local = self.baseView?.rootView /* Pin view bellow status bar */ // Pin - rootView's topAnchor if topSafeAreaLayoutGuide(), let local = local { setupTopSafeAreaLayoutGuide(local) } // Pin - rootView's topAnchor if #available(iOS 11.0, *), horizontalSafeAreaLayoutGuide() { local?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0.0).isActive = true local?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0.0).isActive = true } // Pin - rootView's bottomAnchor if #available(iOS 11.0, *) { local?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0.0).isActive = true } else { local?.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor, constant: 0.0).isActive = true } } func setupTopSafeAreaLayoutGuide(_ local: UIView) { if #available(iOS 11.0, *) { local.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true } else { local.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 0.0).isActive = true } } }
7b9bd304a94c9bbbec44fea096eef5f3
32.466667
124
0.650683
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/ChatModule/CWInput/More/CWMoreInputView.swift
mit
2
// // CWMoreKeyBoard.swift // CWWeChat // // Created by wei chen on 2017/4/11. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import YYText public protocol CWMoreInputViewDelegate: NSObjectProtocol { func moreInputView(_ inputView: CWMoreInputView, didSelect item: MoreItem) } private let kOneLines: Int = 2 private let kOneLineItem: Int = 4 private let kOneItemHeight: CGFloat = 280/3 public class CWMoreInputView: UIView { fileprivate var items = [MoreItem]() // 总共页数 var totalPageCount: Int = 0 var pageItemCount: Int = 0 private convenience init() { let size = CGSize(width: kScreenWidth, height: kMoreInputViewHeight) let origin = CGPoint(x: 0, y: kScreenHeight-size.height) let frame = CGRect(origin: origin, size: size) self.init(frame: frame) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(hex: "#E7EFF5") self.addSubview(collectionView) self.addSubview(pageControl) pageControl.top = collectionView.bottom } weak var deleagte: CWMoreInputViewDelegate? // 加载items func loadMoreItems(_ items: [MoreItem]) { self.items = items pageItemCount = kOneLines * kOneLineItem totalPageCount = Int(ceil(CGFloat(items.count)/CGFloat(pageItemCount))) pageControl.numberOfPages = totalPageCount collectionView.reloadData() } lazy var collectionView: UICollectionView = { // 间距 var itemWidth = (kScreenWidth - 10*2)/CGFloat(kOneLineItem) itemWidth = YYTextCGFloatPixelRound(itemWidth) let padding = (kScreenWidth - CGFloat(kOneLineItem) * itemWidth) / 2.0 let paddingLeft = YYTextCGFloatPixelRound(padding) let paddingRight = kScreenWidth - paddingLeft - itemWidth * CGFloat(kOneLineItem) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: itemWidth, height: kOneItemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsetsMake(0, paddingLeft, 0, paddingRight) let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kOneItemHeight*CGFloat(kOneLines)) var collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) collectionView.dataSource = self collectionView.backgroundColor = UIColor.clear collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.register(MoreItemCell.self, forCellWithReuseIdentifier: MoreItemCell.identifier) collectionView.top = 10 return collectionView }() var pageControl: UIPageControl! public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CWMoreInputView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageItemCount } public func numberOfSections(in collectionView: UICollectionView) -> Int { return totalPageCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MoreItemCell.identifier, for: indexPath) as! MoreItemCell cell.item = moreItemForIndexPath(indexPath) return cell } func moreItemForIndexPath(_ indexPath: IndexPath) -> MoreItem? { var index = indexPath.section * self.pageItemCount + indexPath.row // let page = index / self.pageItemCount index = index % self.pageItemCount let x = index / kOneLines let y = index % kOneLines let resultIndex = self.pageItemCount / kOneLines * y + x + page * self.pageItemCount if resultIndex > items.count - 1 { return nil } return items[resultIndex] } }
b04bbe9250ff90761da62a18ba0d6052
33.826446
132
0.67608
false
false
false
false
BugMomon/weibo
refs/heads/master
NiceWB/NiceWB/Classes/Main(主要)/AccessToken/UserAccountViewModel.swift
apache-2.0
1
// // UserAccountViewModel.swift // NiceWB // // Created by HongWei on 2017/4/5. // Copyright © 2017年 HongWei. All rights reserved. // import Foundation class UserAccountViewModel { static let shareInstance : UserAccountViewModel = UserAccountViewModel() var account : UserAccount? var isLogin : Bool { guard let account = account else { return false } if let expires_date = account.expires_date{ //判断时间升序降序 if expires_date.compare(Date()) == ComparisonResult.orderedDescending{ return true } } return true } var accountPath : String{ let accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return (accountPath as NSString).appendingPathComponent("account.plist") } init() { account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as! UserAccount? // print("viewModel : \(account)") // print(accountPath) } }
f1962dac0f8aeff68f6e56ed32992890
25.5
111
0.601078
false
false
false
false
CodaFi/swift
refs/heads/master
stdlib/public/core/LegacyABI.swift
apache-2.0
8
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // This file contains non-API (or underscored) declarations that are needed to // be kept around for ABI compatibility extension Unicode.UTF16 { @available(*, unavailable, renamed: "Unicode.UTF16.isASCII") @inlinable public static func _isASCII(_ x: CodeUnit) -> Bool { return Unicode.UTF16.isASCII(x) } } @available(*, unavailable, renamed: "Unicode.UTF8.isASCII") @inlinable internal func _isASCII(_ x: UInt8) -> Bool { return Unicode.UTF8.isASCII(x) } @available(*, unavailable, renamed: "Unicode.UTF8.isContinuation") @inlinable internal func _isContinuation(_ x: UInt8) -> Bool { return UTF8.isContinuation(x) } extension Substring { @available(*, unavailable, renamed: "Substring.base") @inlinable internal var _wholeString: String { return base } } extension String { @available(*, unavailable, renamed: "String.withUTF8") @inlinable internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { var copy = self return try copy.withUTF8(body) } } extension Substring { @available(*, unavailable, renamed: "Substring.withUTF8") @inlinable internal func _withUTF8<R>( _ body: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { var copy = self return try copy.withUTF8(body) } } // This function is no longer used but must be kept for ABI compatibility // because references to it may have been inlined. @usableFromInline internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool { // The LLVM intrinsic underlying int_expect_Int1 now requires an immediate // argument for the expected value so we cannot call it here. This should // never be called in cases where performance matters, so just return the // value without any branch hint. return actual } extension String { @usableFromInline // Never actually used in inlinable code... internal func _nativeCopyUTF16CodeUnits( into buffer: UnsafeMutableBufferPointer<UInt16>, range: Range<String.Index> ) { fatalError() } } extension String.UTF16View { // Swift 5.x: This was accidentally shipped as inlinable, but was never used // from an inlinable context. The definition is kept around for techincal ABI // compatibility (even though it shouldn't matter), but is unused. @inlinable @inline(__always) internal var _shortHeuristic: Int { return 32 } }
e01b4b779a6ce65e93793ee1716d5424
31.41573
80
0.682149
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureTransaction/Sources/FeatureTransactionUI/Send/Analytics/NewAnalyticsEvents+Send.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import FeatureTransactionDomain import Foundation import PlatformKit extension AnalyticsEvents.New { public enum Send: AnalyticsEvent { public var type: AnalyticsEventType { .nabu } case sendReceiveClicked( origin: Origin = .navigation, type: Type ) case sendReceiveViewed(type: Type) case sendAmountMaxClicked( currency: String, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendFeeRateSelected( currency: String, feeRate: FeeRate, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendFromSelected( currency: String, fromAccountType: FromAccountType ) case sendSubmitted( currency: String, feeRate: FeeRate, fromAccountType: FromAccountType, toAccountType: ToAccountType ) case sendDomainResolved public enum Origin: String, StringRawRepresentable { case navigation = "NAVIGATION" } public enum `Type`: String, StringRawRepresentable { case receive = "RECEIVE" case send = "SEND" } public enum FromAccountType: String, StringRawRepresentable { case savings = "SAVINGS" case trading = "TRADING" case userKey = "USERKEY" public init(_ account: BlockchainAccount?) { switch account { case is CryptoInterestAccount: self = .savings case is CryptoTradingAccount: self = .trading default: self = .userKey } } } public enum ToAccountType: String, StringRawRepresentable { case external = "EXTERNAL" case savings = "SAVINGS" case trading = "TRADING" case userKey = "USERKEY" case exchange = "EXCHANGE" public init(_ account: CryptoAccount) { switch account { case is CryptoNonCustodialAccount: self = .userKey case is CryptoInterestAccount: self = .savings case is CryptoTradingAccount: self = .trading case is CryptoExchangeAccount: self = .exchange default: self = .external } } public init(_ target: TransactionTarget?) { switch target?.accountType { case .trading: self = .trading case .external: self = .external case .exchange: self = .exchange default: self = .userKey } } } public enum FeeRate: String, StringRawRepresentable { case custom = "CUSTOM" case normal = "NORMAL" case priority = "PRIORITY" init(_ feeLevel: FeeLevel) { switch feeLevel { case .priority: self = .priority case .custom: self = .custom default: self = .normal } } } } }
75ac6d52d54e00fe10bf405dabdf4458
29.159664
69
0.494288
false
false
false
false
barisarsan/ScreenSceneController
refs/heads/master
ScreenSceneController/ScreenSceneController/ScreenSceneSettings.swift
mit
2
// // ScreenSceneSettings.swift // ScreenSceneController // // Copyright (c) 2014 Ruslan Shevchuk // // 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 @objc (ScreenSceneSettings) public class ScreenSceneSettings { private struct Static { static let instance = ScreenSceneSettings() } public class var defaultSettings : ScreenSceneSettings { return Static.instance } public var classesThatDisableScrolling = [AnyClass]() public func addClassThatDisableScrolling(classThatDisableScrolling: AnyClass) { classesThatDisableScrolling.append(classThatDisableScrolling) } public var navigationBarTitleTextAttributes: [String: AnyObject] = [ NSFontAttributeName: UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName: UIColor.whiteColor() ] public var bringFocusAnimationDuration: NSTimeInterval = 0.15 public var attachAnimationDamping: CGFloat = 0.8 public var attachAnimationDuration: NSTimeInterval = 0.4 public var detachAnimationDuration: NSTimeInterval = 0.3 public var detachCap: CGFloat = 0.1 public var attachmentAllowInterpolatingEffect: Bool = true public var attachmentInterpolatingEffectRelativeValue:Int = 20 public var attachmentCornerRadius: CGFloat = 10 public var attachmentPortraitWidth: CGFloat = 0.5 public var attachmentLandscapeWidth: CGFloat = 0.5 public var attachmentRelative: Bool = true public var attachmentExclusiveFocus: Bool = false public var attachmentTopInset: CGFloat = 65 public var attachmentBottomInset: CGFloat = 20 public var attachmentMinLeftInset: CGFloat = 10 public var attachmentMinRightInset: CGFloat = 10 public var attachmentNavigationBarHeight:CGFloat = 65 public var attachmentShadowIntensity:CGFloat = 4 }
808ae9dc47f0eb6820a9655f11f4c0e1
39.805195
83
0.692871
false
false
false
false
dalu93/SwiftHelpSet
refs/heads/master
Sources/UIKIt/SwiftyTableView.swift
mit
1
// // SwiftyTableView.swift // SwiftHelpSet // // Created by Luca D'Alberti on 7/14/16. // Copyright © 2016 dalu93. All rights reserved. // import UIKit public class SwiftyTableView: UITableView { fileprivate var _configureNumberOfSections: (() -> Int)? /// It is called everytime `numberOfSectionsInTableView(tableView: UITableView)` is called public func configureNumberOfSections(closure: @escaping (() -> Int)) -> Self { _configureNumberOfSections = closure return self } fileprivate var _numberOfRowsPerSection: ((_ section: Int) -> Int)? /// It is called everytime `tableView(tableView: UITableView, numberOfRowsInSection section: Int)` is called public func numberOfRowsPerSection(closure: @escaping ((_ section: Int) -> Int)) -> Self { _numberOfRowsPerSection = closure return self } fileprivate var _cellForIndexPath: ((_ indexPath: IndexPath) -> UITableViewCell)? /// It is called everytime `tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)` is called public func cellForIndexPath(closure: @escaping ((_ indexPath: IndexPath) -> UITableViewCell)) -> Self { _cellForIndexPath = closure return self } fileprivate var _onCellSelection: ((_ indexPath: IndexPath) -> ())? /// It is called everytime `tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)` is called public func onCellSelection(closure: @escaping ((_ indexPath: IndexPath) -> ())) -> Self { _onCellSelection = closure return self } fileprivate var _onScroll: ((_ scrollView: UIScrollView) -> ())? /// It is called everytime `scrollViewDidScroll(scrollView: UIScrollView)` is called public func onScroll(closure: @escaping ((_ scrollView: UIScrollView) -> ())) -> Self { _onScroll = closure return self } fileprivate var _footerInSection: ((_ section: Int) -> UIView?)? /// It is called everytime `tableView(tableView: UITableView, viewForFooterInSection section: Int)` is called public func footerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self { _footerInSection = closure return self } fileprivate var _headerInSection: ((_ section: Int) -> UIView?)? /// It is called everytime `tableView(tableView: UITableView, viewForHeaderInSection section: Int)` is called public func headerInSection(closure: @escaping ((_ section: Int) -> UIView?)) -> Self { _headerInSection = closure return self } override public init(frame: CGRect, style: UITableViewStyle) { super.init( frame: frame, style: style ) _setupProtocols() } required public init?(coder aDecoder: NSCoder) { super.init( coder: aDecoder ) _setupProtocols() } } // MARK: - Helpers private extension SwiftyTableView { func _setupProtocols() { self.delegate = self self.dataSource = self } } // MARK: - UITableViewDataSource extension SwiftyTableView: UITableViewDataSource { @nonobjc public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return _configureNumberOfSections?() ?? 0 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _numberOfRowsPerSection?(section) ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return _cellForIndexPath?(indexPath) ?? UITableViewCell() } } // MARK: - UITableViewDelegate extension SwiftyTableView: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { _onCellSelection?(indexPath) } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return _footerInSection?(section) } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return _headerInSection?(section) } public func scrollViewDidScroll(_ scrollView: UIScrollView) { _onScroll?(scrollView) } }
da936f7789424557a8f03c9e72ed6899
34.483607
124
0.661585
false
false
false
false
abarisain/skugga
refs/heads/master
Apple/iOS/Share/ProgressNotifier.swift
apache-2.0
1
// // ProgressNotifier.swift // Skugga // // Created by Arnaud Barisain-Monrose on 18/09/2016. // Copyright © 2016 NamelessDev. All rights reserved. // import Foundation import UIKit import UserNotifications protocol ProgressNotifier { func uploadStarted(itemURL: URL?) func uploadProgress(_ progress: Double) func uploadSuccess(url: String) func uploadFailed(error: NSError) } class NotificationProgressNotifier: AlertProgressNotifier { static let notificationUploadIdentifier = "extension_upload" var alreadyNotifiedProgress = false var cachedItemURL: URL? required init(vc: UIViewController) { super.init(vc: vc) } override func uploadStarted(itemURL: URL?) { super.uploadStarted(itemURL: itemURL) cachedItemURL = itemURL let content = UNMutableNotificationContent() content.body = "Uploading..." content.sound = nil let request = UNNotificationRequest.init(identifier: NotificationProgressNotifier.notificationUploadIdentifier, content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } override func uploadProgress(_ progress: Double) { super.uploadProgress(progress) let percentage = floor(progress) if (percentage >= 60 && !alreadyNotifiedProgress) { alreadyNotifiedProgress = true let content = UNMutableNotificationContent() content.body = "Uploading... \(percentage) %" content.sound = nil let request = UNNotificationRequest.init(identifier: NotificationProgressNotifier.notificationUploadIdentifier, content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } } override func uploadSuccess(url: String) { super.uploadSuccess(url: url) UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [NotificationProgressNotifier.notificationUploadIdentifier]) let content = UNMutableNotificationContent() content.title = "Image uploaded" content.body = "\(url)" content.sound = UNNotificationSound.default() content.categoryIdentifier = "upload_success" content.userInfo["url"] = url appendAttachment(content: content) let request = UNNotificationRequest.init(identifier: UUID.init().uuidString, content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } override func uploadFailed(error: NSError) { super.uploadFailed(error: error) UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [NotificationProgressNotifier.notificationUploadIdentifier]) let content = UNMutableNotificationContent() content.title = "Couldn't upload image" content.body = "\(error)" content.sound = UNNotificationSound.default() appendAttachment(content: content) let request = UNNotificationRequest.init(identifier: UUID.init().uuidString, content: content, trigger: nil) UNUserNotificationCenter.current().add(request) } func appendAttachment(content: UNMutableNotificationContent) { if let cachedItemURL = cachedItemURL { do { let attachment = try UNNotificationAttachment(identifier: "image", url: cachedItemURL, options: nil) content.attachments = [attachment] } catch { print("Error while adding notification attachment \(error)") } } } } class AlertProgressNotifier: ProgressNotifier { var alert: UIAlertController? weak var viewController: UIViewController? required init(vc: UIViewController) { viewController = vc } func uploadStarted(itemURL: URL?) { if let viewController = viewController { alert = UIAlertController(title: "Uploading...", message: "", preferredStyle: .alert) viewController.present(alert!, animated: true, completion: nil) } } func uploadProgress(_ progress: Double) { alert?.message = NSString(format: "%d %%", floor(progress*100)) as String } func uploadSuccess(url: String) { alert?.dismiss(animated: true, completion: nil) } func uploadFailed(error: NSError) { let presentError = { () -> Void in let alert = UIAlertController(title: "Error", message: "Couldn't upload image : \(error) \(error.userInfo)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: { (action: UIAlertAction!) -> () in self.viewController?.extensionContext!.cancelRequest(withError: error) })) self.viewController?.present(alert, animated: true, completion: nil) } if let previousAlert = alert { previousAlert.dismiss(animated: true, completion: presentError) } else { presentError() } } }
0d7f5ad9734ffc30e71ede8a42661eb1
35.027778
155
0.652274
false
false
false
false
Adorkable/StoryboardKit
refs/heads/master
StoryboardKitTests/ViewInstanceInfoTests.swift
mit
1
// // ViewInstanceInfoTests.swift // StoryboardKit // // Created by Ian on 6/30/15. // Copyright (c) 2015 Adorkable. All rights reserved. // import XCTest import StoryboardKit class ViewInstanceInfoTests: XCTestCase { var applicationInfo : ApplicationInfo? var viewInstanceInfoId = "IKn-pG-61R" var viewInstanceInfo : ViewInstanceInfo? override func setUp() { self.continueAfterFailure = false super.setUp() applicationInfo = ApplicationInfo() do { try StoryboardFileParser.parse(applicationInfo!, pathFileName: storyboardPathBuilder()! ) } catch let error as NSError { XCTAssertNil(error, "Expected parse to not throw an error: \(error)") } self.viewInstanceInfo = applicationInfo?.viewInstanceWithId(self.viewInstanceInfoId) } func testClassInfo() { let className = "UIView" let classInfo = self.applicationInfo?.viewClassWithClassName(className) XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertNotNil(classInfo, "\(self.viewInstanceInfo!)'s classInfo should not be nil") XCTAssertEqual(self.viewInstanceInfo!.classInfo, classInfo!, "\(self.viewInstanceInfo!)'s classInfo should be equal to \(classInfo!)") } func testId() { XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertEqual(self.viewInstanceInfo!.id, self.viewInstanceInfoId, "\(self.viewInstanceInfo!)'s id should be equal to \(self.viewInstanceInfo)") } func testFrame() { let equalTo = CGRect(x: 0, y: 0, width: 600, height: 600) XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") // XCTAssertNotNil(self.viewInstanceInfo!.frame, "\(self.viewInstanceInfo)'s frame should not be nil") XCTAssertEqual(self.viewInstanceInfo!.frame!, equalTo, "\(self.viewInstanceInfo!)'s frame should be equal to \(equalTo)") } func testAutoResizingMaskWidthSizable() { let equalTo = true XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskWidthSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskWidthSizable should be equal to \(equalTo)") } func testAutoResizingMaskHeightSizable() { let equalTo = true XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertEqual(self.viewInstanceInfo!.autoResizingMaskHeightSizable, equalTo, "\(self.viewInstanceInfo!)'s autoResizingMaskHeightSizable should be equal to \(equalTo)") } func testSubviews() { let equalTo = 4 XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertNotNil(self.viewInstanceInfo!.subviews, "\(self.viewInstanceInfo!)'s subviews should not be nil") XCTAssertEqual(self.viewInstanceInfo!.subviews!.count, equalTo, "\(self.viewInstanceInfo!)'s subview count should be equal to \(equalTo)") } func testBackgroundColor() { let equalTo = NSColor(calibratedWhite: 0.66666666666666663, alpha: 1.0) XCTAssertNotNil(self.viewInstanceInfo, "Unable to retrieve ViewInstanceInfo with id \(self.viewInstanceInfoId)") XCTAssertNotNil(self.viewInstanceInfo!.backgroundColor, "\(self.viewInstanceInfo!)'s background color should not be nil") XCTAssertEqual(self.viewInstanceInfo!.backgroundColor!, equalTo, "\(self.viewInstanceInfo!)'s background color count should be equal to \(equalTo)") } }
54f3d40072f9394c87327e774dea7576
40.5
176
0.694026
false
true
false
false
a1137611824/YWSmallDay
refs/heads/master
smallDay/AppDelegate.swift
mit
1
// // AppDelegate.swift // smallDay // // Created by Mac on 17/3/14. // Copyright © 2017年 Mac. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { setKeyValue() columnInit() //传值之后的处理事件 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.showMianViewController), name: showMainTabBarController_Notification, object: nil) return true } // MARK: -状态栏初始化 func columnInit() { //在plist设置viewcontroller-base status为no意思是交由uiapplication来管理 UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UIApplication.sharedApplication().statusBarHidden = false } // MARK: - 判断是否进入引导界面 private func setKeyValue() { window = UIWindow(frame: MainBounds) window?.rootViewController = showLeadPage() window?.makeKeyAndVisible() } // MARK: - 引导界面设置 func showLeadPage() -> UIViewController{ let versionStr = "CFBundleShortVersionString" let currentVersion = NSBundle.mainBundle().infoDictionary![versionStr] //取出之前的版本号 let defaults = NSUserDefaults.standardUserDefaults() let oldVersion = defaults.stringForKey(versionStr) ?? "" //比较当前版本是否在老版本基础上降低了 if currentVersion?.compare(oldVersion) == NSComparisonResult.OrderedDescending { //将新的版本号存入手机 defaults.setObject(currentVersion, forKey: versionStr) //将数据同步到文件当中,避免丢失 defaults.synchronize() return LeadPageViewController() } return YWMainTabBarController() } //进入首页面 func showMianViewController() { let mainTabBarVC = YWMainTabBarController() self.window!.rootViewController = mainTabBarVC //设置首页面导航栏格式 // let nav = mainTabBarVC.viewControllers![0] as? MainNavigationController // (nav?.viewControllers[0] as! MainViewController).pushcityView() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
6bffd44784e86f95e3f4a2cedfc613fe
38.484848
285
0.704272
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Account/Tests/AccountTests/Feedly/FeedlyLogoutOperationTests.swift
mit
1
// // FeedlyLogoutOperationTests.swift // AccountTests // // Created by Kiel Gillard on 15/11/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import XCTest @testable import Account import RSCore import Secrets class FeedlyLogoutOperationTests: XCTestCase { private var account: Account! private let support = FeedlyTestSupport() override func setUp() { super.setUp() account = support.makeTestAccount() } override func tearDown() { if let account = account { support.destroy(account) } super.tearDown() } private func getTokens(for account: Account) throws -> (accessToken: Credentials, refreshToken: Credentials) { guard let accessToken = try account.retrieveCredentials(type: .oauthAccessToken), let refreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) else { XCTFail("Unable to retrieve access and/or refresh token from account.") throw CredentialsError.incompleteCredentials } return (accessToken, refreshToken) } class TestFeedlyLogoutService: FeedlyLogoutService { var mockResult: Result<Void, Error>? var logoutExpectation: XCTestExpectation? func logout(completion: @escaping (Result<Void, Error>) -> ()) { guard let result = mockResult else { XCTFail("Missing mock result. Test may time out because the completion will not be called.") return } DispatchQueue.main.async { completion(result) self.logoutExpectation?.fulfill() } } } func testCancel() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.logoutExpectation?.isInverted = true let accessToken: Credentials let refreshToken: Credentials do { (accessToken, refreshToken) = try getTokens(for: account) } catch { XCTFail("Could not retrieve credentials to verify their integrity later.") return } let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log) // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } MainThreadOperationQueue.shared.add(logout) MainThreadOperationQueue.shared.cancelOperations([logout]) waitForExpectations(timeout: 1) XCTAssertTrue(logout.isCanceled) do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) XCTAssertEqual(accountAccessToken, accessToken) XCTAssertEqual(accountRefreshToken, refreshToken) } catch { XCTFail("Could not verify tokens were left intact. Did the operation delete them?") } } func testLogoutSuccess() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.mockResult = .success(()) let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log) // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } MainThreadOperationQueue.shared.add(logout) waitForExpectations(timeout: 1) XCTAssertFalse(logout.isCanceled) do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) XCTAssertNil(accountAccessToken) XCTAssertNil(accountRefreshToken) } catch { XCTFail("Could not verify tokens were deleted.") } } class TestLogoutDelegate: FeedlyOperationDelegate { var error: Error? var didFailExpectation: XCTestExpectation? func feedlyOperation(_ operation: FeedlyOperation, didFailWith error: Error) { self.error = error didFailExpectation?.fulfill() } } func testLogoutMissingAccessToken() { support.removeCredentials(matching: .oauthAccessToken, from: account) let (_, service) = support.makeMockNetworkStack() service.credentials = nil let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log) let delegate = TestLogoutDelegate() delegate.didFailExpectation = expectation(description: "Did Fail") logout.delegate = delegate // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } MainThreadOperationQueue.shared.add(logout) waitForExpectations(timeout: 1) XCTAssertFalse(logout.isCanceled) do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) XCTAssertNil(accountAccessToken) } catch { XCTFail("Could not verify tokens were deleted.") } XCTAssertNotNil(delegate.error, "Should have failed with error.") if let error = delegate.error { switch error { case CredentialsError.incompleteCredentials: break default: XCTFail("Expected \(CredentialsError.incompleteCredentials)") } } } func testLogoutFailure() { let service = TestFeedlyLogoutService() service.logoutExpectation = expectation(description: "Did Call Logout") service.mockResult = .failure(URLError(.timedOut)) let accessToken: Credentials let refreshToken: Credentials do { (accessToken, refreshToken) = try getTokens(for: account) } catch { XCTFail("Could not retrieve credentials to verify their integrity later.") return } let logout = FeedlyLogoutOperation(account: account, service: service, log: support.log) // If this expectation is not fulfilled, the operation is not calling `didFinish`. let completionExpectation = expectation(description: "Did Finish") logout.completionBlock = { _ in completionExpectation.fulfill() } MainThreadOperationQueue.shared.add(logout) waitForExpectations(timeout: 1) XCTAssertFalse(logout.isCanceled) do { let accountAccessToken = try account.retrieveCredentials(type: .oauthAccessToken) let accountRefreshToken = try account.retrieveCredentials(type: .oauthRefreshToken) XCTAssertEqual(accountAccessToken, accessToken) XCTAssertEqual(accountRefreshToken, refreshToken) } catch { XCTFail("Could not verify tokens were left intact. Did the operation delete them?") } } }
ba2eb8ebaf94513cbc67891a18fd01c4
29.313364
167
0.745819
false
true
false
false
AliSoftware/SwiftGen
refs/heads/develop
Tests/SwiftGenKitTests/CoreDataTests.swift
mit
1
// // SwiftGenKit UnitTests // Copyright © 2020 SwiftGen // MIT Licence // @testable import SwiftGenKit import TestUtils import XCTest final class CoreDataTests: XCTestCase { func testEmpty() throws { let parser = try CoreData.Parser() let result = parser.stencilContext() XCTDiffContexts(result, expected: "empty", sub: .coreData) } func testDefaults() throws { let parser = try CoreData.Parser() do { try parser.searchAndParse(path: Fixtures.resource(for: "Model.xcdatamodeld", sub: .coreData)) } catch { print("Error: \(error.localizedDescription)") } let result = parser.stencilContext() XCTDiffContexts(result, expected: "defaults", sub: .coreData) } // MARK: - Custom options func testUnknownOption() throws { do { _ = try CoreData.Parser(options: ["SomeOptionThatDoesntExist": "foo"]) XCTFail("Parser successfully created with an invalid option") } catch ParserOptionList.Error.unknownOption(let key, _) { // That's the expected exception we want to happen XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)") } catch let error { XCTFail("Unexpected error occured: \(error)") } } }
90c40725e655b28d551283fb1420899c
27.159091
99
0.682809
false
true
false
false
SwiftKit/Staging
refs/heads/master
Source/DispatchHelpers.swift
mit
1
// // DispatchHelpers.swift // SwiftKit // // Created by Tadeas Kriz on 08/01/16. // Copyright © 2016 Tadeas Kriz. All rights reserved. // import Foundation public func cancellableDispatchAfter(_ seconds: Double, queue: DispatchQueue = DispatchQueue.main, block: @escaping () -> ()) -> Cancellable { let delay = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) return cancellableDispatchAfter(delay, on: queue, block: block) } public func cancellableDispatchAfter(_ time: DispatchTime, on queue: DispatchQueue, block: @escaping () -> ()) -> Cancellable { var cancelled: Bool = false queue.asyncAfter(deadline: time) { if cancelled == false { block() } } return CancellableToken { cancelled = true } } public func cancellableDispatchAsync(on queue: DispatchQueue = DispatchQueue.main, block: @escaping () -> ()) -> Cancellable { var cancelled: Bool = false queue.async { if cancelled == false { block() } } return CancellableToken { cancelled = true } }
97a8c3c7555cc0b48d649314c9d0f930
27.3
142
0.637809
false
false
false
false
Msr-B/FanFan-iOS
refs/heads/master
WeCenterMobile/Model/DataObject/FeaturedObject.swift
gpl-2.0
3
// // FeaturedObject.swift // WeCenterMobile // // Created by Darren Liu on 15/3/12. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import CoreData import Foundation enum FeaturedObjectTypeID: String { case QuestionAnswer = "question" case Article = "article" } enum FeaturedObjectListType: String { case New = "new" case Hot = "hot" case Unsolved = "unresponsive" case Recommended = "reommended" } class FeaturedObject: DataObject { @NSManaged var date: NSDate? class func fetchFeaturedObjects(page page: Int, count: Int, type: FeaturedObjectListType, success: (([FeaturedObject]) -> Void)?, failure: ((NSError) -> Void)?) { NetworkManager.defaultManager!.GET("Explore List", parameters: [ "page": page, "per_page": count, "day": 30, "is_recommend": type == .Recommended ? 1 : 0, "sort_type": type.rawValue], success: { data in let dataManager = DataManager.temporaryManager! // @TODO: Will move to DataManager.defaultManager in future. var featuredObjects = [FeaturedObject]() if Int(msr_object: data["total_rows"]!!) <= 0 { failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification return } for object in data["rows"] as! [NSDictionary] { if let typeID = FeaturedObjectTypeID(rawValue: object["post_type"] as! String) { var featuredObject: FeaturedObject! switch typeID { case .QuestionAnswer: let question = dataManager.autoGenerate("Question", ID: Int(msr_object: object["question_id"])!) as! Question let featuredQuestionAnswer = dataManager.autoGenerate("FeaturedQuestionAnswer", ID: question.id) as! FeaturedQuestionAnswer featuredObject = featuredQuestionAnswer featuredQuestionAnswer.question = question featuredQuestionAnswer.date = NSDate(timeIntervalSince1970: NSTimeInterval(msr_object: object["add_time"])!) question.date = featuredQuestionAnswer.date question.title = (object["question_content"] as! String) // question.updatedDate = NSDate(timeIntervalSince1970: NSTimeInterval(msr_object: object["update_time"])!) question.viewCount = Int(msr_object: object["view_count"]) // question.focusCount = Int(msr_object: object["focus_count"]) if let userInfo = object["user_info"] as? NSDictionary { question.user = (dataManager.autoGenerate("User", ID: Int(msr_object: userInfo["uid"])!) as! User) question.user!.name = (userInfo["user_name"] as! String) question.user!.avatarURL = userInfo["avatar_file"] as? String } else { question.user = nil } var topics = Set<Topic>() if let topicsInfo = object["topics"] as? [NSDictionary] { for topicInfo in topicsInfo { let topic = dataManager.autoGenerate("Topic", ID: Int(msr_object: topicInfo["topic_id"]!)!) as! Topic topic.title = (topicInfo["topic_title"] as! String) topics.insert(topic) } } question.topics = topics var featuredUsers = Set<User>() for (userID, userInfo) in object["answer_users"] as? [String: NSDictionary] ?? [:] { let user = dataManager.autoGenerate("User", ID: Int(msr_object: userID)!) as! User user.name = userInfo["user_name"] as? String ?? "" user.avatarURL = userInfo["avatar_file"] as? String featuredUsers.insert(user) } featuredQuestionAnswer.answerUsers = featuredUsers var featuredAnswers = Set<Answer>() // Currently, there is just 1 answer. if let answerInfo = object["answer"] as? NSDictionary { /** * @TODO: [Bug][Back-End] Dirty data: * "answer": { * "user_info": null, * "answer_content": null, * "anonymous": null * } */ if !((answerInfo["answer_content"] ?? NSNull()) is NSNull) { let answer = Answer.temporaryObject() // Cause no answer ID. if let userInfo = answerInfo["user_info"] as? NSDictionary { answer.user = (dataManager.autoGenerate("User", ID: Int(msr_object: userInfo["uid"])!) as! User) answer.user!.name = (userInfo["user_name"] as! String) answer.user!.avatarURI = userInfo["avatar_file"] as? String // Might be NSNull or "" here. featuredAnswers.insert(answer) } else { answer.user = nil } answer.body = (answerInfo["answer_content"] as! String) // question.answers.insert(answer) // Bad connections cause no answer ID. } } featuredQuestionAnswer.answers = featuredAnswers break case .Article: let article = dataManager.autoGenerate("Article", ID: Int(msr_object: object["id"])!) as! Article let featuredArticle = dataManager.autoGenerate("FeaturedArticle", ID: article.id) as! FeaturedArticle featuredObject = featuredArticle featuredArticle.article = article featuredArticle.date = NSDate(timeIntervalSince1970: NSTimeInterval(msr_object: object["add_time"])!) article.title = (object["title"] as! String) article.date = featuredArticle.date article.viewCount = Int(msr_object: object["views"]) var topics = Set<Topic>() if let topicsInfo = object["topics"] as? [NSDictionary] { for topicInfo in topicsInfo { let topic = dataManager.autoGenerate("Topic", ID: Int(msr_object: topicInfo["topic_id"])!) as! Topic topic.title = (topicInfo["topic_title"] as! String) topics.insert(topic) } } if let userInfo = object["user_info"] as? NSDictionary { let user = dataManager.autoGenerate("User", ID: Int(msr_object: userInfo["uid"])!) as! User user.name = (userInfo["user_name"] as! String) user.avatarURL = userInfo["avatar_file"] as? String article.user = user } else { article.user = nil } break } featuredObjects.append(featuredObject) } else { failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification return } } _ = try? DataManager.defaultManager.saveChanges() success?(featuredObjects) }, failure: failure) } }
1c1daef971580c6e2470563abbdacb76
58.912752
196
0.46869
false
false
false
false
softwarenerd/TSNPeerNetworking
refs/heads/master
Source/TSNPeerNetworking.swift
mit
1
// // TSNPeerNetworking.swift // TSNPeerNetworking // // Created by Brian Lambert on 1/27/16. // Copyright © 2016 Microsoft. All rights reserved. // import Foundation import MultipeerConnectivity // TSNPeerNetworking class. public class TSNPeerNetworking: NSObject { // The TSNPeerNetworkingDelegate. public weak var delegate: TSNPeerNetworkingDelegate? // The local peer ID key. let LocalPeerIDKey = "LocalPeerIDKey" // The advertise service type. private var advertiseServiceType: String? // The browse service type. private var browseServiceType: String? // The local peer identifier. private var localPeerID: MCPeerID! private var localPeerDisplayName: String! // The session. private var session: MCSession! // The nearby service advertiser. private var nearbyServiceAdvertiser: MCNearbyServiceAdvertiser! // The nearby service browser. private var nearbyServiceBrowser: MCNearbyServiceBrowser! // Returns a value which indicates whether peers are connected. public var peersAreConnected: Bool { get { return session.connectedPeers.count != 0 } } // Initializer. public init(advertiseServiceType advertiseServiceTypeIn: String?, browseServiceType browseServiceTypeIn: String?) { // Initialize. advertiseServiceType = advertiseServiceTypeIn browseServiceType = browseServiceTypeIn } // Starts. public func start() { // Obtain user defaults and see if we have a serialized local peer ID. If we do, deserialize it. If not, make one // and serialize it for later use. If we don't serialize and reuse the local peer ID, we'll see duplicates // of this local peer in sessions. let userDefaults = NSUserDefaults.standardUserDefaults() if let data = userDefaults.dataForKey(LocalPeerIDKey) { // Deserialize the local peer ID. localPeerID = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MCPeerID } else { // Allocate and initialize a new local peer ID. localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name) // Serialize and save the peer ID in user defaults. let data = NSKeyedArchiver.archivedDataWithRootObject(localPeerID) userDefaults.setValue(data, forKey: LocalPeerIDKey) userDefaults.synchronize() } // Set the local peer display name. localPeerDisplayName = localPeerID.displayName // Allocate and initialize the session. session = MCSession(peer: localPeerID, securityIdentity: nil, encryptionPreference: .Required) session.delegate = self // Allocate and initialize the nearby service advertizer. if let advertiseServiceType = advertiseServiceType { nearbyServiceAdvertiser = MCNearbyServiceAdvertiser(peer: localPeerID, discoveryInfo: nil, serviceType: advertiseServiceType) nearbyServiceAdvertiser.delegate = self } // Allocate and initialize the nearby service browser. if let browseServiceType = browseServiceType { nearbyServiceBrowser = MCNearbyServiceBrowser(peer: localPeerID, serviceType: browseServiceType) nearbyServiceBrowser.delegate = self } // Start advertising the local peer and browsing for nearby peers. nearbyServiceAdvertiser?.startAdvertisingPeer() nearbyServiceBrowser?.startBrowsingForPeers() // Log. log("Started.") } // Stops peer networking. public func stop() { // Stop advertising the local peer and browsing for nearby peers. nearbyServiceAdvertiser?.stopAdvertisingPeer() nearbyServiceBrowser?.stopBrowsingForPeers() // Disconnect the session. session.disconnect() // Clean up. nearbyServiceAdvertiser = nil nearbyServiceBrowser = nil session = nil localPeerID = nil // Log. log("Stopped.") } // Sends data. public func sendData(data: NSData) -> Bool { // If there are no connected peers, we cannot send the data. let connectedPeers = session.connectedPeers if connectedPeers.count == 0 { // Log. log("Unable to send \(data.length) bytes. There are no peers are connected.") return false } // There are connected peers. Try to send the data to each of them. var errorsOccurred = false for peerId in connectedPeers { // Try to send. do { try session.sendData(data, toPeers: [peerId], withMode: .Reliable) log("Sent \(data.length) bytes to peer \(peerId.displayName).") } catch { log("Failed to send \(data.length) bytes to peer \(peerId.displayName). Error: \(error).") errorsOccurred = true break } } // Done. return !errorsOccurred } } // MCNearbyServiceAdvertiserDelegate. extension TSNPeerNetworking: MCNearbyServiceAdvertiserDelegate { // Incoming invitation request. Call the invitationHandler block with true // and a valid session to connect the inviting peer to the session. public func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) { // Accept the invitation. invitationHandler(true, session); // Log. log("Accepted invitation from peer \(peerID.displayName).") } // Advertising did not start due to an error. public func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError) { log("Failed to start advertising. Error: \(error)") } } // MCSessionDelegate. extension TSNPeerNetworking: MCNearbyServiceBrowserDelegate { // Found a nearby advertising peer. public func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) { // Invite the peer to the session. nearbyServiceBrowser.invitePeer(peerID, toSession: session, withContext: nil, timeout: 30.0) // Log. log("Found peer \(peerID.displayName) and invited.") } // A nearby peer has stopped advertising. public func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { log("Lost peer \(peerID.displayName).") } // Browsing did not start due to an error. public func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError) { log("Failed to start browsing for peers with service type \(browseServiceType). Error: \(error)") } } // MCSessionDelegate. extension TSNPeerNetworking: MCSessionDelegate { // Nearby peer changed state. public func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { // Log. switch state { case .NotConnected: log("Peer \(peerID.displayName) is not connected.") case .Connecting: log("Peer \(peerID.displayName) is connecting.") case .Connected: log("Peer \(peerID.displayName) is connected.") } // Notify the delegate. if let delegate = delegate { delegate.peerNetworkingPeersChanged(self) } } // Received data from nearby peer. public func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { // Log. log("Peer \(peerID.displayName) sent \(data.length) bytes.") // Notify. if let delegate = delegate { delegate.peerNetworking(self, didReceiveData: data) } } // Received a byte stream from nearby peer. public func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } // Start receiving a resource from nearby peer. public func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { } // Finished receiving a resource from nearby peer and saved the content in a temporary location - the app is responsible for moving the file // to a permanent location within its sandbox. public func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) { } // Made first contact with peer and have identity information about the nearby peer (certificate may be nil). public func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void) { certificateHandler(true); log("Peer \(peerID.displayName) sent certificate and it was accepted."); } } // Privates. extension TSNPeerNetworking { // Log. private func log(string: String) { print("TSNPeerNetworking: \(localPeerDisplayName) - \(string)") } }
90f54c65f62207142b5ce005bd3b6d8e
32.898246
188
0.645585
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeLoading/AwesomeLoading/Classes/Shimmer/ShimmerView.swift
mit
1
// // ShimmerView.swift // AwesomeLoading // // Created by Emmanuel on 21/06/2018. // import UIKit class ShimmerView: UIView, ShimmerEffect { override open static var layerClass: AnyClass { return CAGradientLayer.self } open var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } open var animationDuration: TimeInterval = 3 open var animationDelay: TimeInterval = 1.5 open var gradientHighlightRatio: Double = 0.3 @IBInspectable open var shimmerGradientTint: UIColor = .black @IBInspectable open var shimmerGradientHighlight: UIColor = .white } // MARK: - UIView Extension extension UIView { public func startShimmerAnimation(delay: Double = 0.2, tint: UIColor = UIColor.init(red: 35/255.0, green: 39/255.0, blue: 47/255.0, alpha: 0.2), highlight: UIColor = UIColor.init(red: 40/255.0, green: 45/255.0, blue: 53/255.0, alpha: 0.8), highlightRatio: Double = 0.8, widthRatio: CGFloat = 1, heightRatio: CGFloat = 1, alignment: NSTextAlignment = .center) { stopShimmerAnimation() let shimmerView = ShimmerView() //shimmerView.frame = CGRect(x: 0, y: 0, width: self.bounds.width*widthRatio, height: self.bounds.height*heightRatio) //shimmerView.center = CGPoint(x: self.bounds.width/2, y: self.bounds.height/2) shimmerView.backgroundColor = .clear shimmerView.shimmerGradientTint = tint shimmerView.shimmerGradientHighlight = highlight shimmerView.animationDelay = delay shimmerView.gradientHighlightRatio = highlightRatio shimmerView.addShimmerAnimation() self.addSubview(shimmerView) shimmerView.translatesAutoresizingMaskIntoConstraints = false switch alignment { case .left: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) break case .right: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)) break default: self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) } self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: widthRatio, constant: 0)) self.addConstraint(NSLayoutConstraint(item: shimmerView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: heightRatio, constant: 0)) } public func stopShimmerAnimation() { for subview in subviews { if let subview = subview as? ShimmerView { subview.removeShimmerAnimation() subview.removeFromSuperview() } } } }
864eb45a761d98c68786034df4005c67
40.129412
176
0.624714
false
false
false
false
sochalewski/PSPageControl
refs/heads/master
PSPageControl.swift
mit
1
// // PSPageControl.swift // PSPageControl // // Originaly created by Piotr Sochalewski on 14.08.2015. // Rewritten to Swift by Piotr Sochalewski on 05.02.2016. // import AVFoundation import UIKit import UIImageViewAlignedSwift public protocol PSPageControlDelegate: class { /** The delegate method called when the current index did change. - parameter index: The current index. */ func didChange(index: Int) } open class PSPageControl: UIView { /// The PSPageControl's delegate protocol. open weak var delegate: PSPageControlDelegate? /// The image shown in the background. It should be horizontal with proper ratio and high resolution. open var backgroundPicture: UIImage? { didSet { guard let backgroundPicture = backgroundPicture else { return } let size = AVMakeRect(aspectRatio: backgroundPicture.size, insideRect: CGRect(x: 0.0, y: 0.0, width: CGFloat.greatestFiniteMagnitude, height: frame.height)).size UIGraphicsBeginImageContextWithOptions(size, false, 0.0) backgroundPicture.draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() background.image = image } } /// The array of `UIView`s to be shown by page control. open var views: [UIView]? { didSet { subviews.filter( { !subviewsNotAllowedToRemoveFromSuperview.contains($0) } ).forEach { $0.removeFromSuperview() } guard let views = views else { pageControl.numberOfPages = 0; return } for (index, view) in views.enumerated() { view.frame = CGRect(x: CGFloat(index) * frame.width, y: 0.0, width: frame.width, height: frame.height) addSubview(view) } pageControl.numberOfPages = views.count } } /// Offset per page in pixels. Default is `40`. open var offsetPerPage: UInt = 40 /// The tint color to be used for the page indicator. open var pageIndicatorTintColor: UIColor? { set { pageControl.pageIndicatorTintColor = newValue } get { return pageControl.pageIndicatorTintColor } } /// The tint color to be used for the current page indicator. open var currentPageIndicatorTintColor: UIColor? { set { pageControl.currentPageIndicatorTintColor = newValue } get { return pageControl.currentPageIndicatorTintColor } } /** The frame rectangle, which describes the page indicators' location and size in its superview’s coordinate system. Changes to this property can be animated. */ open var pageIndicatorFrame: CGRect { get { return pageControl.frame } set { pageControl.frame = newValue } } private var subviewsNotAllowedToRemoveFromSuperview = [UIView]() private var background = UIImageViewAligned() private var pageControl = UIPageControl() private var touchPosition: CGPoint? private var backgroundLayerFrameOrigin: CGPoint? /// The current page. private(set) var currentViewIndex = 0 { didSet { delegate?.didChange(index: currentViewIndex) } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } open override func layoutSubviews() { super.layoutSubviews() // Background image background.frame = frame background.layer.frame = CGRect(x: CGFloat(-currentViewIndex - 1) * CGFloat(offsetPerPage), y: 0.0, width: background.layer.frame.width, height: background.layer.frame.height) backgroundLayerFrameOrigin = background.layer.frame.origin // Page control pageControl.frame = CGRect(x: 10.0, y: frame.height - 50.0, width: frame.width - 20.0, height: 40.0) } // MARK: - Views /** Shows a view with a given index. - parameter index: The index of page that should be shown by the receiver as a white dot. The property value is an integer specifying a page shown minus one; thus a value of indicates the first page. Values outside the possible range are pinned to either 0 or numberOfPages minus 1. - returns: A Boolean value that determines whether the function finished with success. */ public func showView(withIndex index: Int) -> Bool { guard let views = views, index < views.count, index >= 0 else { return false } showView(withIndex: index, setCurrentPage: true) return true } private func setup() { // Background image background.contentMode = .scaleAspectFill background.alignment = .left addSubview(background) // Page control addSubview(pageControl) // Array of views not allowed to remove from superview subviewsNotAllowedToRemoveFromSuperview = [background, pageControl] } private func showView(withIndex index: Int, setCurrentPage currentPage: Bool) { // Background image if index != currentViewIndex { let newX = CGFloat(-index - 1) * CGFloat(offsetPerPage) backgroundLayerFrameOrigin = CGPoint(x: newX, y: 0.0) } let duration = (index == currentViewIndex) ? 0.3 : 0.2 currentViewIndex = index UIView.animate(withDuration: duration) { self.background.layer.frame = CGRect(x: self.backgroundLayerFrameOrigin!.x, y: 0.0, width: self.background.layer.frame.width, height: self.background.layer.frame.height) } // Views UIView.animate(withDuration: 0.2, animations: { // Center (show) view with current index let view = self.views![index] view.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: self.frame.height) // Move to the left views with index lower than >index< // and to the right views with index higher than >index< for (i, view) in self.views!.enumerated() { let newX: CGFloat switch i { case let x where x < index: newX = CGFloat(-(index - i)) * self.frame.width case let x where x > index: newX = CGFloat(i - index) * self.frame.width default: newX = 0.0 } view.frame.origin = CGPoint(x: newX, y: 0.0) } }) { _ in if currentPage { self.pageControl.currentPage = index } } } // MARK: - Touches open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) touchPosition = touches.first?.location(in: self) } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) let differenceInTouchXAxis = difference(between: touches) UIView.animate(withDuration: 0.1) { for (index, view) in self.views!.enumerated() { view.frame = CGRect(x: CGFloat(index - self.currentViewIndex) * view.frame.width + CGFloat(differenceInTouchXAxis), y: 0.0, width: self.background.layer.frame.width, height: self.background.layer.frame.height) } let x = CGFloat(-self.currentViewIndex - 1) * CGFloat(self.offsetPerPage) let deltaX = (CGFloat(differenceInTouchXAxis) / self.frame.width) * CGFloat(self.offsetPerPage) self.background.layer.frame = CGRect(x: x + deltaX, y: 0.0, width: self.background.layer.frame.width, height: self.background.layer.frame.height) } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) let differenceInTouchXAxis = difference(between: touches) switch differenceInTouchXAxis { case let x where x < -100: showView(withIndex: currentViewIndex + 1 >= views!.count ? currentViewIndex : currentViewIndex + 1, setCurrentPage: true) case let x where x > 100: showView(withIndex: currentViewIndex < 1 ? currentViewIndex : currentViewIndex - 1, setCurrentPage: true) default: showView(withIndex: currentViewIndex, setCurrentPage: false) } } private func difference(between touches: Set<UITouch>) -> Int { let movingPosition = touches.first?.location(in: self) return Int(movingPosition!.x - touchPosition!.x) } }
5f8cf439611812f5ceea74cb25374db7
37.237705
287
0.598499
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/SDK/Foundation/Measurement.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT import CoreFoundation #else @_exported import Foundation // Clang module import _SwiftCoreFoundationOverlayShims #endif /// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`. /// /// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable { public typealias ReferenceType = NSMeasurement /// The unit component of the `Measurement`. public let unit: UnitType /// The value component of the `Measurement`. public var value: Double /// Create a `Measurement` given a specified value and unit. public init(value: Double, unit: UnitType) { self.value = value self.unit = unit } public var hashValue: Int { return Int(bitPattern: __CFHashDouble(value)) } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { return "\(value) \(unit.symbol)" } public var debugDescription: String { return "\(value) \(unit.symbol)" } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "value", value: value)) c.append((label: "unit", value: unit.symbol)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } /// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension Measurement where UnitType : Dimension { /// Returns a new measurement created by converting to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. /// - returns: A converted measurement. public func converted(to otherUnit: UnitType) -> Measurement<UnitType> { if unit.isEqual(otherUnit) { return Measurement(value: value, unit: otherUnit) } else { let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value) if otherUnit.isEqual(type(of: unit).baseUnit()) { return Measurement(value: valueInTermsOfBase, unit: otherUnit) } else { let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase) return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit) } } } /// Converts the measurement to the specified unit. /// /// - parameter otherUnit: A unit of the same `Dimension`. public mutating func convert(to otherUnit: UnitType) { self = converted(to: otherUnit) } /// Add two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } /// Subtract two measurements of the same Dimension. /// /// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit. /// - returns: The result of adding the two measurements. public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit == rhs.unit { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value) return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit()) } } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension Measurement { /// Add two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`. public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value + rhs.value, unit: lhs.unit) } else { fatalError("Attempt to add measurements with non-equal units") } } /// Subtract two measurements of the same Unit. /// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`. /// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`. public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> { if lhs.unit.isEqual(rhs.unit) { return Measurement(value: lhs.value - rhs.value, unit: lhs.unit) } else { fatalError("Attempt to subtract measurements with non-equal units") } } /// Multiply a measurement by a scalar value. /// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`. public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value * rhs, unit: lhs.unit) } /// Multiply a scalar value by a measurement. /// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`. public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs * rhs.value, unit: rhs.unit) } /// Divide a measurement by a scalar value. /// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`. public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> { return Measurement(value: lhs.value / rhs, unit: lhs.unit) } /// Divide a scalar value by a measurement. /// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`. public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> { return Measurement(value: lhs / rhs.value, unit: rhs.unit) } /// Compare two measurements of the same `Dimension`. /// /// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values. /// - returns: `true` if the measurements are equal. public static func ==<LeftHandSideType, RightHandSideType>(_ lhs: Measurement<LeftHandSideType>, _ rhs: Measurement<RightHandSideType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value == rhs.value } else { if let lhsDimensionalUnit = lhs.unit as? Dimension, let rhsDimensionalUnit = rhs.unit as? Dimension { if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() { let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value) return lhsValueInTermsOfBase == rhsValueInTermsOfBase } } return false } } /// Compare two measurements of the same `Unit`. /// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value. public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool { if lhs.unit == rhs.unit { return lhs.value < rhs.value } else { if let lhsDimensionalUnit = lhs.unit as? Dimension, let rhsDimensionalUnit = rhs.unit as? Dimension { if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() { let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value) let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value) return lhsValueInTermsOfBase < rhsValueInTermsOfBase } } fatalError("Attempt to compare measurements with non-equal dimensions") } } } // Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types. #if DEPLOYMENT_RUNTIME_SWIFT internal typealias MeasurementBridgeType = _ObjectTypeBridgeable #else internal typealias MeasurementBridgeType = _ObjectiveCBridgeable #endif @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension Measurement : MeasurementBridgeType { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSMeasurement { return NSMeasurement(doubleValue: value, unit: unit) } public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) { result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType) } public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool { if let u = source.unit as? UnitType { result = Measurement(value: source.doubleValue, unit: u) return true } else { return false } } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement { let u = source!.unit as! UnitType return Measurement(value: source!.doubleValue, unit: u) } } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension NSMeasurement : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { #if DEPLOYMENT_RUNTIME_SWIFT return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self)) #else return AnyHashable(self as Measurement) #endif } } // This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639) @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension MeasurementFormatter { public func string<UnitType>(from measurement: Measurement<UnitType>) -> String { if let result = string(for: measurement) { return result } else { return "" } } } // @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) // extension Unit : Codable { // public convenience init(from decoder: Decoder) throws { // let container = try decoder.singleValueContainer() // let symbol = try container.decode(String.self) // self.init(symbol: symbol) // } // public func encode(to encoder: Encoder) throws { // var container = encoder.singleValueContainer() // try container.encode(self.symbol) // } // } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) extension Measurement : Codable { private enum CodingKeys : Int, CodingKey { case value case unit } private enum UnitCodingKeys : Int, CodingKey { case symbol case converter } private enum LinearConverterCodingKeys : Int, CodingKey { case coefficient case constant } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let value = try container.decode(Double.self, forKey: .value) let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit) let symbol = try unitContainer.decode(String.self, forKey: .symbol) let unit: UnitType if UnitType.self is Dimension.Type { let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter) let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient) let constant = try converterContainer.decode(Double.self, forKey: .constant) let unitMetaType = (UnitType.self as! Dimension.Type) unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType) } else { unit = UnitType(symbol: symbol) } self.init(value: value, unit: unit) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.value, forKey: .value) var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit) try unitContainer.encode(self.unit.symbol, forKey: .symbol) if UnitType.self is Dimension.Type { guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else { preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.") } let converter = (self.unit as! Dimension).converter as! UnitConverterLinear var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter) try converterContainer.encode(converter.coefficient, forKey: .coefficient) try converterContainer.encode(converter.constant, forKey: .constant) } } }
ff07c248ce6d9b53223d76416a777866
44.678571
280
0.660738
false
false
false
false
Ehrippura/firefox-ios
refs/heads/master
Client/Frontend/Settings/SettingsContentViewController.swift
mpl-2.0
9
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SnapKit import UIKit import WebKit let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild. private var TODOPageLoadErrorString = NSLocalizedString("Could not load page.", comment: "Error message that is shown in settings when there was a problem loading") /** * A controller that manages a single web view and provides a way for * the user to navigate back to Settings. */ class SettingsContentViewController: UIViewController, WKNavigationDelegate { let interstitialBackgroundColor: UIColor var settingsTitle: NSAttributedString? var url: URL! var timer: Timer? var isLoaded: Bool = false { didSet { if isLoaded { UIView.transition(from: interstitialView, to: webView, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, completion: { finished in self.interstitialView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } fileprivate var isError: Bool = false { didSet { if isError { interstitialErrorView.isHidden = false UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, completion: { finished in self.interstitialSpinnerView.removeFromSuperview() self.interstitialSpinnerView.stopAnimating() }) } } } // The view shown while the content is loading in the background web view. fileprivate var interstitialView: UIView! fileprivate var interstitialSpinnerView: UIActivityIndicatorView! fileprivate var interstitialErrorView: UILabel! // The web view that displays content. var webView: WKWebView! fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) { if self.isLoaded { return } if timeout > 0 { self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(SettingsContentViewController.SELdidTimeOut), userInfo: nil, repeats: false) } else { self.timer = nil } self.webView.load(URLRequest(url: url)) self.interstitialSpinnerView.startAnimating() } init(backgroundColor: UIColor = UIColor.white, title: NSAttributedString? = nil) { interstitialBackgroundColor = backgroundColor settingsTitle = title super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // This background agrees with the web page background. // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor self.webView = makeWebView() view.addSubview(webView) self.webView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } // Destructuring let causes problems. let ret = makeInterstitialViews() self.interstitialView = ret.0 self.interstitialSpinnerView = ret.1 self.interstitialErrorView = ret.2 view.addSubview(interstitialView) self.interstitialView.snp.remakeConstraints { make in make.edges.equalTo(self.view) } startLoading() } func makeWebView() -> WKWebView { let config = WKWebViewConfiguration() let webView = WKWebView( frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: config ) webView.allowsLinkPreview = false webView.navigationDelegate = self return webView } fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) { let view = UIView() // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = interstitialBackgroundColor let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) view.addSubview(spinner) let error = UILabel() if let _ = settingsTitle { error.text = TODOPageLoadErrorString error.textColor = UIColor.red // Firefox Orange! error.textAlignment = NSTextAlignment.center } error.isHidden = true view.addSubview(error) spinner.snp.makeConstraints { make in make.center.equalTo(view) return } error.snp.makeConstraints { make in make.center.equalTo(view) make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) return } return (view, spinner, error) } func SELdidTimeOut() { self.timer = nil self.isError = true } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // If this is a request to our local web server, use our private credentials. if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) { completionHandler(.useCredential, WebServer.sharedInstance.credentials) return } completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { SELdidTimeOut() } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { SELdidTimeOut() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.timer?.invalidate() self.timer = nil self.isLoaded = true } }
f8c224f31c53260505448970aa43919f
35.192308
182
0.64521
false
false
false
false
keitaito/HackuponApp
refs/heads/master
HackuponApp/ViewControllers/MainTableViewController.swift
mit
1
// // MainTableViewController.swift // HackuponApp // // Created by Keita Ito on 3/14/16. // Copyright © 2016 Keita Ito. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { // MARK: - Properties let url = NSURL(string: "http://localhost:3000/foos.json")! var peopleArray = [Person]() override func viewDidLoad() { super.viewDidLoad() // Download data from the server. NetworkClient.downloadDataWithURL(url) { (resultArray) -> Void in // resultsArray is of type Array<Person>. resultArray.forEach { self.peopleArray.append($0) } // Update UI from the main queue. dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 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 peopleArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MainTableViewCell // Configure the cell... let person = peopleArray[indexPath.row] cell.nameLabel.text = person.name cell.idLabel.text = String(person.id) return cell } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
ffa48be30b4cea97c8c00d1dbd35a2a2
30.820225
126
0.641243
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00085-swift-typechecker-typecheckpattern.swift
apache-2.0
11
// 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 // RUN: not %target-swift-frontend %s -parse func fe<on>() -> (on, on -> on) -> on { cb w cb.gf = { } { on) { > ji) -> ji in dc ih(on, s) } } func w(ed: (((ji, ji) -> ji) -> ji)) -> ji { dc ed({ (x: ji, h:ji) -> ji in dc x }) } w(fe(hg, fe(kj, lk))) t l { ml b } y ih<cb> { nm <l: l q l.b == cb>(x: l.b) { } } func fe<po : n>(w: po) { } fe(r qp n) x o = u rq: Int -> Int = { dc $sr } let k: Int = { (on: Int, fe: Int in dc fe(on) }(o, rq) let w: Int = { on, fe in dc fe(on) }(o, rq) func c(fe: v) -> <po>(() -> po) -> gf
bb620c41899359587664a8710edecee6
20.340909
78
0.529286
false
false
false
false
EZ-NET/CodePiece
refs/heads/Rev2
ESTwitter/API/APIError.swift
gpl-3.0
1
// // APIError.swift // ESTwitter // // Created by Tomohiro Kumagai on 2020/01/27. // Copyright © 2020 Tomohiro Kumagai. All rights reserved. // import Swifter public enum APIError : Error { case notReady case responseError(code: Int, message: String) case operationError(String) case offline(String) case unexpected(Error) } internal extension APIError { init(from error: SwifterError) { if case .urlResponseError = error.kind, let response = SwifterError.Response(fromMessage: error.message) { self = .responseError(code: response.code, message: response.message) } else { self = .unexpected(error) } } init(from error: NSError) { switch error.code { case -1009: self = .offline(error.localizedDescription) default: self = .unexpected(error) } } } extension APIError : CustomStringConvertible { public var description: String { switch self { case .notReady: return "API is not ready." case .responseError(_, let message): return message case .operationError(let message): return message case .offline(let message): return message case .unexpected(let error): return "Unexpected error: \(error)" } } }
0f515163ce69211ac728f391e32cdc9e
16.753623
108
0.680816
false
false
false
false
SearchDream/iOS-9-Sampler
refs/heads/master
iOS9Sampler/SampleViewControllers/QuickActionsViewController.swift
mit
2
// // QuickActionsViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 9/28/15. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import UIKit class QuickActionsViewController: UIViewController { @IBOutlet weak fileprivate var label: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if traitCollection.forceTouchCapability == UIForceTouchCapability.available { label.text = "Your device supports 3D Touch!" label.textColor = UIColor.green } else { label.text = "Your device does NOT support 3D Touch!" label.textColor = UIColor.red } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
621d59b18b2c0f552beecab123396ec8
25.029412
85
0.651977
false
false
false
false
inamiy/VTree
refs/heads/master
Sources/Message.swift
mit
1
/// Message protocol that `VTree` generates from Cocoa's events, /// then it dispatches corresponding **`AnyMsg`** via `Messenger`. /// /// - Note: /// Implementing `Message` will be a tedious work, /// so use https://github.com/krzysztofzablocki/Sourcery /// to assist code-generation for **`enum Msg` with associated values**. /// /// 1. Conform to `AutoMessage` protocol (instead of `Message`). /// 2. Run below script to automatically generate `extension Msg: Message`. /// /// ``` /// enum Msg: AutoMessage { case tap(GestureContext), longPress(GestureContext), ... } /// /// // Run script: /// // $ <VTree-root>/Scripts/generate-message.sh <source-dir> <code-generated-dir> /// ``` public protocol Message: MessageContext { init?(rawMessage: RawMessage) var rawMessage: RawMessage { get } } extension Message { public init?(rawArguments: [Any]) { var rawArguments = rawArguments guard let funcName = rawArguments.popLast() as? String else { return nil } self.init(rawMessage: RawMessage(funcName: funcName, arguments: rawArguments)) } public var rawArguments: [Any] { var arguments = self.rawMessage.arguments arguments.append(self.rawMessage.funcName) return arguments } } // MARK: RawMessage public struct RawMessage { public let funcName: String public let arguments: [Any] public init(funcName: String, arguments: [Any]) { self.funcName = funcName self.arguments = arguments } } // MARK: NoMsg /// "No message" type that conforms to `Message` protocol. public enum NoMsg: Message { public init?(rawMessage: RawMessage) { return nil } public var rawMessage: RawMessage { return RawMessage(funcName: "", arguments: []) } } // MARK: AnyMsg /// Type-erased `Message`. public struct AnyMsg: Message { private let _rawMessage: RawMessage public init<Msg: Message>(_ base: Msg) { self._rawMessage = base.rawMessage } public init?(rawMessage: RawMessage) { return nil } public var rawMessage: RawMessage { return self._rawMessage } } extension Message { /// Converts from `AnyMsg`. public init?(_ anyMsg: AnyMsg) { self.init(rawMessage: anyMsg.rawMessage) } }
473f64a7634f3626fd9352573f19e710
21.754902
86
0.64455
false
false
false
false
luanlzsn/pos
refs/heads/master
pos/pos_iphone/AppDelegate.swift
mit
1
// // AppDelegate.swift // pos_iphone // // Created by luan on 2017/5/14. // Copyright © 2017年 luan. All rights reserved. // import UIKit import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().barTintColor = UIColor.init(rgb: 0xe60a16) UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] IQKeyboardManager.sharedManager().enable = true IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true LanguageManager.setupCurrentLanguage() AntManage.iphonePostRequest(path: "route=feed/rest_api/gettoken&grant_type=client_credentials", params: nil, successResult: { (response) in if let data = response["data"] as? [String : Any] { if let accseeToken = data["access_token"] as? String { AntManage.iphoneToken = accseeToken } } }, failureResult: {}) Thread.detachNewThreadSelector(#selector(runOnNewThread), toTarget: self, with: nil) while AntManage.iphoneToken.isEmpty { RunLoop.current.run(mode: .defaultRunLoopMode, before: Date.distantFuture) } return true } func runOnNewThread() { sleep(1) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
7b46a49700e731cabeb58d42dddf6ca2
44.364865
285
0.711349
false
false
false
false
KieranWynn/piccolo
refs/heads/master
Piccolo/StatusItemView.swift
mit
1
// // StatusItemView.swift // Piccolo // // Created by Kieran Wynn on 14/11/2014. // Copyright (c) 2014 Kieran Wynn. All rights reserved. // //import Foundation //import AppKit // //class StatusItemView: NSControl { // // var _statusItem: NSStatusItem // // var _image: NSImage // var _alternateImage: NSImage // // var _rightAction = 0 // // var _leftMenu: NSMenu // var _rightMenu: NSMenu // // var _isMouseDown = false; // var _isMenuVisible = false; // // init() // { // _image = NSImage() // } // // init?(coder: NSCoder) { // code = coder // } // //}
a40cce687a0b944f9c751ed184a05978
17
56
0.535494
false
false
false
false
tiagomartinho/webhose-cocoa
refs/heads/master
webhose-cocoa/Webhose/WebhosePost+SwiftyJSON.swift
mit
1
import SwiftyJSON extension WebhosePost { init(json: JSON) { self.uuid = json["uuid"].stringValue self.url = URL(string: json["url"].stringValue)! self.published = Date.dateFromString(json["published"].stringValue) self.title = json["title"].stringValue self.orderInThread = json["ord_in_thread"].intValue self.author = json["author"].stringValue self.text = json["text"].stringValue self.highlightText = json["highlightText"].stringValue self.highlightTitle = json["highlightTitle"].stringValue self.language = json["language"].stringValue self.externalLinks = json["external_links"].arrayValue.map { $0.stringValue } self.persons = json["persons"].arrayValue.map { $0.stringValue } self.locations = json["locations"].arrayValue.map { $0.stringValue } self.organizations = json["organizations"].arrayValue.map { $0.stringValue } self.crawled = Date.dateFromString(json["crawled"].stringValue) self.thread = WebhoseThread(json: json["thread"]) } } extension WebhosePost { static func collection(_ json: JSON) -> [WebhosePost] { return json.map { WebhosePost(json: $1) } } }
2de66c3c8f0ea8d2a0a0faf0d0df2d43
42.857143
85
0.659609
false
false
false
false
pawel-sp/PSZCircularPicker
refs/heads/master
PSZCircularPicker/CollectionViewDragAndDropController.swift
mit
1
// // CollectionViewDragAndDropController.swift // PSZCircularPicker // // Created by Paweł Sporysz on 30.10.2014. // Copyright (c) 2014 Paweł Sporysz. All rights reserved. // import UIKit public class CollectionViewDragAndDropController:NSObject { // MARK: - Public properties public var delegate:CollectionViewDragAndDropControllerDelegate? // MARK: - Private properties private let pickerCollectionView:UICollectionView private let presenterCollectionView:UICollectionView private let containerView:UIView private struct Dragger { static var pickedView:UIView? static var locationInPickedView:CGPoint? static var pickedIndexPath:NSIndexPath? static func setupCell(cell:UICollectionViewCell, fromCollectionView collectionView:UICollectionView, toFrame frame:CGRect) { self.pickedIndexPath = collectionView.indexPathForCell(cell) cell.alpha = 1.0 self.pickedView = cell.snapshotViewAfterScreenUpdates(true) self.pickedView?.frame = frame } static func updatePickedViewOrigin(origin:CGPoint) { if let _pickedView = pickedView { if let _locationInPickedView = locationInPickedView { _pickedView.frame.origin = CGPointMake( origin.x - _locationInPickedView.x, origin.y - _locationInPickedView.y) } } } static func resetData() { pickedView = nil pickedIndexPath = nil locationInPickedView = nil } } // MARK: - Init public init(pickerCollectionView:UICollectionView, presenterCollectionView:UICollectionView, containerView:UIView) { self.pickerCollectionView = pickerCollectionView self.presenterCollectionView = presenterCollectionView self.containerView = containerView super.init() } // MARK: - Gestures public var dragAndDropLongPressGestureRecognizer:UILongPressGestureRecognizer { return UILongPressGestureRecognizer(target:self, action:Selector("dragAndDropGestureAction:")) } public func dragAndDropGestureAction(gestureRecognizer:UILongPressGestureRecognizer) { var gestureLocation = gestureRecognizer.locationInView(self.containerView) if let cell = gestureRecognizer.view as? UICollectionViewCell { switch gestureRecognizer.state { case .Began: Dragger.setupCell( cell, fromCollectionView: self.pickerCollectionView, toFrame: self.pickerCollectionView.convertRect(cell.frame, toView: self.containerView) ) Dragger.locationInPickedView = gestureRecognizer.locationInView(cell) self.containerView.addSubview(Dragger.pickedView!) self.delegate?.collectionViewDragAndDropController(self, pickingUpView: Dragger.pickedView!, fromCollectionViewIndexPath: Dragger.pickedIndexPath!) case .Changed: Dragger.updatePickedViewOrigin(gestureLocation) self.delegate?.collectionViewDragAndDropController(self, dragginView: Dragger.pickedView!, pickedInLocation: Dragger.locationInPickedView!) case .Ended: let targetLocation = self.containerView.convertPoint(gestureLocation, toView: self.presenterCollectionView) var targetIndexPath = self.presenterCollectionView.indexPathForItemAtPoint(targetLocation) if let delegate = self.delegate { delegate.collectionViewDragAndDropController( self, droppedView: Dragger.pickedView!, fromCollectionViewIndexPath: Dragger.pickedIndexPath!, toCollectionViewIndexPath: targetIndexPath!, isCanceled: !CGRectContainsPoint(self.presenterCollectionView.frame, gestureLocation)) } else { Dragger.pickedView?.removeFromSuperview() } default: break } } } }
68f7a55ed7922ab92a3ecc59dce217b9
41.798077
167
0.620085
false
false
false
false
uwinkler/commons
refs/heads/master
commons/NSData.swift
mit
1
// // NSData.swift // // Created by Ulrich Winkler on 19/01/2015. // Copyright (c) 2015 Ulrich Winkler. All rights reserved. // import Foundation public extension NSData { /// /// Converts "size" bytes at given location into an Int /// public func toInt (location:Int, size:Int) -> Int { let bytes = self.subdataWithRange(NSMakeRange(location,size)).bytes return UnsafePointer<Int>(bytes).memory } // // Converts the bytes to UInt8 Array // public func toUInt8Array () -> [UInt8] { var byteArray = [UInt8](count: self.length, repeatedValue: 0x0) self.getBytes(&byteArray, length:self.length) return byteArray } /// /// Returns a data object in 'nono' notation /// public var nono : String { get { return self.toUInt8Array().nono } } public func subdata(length:Int, andFill:UInt8) -> NSData { let l = min(self.length, length) var ret = self.subdataWithRange(NSMakeRange(0, l)).mutableCopy() as! NSMutableData var andFillRef = andFill let data = NSData(bytes: &andFillRef, length: sizeof(UInt8)) for var i = l; i < length; i = i + sizeof(UInt8) { ret.appendData(data) } return ret } }
b1417311cefe6ae181798fcb7e049796
22.2
90
0.557471
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/ChatModule/CWChatClient/MessageHandle/CWChatMessageHandle.swift
mit
2
// // CWChatMessageHandle.swift // CWWeChat // // Created by chenwei on 2017/3/30. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import XMPPFramework class CWChatMessageHandle: CWMessageHandle { override func handleMessage(message: XMPPMessage) -> Bool { if message.isChatMessageWithBody() { // 内容 来源 目标人 消息id guard let body = message.body(), let from = message.from().user, let to = message.to().user, let messageId = message.elementID() else { return false } //默认是文字 let bodyType = message.forName("body")?.attribute(forName: "msgtype")?.stringValue ?? "1" let bodyValue = Int(bodyType) ?? 1 var messageDate = Date() if message.wasDelayed() { messageDate = message.delayedDeliveryDate() } let type = CWMessageType(rawValue: bodyValue) ?? CWMessageType.none var messageBody: CWMessageBody! switch type { case .text: messageBody = CWTextMessageBody(text: body) case .image: messageBody = CWImageMessageBody() messageBody.messageDecode(string: body) default: break } let chatMessage = CWMessage(targetId: from, messageID: messageId, direction: .receive, timestamp: messageDate.timeIntervalSince1970, messageBody: messageBody) chatMessage.senderId = to self.delegate?.handMessageComplete(message: chatMessage) return true } return false } }
5759cbbb39e30944aa6a1a67a3fd030e
31.59322
101
0.50286
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Collections/CollectionFileCell.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 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 UIKit import WireDataModel import WireCommonComponents final class CollectionFileCell: CollectionCell { private var containerView = UIView() private let fileTransferView = FileTransferView() private let restrictionView = FileMessageRestrictionView() private let headerView = CollectionCellHeader() override func updateForMessage(changeInfo: MessageChangeInfo?) { super.updateForMessage(changeInfo: changeInfo) guard let message = self.message else { return } headerView.message = message if message.canBeShared { fileTransferView.delegate = self setup(fileTransferView) fileTransferView.configure(for: message, isInitial: changeInfo == .none) } else { setup(restrictionView) restrictionView.configure(for: message) } } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) loadView() } func loadView() { headerView.translatesAutoresizingMaskIntoConstraints = false containerView.translatesAutoresizingMaskIntoConstraints = false secureContentsView.addSubview(headerView) secureContentsView.addSubview(containerView) NSLayoutConstraint.activate([ // headerView headerView.topAnchor.constraint(equalTo: secureContentsView.topAnchor, constant: 16), headerView.leadingAnchor.constraint(equalTo: secureContentsView.leadingAnchor, constant: 16), headerView.trailingAnchor.constraint(equalTo: secureContentsView.trailingAnchor, constant: -16), // containerView containerView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 4), containerView.leadingAnchor.constraint(equalTo: secureContentsView.leadingAnchor), containerView.trailingAnchor.constraint(equalTo: secureContentsView.trailingAnchor), containerView.bottomAnchor.constraint(equalTo: secureContentsView.bottomAnchor) ]) } override var obfuscationIcon: StyleKitIcon { return .document } private func setup(_ view: UIView) { view.layer.cornerRadius = 4 view.clipsToBounds = true containerView.removeSubviews() containerView.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ view.topAnchor.constraint(equalTo: containerView.topAnchor), view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 4), view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -4), view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -4) ]) } } extension CollectionFileCell: TransferViewDelegate { func transferView(_ view: TransferView, didSelect action: MessageAction) { self.delegate?.collectionCell(self, performAction: action) } }
1ad4443e12b4585d4abfc9bb3d9107ae
35.819048
108
0.705122
false
false
false
false
zhenghuadong11/firstGitHub
refs/heads/master
旅游app_useSwift/旅游app_useSwift/MYEvaluationViewController.swift
apache-2.0
1
// // MYEvaluationViewController.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/27. // Copyright © 2016年 zhenghuadong. All rights reserved. // import UIKit class MYEvaluationViewController: UIViewController,MYImageEvvaluationViewControllerDelegate { weak var _viewController:UIViewController? var _num:String? var _evalutionIndex:Int? var _myPickerHaveModel:MYMYticketHaveModel? var _buttons:Array<UIButton> = Array<UIButton>() @IBOutlet weak var textView: UITextView! var _star:Int = 0 var imageNum = 0 override func viewDidLoad() { super.viewDidLoad() for var i1 in 0..<5 { var button = UIButton.init(type: UIButtonType.Custom) button.frame = CGRectMake(CGFloat(i1)*30+100, 80, 30, 30) button.setImage(UIImage.init(named: "hightLightStar"), forState: UIControlState.Selected) button.setImage(UIImage.init(named: "star_none"), forState: UIControlState.Normal) button.addTarget(self, action: #selector(buttonClick), forControlEvents: UIControlEvents.TouchUpInside) button.tag = i1 _buttons.append(button) self.view.addSubview(button) } } @IBAction func cancelButtonClick(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } func buttonClick(sender:UIButton) -> Void { for i1 in 0...sender.tag { _buttons[i1].selected = true } _star = sender.tag+1 if sender.tag+1 > 4 { return } for i1 in sender.tag+1...4 { _buttons[i1].selected = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func evaluationButotnClick(sender: AnyObject) { let path = NSBundle.mainBundle().pathForResource("myPickerHave", ofType: "plist") if let _ = path { var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> var dict = array![_evalutionIndex!] array?.removeAtIndex(_evalutionIndex!) dict["isEvaluation"] = "true" array?.append(dict) (array! as NSArray).writeToFile(path!, atomically: true) } let pathEvaluetion = NSBundle.mainBundle().pathForResource("evaluetion", ofType: "plist") if let _ = pathEvaluetion { var array = NSArray.init(contentsOfFile: pathEvaluetion!) as? Array<[String:AnyObject]> var index = 0 var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first path = path?.stringByAppendingString("/ImageFile/") var imageNames = Array<String>() for var view in self.textView.subviews { if view.isKindOfClass(MYImageView) { var imagePath = path let imageName = getCurrentTime()+index.description+rand().description imageNames.append(imageName) imagePath = imagePath?.stringByAppendingString(imageName) let imageView = (view as! UIImageView) print(imagePath) try? UIImagePNGRepresentation(imageView.image!)?.writeToFile(imagePath!, options: NSDataWritingOptions.AtomicWrite) index += 1 } } print(imageNames) let dict:[String:AnyObject] = ["num":_num!,"evalution":textView.text,"star":_star.description,"user":MYMineModel._shareMineModel.name!,"evalutionNum":(array?.count)!.description,"images":imageNames] array?.append(dict) (array! as NSArray).writeToFile(pathEvaluetion!, atomically: true) } self.dismissViewControllerAnimated(true) { (self._viewController as! MYMineShowTicketViewController).setUpmyTicketHaveModels() (self._viewController as! MYMineShowTicketViewController)._tableView?.reloadData() } } @IBAction func addPicktureClick(sender: AnyObject) { let headImageController = MYImageEvvaluationViewController() headImageController.delegate = self self.presentViewController(headImageController, animated: true, completion: nil) } @IBAction func cancelImageClick(sender: AnyObject) { if self.imageNum == 0 { return } self.textView.subviews.last?.removeFromSuperview() self.imageNum -= 1 } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { textView.resignFirstResponder() } func imageEvvaluationViewController(viewController: MYImageEvvaluationViewController, image: UIImage) { if self.imageNum == 8 { return } let imageView = MYImageView.init(image: image) self.textView.addSubview(imageView) self.imageNum += 1 } override func viewDidLayoutSubviews() { var index = 0 for var view in self.textView.subviews { if view.isKindOfClass(MYImageView) { let width = self.textView.frame.width/4 let height = self.textView.frame.height/4 view.frame = CGRectMake(CGFloat(index%4)*width,CGFloat(index/4+2)*height,width,height) index += 1 } } } }
a13794a5a5334c565db3a423fef23b65
35.451807
210
0.57098
false
false
false
false
LY-Coder/LYPlayer
refs/heads/master
LYPlayerExample/LYPlayer/LYProgressSlider.swift
mit
1
// // LYProgressSlider.swift // // Copyright © 2017年 ly_coder. All rights reserved. // // GitHub地址:https://github.com/LY-Coder/LYPlayer // import UIKit class LYProgressSlider: UIControl { // 判断是否触摸中 private var isTouching: Bool = false // 0 - 1 public var thumbImageValue: CGFloat = 0.0 // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) setupUI() setupUIFrame() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 缓冲条的颜色 */ public var bufferedProgressColor: UIColor! { willSet { bufferedView.backgroundColor = newValue } } /** 播放进度条的颜色 */ public var playProgressColor: UIColor! { willSet { playProgressView.backgroundColor = newValue } } /** 未缓冲出来的颜色 */ public var noBufferProgressColor: UIColor! { willSet { noBufferView.backgroundColor = newValue } } /** 视频缓冲进度 */ public var bufferedProgress: CGFloat = 0.0 { didSet { bufferedView.snp.updateConstraints { (make) in make.width.equalTo(bufferedProgress * frame.size.width) } } } /** 播放进度 */ public var playProgress: CGFloat = 0.0 { didSet { // 在拖动时停止赋值 if playProgress.isNaN || playProgress > 1.0 || isTouching { return } dragImageView.snp.updateConstraints({ (make) in make.centerX.equalTo(playProgress * frame.size.width) }) } } // MARK: - setter and getter // 播放进度视图 private lazy var playProgressView: UIView = { let playProgressView = UIView() playProgressView.backgroundColor = UIColor.red return playProgressView }() // 缓冲进度视图 private lazy var bufferedView: UIView = { let bufferedView = UIView() bufferedView.backgroundColor = UIColor.clear return bufferedView }() // 没有缓冲出来的部分 private lazy var noBufferView: UIView = { let noBufferView = UIView() noBufferView.backgroundColor = UIColor.white return noBufferView }() // 拖动的小圆点 lazy var dragImageView: UIImageView = { let dragImageView = UIImageView() dragImageView.image = UIImage(named: "dot") dragImageView.isUserInteractionEnabled = true dragImageView.backgroundColor = UIColor.white dragImageView.layer.cornerRadius = 7 return dragImageView }() // MARK: - private method fileprivate func setupUI() { addSubview(bufferedView) addSubview(noBufferView) addSubview(playProgressView) addSubview(dragImageView) } fileprivate func setupUIFrame() { dragImageView.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.centerX.equalTo(0) make.size.equalTo(CGSize(width: 14, height: 14)) } playProgressView.snp.makeConstraints { (make) in make.left.centerY.equalTo(self) make.right.equalTo(dragImageView.snp.centerX) make.height.equalTo(2) } bufferedView.snp.makeConstraints { (make) in make.left.centerY.equalTo(self) make.height.equalTo(2) make.width.equalTo(0) } noBufferView.snp.makeConstraints { (make) in make.centerY.right.equalTo(self) make.left.equalTo(dragImageView.snp.centerX) make.height.equalTo(2) } } // MARK: - event response // 开始点击 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) isTouching = true // for touch in touches { // let point = touch.location(in: self) // } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) isTouching = false } // 手指在移动 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) for touch in touches { // 获取当前位置 let point = touch.location(in: self) // 在小圆点内并且在self内时,设置当前进度 if point.x > 0 && point.x < frame.width { dragImageView.snp.updateConstraints({ (make) in make.centerX.equalTo(point.x) }) thumbImageValue = point.x / frame.width } } } }
c93befba511baab637133bb329c19761
26.293785
79
0.559925
false
false
false
false
debugsquad/nubecero
refs/heads/master
nubecero/Tests/Firebase/Database/Model/TFDatabaseModelUserSession.swift
mit
1
import XCTest @testable import nubecero class TFDatabaseModelUserSession:XCTestCase { private let kToken:String? = "ddsfkjfsjksd3324fd" private let kVersion:String = "312" private let kTtl:Int? = 134398765 private let kTimestamp:TimeInterval = 1344556 private let kEmpty:String = "" private let kNoTime:TimeInterval = 0 private let kNoTtl:Int = 0 func testInitTokenVersionTtl() { let initialStatus:MSession.Status = MSession.Status.active let currentTime:TimeInterval = NSDate().timeIntervalSince1970 let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue let keyToken:String = FDatabaseModelUserSession.Property.token.rawValue let keyVersion:String = FDatabaseModelUserSession.Property.version.rawValue let keyTimestamp:String = FDatabaseModelUserSession.Property.timestamp.rawValue let keyTtl:String = FDatabaseModelUserSession.Property.ttl.rawValue let model:FDatabaseModelUserSession = FDatabaseModelUserSession( token:kToken, version:kVersion, ttl:kTtl) XCTAssertEqual( model.token, kToken, "Error storing token") XCTAssertEqual( model.version, kVersion, "Error storing version") XCTAssertEqual( model.ttl, kTtl, "Error storing ttl") XCTAssertGreaterThanOrEqual( model.timestamp, currentTime, "Error timestamp should be greater or equal to starting time") XCTAssertEqual( model.status, initialStatus, "Error user should be acitve on creation") let modelJson:[String:Any]? = model.modelJson() as? [String:Any] XCTAssertNotNil( modelJson, "Error creating model json") let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int let jsonToken:String? = modelJson?[keyToken] as? String let jsonVersion:String? = modelJson?[keyVersion] as? String let jsonTimeStamp:TimeInterval? = modelJson?[keyTimestamp] as? TimeInterval let jsonTtl:Int? = modelJson?[keyTtl] as? Int XCTAssertNotNil( jsonStatusInt, "Error with status on json") let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!) XCTAssertEqual( initialStatus, jsonStatus, "Error with initial status on json") XCTAssertEqual( kToken, jsonToken, "Error with token on json") XCTAssertEqual( kVersion, jsonVersion, "Error with version on json") XCTAssertNotNil( jsonTimeStamp, "Error timestamp is nil") XCTAssertGreaterThanOrEqual( jsonTimeStamp!, currentTime, "Error with timestamp on json") XCTAssertEqual( kTtl, jsonTtl, "Error with ttl on json") } func testInitTokenNil() { let model:FDatabaseModelUserSession = FDatabaseModelUserSession( token:nil, version:kVersion, ttl:kTtl) XCTAssertEqual( model.token, kEmpty, "Error token should be empty") } func testInitTtlNil() { let model:FDatabaseModelUserSession = FDatabaseModelUserSession( token:kToken, version:kVersion, ttl:nil) XCTAssertEqual( model.ttl, kNoTtl, "Error ttl should be zero") } func testInitSnapshot() { let initialStatus:MSession.Status = MSession.Status.active let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue let keyToken:String = FDatabaseModelUserSession.Property.token.rawValue let keyVersion:String = FDatabaseModelUserSession.Property.version.rawValue let keyTimestamp:String = FDatabaseModelUserSession.Property.timestamp.rawValue let keyTtl:String = FDatabaseModelUserSession.Property.ttl.rawValue let snapshot:[String:Any] = [ keyStatus:initialStatus.rawValue, keyToken:kToken, keyVersion:kVersion, keyTimestamp:kTimestamp, keyTtl:kTtl ] let model:FDatabaseModelUserSession = FDatabaseModelUserSession( snapshot:snapshot) XCTAssertEqual( model.status, initialStatus, "Error storing status") XCTAssertEqual( model.token, kToken, "Error storing token") XCTAssertEqual( model.version, kVersion, "Error storing version") XCTAssertEqual( model.timestamp, kTimestamp, "Error storing timestamp") XCTAssertEqual( model.ttl, kTtl, "Error storing ttl") } func testInitSnapshotNil() { let snapshot:Any? = nil let model:FDatabaseModelUserSession = FDatabaseModelUserSession( snapshot:snapshot) XCTAssertEqual( model.status, MSession.Status.unknown, "Error default status") XCTAssertEqual( model.token, kEmpty, "Error default token") XCTAssertEqual( model.version, kEmpty, "Error default version") XCTAssertEqual( model.timestamp, kNoTime, "Error default timestamp") XCTAssertEqual( model.ttl, kNoTtl, "Error default ttl") } func testInitStatusActive() { let status:MSession.Status = MSession.Status.active let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue let snapshot:[String:Any] = [ keyStatus:status.rawValue, ] let model:FDatabaseModelUserSession = FDatabaseModelUserSession( snapshot:snapshot) XCTAssertEqual( model.status, status, "Error status active") let modelJson:[String:AnyObject]? = model.modelJson() as? [String:AnyObject] let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!) XCTAssertEqual( jsonStatus, status, "Error json status") } func testInitStatusBanned() { let status:MSession.Status = MSession.Status.banned let keyStatus:String = FDatabaseModelUserSession.Property.status.rawValue let snapshot:[String:Any] = [ keyStatus:status.rawValue, ] let model:FDatabaseModelUserSession = FDatabaseModelUserSession( snapshot:snapshot) XCTAssertEqual( model.status, status, "Error status banned") let modelJson:[String:AnyObject]? = model.modelJson() as? [String:AnyObject] let jsonStatusInt:Int? = modelJson?[keyStatus] as? Int let jsonStatus:MSession.Status? = MSession.Status(rawValue:jsonStatusInt!) XCTAssertEqual( jsonStatus, status, "Error json status") } }
2e3325ef863ae48956153a455fcf6549
28.753788
87
0.565627
false
false
false
false
mikina/SwiftNews
refs/heads/develop
SwiftNews/SwiftNews/Utils/Constants.swift
mit
1
// // Constants.swift // SwiftNews // // Created by Mike Mikina on 11/5/16. // Copyright © 2016 SwiftCookies.com. All rights reserved. // import Foundation struct Constants { struct TabBar { static let Height = 45 static let TopBorderColor = "#CECFD0" static let TopBorderHeight = 1 static let DefaultButtonColor = "#ABA5A6" static let DefaultSelectedButtonColor = "#4A4A4A" static let SpikeButtonColor = "#FFFFFF" static let SpikeSelectedButtonColor = "#F8E71C" } }
2a6e3b4a3bb07bb56e9d1b94f44ea62e
23.047619
59
0.69703
false
false
false
false
pseudomuto/Retired
refs/heads/master
Examples/Retired iOS Demo/Retired iOS Demo/AppDelegate.swift
mit
1
// // AppDelegate.swift // Retired iOS Demo // // Created by David Muto on 2016-04-01. // Copyright © 2016 pseudomuto. All rights reserved. // import Retired import UIKit // GET LINK FROM: https://linkmaker.itunes.apple.com/ let iTunesURL = NSURL(string: "itms-apps://geo.itunes.apple.com/us/app/popup-amazing-products-gift/id1057634612?mt=8")! let versionURL = NSURL(string: "http://localhost:8000/Versions.json")! let intervalBetweenRequests: NSTimeInterval = 60 * 60 * 24 // wait a day between requests (i.e. don't pester the user) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Retired.configure(versionURL, suppressionInterval: intervalBetweenRequests) return true } func applicationDidBecomeActive(application: UIApplication) { try! Retired.check() { updateRequired, message, error in guard updateRequired else { return } // handle error (non 200 status or network issue) if let message = message { message.presentInController(application.keyWindow?.rootViewController) } } } } extension Message { func presentInController(controller: UIViewController?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: continueButtonText, style: .Default, handler: goToAppStore)) if cancelButtonText != nil { alert.addAction(UIAlertAction(title: cancelButtonText, style: .Cancel, handler: nil)) } controller?.presentViewController(alert, animated: true, completion: nil) } private func goToAppStore(action: UIAlertAction) { UIApplication.sharedApplication().openURL(iTunesURL) } }
6c07c2c3878db8e81100db5a7ee9e46d
31.767857
125
0.73842
false
false
false
false
kumabook/FeedlyKit
refs/heads/master
Source/StreamsAPI.swift
mit
1
// // StreamsAPI.swift // FeedlyKit // // Created by Hiroki Kumamoto on 1/20/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import Alamofire import SwiftyJSON open class PaginationParams: ParameterEncodable { open var count: Int? open var ranked: String? open var unreadOnly: Bool? open var newerThan: Int64? open var continuation: String? public init() {} open func toParameters() -> [String : Any] { var params: [String:AnyObject] = [:] if let c = count { params["count"] = c as AnyObject? } if let r = ranked { params["ranked"] = r as AnyObject? } if let u = unreadOnly { params["unreadOnly"] = u ? "true" as AnyObject? : "false" as AnyObject? } if let n = newerThan { params["newerThan"] = NSNumber(value: n as Int64) } if let co = continuation { params["continuation"] = co as AnyObject? } return params } } open class PaginatedEntryCollection: ResponseObjectSerializable { open fileprivate(set) var id: String open fileprivate(set) var updated: Int64? open fileprivate(set) var continuation: String? open fileprivate(set) var title: String? open fileprivate(set) var direction: String? open fileprivate(set) var alternate: Link? open fileprivate(set) var items: [Entry] required public convenience init?(response: HTTPURLResponse, representation: Any) { self.init(json: JSON(representation)) } public init(json: JSON) { id = json["id"].stringValue updated = json["updated"].int64 continuation = json["continuation"].string title = json["title"].string direction = json["direction"].string alternate = json["alternate"].isEmpty ? nil : Link(json: json["alternate"]) items = json["items"].arrayValue.map({Entry(json: $0)}) } public init(id: String, updated: Int64?, continuation: String?, title: String?, direction: String?, alternate: Link?, items: [Entry]) { self.id = id self.updated = updated self.continuation = continuation self.title = title self.direction = direction self.alternate = alternate self.items = items } } open class PaginatedIdCollection: ResponseObjectSerializable { public let continuation: String? public let ids: [String] required public init?(response: HTTPURLResponse, representation: Any) { let json = JSON(representation) continuation = json["continuation"].string ids = json["ids"].arrayValue.map({ $0.stringValue }) } } extension CloudAPIClient { /** Get a list of entry ids for a specific stream GET /v3/streams/:streamId/ids or GET /v3/streams/ids?streamId=:streamId (Authorization is optional; it is required for category and tag streams) */ public func fetchEntryIds(_ streamId: String, paginationParams: PaginationParams, completionHandler: @escaping (DataResponse<PaginatedIdCollection>) -> Void) -> Request { return manager.request(Router.fetchEntryIds(target, streamId, paginationParams)) .validate() .responseObject(completionHandler: completionHandler) } /** Get the content of a stream GET /v3/streams/:streamId/contents or GET /v3/streams/contents?streamId=:streamId (Authorization is optional; it is required for category and tag streams) */ public func fetchContents(_ streamId: String, paginationParams: PaginationParams, completionHandler: @escaping (DataResponse<PaginatedEntryCollection>) -> Void) -> Request { return manager.request(Router.fetchContents(target, streamId, paginationParams)) .validate() .responseObject(completionHandler: completionHandler) } }
389b89c117fbbae0eff025c7443cd10d
39.316832
177
0.626228
false
false
false
false
icoderRo/SMAnimation
refs/heads/master
SMDemo/iOS-MVX/MVVM/TableView/MVVMController.swift
mit
2
// // MVVMController.swift // iOS-MVX // // Created by simon on 2017/3/2. // Copyright © 2017年 simon. All rights reserved. // import UIKit class MVVMController: UIViewController { fileprivate lazy var mvvmVM: MVVMVM = {return $0}(MVVMVM()) fileprivate lazy var tableView: UITableView = {[unowned self] in let tableView = UITableView(frame: self.view.bounds) tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = .yellow tableView.rowHeight = 70 tableView.register(UINib(nibName: "MVVMCell", bundle: nil), forCellReuseIdentifier: "cellId") return tableView }() override func viewDidLoad() { super.viewDidLoad() title = "MVVMTableView" view.addSubview(tableView) mvvmVM.loadData() mvvmVM.reloadData = {[weak self] in self?.tableView.reloadData() } } } extension MVVMController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mvvmVM.models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") mvvmVM.setCell(cell!, indexPath.row) return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
d34266c7ebbd0e0670d9e708f91061c7
27.203704
101
0.644123
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Effects/Distortion/Decimator/AKDecimator.swift
mit
1
// // AKDecimator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// AudioKit version of Apple's Decimator from the Distortion Audio Unit /// /// - parameter input: Input node to process /// - parameter decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - parameter rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0) /// - parameter mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1) /// public class AKDecimator: AKNode, AKToggleable { // MARK: - Properties private let cd = AudioComponentDescription( componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_Distortion, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) internal var internalEffect = AVAudioUnitEffect() internal var internalAU = AudioUnit() private var lastKnownMix: Double = 1 /// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) public var decimation: Double = 0.5 { didSet { if decimation < 0 { decimation = 0 } if decimation > 1 { decimation = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_Decimation, kAudioUnitScope_Global, 0, Float(decimation) * 100.0, 0) } } /// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0) public var rounding: Double = 0 { didSet { if rounding < 0 { rounding = 0 } if rounding > 1 { rounding = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_Rounding, kAudioUnitScope_Global, 0, Float(rounding) * 100.0, 0) } } /// Mix (Normalized Value) ranges from 0 to 1 (Default: 1) public var mix: Double = 1 { didSet { if mix < 0 { mix = 0 } if mix > 1 { mix = 1 } AudioUnitSetParameter( internalAU, kDistortionParam_FinalMix, kAudioUnitScope_Global, 0, Float(mix) * 100.0, 0) } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted = true // MARK: - Initialization /// Initialize the decimator node /// /// - parameter input: Input node to process /// - parameter decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5) /// - parameter rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0) /// - parameter mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1) /// public init( _ input: AKNode, decimation: Double = 0.5, rounding: Double = 0, mix: Double = 1) { self.decimation = decimation self.rounding = rounding self.mix = mix internalEffect = AVAudioUnitEffect(audioComponentDescription: cd) super.init() avAudioNode = internalEffect AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) internalAU = internalEffect.audioUnit // Since this is the Decimator, mix it to 100% and use the final mix as the mix parameter AudioUnitSetParameter(internalAU, kDistortionParam_DecimationMix, kAudioUnitScope_Global, 0, 100, 0) AudioUnitSetParameter(internalAU, kDistortionParam_Decimation, kAudioUnitScope_Global, 0, Float(decimation) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_Rounding, kAudioUnitScope_Global, 0, Float(rounding) * 100.0, 0) AudioUnitSetParameter(internalAU, kDistortionParam_FinalMix, kAudioUnitScope_Global, 0, Float(mix) * 100.0, 0) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { mix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownMix = mix mix = 0 isStarted = false } } }
9c8b16b8888c46869ee381a3833f741e
32.262411
131
0.570362
false
false
false
false
fabiomassimo/eidolon
refs/heads/master
KioskTests/App/SwiftExtensionsTests.swift
mit
1
import Quick import Nimble import Kiosk import ReactiveCocoa class SwiftExtensionsTests: QuickSpec { override func spec() { describe("String") { it("converts to UInt") { let input = "4" expect(input.toUInt()) == 4 } it("returns nil if no conversion is available") { let input = "not a number" expect(input.toUInt()).to( beNil() ) } it("uses a default if no conversion is available") { let input = "not a number" expect(input.toUInt(defaultValue: 4)) == 4 } } } }
a7fc0fd1d6e3925ee143ba4028b34a2b
25.32
64
0.49696
false
false
false
false
Ferrari-lee/firefox-ios
refs/heads/autocomplete-highlight
Storage/FileAccessor.swift
mpl-2.0
26
/* 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 /** * A convenience class for file operations under a given root directory. * Note that while this class is intended to be used to operate only on files * under the root, this is not strictly enforced: clients can go outside * the path using ".." or symlinks. */ public class FileAccessor { public let rootPath: NSString public init(rootPath: String) { self.rootPath = NSString(string:rootPath) } /** * Gets the absolute directory path at the given relative path, creating it if it does not exist. */ public func getAndEnsureDirectory(relativeDir: String? = nil) throws -> String { var absolutePath = rootPath if let relativeDir = relativeDir { absolutePath = absolutePath.stringByAppendingPathComponent(relativeDir) } let absPath = absolutePath as String try createDir(absPath) return absPath } /** * Gets the file or directory at the given path, relative to the root. */ public func remove(relativePath: String) throws { let path = rootPath.stringByAppendingPathComponent(relativePath) try NSFileManager.defaultManager().removeItemAtPath(path) } /** * Removes the contents of the directory without removing the directory itself. */ public func removeFilesInDirectory(relativePath: String = "") throws { let fileManager = NSFileManager.defaultManager() let path = rootPath.stringByAppendingPathComponent(relativePath) let files = try fileManager.contentsOfDirectoryAtPath(path) for file in files { try remove(NSString(string:relativePath).stringByAppendingPathComponent(file)) } return } /** * Determines whether a file exists at the given path, relative to the root. */ public func exists(relativePath: String) -> Bool { let path = rootPath.stringByAppendingPathComponent(relativePath) return NSFileManager.defaultManager().fileExistsAtPath(path) } /** * Moves the file or directory to the given destination, with both paths relative to the root. * The destination directory is created if it does not exist. */ public func move(fromRelativePath: String, toRelativePath: String) throws { let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath) let toPath = rootPath.stringByAppendingPathComponent(toRelativePath) as NSString let toDir = toPath.stringByDeletingLastPathComponent try createDir(toDir) try NSFileManager.defaultManager().moveItemAtPath(fromPath, toPath: toPath as String) } public func copy(fromRelativePath: String, toAbsolutePath: String) throws -> Bool { let fromPath = rootPath.stringByAppendingPathComponent(fromRelativePath) guard let dest = NSURL.fileURLWithPath(toAbsolutePath).URLByDeletingLastPathComponent?.path else { return false } try createDir(dest) try NSFileManager.defaultManager().copyItemAtPath(fromPath, toPath: toAbsolutePath) return true } /** * Creates a directory with the given path, including any intermediate directories. * Does nothing if the directory already exists. */ private func createDir(absolutePath: String) throws { try NSFileManager.defaultManager().createDirectoryAtPath(absolutePath, withIntermediateDirectories: true, attributes: nil) } }
15f164b927b318eb610103e592f2551d
37.789474
130
0.700678
false
false
false
false
algolia/algoliasearch-client-swift
refs/heads/master
Sources/AlgoliaSearchClient/Models/Search/MultipleIndex/BatchesResponse.swift
mit
1
// // BatchesResponse.swift // // // Created by Vladislav Fitc on 04/04/2020. // import Foundation public struct BatchesResponse { /// A list of TaskIndex to use with .waitAll. public let tasks: [IndexedTask] /// List of ObjectID affected by .multipleBatchObjects. public let objectIDs: [ObjectID?] } extension BatchesResponse { init(indexName: IndexName, responses: [BatchResponse]) { let tasks: [IndexedTask] = responses.map { .init(indexName: indexName, taskID: $0.taskID) } let objectIDs = responses.map(\.objectIDs).flatMap { $0 } self.init(tasks: tasks, objectIDs: objectIDs) } } extension BatchesResponse: Codable { enum CodingKeys: String, CodingKey { case tasks = "taskID" case objectIDs } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let rawTasks: [String: Int] = try container.decode(forKey: .tasks) self.tasks = rawTasks.map { rawIndexName, rawTaskID in IndexedTask(indexName: .init(rawValue: rawIndexName), taskID: .init(rawValue: String(rawTaskID))) } self.objectIDs = try container.decode(forKey: .objectIDs) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) let rawTasks = [String: String](uniqueKeysWithValues: tasks.map { ($0.indexName.rawValue, $0.taskID.rawValue) }) try container.encode(rawTasks, forKey: .tasks) try container.encode(objectIDs, forKey: .objectIDs) } }
eabf3611f8dcce75c3ada35317510209
28.54902
158
0.711347
false
false
false
false
benzguo/MusicKit
refs/heads/master
MusicKit/MIDIMessage.swift
mit
1
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation public protocol MIDIMessage { /// The message's channel var channel: UInt { get } /// Returns the MIDI packet data representation of this message func data() -> [UInt8] /// Returns a copy of this message on the given channel func copyOnChannel(_ channel: UInt) -> Self } public struct MIDINoteMessage: MIDIMessage { /// Note on: true, Note off: false public let on: Bool public let channel: UInt public let noteNumber: UInt public let velocity: UInt public init(on: Bool, channel: UInt = 0, noteNumber: UInt, velocity: UInt) { self.on = on self.channel = channel self.noteNumber = noteNumber self.velocity = velocity } public func data() -> [UInt8] { let messageType = self.on ? MKMIDIMessage.noteOn.rawValue : MKMIDIMessage.noteOff.rawValue let status = UInt8(messageType + UInt8(self.channel)) return [UInt8(status), UInt8(self.noteNumber), UInt8(self.velocity)] } public func copyOnChannel(_ channel: UInt) -> MIDINoteMessage { return MIDINoteMessage(on: on, channel: channel, noteNumber: noteNumber, velocity: velocity) } /// The message's pitch public var pitch: Pitch { return Pitch(midi: Float(noteNumber)) } /// Applies the given `Harmonizer` to the message. public func harmonize(_ harmonizer: Harmonizer) -> [MIDINoteMessage] { let ps = harmonizer(pitch) var messages = [MIDINoteMessage]() // TODO: add a PitchSet -> Array method so this can be mapped for p in ps { messages.append(MIDINoteMessage(on: self.on, channel: self.channel, noteNumber: UInt(p.midi), velocity: self.velocity)) } return messages } } extension MIDINoteMessage: CustomStringConvertible { public var description: String { let onString = on ? "On" : "Off" return "\(channel): Note \(onString): \(noteNumber) \(velocity)" } } extension MIDINoteMessage: Transposable { public func transpose(_ semitones: Float) -> MIDINoteMessage { return MIDINoteMessage(on: self.on, channel: self.channel, noteNumber: self.noteNumber + UInt(semitones), velocity: self.velocity) } }
75eb115e99a2b89e9f62c95900c0a929
31.569444
100
0.643923
false
false
false
false
codwam/NPB
refs/heads/master
Demos/NPBDemo/NPB/Private/NPBConstant.swift
mit
1
// // NPBConstant.swift // NPBDemo // // Created by 李辉 on 2017/4/8. // Copyright © 2017年 codwam. All rights reserved. // import Foundation /* 系统私有属性 */ // MARK: - UINavigationInteractiveTransition let _UINavigationInteractiveTransition = "_UINavigationInteractiveTransition" // 实际上就是 UINavigationController let _UINavigationInteractiveTransition_Parent = "__parent" // MARK: - UINavigationController let _UINavigationController_IsTransitioning = "_isTransitioning" let _UINavigationController_IsInteractiveTransition = "isInteractiveTransition" let _UINavigationController_IsBuiltinTransition = "isBuiltinTransition" // MARK: - interactivePopGestureRecognizer let _InteractivePopGestureRecognizer_Targets = "_targets" let _InteractivePopGestureRecognizer_HandleNavigationTransition = "handleNavigationTransition:" let _InteractivePopGestureRecognizer_CanPanVertically = "canPanVertically" // MARK: - UINavigationBar let _UINavigationBar_PopForTouchAtPoint = "_popForTouchAtPoint" let _UINavigationBar_BackgroundView = "_backgroundView" let NPB_NavigationBarHeight = 44.0 // MARK: - UIToolbar let _UIToolbar_ShadowView = "_shadowView" // MARK: - CALayer let kSnapshotLayerNameForTransition = "NPBNavigationExtensionSnapshotLayerName"
7a44925bb9c86dc6ca7f61881d99f436
23.230769
95
0.8
false
false
false
false
Adlai-Holler/BondPlusCoreData
refs/heads/master
BondPlusCoreDataTests/BondPlusCoreDataTests.swift
mit
2
import CoreData import Nimble import Quick import BondPlusCoreData import Bond import AlecrimCoreData class DataContext: Context { var stores: Table<Store> { return Table<Store>(context: self) } var items: Table<Item> { return Table<Item>(context: self) } } class NSFetchedResultsDynamicArraySpec: QuickSpec { override func spec() { var context: DataContext! var store: Store! var importMore: (() -> ())! beforeEach { let bundle = NSBundle(forClass: self.classForCoder) // create DB AlecrimCoreData.Config.modelBundle = bundle context = DataContext(stackType: .InMemory, managedObjectModelName: "BondPlusCoreDataTests", storeOptions: nil) // load seed let url = bundle.URLForResource("SeedData", withExtension: "json")! let file = NSInputStream(URL: url)! file.open() var parseError: NSError? let seedData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject] file.close() store = EKManagedObjectMapper.objectFromExternalRepresentation(seedData["store"]! as! [NSObject: AnyObject], withMapping: Store.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! Store context.managedObjectContext.processPendingChanges() importMore = { let url = bundle.URLForResource("MoreData", withExtension: "json")! let file = NSInputStream(URL: url)! file.open() var parseError: NSError? let moreData = NSJSONSerialization.JSONObjectWithStream(file, options: .allZeros, error: &parseError)! as! [String: AnyObject] file.close() let newItems = EKManagedObjectMapper.arrayOfObjectsFromExternalRepresentation(moreData["items"]! as! [[String: AnyObject]], withMapping: Item.objectMapping(), inManagedObjectContext: context.managedObjectContext) as! [Item] store.mutableSetValueForKey("items").addObjectsFromArray(newItems) context.managedObjectContext.processPendingChanges() } } describe("Test Import") { it("should load the store correctly") { expect(store.name).to(equal("Adlai's Grocery")) } it("should load store.items correctly") { expect(store.items.count).to(equal(6)) } it("should load item attributes correctly") { let anyItem = store.items.anyObject()! as! Item let expectedItemNames = Set(["Apple", "Banana", "Cherry", "Asparagus", "Broccoli", "Celery"]) let actualItemNames = Set(context.items.toArray().map { $0.name }) expect(actualItemNames).to(equal(expectedItemNames)) } } describe("Fetched Results Array") { var array: NSFetchedResultsDynamicArray<Item>! var sectionBond: ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>! beforeEach { let importantStore = context.stores.filterBy(attribute: "uuid", value: "2AB5041B-EF80-4910-8105-EC06B978C5DE").first()! let fr = context.items .filterBy(attribute: "store", value: importantStore) .sortBy("itemType", ascending: true) .thenByAscending("name") .toFetchRequest() let frc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context.managedObjectContext, sectionNameKeyPath: "itemType", cacheName: nil) array = NSFetchedResultsDynamicArray(fetchedResultsController: frc) sectionBond = ArrayBond() array ->> sectionBond } it("should report correct number of sections") { expect(array.count).to(equal(2)) } it("should handle deleting the last section correctly") { var removedSections = [Int]() sectionBond.willRemoveListener = {array, indices in removedSections += indices } context.items.filterBy(attribute: "itemType", value: "veggie").delete() context.managedObjectContext.processPendingChanges() expect(removedSections).to(equal([1])) expect(array.count).to(equal(1)) } it("should handle deleting all items correctly") { var removedSections = [Int]() sectionBond.willRemoveListener = {array, indices in removedSections += indices } context.items.delete() context.managedObjectContext.processPendingChanges() for item in context.items { println("item: \(item)") } expect(Set(removedSections)).to(equal(Set([0,1]))) expect(array.count).to(equal(0)) } it("should handle delete at 0,0 correctly") { let firstSectionBond = ArrayBond<Item>() var removedIndices = [Int]() firstSectionBond.willRemoveListener = { array, indices in removedIndices += indices } array[0] ->> firstSectionBond context.managedObjectContext.deleteObject(array[0][0]) context.managedObjectContext.processPendingChanges() expect(removedIndices).to(equal([0])) expect(array.count).to(equal(2)) expect(array[0].count).to(equal(2)) expect(array[0].first!.name).to(equal("Banana")) } it("should handle inserting many items (potentially out-of-order) correctly") { let firstSectionBond = ArrayBond<Item>() var insertedIndices = [Int]() println("Items: \(array[0].value)") firstSectionBond.willInsertListener = { array, indices in insertedIndices += indices } array[0] ->> firstSectionBond importMore() println("Items: \(array[0].value)") expect(insertedIndices).to(equal(Array(3...8))) } it("should handle update at 1,1 correctly") { let lastSectionBond = ArrayBond<Item>() var updatedIndices = [Int]() lastSectionBond.willUpdateListener = { array, indices in updatedIndices = indices } array[1] ->> lastSectionBond let item = array[1][1] item.count-- context.managedObjectContext.processPendingChanges() expect(updatedIndices).to(equal([1])) } it("should handle inserting a section at index 1 correctly") { let sectionsBond = ArrayBond<NSFetchedResultsSectionDynamicArray<Item>>() var insertedSections = [Int]() sectionsBond.willInsertListener = { array, indices in insertedSections += indices } array ->> sectionsBond let newItem = context.items.createEntity() newItem.uuid = NSUUID().UUIDString newItem.name = "Ground beef" newItem.count = 10 newItem.itemType = "meat" newItem.store = store context.managedObjectContext.processPendingChanges() expect(insertedSections).to(equal([1])) } } } }
f15369ea19d2db73a71652f44d985050
37.335196
231
0.644273
false
false
false
false
bananafish911/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Utils/ReportAssetsGenerator.swift
agpl-3.0
1
// // ReportAssetsGenerator.swift // SmartReceipts // // Created by Jaanus Siim on 06/06/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation private struct Generation { let fullPDF: Bool let imagesPDF: Bool let csv: Bool let imagesZip: Bool } class ReportAssetsGenerator: NSObject { // Generator's error representation enum GeneratorError { case fullPdfFailed // error in general case fullPdfTooManyColumns // can't place all PDF columns case imagesPdf case csvFailed case zipImagesFailed } fileprivate let trip: WBTrip fileprivate var generate: Generation! init(trip: WBTrip) { self.trip = trip } func setGenerated(_ fullPDF: Bool, imagesPDF: Bool, csv: Bool, imagesZip: Bool) { generate = Generation(fullPDF: fullPDF, imagesPDF: imagesPDF, csv: csv, imagesZip: imagesZip) Logger.info("setGenerated: \(generate)") } /// Generate reports /// /// - Parameter completion: [String] - array of resulting files (paths), GeneratorError - optional error func generate(onSuccessHandler: ([String]) -> (), onErrorHandler: (GeneratorError) -> ()) { var files = [String]() let db = Database.sharedInstance() trip.createDirectoryIfNotExists() let tripName = trip.name ?? "Report" let pdfPath = trip.file(inDirectoryPath: "\(tripName).pdf") let pdfImagesPath = trip.file(inDirectoryPath: "\(tripName)Images.pdf") let csvPath = trip.file(inDirectoryPath: "\(tripName).csv") let zipPath = trip.file(inDirectoryPath: "\(tripName).zip") if generate.fullPDF { Logger.info("generate.fullPDF") clearPath(pdfPath!) guard let generator = TripFullPDFGenerator(trip: trip, database: db) else { onErrorHandler(.fullPdfFailed) return } if generator.generate(toPath: pdfPath) { files.append(pdfPath!) } else { if generator.pdfRender.tableHasTooManyColumns { onErrorHandler(.fullPdfTooManyColumns) } else { onErrorHandler(.fullPdfFailed) } return } } if generate.imagesPDF { Logger.info("generate.imagesPDF") clearPath(pdfImagesPath!) guard let generator = TripImagesPDFGenerator(trip: trip, database:db) else { onErrorHandler(.imagesPdf) return } if generator.generate(toPath: pdfImagesPath) { files.append(pdfImagesPath!) } else { onErrorHandler(.imagesPdf) return } } if generate.csv { Logger.info("generate.csv") clearPath(csvPath!) guard let generator = TripCSVGenerator(trip: trip, database: db) else { onErrorHandler(.csvFailed) return } if generator.generate(toPath: csvPath) { files.append(csvPath!) } else { onErrorHandler(.csvFailed) return } } if generate.imagesZip { Logger.info("generate.imagesZip") clearPath(zipPath!) let rai = WBReceiptAndIndex.receiptsAndIndices(fromReceipts: db?.allReceipts(for: trip), filteredWith: { receipt in return WBReportUtils.filterOutReceipt(receipt) }) let stamper = WBImageStampler() if stamper.zip(toFile: zipPath, stampedImagesForReceiptsAndIndexes: rai, in: trip) { files.append(zipPath!) } else { onErrorHandler(.zipImagesFailed) return } } onSuccessHandler(files) } fileprivate func clearPath(_ path: String) { if !FileManager.default.fileExists(atPath: path) { return } do { try FileManager.default.removeItem(atPath: path) } catch let error as NSError { let errorEvent = ErrorEvent(error: error) AnalyticsManager.sharedManager.record(event: errorEvent) Logger.error("Remove file error \(error)") } } }
dd6667b5c56d62c37c79fd5ac4bd3c13
31.12766
128
0.553422
false
false
false
false
lhc70000/iina
refs/heads/develop
iina/MenuController.swift
gpl-3.0
1
// // MenuController.swift // iina // // Created by lhc on 31/8/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa fileprivate func sameKeyAction(_ lhs: [String], _ rhs: [String], _ normalizeLastNum: Bool, _ numRange: ClosedRange<Double>?) -> (Bool, Double?) { var lhs = lhs if lhs.first == "seek" && (lhs.last == "exact" || lhs.last == "keyframe") { lhs = [String](lhs.dropLast()) } guard lhs.count > 0 && lhs.count == rhs.count else { return (false, nil) } if normalizeLastNum { for i in 0..<lhs.count-1 { if lhs[i] != rhs[i] { return (false, nil) } } guard let ld = Double(lhs.last!), let rd = Double(rhs.last!) else { return (false, nil) } if let range = numRange { return (range.contains(ld), ld) } else { return (ld == rd, ld) } } else { for i in 0..<lhs.count { if lhs[i] != rhs[i] { return (false, nil) } } } return (true, nil) } class MenuController: NSObject, NSMenuDelegate { /** For convinent bindings. see `bind(...)` below. [menu: check state block] */ private var menuBindingList: [NSMenu: (NSMenuItem) -> Bool] = [:] private var stringForOpen: String! private var stringForOpenAlternative: String! private var stringForOpenURL: String! private var stringForOpenURLAlternative: String! // File @IBOutlet weak var fileMenu: NSMenu! @IBOutlet weak var open: NSMenuItem! @IBOutlet weak var openAlternative: NSMenuItem! @IBOutlet weak var openURL: NSMenuItem! @IBOutlet weak var openURLAlternative: NSMenuItem! @IBOutlet weak var savePlaylist: NSMenuItem! @IBOutlet weak var deleteCurrentFile: NSMenuItem! @IBOutlet weak var newWindow: NSMenuItem! @IBOutlet weak var newWindowSeparator: NSMenuItem! // Playback @IBOutlet weak var playbackMenu: NSMenu! @IBOutlet weak var pause: NSMenuItem! @IBOutlet weak var stop: NSMenuItem! @IBOutlet weak var forward: NSMenuItem! @IBOutlet weak var nextFrame: NSMenuItem! @IBOutlet weak var backward: NSMenuItem! @IBOutlet weak var previousFrame: NSMenuItem! @IBOutlet weak var jumpToBegin: NSMenuItem! @IBOutlet weak var jumpTo: NSMenuItem! @IBOutlet weak var speedIndicator: NSMenuItem! @IBOutlet weak var speedUp: NSMenuItem! @IBOutlet weak var speedUpSlightly: NSMenuItem! @IBOutlet weak var speedDown: NSMenuItem! @IBOutlet weak var speedDownSlightly: NSMenuItem! @IBOutlet weak var speedReset: NSMenuItem! @IBOutlet weak var screenshot: NSMenuItem! @IBOutlet weak var gotoScreenshotFolder: NSMenuItem! @IBOutlet weak var advancedScreenshot: NSMenuItem! @IBOutlet weak var abLoop: NSMenuItem! @IBOutlet weak var fileLoop: NSMenuItem! @IBOutlet weak var playlistPanel: NSMenuItem! @IBOutlet weak var playlist: NSMenuItem! @IBOutlet weak var playlistLoop: NSMenuItem! @IBOutlet weak var playlistMenu: NSMenu! @IBOutlet weak var nextMedia: NSMenuItem! @IBOutlet weak var previousMedia: NSMenuItem! @IBOutlet weak var chapterPanel: NSMenuItem! @IBOutlet weak var nextChapter: NSMenuItem! @IBOutlet weak var previousChapter: NSMenuItem! @IBOutlet weak var chapter: NSMenuItem! @IBOutlet weak var chapterMenu: NSMenu! // Video @IBOutlet weak var videoMenu: NSMenu! @IBOutlet weak var quickSettingsVideo: NSMenuItem! @IBOutlet weak var cycleVideoTracks: NSMenuItem! @IBOutlet weak var videoTrack: NSMenuItem! @IBOutlet weak var videoTrackMenu: NSMenu! @IBOutlet weak var halfSize: NSMenuItem! @IBOutlet weak var normalSize: NSMenuItem! @IBOutlet weak var normalSizeRetina: NSMenuItem! @IBOutlet weak var doubleSize: NSMenuItem! @IBOutlet weak var biggerSize: NSMenuItem! @IBOutlet weak var smallerSize: NSMenuItem! @IBOutlet weak var fitToScreen: NSMenuItem! @IBOutlet weak var fullScreen: NSMenuItem! @IBOutlet weak var pictureInPicture: NSMenuItem! @IBOutlet weak var alwaysOnTop: NSMenuItem! @IBOutlet weak var aspectMenu: NSMenu! @IBOutlet weak var cropMenu: NSMenu! @IBOutlet weak var rotationMenu: NSMenu! @IBOutlet weak var flipMenu: NSMenu! @IBOutlet weak var mirror: NSMenuItem! @IBOutlet weak var flip: NSMenuItem! @IBOutlet weak var deinterlace: NSMenuItem! @IBOutlet weak var delogo: NSMenuItem! @IBOutlet weak var videoFilters: NSMenuItem! @IBOutlet weak var savedVideoFiltersMenu: NSMenu! //Audio @IBOutlet weak var audioMenu: NSMenu! @IBOutlet weak var quickSettingsAudio: NSMenuItem! @IBOutlet weak var cycleAudioTracks: NSMenuItem! @IBOutlet weak var audioTrackMenu: NSMenu! @IBOutlet weak var volumeIndicator: NSMenuItem! @IBOutlet weak var increaseVolume: NSMenuItem! @IBOutlet weak var increaseVolumeSlightly: NSMenuItem! @IBOutlet weak var decreaseVolume: NSMenuItem! @IBOutlet weak var decreaseVolumeSlightly: NSMenuItem! @IBOutlet weak var mute: NSMenuItem! @IBOutlet weak var audioDelayIndicator: NSMenuItem! @IBOutlet weak var increaseAudioDelay: NSMenuItem! @IBOutlet weak var increaseAudioDelaySlightly: NSMenuItem! @IBOutlet weak var decreaseAudioDelay: NSMenuItem! @IBOutlet weak var decreaseAudioDelaySlightly: NSMenuItem! @IBOutlet weak var resetAudioDelay: NSMenuItem! @IBOutlet weak var audioFilters: NSMenuItem! @IBOutlet weak var audioDeviceMenu: NSMenu! @IBOutlet weak var savedAudioFiltersMenu: NSMenu! // Subtitle @IBOutlet weak var subMenu: NSMenu! @IBOutlet weak var quickSettingsSub: NSMenuItem! @IBOutlet weak var cycleSubtitles: NSMenuItem! @IBOutlet weak var subTrackMenu: NSMenu! @IBOutlet weak var secondSubTrackMenu: NSMenu! @IBOutlet weak var loadExternalSub: NSMenuItem! @IBOutlet weak var increaseTextSize: NSMenuItem! @IBOutlet weak var decreaseTextSize: NSMenuItem! @IBOutlet weak var resetTextSize: NSMenuItem! @IBOutlet weak var subDelayIndicator: NSMenuItem! @IBOutlet weak var increaseSubDelay: NSMenuItem! @IBOutlet weak var increaseSubDelaySlightly: NSMenuItem! @IBOutlet weak var decreaseSubDelay: NSMenuItem! @IBOutlet weak var decreaseSubDelaySlightly: NSMenuItem! @IBOutlet weak var resetSubDelay: NSMenuItem! @IBOutlet weak var encodingMenu: NSMenu! @IBOutlet weak var subFont: NSMenuItem! @IBOutlet weak var findOnlineSub: NSMenuItem! @IBOutlet weak var saveDownloadedSub: NSMenuItem! // Window @IBOutlet weak var customTouchBar: NSMenuItem! @IBOutlet weak var inspector: NSMenuItem! @IBOutlet weak var miniPlayer: NSMenuItem! // MARK: - Construct Menus func bindMenuItems() { [cycleSubtitles, cycleAudioTracks, cycleVideoTracks].forEach { item in item?.action = #selector(MainMenuActionHandler.menuCycleTrack(_:)) } // File menu fileMenu.delegate = self stringForOpen = open.title stringForOpenURL = openURL.title stringForOpenAlternative = openAlternative.title stringForOpenURLAlternative = openURLAlternative.title savePlaylist.action = #selector(MainMenuActionHandler.menuSavePlaylist(_:)) deleteCurrentFile.action = #selector(MainMenuActionHandler.menuDeleteCurrentFile(_:)) if Preference.bool(for: .enableCmdN) { newWindowSeparator.isHidden = false newWindow.isHidden = false } // Playback menu playbackMenu.delegate = self pause.action = #selector(MainMenuActionHandler.menuTogglePause(_:)) stop.action = #selector(MainMenuActionHandler.menuStop(_:)) // -- seeking forward.action = #selector(MainMenuActionHandler.menuStep(_:)) nextFrame.action = #selector(MainMenuActionHandler.menuStepFrame(_:)) backward.action = #selector(MainMenuActionHandler.menuStep(_:)) previousFrame.action = #selector(MainMenuActionHandler.menuStepFrame(_:)) jumpToBegin.action = #selector(MainMenuActionHandler.menuJumpToBegin(_:)) jumpTo.action = #selector(MainMenuActionHandler.menuJumpTo(_:)) // -- speed (speedUp.representedObject, speedUpSlightly.representedObject, speedDown.representedObject, speedDownSlightly.representedObject) = (2.0, 1.1, 0.5, 0.9) [speedUp, speedDown, speedUpSlightly, speedDownSlightly, speedReset].forEach { item in item?.action = #selector(MainMenuActionHandler.menuChangeSpeed(_:)) } // -- screenshot screenshot.action = #selector(MainMenuActionHandler.menuSnapshot(_:)) gotoScreenshotFolder.action = #selector(AppDelegate.menuOpenScreenshotFolder(_:)) // advancedScreenShot // -- list and chapter abLoop.action = #selector(MainMenuActionHandler.menuABLoop(_:)) fileLoop.action = #selector(MainMenuActionHandler.menuFileLoop(_:)) playlistMenu.delegate = self chapterMenu.delegate = self playlistLoop.action = #selector(MainMenuActionHandler.menuPlaylistLoop(_:)) playlistPanel.action = #selector(MainWindowController.menuShowPlaylistPanel(_:)) chapterPanel.action = #selector(MainWindowController.menuShowChaptersPanel(_:)) nextMedia.action = #selector(MainMenuActionHandler.menuNextMedia(_:)) previousMedia.action = #selector(MainMenuActionHandler.menuPreviousMedia(_:)) nextChapter.action = #selector(MainMenuActionHandler.menuNextChapter(_:)) previousChapter.action = #selector(MainMenuActionHandler.menuPreviousChapter(_:)) // Video menu videoMenu.delegate = self quickSettingsVideo.action = #selector(MainWindowController.menuShowVideoQuickSettings(_:)) videoTrackMenu.delegate = self // -- window size (halfSize.tag, normalSize.tag, normalSizeRetina.tag, doubleSize.tag, fitToScreen.tag, biggerSize.tag, smallerSize.tag) = (0, 1, -1, 2, 3, 11, 10) for item in [halfSize, normalSize, normalSizeRetina, doubleSize, fitToScreen, biggerSize, smallerSize] { item?.action = #selector(MainWindowController.menuChangeWindowSize(_:)) } // -- screen fullScreen.action = #selector(MainWindowController.menuToggleFullScreen(_:)) if #available(macOS 10.12, *) { pictureInPicture.action = #selector(MainWindowController.menuTogglePIP(_:)) } else { videoMenu.removeItem(pictureInPicture) } alwaysOnTop.action = #selector(MainWindowController.menuAlwaysOnTop(_:)) // -- aspect var aspectList = AppData.aspects // we need to set the represented object separately, since `Constants.String.default` may be localized. var aspectListObject = AppData.aspects aspectList.insert(Constants.String.default, at: 0) aspectListObject.insert("Default", at: 0) bind(menu: aspectMenu, withOptions: aspectList, objects: aspectListObject, objectMap: nil, action: #selector(MainMenuActionHandler.menuChangeAspect(_:))) { PlayerCore.active.info.unsureAspect == $0.representedObject as? String } // -- crop var cropList = AppData.aspects // same as aspectList above. var cropListForObject = AppData.aspects cropList.insert(Constants.String.none, at: 0) cropListForObject.insert("None", at: 0) bind(menu: cropMenu, withOptions: cropList, objects: cropListForObject, objectMap: nil, action: #selector(MainMenuActionHandler.menuChangeCrop(_:))) { return PlayerCore.active.info.unsureCrop == $0.representedObject as? String } // -- rotation let rotationTitles = AppData.rotations.map { "\($0)\(Constants.String.degree)" } bind(menu: rotationMenu, withOptions: rotationTitles, objects: AppData.rotations, objectMap: nil, action: #selector(MainMenuActionHandler.menuChangeRotation(_:))) { PlayerCore.active.info.rotation == $0.representedObject as? Int } // -- flip and mirror flipMenu.delegate = self flip.action = #selector(MainMenuActionHandler.menuToggleFlip(_:)) mirror.action = #selector(MainMenuActionHandler.menuToggleMirror(_:)) // -- deinterlace deinterlace.action = #selector(MainMenuActionHandler.menuToggleDeinterlace(_:)) // -- delogo delogo.action = #selector(MainWindowController.menuSetDelogo(_:)) // -- filter videoFilters.action = #selector(AppDelegate.showVideoFilterWindow(_:)) savedVideoFiltersMenu.delegate = self updateSavedFilters(forType: MPVProperty.vf, from: Preference.array(for: .savedVideoFilters)?.compactMap(SavedFilter.init(dict:)) ?? []) // Audio menu audioMenu.delegate = self quickSettingsAudio.action = #selector(MainWindowController.menuShowAudioQuickSettings(_:)) audioTrackMenu.delegate = self // - volume (increaseVolume.representedObject, decreaseVolume.representedObject, increaseVolumeSlightly.representedObject, decreaseVolumeSlightly.representedObject) = (5, -5, 1, -1) [increaseVolume, decreaseVolume, increaseVolumeSlightly, decreaseVolumeSlightly].forEach { item in item?.action = #selector(MainMenuActionHandler.menuChangeVolume(_:)) } mute.action = #selector(MainMenuActionHandler.menuToggleMute(_:)) // - audio delay (increaseAudioDelay.representedObject, increaseAudioDelaySlightly.representedObject, decreaseAudioDelay.representedObject, decreaseAudioDelaySlightly.representedObject) = (0.5, 0.1, -0.5, -0.1) [increaseAudioDelay, decreaseAudioDelay, increaseAudioDelaySlightly, decreaseAudioDelaySlightly].forEach { item in item?.action = #selector(MainMenuActionHandler.menuChangeAudioDelay(_:)) } resetAudioDelay.action = #selector(MainMenuActionHandler.menuResetAudioDelay(_:)) // - audio device audioDeviceMenu.delegate = self // - filters audioFilters.action = #selector(AppDelegate.showAudioFilterWindow(_:)) savedAudioFiltersMenu.delegate = self updateSavedFilters(forType: MPVProperty.af, from: Preference.array(for: .savedAudioFilters)?.compactMap(SavedFilter.init(dict:)) ?? []) // Subtitle subMenu.delegate = self quickSettingsSub.action = #selector(MainWindowController.menuShowSubQuickSettings(_:)) loadExternalSub.action = #selector(MainMenuActionHandler.menuLoadExternalSub(_:)) subTrackMenu.delegate = self secondSubTrackMenu.delegate = self findOnlineSub.action = #selector(MainMenuActionHandler.menuFindOnlineSub(_:)) saveDownloadedSub.action = #selector(MainMenuActionHandler.saveDownloadedSub(_:)) // - text size [increaseTextSize, decreaseTextSize, resetTextSize].forEach { $0.action = #selector(MainMenuActionHandler.menuChangeSubScale(_:)) } // - delay (increaseSubDelay.representedObject, increaseSubDelaySlightly.representedObject, decreaseSubDelay.representedObject, decreaseSubDelaySlightly.representedObject) = (0.5, 0.1, -0.5, -0.1) [increaseSubDelay, decreaseSubDelay, increaseSubDelaySlightly, decreaseSubDelaySlightly].forEach { item in item?.action = #selector(MainMenuActionHandler.menuChangeSubDelay(_:)) } resetSubDelay.action = #selector(MainMenuActionHandler.menuResetSubDelay(_:)) // encoding let encodingTitles = AppData.encodings.map { $0.title } let encodingObjects = AppData.encodings.map { $0.code } bind(menu: encodingMenu, withOptions: encodingTitles, objects: encodingObjects, objectMap: nil, action: #selector(MainMenuActionHandler.menuSetSubEncoding(_:))) { PlayerCore.active.info.subEncoding == $0.representedObject as? String } subFont.action = #selector(MainMenuActionHandler.menuSubFont(_:)) // Separate Auto from other encoding types encodingMenu.insertItem(NSMenuItem.separator(), at: 1) // Window if #available(macOS 10.12.2, *) { customTouchBar.action = #selector(NSApplication.toggleTouchBarCustomizationPalette(_:)) } else { customTouchBar.isHidden = true } inspector.action = #selector(MainMenuActionHandler.menuShowInspector(_:)) miniPlayer.action = #selector(MainWindowController.menuSwitchToMiniPlayer(_:)) } // MARK: - Update Menus private func updatePlaylist() { playlistMenu.removeAllItems() for (index, item) in PlayerCore.active.info.playlist.enumerated() { playlistMenu.addItem(withTitle: item.filenameForDisplay, action: #selector(MainMenuActionHandler.menuPlaylistItem(_:)), tag: index, obj: nil, stateOn: item.isCurrent) } } private func updateChapterList() { chapterMenu.removeAllItems() let info = PlayerCore.active.info for (index, chapter) in info.chapters.enumerated() { let menuTitle = "\(chapter.time.stringRepresentation) - \(chapter.title)" let nextChapterTime = info.chapters[at: index+1]?.time ?? Constants.Time.infinite let isPlaying = info.videoPosition?.between(chapter.time, nextChapterTime) ?? false chapterMenu.addItem(withTitle: menuTitle, action: #selector(MainMenuActionHandler.menuChapterSwitch(_:)), tag: index, obj: nil, stateOn: isPlaying) } } private func updateTracks(forMenu menu: NSMenu, type: MPVTrack.TrackType) { let info = PlayerCore.active.info menu.removeAllItems() let noTrackMenuItem = NSMenuItem(title: Constants.String.trackNone, action: #selector(MainMenuActionHandler.menuChangeTrack(_:)), keyEquivalent: "") noTrackMenuItem.representedObject = MPVTrack.emptyTrack(for: type) if info.trackId(type) == 0 { // no track noTrackMenuItem.state = .on } menu.addItem(noTrackMenuItem) for track in info.trackList(type) { menu.addItem(withTitle: track.readableTitle, action: #selector(MainMenuActionHandler.menuChangeTrack(_:)), tag: nil, obj: (track, type), stateOn: track.id == info.trackId(type)) } } private func updatePlaybackMenu() { let player = PlayerCore.active pause.title = player.info.isPaused ? Constants.String.resume : Constants.String.pause let isLoop = player.mpv.getFlag(MPVOption.PlaybackControl.loopFile) fileLoop.state = isLoop ? .on : .off let isPlaylistLoop = player.mpv.getString(MPVOption.PlaybackControl.loopPlaylist) playlistLoop.state = (isPlaylistLoop == "inf" || isPlaylistLoop == "force") ? .on : .off speedIndicator.title = String(format: NSLocalizedString("menu.speed", comment: "Speed:"), player.info.playSpeed) } private func updateVideoMenu() { let isInFullScreen = PlayerCore.active.mainWindow.fsState.isFullscreen let isInPIP = PlayerCore.active.mainWindow.pipStatus == .inPIP let isOntop = PlayerCore.active.isInMiniPlayer ? PlayerCore.active.miniPlayer.isOntop : PlayerCore.active.mainWindow.isOntop let isDelogo = PlayerCore.active.info.delogoFilter != nil alwaysOnTop.state = isOntop ? .on : .off deinterlace.state = PlayerCore.active.info.deinterlace ? .on : .off fullScreen.title = isInFullScreen ? Constants.String.exitFullScreen : Constants.String.fullScreen pictureInPicture?.title = isInPIP ? Constants.String.exitPIP : Constants.String.pip delogo.state = isDelogo ? .on : .off } private func updateAudioMenu() { let player = PlayerCore.active volumeIndicator.title = String(format: NSLocalizedString("menu.volume", comment: "Volume:"), Int(player.info.volume)) audioDelayIndicator.title = String(format: NSLocalizedString("menu.audio_delay", comment: "Audio Delay:"), player.info.audioDelay) } private func updateAudioDevice() { let devices = PlayerCore.active.getAudioDevices() let currAudioDevice = PlayerCore.active.mpv.getString(MPVProperty.audioDevice) audioDeviceMenu.removeAllItems() devices.forEach { d in let name = d["name"]! let desc = d["description"]! audioDeviceMenu.addItem(withTitle: "[\(desc)] \(name)", action: #selector(AppDelegate.menuSelectAudioDevice(_:)), tag: nil, obj: name, stateOn: name == currAudioDevice) } } private func updateFlipAndMirror() { let info = PlayerCore.active.info flip.state = info.flipFilter == nil ? .off : .on mirror.state = info.mirrorFilter == nil ? .off : .on } private func updateSubMenu() { let player = PlayerCore.active subDelayIndicator.title = String(format: NSLocalizedString("menu.sub_delay", comment: "Subtitle Delay:"), player.info.subDelay) let encodingCode = player.info.subEncoding ?? "auto" for encoding in AppData.encodings { if encoding.code == encodingCode { encodingMenu.item(withTitle: encoding.title)?.state = .on } } } func updateSavedFiltersMenu(type: String) { let filters = PlayerCore.active.mpv.getFilters(type) let menu: NSMenu! = type == MPVProperty.vf ? savedVideoFiltersMenu : savedAudioFiltersMenu for item in menu.items { if let string = (item.representedObject as? String) { item.state = filters.contains { $0.stringFormat == string } ? .on : .off } } } /** Bind a menu with a list of available options. - parameter menu: the NSMenu - parameter withOptions: option titles for each menu item, as an array - parameter objects: objects that will be bind to each menu item, as an array - parameter objectMap: alternatively, can pass a map like [title: object] - parameter action: the action for each menu item - parameter checkStateBlock: a block to set each menu item's state */ private func bind(menu: NSMenu, withOptions titles: [String]?, objects: [Any?]?, objectMap: [String: Any?]?, action: Selector?, checkStateBlock block: @escaping (NSMenuItem) -> Bool) { // if use title if let titles = titles { // options and objects must be same guard objects == nil || titles.count == objects?.count else { Logger.log("different object count when binding menu", level: .error) return } // add menu items for (index, title) in titles.enumerated() { let menuItem = NSMenuItem(title: title, action: action, keyEquivalent: "") if let object = objects?[index] { menuItem.representedObject = object } else { menuItem.representedObject = title } menu.addItem(menuItem) } } // if use map if let objectMap = objectMap { for (title, obj) in objectMap { let menuItem = NSMenuItem(title: title, action: action, keyEquivalent: "") menuItem.representedObject = obj menu.addItem(menuItem) } } // add to list menu.delegate = self menuBindingList.updateValue(block, forKey: menu) } private func updateOpenMenuItems() { if PlayerCore.playing.count == 0 { open.title = stringForOpen openAlternative.title = stringForOpen openURL.title = stringForOpenURL openURLAlternative.title = stringForOpenURL } else { if Preference.bool(for: .alwaysOpenInNewWindow) { open.title = stringForOpenAlternative openAlternative.title = stringForOpen openURL.title = stringForOpenURLAlternative openURLAlternative.title = stringForOpenURL } else { open.title = stringForOpen openAlternative.title = stringForOpenAlternative openURL.title = stringForOpenURL openURLAlternative.title = stringForOpenURLAlternative } } } // MARK: - Menu delegate func menuWillOpen(_ menu: NSMenu) { if menu == fileMenu { updateOpenMenuItems() } else if menu == playlistMenu { updatePlaylist() } else if menu == chapterMenu { updateChapterList() } else if menu == playbackMenu { updatePlaybackMenu() } else if menu == videoMenu { updateVideoMenu() } else if menu == videoTrackMenu { updateTracks(forMenu: menu, type: .video) } else if menu == flipMenu { updateFlipAndMirror() } else if menu == audioMenu { updateAudioMenu() } else if menu == audioTrackMenu { updateTracks(forMenu: menu, type: .audio) } else if menu == audioDeviceMenu { updateAudioDevice() } else if menu == subMenu { updateSubMenu() } else if menu == subTrackMenu { updateTracks(forMenu: menu, type: .sub) } else if menu == secondSubTrackMenu { updateTracks(forMenu: menu, type: .secondSub) } else if menu == savedVideoFiltersMenu { updateSavedFiltersMenu(type: MPVProperty.vf) } else if menu == savedAudioFiltersMenu { updateSavedFiltersMenu(type: MPVProperty.af) } // check convinently binded menus if let checkEnableBlock = menuBindingList[menu] { for item in menu.items { item.state = checkEnableBlock(item) ? .on : .off } } } // MARK: - Others func updateSavedFilters(forType type: String, from filters: [SavedFilter]) { let isVideo = type == MPVProperty.vf let menu: NSMenu! = isVideo ? savedVideoFiltersMenu : savedAudioFiltersMenu menu.removeAllItems() for filter in filters { let menuItem = NSMenuItem() menuItem.title = filter.name menuItem.action = isVideo ? #selector(MainWindowController.menuToggleVideoFilterString(_:)) : #selector(MainWindowController.menuToggleAudioFilterString(_:)) menuItem.keyEquivalent = filter.shortcutKey menuItem.keyEquivalentModifierMask = filter.shortcutKeyModifiers menuItem.representedObject = filter.filterString menu.addItem(menuItem) } } func updateKeyEquivalentsFrom(_ keyBindings: [KeyMapping]) { var settings: [(NSMenuItem, Bool, [String], Bool, ClosedRange<Double>?, String?)] = [ (deleteCurrentFile, true, ["delete-current-file"], false, nil, nil), (savePlaylist, true, ["save-playlist"], false, nil, nil), (quickSettingsVideo, true, ["video-panel"], false, nil, nil), (quickSettingsAudio, true, ["audio-panel"], false, nil, nil), (quickSettingsSub, true, ["sub-panel"], false, nil, nil), (playlistPanel, true, ["playlist-panel"], false, nil, nil), (chapterPanel, true, ["chapter-panel"], false, nil, nil), (findOnlineSub, true, ["find-online-subs"], false, nil, nil), (saveDownloadedSub, true, ["save-downloaded-sub"], false, nil, nil), (biggerSize, true, ["bigger-window"], false, nil, nil), (smallerSize, true, ["smaller-window"], false, nil, nil), (fitToScreen, true, ["fit-to-screen"], false, nil, nil), (miniPlayer, true, ["toggle-music-mode"], false, nil, nil), (cycleVideoTracks, false, ["cycle", "video"], false, nil, nil), (cycleAudioTracks, false, ["cycle", "audio"], false, nil, nil), (cycleSubtitles, false, ["cycle", "sub"], false, nil, nil), (nextChapter, false, ["add", "chapter", "1"], false, nil, nil), (previousChapter, false, ["add", "chapter", "-1"], false, nil, nil), (pause, false, ["cycle", "pause"], false, nil, nil), (stop, false, ["stop"], false, nil, nil), (forward, false, ["seek", "5"], true, 5.0...10.0, "seek_forward"), (backward, false, ["seek", "-5"], true, -10.0...(-5.0), "seek_backward"), (nextFrame, false, ["frame-step"], false, nil, nil), (previousFrame, false, ["frame-back-step"], false, nil, nil), (nextMedia, false, ["playlist-next"], false, nil, nil), (previousMedia, false, ["playlist-prev"], false, nil, nil), (speedUp, false, ["multiply", "speed", "2.0"], true, 1.5...3.0, "speed_up"), (speedUpSlightly, false, ["multiply", "speed", "1.1"], true, 1.01...1.49, "speed_up"), (speedDown, false, ["multiply", "speed", "0.5"], true, 0...0.7, "speed_down"), (speedDownSlightly, false, ["multiply", "speed", "0.9"], true, 0.71...0.99, "speed_down"), (speedReset, false, ["set", "speed", "1.0"], true, nil, nil), (abLoop, false, ["ab-loop"], false, nil, nil), (fileLoop, false, ["cycle-values", "loop", "\"inf\"", "\"no\""], false, nil, nil), (screenshot, false, ["screenshot"], false, nil, nil), (halfSize, false, ["set", "window-scale", "0.5"], true, nil, nil), (normalSize, false, ["set", "window-scale", "1"], true, nil, nil), (doubleSize, false, ["set", "window-scale", "2"], true, nil, nil), (fullScreen, false, ["cycle", "fullscreen"], false, nil, nil), (alwaysOnTop, false, ["cycle", "ontop"], false, nil, nil), (mute, false, ["cycle", "mute"], false, nil, nil), (increaseVolume, false, ["add", "volume", "5"], true, 5.0...10.0, "volume_up"), (decreaseVolume, false, ["add", "volume", "-5"], true, -10.0...(-5.0), "volume_down"), (increaseVolumeSlightly, false, ["add", "volume", "1"], true, 1.0...2.0, "volume_up"), (decreaseVolumeSlightly, false, ["add", "volume", "-1"], true, -2.0...(-1.0), "volume_down"), (decreaseAudioDelay, false, ["add", "audio-delay", "-0.5"], true, nil, "audio_delay_down"), (decreaseAudioDelaySlightly, false, ["add", "audio-delay", "-0.1"], true, nil, "audio_delay_down"), (increaseAudioDelay, false, ["add", "audio-delay", "0.5"], true, nil, "audio_delay_up"), (increaseAudioDelaySlightly, false, ["add", "audio-delay", "0.1"], true, nil, "audio_delay_up"), (resetAudioDelay, false, ["set", "audio-delay", "0"], true, nil, nil), (decreaseSubDelay, false, ["add", "sub-delay", "-0.5"], true, nil, "sub_delay_down"), (decreaseSubDelaySlightly, false, ["add", "sub-delay", "-0.1"], true, nil, "sub_delay_down"), (increaseSubDelay, false, ["add", "sub-delay", "0.5"], true, nil, "sub_delay_up"), (increaseSubDelaySlightly, false, ["add", "sub-delay", "0.1"], true, nil, "sub_delay_up"), (resetSubDelay, false, ["set", "sub-delay", "0"], true, nil, nil), (increaseTextSize, false, ["multiply", "sub-scale", "1.1"], true, 1.01...1.49, nil), (decreaseTextSize, false, ["multiply", "sub-scale", "0.9"], true, 0.71...0.99, nil), (resetTextSize, false, ["set", "sub-scale", "1"], true, nil, nil), (alwaysOnTop, false, ["cycle", "ontop"], false, nil, nil), (fullScreen, false, ["cycle", "fullscreen"], false, nil, nil) ] if #available(macOS 10.12, *) { settings.append((pictureInPicture, true, ["toggle-pip"], false, nil, nil)) } settings.forEach { (menuItem, isIINACmd, actions, normalizeLastNum, numRange, l10nKey) in var bound = false for kb in keyBindings { guard kb.isIINACommand == isIINACmd else { continue } let (sameAction, value) = sameKeyAction(kb.action, actions, normalizeLastNum, numRange) if sameAction, let (kEqv, kMdf) = KeyCodeHelper.macOSKeyEquivalent(from: kb.key) { menuItem.keyEquivalent = kEqv menuItem.keyEquivalentModifierMask = kMdf if let value = value, let l10nKey = l10nKey { menuItem.title = String(format: NSLocalizedString("menu." + l10nKey, comment: ""), abs(value)) menuItem.representedObject = value } bound = true break } } if !bound { menuItem.keyEquivalent = "" menuItem.keyEquivalentModifierMask = [] } } } }
548defa47843cc6d166bbf2675891e19
42.678977
174
0.689919
false
false
false
false
entotsu/TKSwarmAlert
refs/heads/master
TKSwarmAlert/Examples/SimplestExample.swift
mit
1
// // ViewController.swift // test // // Created by Takuya Okamoto on 2015/08/25. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit import TKSwarmAlert class SimpleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("view did load of simple view controller") view.backgroundColor = UIColor.blue.withAlphaComponent(0.5) let testView = UIView() testView.backgroundColor = UIColor.orange testView.frame = CGRect(x: 40, y: 40, width: 40, height: 40) view.addSubview(testView) let fallView = UIView() fallView.backgroundColor = UIColor.red fallView.frame = CGRect(x: 100, y: 100, width: 100, height: 100) fallView.center = view.center let staticView = UIView() staticView.backgroundColor = UIColor.blue staticView.frame = CGRect(x: 250, y: 250, width: 50, height: 50) Timer.schedule(delay: 1) { timer in let alert = TKSwarmAlert(backgroundType: .brightBlur) alert.durationOfPreventingTapBackgroundArea = 3 alert.addSubStaticView(staticView) alert.show([fallView]) alert.didDissmissAllViews = { print("didDissmissAllViews") } } } }
dc87a5fcdc2d66c0beaa303bc97c96b8
26.48
72
0.605531
false
true
false
false
billdonner/sheetcheats9
refs/heads/master
CircleMenuLib/CircleMenu.swift
apache-2.0
1
// // CircleMenu.swift // ButtonTest // // Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: helpers func Init<Type>(_ value: Type, block: (_ object: Type) -> Void) -> Type { block(value) return value } // MARK: Protocol /** * CircleMenuDelegate */ @objc public protocol CircleMenuDelegate { /** Tells the delegate the circle menu is about to draw a button for a particular index. - parameter circleMenu: The circle menu object informing the delegate of this impending event. - parameter button: A circle menu button object that circle menu is going to use when drawing the row. Don't change button.tag - parameter atIndex: An button index. */ @objc optional func circleMenu(_ circleMenu: CircleMenu, willDisplay button: UIButton, atIndex: Int) /** Tells the delegate that a specified index is about to be selected. - parameter circleMenu: A circle menu object informing the delegate about the impending selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonWillSelected button: UIButton, atIndex: Int) /** Tells the delegate that the specified index is now selected. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) /** Tells the delegate that the menu was collapsed - the cancel action. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. */ @objc optional func menuCollapsed(_ circleMenu: CircleMenu) } // MARK: CircleMenu /// A Button object with pop ups buttons open class CircleMenu: UIButton { // MARK: properties /// Buttons count @IBInspectable open var buttonsCount: Int = 3 /// Circle animation duration @IBInspectable open var duration: Double = 2 /// Distance between center button and buttons @IBInspectable open var distance: Float = 100 /// Delay between show buttons @IBInspectable open var showDelay: Double = 0 /// The object that acts as the delegate of the circle menu. @IBOutlet weak open var delegate: AnyObject? //CircleMenuDelegate? var buttons: [UIButton]? weak var platform: UIView? fileprivate var customNormalIconView: UIImageView? fileprivate var customSelectedIconView: UIImageView? /** Initializes and returns a circle menu object. - parameter frame: A rectangle specifying the initial location and size of the circle menu in its superview’€™s coordinates. - parameter normalIcon: The image to use for the specified normal state. - parameter selectedIcon: The image to use for the specified selected state. - parameter buttonsCount: The number of buttons. - parameter duration: The duration, in seconds, of the animation. - parameter distance: Distance between center button and sub buttons. - returns: A newly created circle menu. */ public init(frame: CGRect, normalIcon: String?, selectedIcon: String?, buttonsCount: Int = 3, duration: Double = 2, distance: Float = 100) { super.init(frame: frame) if let icon = normalIcon { setImage(UIImage(named: icon), for: UIControlState()) } if let icon = selectedIcon { setImage(UIImage(named: icon), for: .selected) } self.buttonsCount = buttonsCount self.duration = duration self.distance = distance commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { addActions() customNormalIconView = addCustomImageView(state: UIControlState()) customSelectedIconView = addCustomImageView(state: .selected) if customSelectedIconView != nil { customSelectedIconView?.alpha = 0 } setImage(UIImage(), for: UIControlState()) setImage(UIImage(), for: .selected) } // MARK: methods /** Hide button - parameter duration: The duration, in seconds, of the animation. - parameter hideDelay: The time to delay, in seconds. */ open func hideButtons(_ duration: Double, hideDelay: Double = 0) { if buttons == nil { return } buttonsAnimationIsShow(isShow: false, duration: duration, hideDelay: hideDelay) tapBounceAnimation() tapRotatedAnimation(0.3, isSelected: false) } /** Check is sub buttons showed */ open func buttonsIsShown() -> Bool { guard let buttons = self.buttons else { return false } for button in buttons { if button.alpha == 0 { return false } } return true } // MARK: create fileprivate func createButtons(platform: UIView) -> [UIButton] { var buttons = [UIButton]() let step: Float = 360.0 / Float(self.buttonsCount) for index in 0..<self.buttonsCount { let angle: Float = Float(index) * step let distance = Float(self.bounds.size.height/2.0) let button = Init(CircleMenuButton(size: self.bounds.size, platform: platform, distance:distance, angle: angle)) { $0.tag = index $0.addTarget(self, action: #selector(CircleMenu.buttonHandler(_:)), for: UIControlEvents.touchUpInside) $0.alpha = 0 } buttons.append(button) } return buttons } fileprivate func addCustomImageView(state: UIControlState) -> UIImageView? { guard let image = image(for: state) else { return nil } let iconView = Init(UIImageView(image: image)) { $0.translatesAutoresizingMaskIntoConstraints = false $0.contentMode = .center $0.isUserInteractionEnabled = false } addSubview(iconView) // added constraints iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bounds.size.height)) iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: bounds.size.width)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1, constant:0)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1, constant:0)) return iconView } fileprivate func createPlatform() -> UIView { let platform = Init(UIView(frame: .zero)) { $0.backgroundColor = .clear $0.translatesAutoresizingMaskIntoConstraints = false } superview?.insertSubview(platform, belowSubview: self) // constraints let sizeConstraints = [NSLayoutAttribute.width, .height].map { NSLayoutConstraint(item: platform, attribute: $0, relatedBy: .equal, toItem: nil, attribute: $0, multiplier: 1, constant: CGFloat(distance * Float(2.0))) } platform.addConstraints(sizeConstraints) let centerConstraints = [NSLayoutAttribute.centerX, .centerY].map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: platform, attribute: $0, multiplier: 1, constant:0) } superview?.addConstraints(centerConstraints) return platform } // MARK: configure fileprivate func addActions() { self.addTarget(self, action: #selector(CircleMenu.onTap), for: UIControlEvents.touchUpInside) } // MARK: actions @objc func onTap() { if buttonsIsShown() == false { let platform = createPlatform() buttons = createButtons(platform: platform) self.platform = platform } let isShow = !buttonsIsShown() let duration = isShow ? 0.5 : 0.2 buttonsAnimationIsShow(isShow: isShow, duration: duration) tapBounceAnimation() tapRotatedAnimation(0.3, isSelected: isShow) } @objc func buttonHandler(_ sender: CircleMenuButton) { guard let platform = self.platform else { return } delegate?.circleMenu?(self, buttonWillSelected: sender, atIndex: sender.tag) let circle = CircleMenuLoader(radius: CGFloat(distance), strokeWidth: bounds.size.height, platform: platform, color: sender.backgroundColor) if let container = sender.container { // rotation animation sender.rotationAnimation(container.angleZ + 360, duration: duration) container.superview?.bringSubview(toFront: container) } if let buttons = buttons { circle.fillAnimation(duration, startAngle: -90 + Float(360 / buttons.count) * Float(sender.tag)) { [weak self] in self?.buttons?.forEach { $0.alpha = 0 } } circle.hideAnimation(0.5, delay: duration) { [weak self] in if self?.platform?.superview != nil { self?.platform?.removeFromSuperview() } } hideCenterButton(duration: 0.3) showCenterButton(duration: 0.525, delay: duration) if customNormalIconView != nil && customSelectedIconView != nil { DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: { self.delegate?.circleMenu?(self, buttonDidSelected: sender, atIndex: sender.tag) }) } } } // MARK: animations fileprivate func buttonsAnimationIsShow(isShow: Bool, duration: Double, hideDelay: Double = 0) { guard let buttons = self.buttons else { return } let step: Float = 360.0 / Float(self.buttonsCount) for index in 0..<self.buttonsCount { guard case let button as CircleMenuButton = buttons[index] else { continue } let angle: Float = Float(index) * step if isShow == true { delegate?.circleMenu?(self, willDisplay: button, atIndex: index) button.rotatedZ(angle: angle, animated: false, delay: Double(index) * showDelay) button.showAnimation(distance: distance, duration: duration, delay: Double(index) * showDelay) } else { button.hideAnimation( distance: Float(self.bounds.size.height / 2.0), duration: duration, delay: hideDelay) self.delegate?.menuCollapsed?(self) } } if isShow == false { // hide buttons and remove self.buttons = nil } } fileprivate func tapBounceAnimation() { self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 5, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } fileprivate func tapRotatedAnimation(_ duration: Float, isSelected: Bool) { let addAnimations: (_ view: UIImageView, _ isShow: Bool) -> () = { (view, isShow) in var toAngle: Float = 180.0 var fromAngle: Float = 0 var fromScale = 1.0 var toScale = 0.2 var fromOpacity = 1 var toOpacity = 0 if isShow == true { toAngle = 0 fromAngle = -180 fromScale = 0.2 toScale = 1.0 fromOpacity = 0 toOpacity = 1 } let rotation = Init(CABasicAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(duration) $0.toValue = (toAngle.degrees) $0.fromValue = (fromAngle.degrees) $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } let fade = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.fromValue = fromOpacity $0.toValue = toOpacity $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false } let scale = Init(CABasicAnimation(keyPath: "transform.scale")) { $0.duration = TimeInterval(duration) $0.toValue = toScale $0.fromValue = fromScale $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } view.layer.add(rotation, forKey: nil) view.layer.add(fade, forKey: nil) view.layer.add(scale, forKey: nil) } if let customNormalIconView = self.customNormalIconView { addAnimations(customNormalIconView, !isSelected) } if let customSelectedIconView = self.customSelectedIconView { addAnimations(customSelectedIconView, isSelected) } self.isSelected = isSelected self.alpha = isSelected ? 0.3 : 1 } fileprivate func hideCenterButton(duration: Double, delay: Double = 0) { UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) }, completion: nil) } fileprivate func showCenterButton(duration: Float, delay: Double) { UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: 0.78, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) self.alpha = 1 }, completion: nil) let rotation = Init(CASpringAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(1.5) $0.toValue = (0) $0.fromValue = (Float(-180).degrees) $0.damping = 10 $0.initialVelocity = 0 $0.beginTime = CACurrentMediaTime() + delay } let fade = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(0.01) $0.toValue = 0 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } let show = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.toValue = 1 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } customNormalIconView?.layer.add(rotation, forKey: nil) customNormalIconView?.layer.add(show, forKey: nil) customSelectedIconView?.layer.add(fade, forKey: nil) } } // MARK: extension internal extension Float { var radians: Float { return self * (Float(180) / Float(Double.pi)) } var degrees: Float { return self * Float(Double.pi) / 180.0 } } internal extension UIView { var angleZ: Float { return atan2(Float(self.transform.b), Float(self.transform.a)).radians } }
7b4efd01bcc23a7e896289075e26e931
34.618852
134
0.633817
false
false
false
false
Vienta/kuafu
refs/heads/master
kuafu/kuafu/src/Controller/KFLisenceDetailViewController.swift
mit
1
// // KFLisenceDetailViewController.swift // kuafu // // Created by Vienta on 15/7/18. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit class KFLisenceDetailViewController: UIViewController { @IBOutlet weak var txvLisence: UITextView! var lisenceName: String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = self.lisenceName var lisenceFileName: String = self.lisenceName + "_LICENSE" let path = NSBundle.mainBundle().pathForResource(lisenceFileName, ofType: "txt") var lisenceContent: String! = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil) self.txvLisence.text = lisenceContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
1b309a839db64fcb64b0fb919651be63
28.4375
111
0.68896
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/Swift Note/PhotoBrowser/PhotoBrowser/Classes/Home/FlowLayout/HomeFlowLayout.swift
mit
1
// // HomeFlowLayout.swift // PhotoBrowser // // Created by 朱双泉 on 2018/10/30. // Copyright © 2018 Castie!. All rights reserved. // import UIKit class HomeFlowLayout: UICollectionViewFlowLayout { override func prepare() { let itemCountInRow: CGFloat = 3 let margin: CGFloat = 10 let itemW = (kScreenW - (itemCountInRow + 1) * margin) / itemCountInRow let itemH = itemW * 1.3 itemSize = CGSize(width: itemW, height: itemH) minimumLineSpacing = margin minimumInteritemSpacing = margin collectionView?.contentInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) } }
b1c3bfa2d36e619125df8e9fe8068fec
28.043478
109
0.66018
false
false
false
false
thisfin/HostsManager
refs/heads/develop
HostsManager/WYVerticalCenterTextField.swift
mit
1
// // WYVerticalCenterTextField.swift // EmptyProject // // Created by wenyou on 2017/6/16. // Copyright © 2017年 fin. All rights reserved. // import AppKit // https://stackoverflow.com/questions/11775128/set-text-vertical-center-in-nstextfield // NSTextField().cell = WYVerticalCenterTextFieldCell() class WYVerticalCenterTextFieldCell: NSTextFieldCell { override func titleRect(forBounds rect: NSRect) -> NSRect { var titleRect = super.titleRect(forBounds: rect) let minimumHeight = cellSize(forBounds: rect).height titleRect.origin.y += (titleRect.height - minimumHeight) / 2 titleRect.size.height = minimumHeight return titleRect } override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) { super.drawInterior(withFrame: titleRect(forBounds: cellFrame), in: controlView) } override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) { super.select(withFrame: titleRect(forBounds: rect), in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength) } }
3d0af5d793ef336c453201a5d9f44b1f
39.965517
158
0.725589
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Mixing/Dry Wet Mixer/AKDryWetMixer.swift
mit
2
// // AKDryWetMixer.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Balanceable Mix between two signals, usually used for a dry signal and wet signal /// /// - Parameters: /// - dry: Dry Input (or just input 1) /// - wet: Wet Input (or just input 2) /// - balance: Balance Point (0 = all dry, 1 = all wet) /// public class AKDryWetMixer: AKNode { private let mixer = AKMixer() /// Balance (Default 0.5) public var balance: Double = 0.5 { didSet { if balance < 0 { balance = 0 } if balance > 1 { balance = 1 } dryGain?.volume = 1 - balance wetGain?.volume = balance } } private var dryGain: AKMixer? private var wetGain: AKMixer? /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted = true /// Initialize this dry wet mixer node /// /// - Parameters: /// - dry: Dry Input (or just input 1) /// - wet: Wet Input (or just input 2) /// - balance: Balance Point (0 = all dry, 1 = all wet) /// public init(_ dry: AKNode, _ wet: AKNode, balance: Double = 0.5) { self.balance = balance super.init() avAudioNode = mixer.avAudioNode dryGain = AKMixer(dry) dryGain!.volume = 1 - balance mixer.connect(dryGain!) wetGain = AKMixer(wet) wetGain!.volume = balance mixer.connect(wetGain!) } }
dacbaee1deb9e4532113399fea1d3f10
24.578125
85
0.568723
false
false
false
false
erusso1/ERNiftyFoundation
refs/heads/master
ERNiftyFoundation/Source/Classes/ERModelType.swift
mit
1
// // ERModelType.swift // Pods // // Created by Ephraim Russo on 8/31/17. // // import Unbox import Wrap public protocol ERModelType: Equatable, Unboxable, WrapCustomizable, CustomDebugStringConvertible { /// Returns the unique identifier of the model object. var id: String { get } /// Returns the JSON dictionary representation of the model object. May return `nil` due to Wrap errors. var JSON: JSONObject? { get } /// Creates a new model object given the passed JSON argument. Call can throw Unbox errors. init(JSON: JSONObject) throws } extension ERModelType { /// Returns the JSON dictionary computed by the `Wrap` framework. The encoded keys are determined by the `wrapKeyStyle` property, with a default set to `matchPropertyName`. public var JSON: JSONObject? { do { return try Wrap.wrap(self) } catch { printPretty("Cannot return JSON for model with id: \(id) - error: \(error.localizedDescription)"); return nil } } /// Creates a new model object by unboxing the passed `JSON` dictionary. public init(JSON: JSONObject) throws { try self.init(unboxer: Unboxer(dictionary: JSON)) } } public func ==<T: ERModelType>(lhs: T, rhs: T) -> Bool { return lhs.id == rhs.id } extension ERModelType { public var debugDescription: String { if let json = self.JSON { let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! return string as String } else { return "\(self)" } } } extension ERModelType { /// The key style encoding type used by the `Wrap` framework. Default is set to `.matchPropertyName`. public var wrapKeyStyle: WrapKeyStyle { return .matchPropertyName } public func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? { guard let date = originalValue as? Date else {return nil} return ERDateIntervalFormatter.formatterType == .milliseconds ? Double(Int(date.timeIntervalSince1970*1000.0.rounded())) : (Int(date.timeIntervalSince1970.rounded())) } }
e848c83c58228bca0e6a9312634e5b74
32.166667
174
0.702604
false
false
false
false
AnneBlair/YYGRegular
refs/heads/master
YYGRegular/YYGText.swift
mit
1
// // YYGText.swift // 24demo // // Created by 区块国际-yin on 17/2/10. // Copyright © 2017年 区块国际-yin. All rights reserved. // import UIKit /// Seting AttributedString /// /// - Parameters: /// - color: 颜色 Arry [[RGB,RGB,RGB],[RGB,RGB,RGB]] /// - content: 内容 Arry ["第一个","第二个"] /// - size: 字体 Arry [size1,size2] /// - Returns: 富文本 public func setAttribute(color: [[Int]],content:[String],size: [CGFloat])-> NSMutableAttributedString { let str = NSMutableAttributedString() for i in 0..<color.count { str.append(NSAttributedString(string: content[i], attributes: [NSForegroundColorAttributeName: UIColor(hex: color[i][0]), NSFontAttributeName:UIFont.systemFont(ofSize: size[i])])) } return str } /// scientific Notation Transition Normal String /// 9.0006e+07 Transition 90,006,000 /// - Parameter f_loat: Input /// - Returns: Output public func inputFOutputS(f_loat: Double) -> String { let numFormat = NumberFormatter() numFormat.numberStyle = NumberFormatter.Style.decimal let num = NSNumber.init(value: f_loat) return numFormat.string(from: num)! } // MARK: - 数字转换成字符串金额 11121.01 -> "11,121.01" 三位一个逗号 extension NSNumber { var dollars: String { let formatter: NumberFormatter = NumberFormatter() var result: String? formatter.numberStyle = NumberFormatter.Style.decimal result = formatter.string(from: self) if result == nil { return "error" } return result! } } extension String { /// 截取第一个到第任意位置 /// /// - Parameter end: 结束的位值 /// - Returns: 截取后的字符串 func stringCut(end: Int) ->String{ printLogDebug(self.characters.count) if !(end < characters.count) { return "截取超出范围" } let sInde = index(startIndex, offsetBy: end) return substring(to: sInde) } /// 截取人任意位置到结束 /// /// - Parameter end: /// - Returns: 截取后的字符串 func stringCutToEnd(star: Int) -> String { if !(star < characters.count) { return "截取超出范围" } let sRang = index(startIndex, offsetBy: star)..<endIndex return substring(with: sRang) } /// 字符串任意位置插入 /// /// - Parameters: /// - content: 插入内容 /// - locat: 插入的位置 /// - Returns: 添加后的字符串 func stringInsert(content: String,locat: Int) -> String { if !(locat < characters.count) { return "截取超出范围" } let str1 = stringCut(end: locat) let str2 = stringCutToEnd(star: locat) return str1 + content + str2 } /// 计算字符串宽高 /// /// - Parameter size: size /// - Returns: CGSize func getStringSzie(size: CGFloat = 10) -> CGSize { let baseFont = UIFont.systemFont(ofSize: size) let size = self.size(attributes: [NSFontAttributeName: baseFont]) let width = ceil(size.width) + 5 let height = ceil(size.height) return CGSize(width: width, height: height) } /// 输入字符串 输出数组 /// e.g "qwert" -> ["q","w","e","r","t"] /// - Returns: ["q","w","e","r","t"] func stringToArr() -> [String] { let num = characters.count if !(num > 0) { return [""] } var arr: [String] = [] for i in 0..<num { let tempStr: String = self[self.index(self.startIndex, offsetBy: i)].description arr.append(tempStr) } return arr } /// 字符串截取 3 6 /// e.g let aaa = "abcdefghijklmnopqrstuvwxyz" -> "cdef" /// - Parameters: /// - start: 开始位置 3 /// - end: 结束位置 6 /// - Returns: 截取后的字符串 "cdef" func startToEnd(start: Int,end: Int) -> String { if !(end < characters.count) || start > end { return "取值范围错误" } var tempStr: String = "" for i in start...end { let temp: String = self[self.index(self.startIndex, offsetBy: i - 1)].description tempStr += temp } return tempStr } /// 字符URL格式化 /// /// - Returns: 格式化的 url func stringEncoding() -> String { let url = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) return url! } }
efc136c313594f727aa82131b4ef5a06
29.072464
187
0.580482
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Frontend/Widgets/ChevronView.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 enum ChevronDirection { case left case up case right case down } enum ChevronStyle { case angular case rounded } class ChevronView: UIView { fileprivate let Padding: CGFloat = 2.5 fileprivate var direction = ChevronDirection.right fileprivate var lineCapStyle = CGLineCap.round fileprivate var lineJoinStyle = CGLineJoin.round var lineWidth: CGFloat = 3.0 var style: ChevronStyle = .rounded { didSet { switch style { case .rounded: lineCapStyle = CGLineCap.round lineJoinStyle = CGLineJoin.round case .angular: lineCapStyle = CGLineCap.butt lineJoinStyle = CGLineJoin.miter } } } init(direction: ChevronDirection) { super.init(frame: CGRect.zero) self.direction = direction if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft { if direction == .left { self.direction = .right } else if direction == .right { self.direction = .left } } self.backgroundColor = UIColor.clear self.contentMode = UIViewContentMode.redraw } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let strokeLength = (rect.size.height / 2) - Padding; let path: UIBezierPath switch (direction) { case .left: path = drawLeftChevronAt(CGPoint(x: rect.size.width - (strokeLength + Padding), y: strokeLength + Padding), strokeLength:strokeLength) case .up: path = drawUpChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength / 2) + Padding), strokeLength:strokeLength) case .right: path = drawRightChevronAt(CGPoint(x: rect.size.width - Padding, y: strokeLength + Padding), strokeLength:strokeLength) case .down: path = drawDownChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength * 1.5) + Padding), strokeLength:strokeLength) } tintColor.set() // The line thickness needs to be proportional to the distance from the arrow head to the tips. Making it half seems about right. path.lineCapStyle = lineCapStyle path.lineJoinStyle = lineJoinStyle path.lineWidth = lineWidth path.stroke(); } fileprivate func drawUpChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength)) } fileprivate func drawDownChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength)) } fileprivate func drawLeftChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength)) } fileprivate func drawRightChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength)) } fileprivate func drawChevron(_ leftTip: CGPoint, head: CGPoint, rightTip: CGPoint) -> UIBezierPath { let path = UIBezierPath() // Left tip path.move(to: leftTip) // Arrow head path.addLine(to: head) // Right tip path.addLine(to: rightTip) return path } }
6f0753f5e7c68ed7263324b93d71a610
34.869919
154
0.633726
false
false
false
false
slmcmahon/Coins2
refs/heads/master
Coins2/CoinViewModel.swift
mit
1
// // CoinViewModel.swift // Coins2 // // Created by Stephen McMahon on 6/20/17. // Copyright © 2017 Stephen McMahon. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class CoinViewModel { func recognizeImage(onSuccess:@escaping (String) -> Void, onFailure:@escaping (String) -> Void, image : UIImage) { let resized = self.resizeImage(image: image, size: CGSize(width: image.size.width / 4.0, height: image.size.height / 4.0)) let imgData = UIImagePNGRepresentation(resized) Alamofire.upload(multipartFormData: { multipartFormData in multipartFormData.append(imgData!, withName: "image",fileName: "png", mimeType: "image/png") }, to:Constants.RecognizerUrl, headers: ["Prediction-Key" : Constants.PredictionKey]) { (result) in switch result { case .success(let upload, _, _): upload.uploadProgress(closure: { (progress) in print("Upload Progress: \(progress.fractionCompleted)") }) upload.responseJSON { response in print(response.result.value ?? "") let json = JSON(response.result.value ?? "") let predictions = json["Predictions"].array! onSuccess(self.readPredictions(predictions: predictions)) } case .failure(let encodingError): onFailure(encodingError as! String) } } } func readPredictions(predictions : [JSON]) -> String { var allCoinsProbability = 0 var coinName = "unknown" var coinProbability = 0.00000001 for dic in predictions { let tag = dic["Tag"].string! let pb = dic["Probability"].doubleValue let percent = pb * 100 if tag == "All Coins" { if Int(percent) < Constants.MinimumProbability { return "We didn't recognize any coins in this photo" } else { allCoinsProbability = Int(percent) continue } } if (pb > coinProbability) { coinProbability = pb // all of the tags are pluralized, but we want to refer to the singular form in the response. coinName = tag == "Pennies" ? "Penny" : tag.substring(to: tag.index(before: tag.endIndex)) } } return "We are \(allCoinsProbability) certain that the photo contains a \(coinName)." } private func resizeImage(image : UIImage, size : CGSize) -> UIImage { UIGraphicsBeginImageContext(size) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) image.draw(in: rect) let destImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return destImage! } }
72a1da4fc949645fbdd7ede1534a56fc
37.602564
130
0.564264
false
false
false
false
szk-atmosphere/MartyJunior
refs/heads/master
MartyJunior/MJViewController.swift
mit
1
// // MJSlideViewController.swift // MartyJunior // // Created by 鈴木大貴 on 2015/11/26. // Copyright © 2015年 Taiki Suzuki. All rights reserved. // import UIKit import MisterFusion open class MJViewController: UIViewController { //MARK: - Inner class private class RegisterCellContainer { struct NibAndIdentifierContainer { let nib: UINib? let reuseIdentifier: String } struct ClassAndIdentifierContainer { let aClass: AnyClass? let reuseIdentifier: String } var cellNib: [NibAndIdentifierContainer] = [] var cellClass: [ClassAndIdentifierContainer] = [] var headerFooterNib: [NibAndIdentifierContainer] = [] var headerFooterClass: [ClassAndIdentifierContainer] = [] } //MAKR: - Properties public weak var delegate: MJViewControllerDelegate? public weak var dataSource: MJViewControllerDataSource? private let scrollView: UIScrollView = UIScrollView() private let scrollContainerView: UIView = UIView() private var scrollContainerViewWidthConstraint: NSLayoutConstraint? fileprivate let contentView: MJContentView = MJContentView() fileprivate let contentEscapeView: UIView = UIView() fileprivate var contentEscapeViewTopConstraint: NSLayoutConstraint? public private(set) var navigationView: MJNavigationView? private let navigationContainerView = UIView() private var containerViews: [UIView] = [] fileprivate var viewControllers: [MJTableViewController] = [] private let registerCellContainer: RegisterCellContainer = RegisterCellContainer() public var hiddenNavigationView: Bool = false public var tableViews: [UITableView] { return viewControllers.map { $0.tableView } } public private(set) var titles: [String]? public private(set) var numberOfTabs: Int = 0 private var _selectedIndex: Int = 0 { didSet { delegate?.mjViewController?(self, didChangeSelectedIndex: _selectedIndex) } } public var selectedIndex: Int { get { let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width) if _selectedIndex != index { _selectedIndex = index viewControllers.enumerated().forEach { $0.element.tableView.scrollsToTop = $0.offset == index } } return index } set { _selectedIndex = newValue addContentViewToEscapeView() UIView.animate(withDuration: 0.25, animations: { self.scrollView.setContentOffset(CGPoint(x: self.scrollView.bounds.size.width * CGFloat(newValue), y: 0), animated: false) }) { _ in if let superview = self.contentView.superview, let constant = self.contentEscapeViewTopConstraint?.constant, superview == self.contentEscapeView && self.scrollView.contentOffset.y < constant { self.addContentViewToCell() } } } } public var headerHeight: CGFloat { return contentView.tabContainerView.frame.size.height + navigationContainerViewHeight } public var selectedViewController: MJTableViewController { return viewControllers[selectedIndex] } private var navigationContainerViewHeight: CGFloat { let sharedApplication = UIApplication.shared let statusBarHeight = sharedApplication.isStatusBarHidden ? 0 : sharedApplication.statusBarFrame.size.height let navigationViewHeight: CGFloat = hiddenNavigationView ? 0 : 44 return statusBarHeight + navigationViewHeight } fileprivate func indexOfViewController(_ viewController: MJTableViewController) -> Int { return viewControllers.index(of: viewController) ?? 0 } //MARK: - Life cycle open func viewWillSetupForMartyJunior() {} open func viewDidSetupForMartyJunior() {} open override func viewDidLoad() { super.viewDidLoad() viewWillSetupForMartyJunior() guard let dataSource = dataSource else { return } titles = dataSource.mjViewControllerTitlesForTab?(self) numberOfTabs = dataSource.mjViewControllerNumberOfTabs(self) setupContentView(dataSource) setupScrollView() setupScrollContainerView() setupContainerViews() setupTableViewControllers() registerNibAndClassForTableViews() setupContentEscapeView() setNavigationView() viewDidSetupForMartyJunior() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewControllers.forEach { $0.tableView.reloadData() } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view.setNeedsDisplay() view.layoutIfNeeded() } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Setup views private func setupContentView(_ dataSource: MJViewControllerDataSource) { contentView.titles = titles contentView.segmentedControl.selectedSegmentIndex = 0 contentView.userDefinedView = dataSource.mjViewControllerContentViewForTop(self) contentView.userDefinedTabView = dataSource.mjViewControllerTabViewForTop?(self) contentView.setupTabView() } private func setupScrollView() { scrollView.scrollsToTop = false scrollView.isPagingEnabled = true scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false view.addLayoutSubview(scrollView, andConstraints: scrollView.top, scrollView.left, scrollView.right, scrollView.bottom ) } private func setupScrollContainerView() { scrollContainerViewWidthConstraint = scrollView.addLayoutSubview(scrollContainerView, andConstraints: scrollContainerView.top, scrollContainerView.left, scrollContainerView.right, scrollContainerView.bottom, scrollContainerView.height |==| scrollView.height, scrollContainerView.width |==| scrollView.width |*| CGFloat(numberOfTabs) ).firstAttribute(.width).first } private func setupContentEscapeView() { contentEscapeViewTopConstraint = view.addLayoutSubview(contentEscapeView, andConstraints: contentEscapeView.top, contentEscapeView.left, contentEscapeView.right, contentEscapeView.height |==| contentView.currentHeight ).firstAttribute(.top).first view.layoutIfNeeded() contentEscapeView.backgroundColor = .clear contentEscapeView.isUserInteractionEnabled = false contentEscapeView.isHidden = true } private func setNavigationView() { view.addLayoutSubview(navigationContainerView, andConstraints: navigationContainerView.top, navigationContainerView.left, navigationContainerView.right, navigationContainerView.height |==| navigationContainerViewHeight ) if hiddenNavigationView { return } let navigationView = MJNavigationView() navigationContainerView.addLayoutSubview(navigationView, andConstraints: navigationView.height |==| MJNavigationView.Height, navigationView.left, navigationView.bottom, navigationView.right ) navigationView.titleLabel.text = title self.navigationView = navigationView } private func setupContainerViews() { (0..<numberOfTabs).forEach { let containerView = UIView() let misterFusions: [MisterFusion] switch $0 { case 0: misterFusions = [ containerView.left, ] case (numberOfTabs - 1): guard let previousContainerView = containerViews.last else { return } misterFusions = [ containerView.right, containerView.left |==| previousContainerView.right, ] default: guard let previousContainerView = containerViews.last else { return } misterFusions = [ containerView.left |==| previousContainerView.right, ] } let commomMisterFusions = [ containerView.top, containerView.bottom, containerView.width |/| CGFloat(numberOfTabs) ] scrollContainerView.addLayoutSubview(containerView, andConstraints: misterFusions + commomMisterFusions) containerViews += [containerView] } contentView.delegate = self } private func setupTableViewControllers() { containerViews.forEach { let viewController = MJTableViewController() viewController.delegate = self viewController.dataSource = self viewController.contentView = self.contentView $0.addLayoutSubview(viewController.view, andConstraints: viewController.view.top, viewController.view.left, viewController.view.right, viewController.view.bottom ) addChildViewController(viewController) viewController.didMove(toParentViewController: self) viewControllers += [viewController] } } private func registerNibAndClassForTableViews() { tableViews.forEach { tableView in registerCellContainer.cellNib.forEach { tableView.register($0.nib, forCellReuseIdentifier: $0.reuseIdentifier) } registerCellContainer.headerFooterNib.forEach { tableView.register($0.nib, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) } registerCellContainer.cellClass.forEach { tableView.register($0.aClass, forCellReuseIdentifier: $0.reuseIdentifier) } registerCellContainer.headerFooterClass.forEach { tableView.register($0.aClass, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) } } } //MARK: - ContentView moving fileprivate func addContentViewToCell() { if contentView.superview != contentEscapeView { return } contentEscapeView.isHidden = true contentEscapeView.isUserInteractionEnabled = false let cells = selectedViewController.tableView.visibleCells.filter { $0.isKind(of: MJTableViewTopCell.self) } let cell = cells.first as? MJTableViewTopCell cell?.mainContentView = contentView } fileprivate func addContentViewToEscapeView() { if contentView.superview == contentEscapeView { return } contentEscapeView.isHidden = false contentEscapeView.isUserInteractionEnabled = true contentEscapeView.addLayoutSubview(contentView, andConstraints: contentView.top, contentView.left, contentView.right, contentView.bottom ) let topConstant = max(0, min(contentView.frame.size.height - headerHeight, selectedViewController.tableView.contentOffset.y)) contentEscapeViewTopConstraint?.constant = -topConstant contentEscapeView.layoutIfNeeded() } //MARK: - Private fileprivate func setTableViewControllersContentOffsetBasedOnScrollView(_ scrollView: UIScrollView, withoutSelectedViewController: Bool) { let viewControllers = self.viewControllers.filter { $0 != selectedViewController } let contentHeight = contentView.frame.size.height - headerHeight viewControllers.forEach { let tableView = $0.tableView let contentOffset: CGPoint if scrollView.contentOffset.y <= contentHeight { contentOffset = scrollView.contentOffset } else { contentOffset = tableView.contentOffset.y >= contentHeight ? tableView.contentOffset : CGPoint(x: 0, y: contentHeight) } tableView.setContentOffset(contentOffset, animated: false) } } //MARK: - Public public func registerNibToAllTableViews(_ nib: UINib?, forCellReuseIdentifier reuseIdentifier: String) { registerCellContainer.cellNib += [RegisterCellContainer.NibAndIdentifierContainer(nib: nib, reuseIdentifier: reuseIdentifier)] } public func registerNibToAllTableViews(_ nib: UINib?, forHeaderFooterViewReuseIdentifier reuseIdentifier: String) { registerCellContainer.headerFooterNib += [RegisterCellContainer.NibAndIdentifierContainer(nib: nib, reuseIdentifier: reuseIdentifier)] } public func registerClassToAllTableViews(_ aClass: AnyClass?, forCellReuseIdentifier reuseIdentifier: String) { registerCellContainer.cellClass += [RegisterCellContainer.ClassAndIdentifierContainer(aClass: aClass, reuseIdentifier: reuseIdentifier)] } public func registerClassToAllTableViews(_ aClass: AnyClass?, forHeaderFooterViewReuseIdentifier reuseIdentifier: String) { registerCellContainer.headerFooterClass += [RegisterCellContainer.ClassAndIdentifierContainer(aClass: aClass, reuseIdentifier: reuseIdentifier)] } } //MARK: - UIScrollViewDelegate extension MJViewController: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { delegate?.mjViewController?(self, contentScrollViewDidScroll: scrollView) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if let constant = contentEscapeViewTopConstraint?.constant, !decelerate && scrollView.contentOffset.y < constant { addContentViewToCell() } contentView.segmentedControl.selectedSegmentIndex = selectedIndex delegate?.mjViewController?(self, contentScrollViewDidEndDragging: scrollView, willDecelerate: decelerate) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if let constant = contentEscapeViewTopConstraint?.constant, scrollView.contentOffset.y < constant { addContentViewToCell() } contentView.segmentedControl.selectedSegmentIndex = selectedIndex delegate?.mjViewController?(self, contentScrollViewDidEndDecelerating: scrollView) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { addContentViewToEscapeView() delegate?.mjViewController?(self, contentScrollViewWillBeginDragging: scrollView) } } //MARK: - MJTableViewControllerDataSource extension MJViewController: MJTableViewControllerDataSource { func tableViewControllerHeaderHeight(_ viewController: MJTableViewController) -> CGFloat { return headerHeight } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell? { return dataSource?.mjViewController(self, targetIndex: indexOfViewController(viewController), tableView: tableView, cellForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, numberOfRowsInSection section: Int) -> Int? { return dataSource?.mjViewController(self, targetIndex: indexOfViewController(viewController), tableView: tableView, numberOfRowsInSection: section) } func tableViewController(_ viewController: MJTableViewController, numberOfSectionsInTableView tableView: UITableView) -> Int? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), numberOfSectionsInTableView: tableView) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForHeaderInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForFooterInSection section: Int) -> String? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForFooterInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canEditRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canMoveRowAtIndexPath indexPath: IndexPath) -> Bool? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canMoveRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, sectionIndexTitlesForTableView tableView: UITableView) -> [String]? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), sectionIndexTitlesForTableView: tableView) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int? { return dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, sectionForSectionIndexTitle: title, atIndex: index) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) { dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) { dataSource?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } //MARK: - MJTableViewControllerDelegate extension MJViewController: MJTableViewControllerDelegate { func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForTopCellAtIndexPath indexPath: IndexPath) -> CGFloat { return contentView.currentHeight } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForTopCellAtIndexPath indexPath: IndexPath) -> CGFloat { return contentView.currentHeight } func tableViewController(_ viewController: MJTableViewController, tableViewTopCell cell: MJTableViewTopCell) { if viewController != selectedViewController { return } if contentView.superview != contentEscapeView { cell.mainContentView = contentView } } func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndDecelerating scrollView: UIScrollView) { if viewController != selectedViewController { return } setTableViewControllersContentOffsetBasedOnScrollView(scrollView, withoutSelectedViewController: true) delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndDecelerating: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidScroll scrollView: UIScrollView) { if viewController != selectedViewController { return } if scrollView.contentOffset.y > contentView.frame.size.height - headerHeight { addContentViewToEscapeView() } else { addContentViewToCell() } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidScroll: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndDragging scrollView: UIScrollView, willDecelerate decelerate: Bool) { if viewController != selectedViewController { return } setTableViewControllersContentOffsetBasedOnScrollView(scrollView, withoutSelectedViewController: true) delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndDragging: scrollView, willDecelerate: decelerate) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidZoom scrollView: UIScrollView) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidZoom: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginDragging scrollView: UIScrollView) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginDragging: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewWillEndDragging scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillEndDragging: scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginDecelerating scrollView: UIScrollView) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginDecelerating: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndScrollingAnimation scrollView: UIScrollView) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndScrollingAnimation: scrollView) } func tableViewController(_ viewController: MJTableViewController, viewForZoomingInScrollView scrollView: UIScrollView) -> UIView? { if viewController != selectedViewController { return nil } return delegate?.mjViewController?(self, selectedIndex: selectedIndex, viewForZoomingInScrollView: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewWillBeginZooming scrollView: UIScrollView, withView view: UIView?) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewWillBeginZooming: scrollView, withView: view) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidEndZooming scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidEndZooming: scrollView, withView: view, atScale: scale) } func tableViewController(_ viewController: MJTableViewController, scrollViewShouldScrollToTop scrollView: UIScrollView) -> Bool? { if viewController != selectedViewController { return false } return delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewShouldScrollToTop: scrollView) } func tableViewController(_ viewController: MJTableViewController, scrollViewDidScrollToTop scrollView: UIScrollView) { viewControllers.filter { $0 != self.selectedViewController }.forEach { $0.tableView.setContentOffset(.zero, animated: false) } if viewController != selectedViewController { return } delegate?.mjViewController?(self, selectedIndex: selectedIndex, scrollViewDidScrollToTop: scrollView) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayHeaderView: view, forSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDisplayFooterView: view, forSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingCell: cell, forRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingHeaderView: view, forSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndDisplayingFooterView: view, forSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForHeaderInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, heightForFooterInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: IndexPath) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForHeaderInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, estimatedHeightForFooterInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, viewForHeaderInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, viewForFooterInSection: section) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, accessoryButtonTappedForRowWithIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: IndexPath) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldHighlightRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didHighlightRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didHighlightRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didUnhighlightRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willSelectRowAtIndexPath indexPath: IndexPath) -> IndexPath? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willSelectRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willDeselectRowAtIndexPath indexPath: IndexPath) -> IndexPath? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willDeselectRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didSelectRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didDeselectRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didDeselectRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, editingStyleForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: IndexPath) -> String? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, titleForDeleteConfirmationButtonForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [UITableViewRowAction]? { return delegate?.mjViewController?(self, selectedIndex: indexOfViewController(viewController), tableView: tableView, editActionsForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: IndexPath) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldIndentWhileEditingRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, willBeginEditingRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didEndEditingRowAtIndexPath indexPath: IndexPath) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didEndEditingRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, targetIndexPathForMoveFromRowAtIndexPath: sourceIndexPath, toProposedIndexPath: proposedDestinationIndexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: IndexPath) -> Int? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, indentationLevelForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: IndexPath) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldShowMenuForRowAtIndexPath: indexPath) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: IndexPath, withSender sender: AnyObject?) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canPerformAction: action, forRowAtIndexPath: indexPath, withSender: sender) } func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: IndexPath, withSender sender: AnyObject?) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, performAction: action, forRowAtIndexPath: indexPath, withSender: sender) } @available(iOS 9.0, *) func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, canFocusRowAtIndexPath indexPath: IndexPath) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, canFocusRowAtIndexPath: indexPath) } @available(iOS 9.0, *) func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, shouldUpdateFocusInContext context: UITableViewFocusUpdateContext) -> Bool? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, shouldUpdateFocusInContext: context) } @available(iOS 9.0, *) func tableViewController(_ viewController: MJTableViewController, tableView: UITableView, didUpdateFocusInContext context: UITableViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), tableView: tableView, didUpdateFocusInContext: context, withAnimationCoordinator: coordinator) } @available(iOS 9.0, *) func tableViewController(_ viewController: MJTableViewController, indexPathForPreferredFocusedViewInTableView tableView: UITableView) -> IndexPath? { return delegate?.mjViewController?(self, targetIndex: indexOfViewController(viewController), indexPathForPreferredFocusedViewInTableView: tableView) } } //MARK: - MJContentViewDelegate extension MJViewController: MJContentViewDelegate { func contentView(_ contentView: MJContentView, didChangeValueOfSegmentedControl segmentedControl: UISegmentedControl) { selectedIndex = segmentedControl.selectedSegmentIndex } }
68740447ec392b182c26dc18592effaa
55.473763
239
0.741956
false
false
false
false
phimage/Prephirences
refs/heads/master
Xcodes/Mac/PreferencesTabViewController.swift
mit
1
// // PreferencesTabViewController.swift // Prephirences /* The MIT License (MIT) Copyright (c) 2017 Eric Marchand (phimage) 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(macOS) import Cocoa /* Controller of tab view item can give prefered size by implementing this protocol */ @objc public protocol PreferencesTabViewItemControllerType { var preferencesTabViewSize: NSSize {get} } /* Key for event on property preferencesTabViewSize */ public let kPreferencesTabViewSize = "preferencesTabViewSize" /* Controller which resize parent window according to tab view items, useful for preferences */ @available(OSX 10.10, *) public class PreferencesTabViewController: NSTabViewController { private var observe = false // Keep size of subview private var cacheSize = [NSView: NSSize]() // MARK: overrides override public func viewDidLoad() { super.viewDidLoad() self.transitionOptions = [] } override public func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { // remove listener on previous selected tab view if let selectedTabViewItem = self.selectedTabViewItem as? NSTabViewItem, let viewController = selectedTabViewItem.viewController as? PreferencesTabViewItemControllerType, observe { (viewController as! NSViewController).removeObserver(self, forKeyPath: kPreferencesTabViewSize, context: nil) observe = false } super.tabView(tabView, willSelect: tabViewItem) // get size and listen to change on futur selected tab view item if let view = tabViewItem?.view { let currentSize = view.frame.size // Expect size from storyboard constraints or previous size if let viewController = tabViewItem?.viewController as? PreferencesTabViewItemControllerType { cacheSize[view] = getPreferencesTabViewSize(viewController, currentSize) // Observe kPreferencesTabViewSize let options = NSKeyValueObservingOptions.new.union(.old) (viewController as! NSViewController).addObserver(self, forKeyPath: kPreferencesTabViewSize, options: options, context: nil) observe = true } else { cacheSize[view] = cacheSize[view] ?? currentSize } } } override public func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { super.tabView(tabView, didSelect: tabViewItem) if let view = tabViewItem?.view, let window = self.view.window, let contentSize = cacheSize[view] { self.setFrameSize(size: contentSize, forWindow: window) } } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let kp = keyPath, kp == kPreferencesTabViewSize { if let window = self.view.window, let viewController = object as? PreferencesTabViewItemControllerType, let view = (viewController as? NSViewController)?.view, let currentSize = cacheSize[view] { let contentSize = self.getPreferencesTabViewSize(viewController, currentSize) cacheSize[view] = contentSize DispatchQueue.main.async { self.setFrameSize(size: contentSize, forWindow: window) } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } override public func removeTabViewItem(_ tabViewItem: NSTabViewItem) { if let _ = tabViewItem.view { if let viewController = tabViewItem.viewController as? PreferencesTabViewItemControllerType { tabViewItem.removeObserver(viewController as! NSViewController, forKeyPath: kPreferencesTabViewSize) } } } func _removeAllToolbarItems(){ // Maybe fix a bug with toolbar style } deinit { if let selectedTabViewItem = self.selectedTabViewItem as? NSTabViewItem, let viewController = selectedTabViewItem.viewController as? PreferencesTabViewItemControllerType, observe { (viewController as! NSViewController).removeObserver(self, forKeyPath: kPreferencesTabViewSize, context: nil) } } // MARK: public public var selectedTabViewItem: AnyObject? { return selectedTabViewItemIndex<0 ? nil : tabViewItems[selectedTabViewItemIndex] } // MARK: privates private func getPreferencesTabViewSize(_ viewController: PreferencesTabViewItemControllerType,_ referenceSize: NSSize) -> NSSize { var controllerProposedSize = viewController.preferencesTabViewSize if controllerProposedSize.width <= 0 { // 0 means keep size controllerProposedSize.width = referenceSize.width } if controllerProposedSize.height <= 0 { controllerProposedSize.height = referenceSize.height } return controllerProposedSize } private func setFrameSize(size: NSSize, forWindow window: NSWindow) { let newWindowSize = window.frameRect(forContentRect: NSRect(origin: CGPoint.zero, size: size)).size var frame = window.frame frame.origin.y += frame.size.height frame.origin.y -= newWindowSize.height frame.size = newWindowSize window.setFrame(frame, display:true, animate:true) } } #endif
a16dd2f92dd26bbf2cbaf781bf20850b
41.006452
158
0.699585
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AACountryViewController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit public protocol AACountryViewControllerDelegate { func countriesController(countriesController: AACountryViewController, didChangeCurrentIso currentIso: String) } public class AACountryViewController: AATableViewController { private var _countries: NSDictionary! private var _letters: NSArray! public var delegate: AACountryViewControllerDelegate? public init() { super.init(style: UITableViewStyle.Plain) self.title = AALocalized("AuthCountryTitle") let cancelButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss")) self.navigationItem.setLeftBarButtonItem(cancelButtonItem, animated: false) self.content = ACAllEvents_Auth.AUTH_PICK_COUNTRY() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 44.0 tableView.sectionIndexBackgroundColor = UIColor.clearColor() } private func countries() -> NSDictionary { if (_countries == nil) { let countries = NSMutableDictionary() for (_, iso) in ABPhoneField.sortedIsoCodes().enumerate() { let countryName = ABPhoneField.countryNameByCountryCode()[iso as! String] as! String let phoneCode = ABPhoneField.callingCodeByCountryCode()[iso as! String] as! String // if (self.searchBar.text.length == 0 || [countryName rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch].location != NSNotFound) let countryLetter = countryName.substringToIndex(countryName.startIndex.advancedBy(1)) if (countries[countryLetter] == nil) { countries[countryLetter] = NSMutableArray() } countries[countryLetter]!.addObject([countryName, iso, phoneCode]) } _countries = countries; } return _countries; } private func letters() -> NSArray { if (_letters == nil) { _letters = (countries().allKeys as NSArray).sortedArrayUsingSelector(#selector(YYTextPosition.compare(_:))) } return _letters; } public func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return letters() as [AnyObject] } public func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return index } public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return letters().count; } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (countries()[letters()[section] as! String] as! NSArray).count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: AAAuthCountryCell = tableView.dequeueCell(indexPath) let letter = letters()[indexPath.section] as! String let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String] cell.setTitle(countryData[0]) cell.setCode("+\(countryData[2])") cell.setSearchMode(false) return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let letter = letters()[indexPath.section] as! String let countryData = (countries().objectForKey(letter) as! NSArray)[indexPath.row] as! [String] delegate?.countriesController(self, didChangeCurrentIso: countryData[1]) dismiss() } public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25.0 } public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return letters()[section] as? String } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: true) } }
6eaf5933abfde6e36d707a242c203dc8
37.672269
172
0.653988
false
false
false
false
frootloops/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSDictionary.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : ExpressibleByDictionaryLiteral { public required convenience init( dictionaryLiteral elements: (Any, Any)... ) { // FIXME: Unfortunate that the `NSCopying` check has to be done at runtime. self.init( objects: elements.map { $0.1 as AnyObject }, forKeys: elements.map { $0.0 as AnyObject as! NSCopying }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil) as AnyObject, to: _NSDictionary.self)) } } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( _ d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d as AnyObject, to: _NSDictionary.self)) return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in let anyObjectKey = anyKey as AnyObject let anyObjectValue = anyValue as AnyObject builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ d: NSDictionary? ) -> Dictionary { // `nil` has historically been used as a stand-in for an empty // dictionary; map it to an empty dictionary. if _slowPath(d == nil) { return Dictionary() } if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d! as AnyObject) { return native } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { return [Key : Value]( _cocoaDictionary: unsafeBitCast(d! as AnyObject, to: _NSDictionary.self)) } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d!.count) d!.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyKey as AnyObject, Key.self), value: Swift._forceBridgeFromObjectiveC(anyValue as AnyObject, Value.self)) }) return builder.take() } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: Any, value: Any)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } // Bridging subscript. @objc public subscript(key: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return self.object(forKey: key) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSMutableDictionary { // Bridging subscript. override public subscript(key: Any) -> Any? { get { return self.object(forKey: key) } @objc(_swift_setObject:forKeyedSubscript:) set { // FIXME: Unfortunate that the `NSCopying` check has to be done at // runtime. let copyingKey = key as AnyObject as! NSCopying if let newValue = newValue { self.setObject(newValue, forKey: copyingKey) } else { self.removeObject(forKey: copyingKey) } } } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary--which might be different /// than the original receiver--containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { // FIXME(performance)(compiler limitation): we actually want to do just // `self = otherDictionary.copy()`, but Swift does not have factory // initializers right now. let numElems = otherDictionary.count let stride = MemoryLayout<AnyObject>.stride let alignment = MemoryLayout<AnyObject>.alignment let singleSize = stride * numElems let totalSize = singleSize * 2 _sanityCheck(stride == MemoryLayout<NSCopying>.stride) _sanityCheck(alignment == MemoryLayout<NSCopying>.alignment) // Allocate a buffer containing both the keys and values. let buffer = UnsafeMutableRawPointer.allocate( byteCount: totalSize, alignment: alignment) defer { buffer.deallocate() _fixLifetime(otherDictionary) } let valueBuffer = buffer.bindMemory(to: AnyObject.self, capacity: numElems) let buffer2 = buffer + singleSize __NSDictionaryGetObjects(otherDictionary, buffer, buffer2, numElems) let keyBufferCopying = buffer2.assumingMemoryBound(to: NSCopying.self) self.init(objects: valueBuffer, forKeys: keyBufferCopying, count: numElems) } } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } } extension Dictionary: CVarArg {}
5383264fb37385a0255736dbc9e9eae1
35.289157
122
0.666224
false
false
false
false
chaoyang805/DoubanMovie
refs/heads/master
DoubanMovie/Snackbar.swift
apache-2.0
1
/* * Copyright 2016 chaoyang805 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit let SnackbarShouldShowNotification = Notification.Name("show snackbar") let SnackbarShouldDismissNotification = Notification.Name("dismiss snackbar") let SnackbarUserInfoKey = "targetSnackbar" @objc protocol SnackbarDelegate: NSObjectProtocol { @objc optional func snackbarWillAppear(_ snackbar: Snackbar) @objc optional func snackbarDidAppear(_ snackbar: Snackbar) @objc optional func snackbarWillDisappear(_ snackbar: Snackbar) @objc optional func snackbarDidDisappear(_ snackbar: Snackbar) } enum SnackbarDuration: TimeInterval { case Short = 1.5 case Long = 3 } class Snackbar: NSObject { private(set) lazy var view: SnackbarView = { let _barView = SnackbarView() // 为了Snackbar不被销毁 _barView.snackbar = self return _barView }() private var showing: Bool = false private var dismissHandler: (() -> Void)? var duration: TimeInterval! private weak var delegate: SnackbarDelegate? class func make(text: String, duration: SnackbarDuration) -> Snackbar { return make(text, duration: duration.rawValue) } private class func make(_ text: String, duration: TimeInterval) -> Snackbar { let snackbar = Snackbar() snackbar.setSnackbarText(text: text) snackbar.duration = duration snackbar.registerNotification() snackbar.delegate = SnackbarManager.defaultManager() return snackbar } func show() { let record = SnackbarRecord(duration: duration, identifier: hash) SnackbarManager.defaultManager().show(record) } func dispatchDismiss() { let record = SnackbarRecord(duration: duration, identifier: hash) SnackbarManager.defaultManager().dismiss(record) } // MARK: - Notification func registerNotification() { let manager = SnackbarManager.defaultManager() NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldShowNotification, object: manager) NotificationCenter.default.addObserver(self, selector: #selector(Snackbar.handleNotification(_:)), name: SnackbarShouldDismissNotification, object: manager) } func unregisterNotification() { NotificationCenter.default.removeObserver(self) } deinit { NSLog("deinit") } func handleNotification(_ notification: NSNotification) { guard let identifier = notification.userInfo?[SnackbarUserInfoKey] as? Int else { NSLog("not found snackbar in notification's userInfo") return } guard identifier == self.hash else { NSLog("not found specified snackbar:\(identifier)") return } switch notification.name { case SnackbarShouldShowNotification: handleShowNotification() case SnackbarShouldDismissNotification: handleDismissNotification() default: break } } func handleShowNotification() { self.showView() } func handleDismissNotification() { self.dismissView() } // MARK: - Configure Snackbar func setSnackbarText(text: String) { view.messageView.text = text view.messageView.sizeToFit() } // MARK: - Warning Retain cycle(solved) func setAction(title: String, action: @escaping ((_ sender: AnyObject) -> Void)) -> Snackbar { view.setAction(title: title) { (sender) in action(sender) self.dispatchDismiss() } return self } func dismissHandler(block: @escaping (() -> Void)) -> Snackbar { self.dismissHandler = block return self } // MARK: - Snackbar View show & dismiss private func showView() { guard let window = UIApplication.shared.keyWindow else { return } self.delegate?.snackbarWillAppear?(self) window.addSubview(view) UIView.animate( withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: -40) }, completion: { (done ) in self.delegate?.snackbarDidAppear?(self) self.showing = true }) } func dismissView() { guard self.showing else { return } self.delegate?.snackbarWillDisappear?(self) UIView.animate( withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 40) }, completion: { (done) in self.showing = false self.view.snackbar = nil self.view.removeFromSuperview() self.dismissHandler?() self.delegate?.snackbarDidDisappear?(self) self.delegate = nil self.unregisterNotification() } ) } }
96d8aa7f717a45976459d384d002f611
29.796117
164
0.583859
false
false
false
false
bitjammer/swift
refs/heads/master
test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
apache-2.0
3
@_exported import ObjectiveC // Clang module // The iOS/arm64 target uses _Bool for Objective-C's BOOL. We include // x86_64 here as well because the iOS simulator also uses _Bool. #if ((os(iOS) || os(tvOS)) && (arch(arm64) || arch(x86_64))) || os(watchOS) public struct ObjCBool { private var value : Bool public init(_ value: Bool) { self.value = value } public var boolValue: Bool { return value } } #else public struct ObjCBool { private var value : UInt8 public init(_ value: Bool) { self.value = value ? 1 : 0 } public init(_ value: UInt8) { self.value = value } public var boolValue: Bool { if value == 0 { return false } return true } } #endif extension ObjCBool : ExpressibleByBooleanLiteral { public init(booleanLiteral: Bool) { self.init(booleanLiteral) } } public struct Selector : ExpressibleByStringLiteral { private var ptr : OpaquePointer public init(_ value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init (stringLiteral value: String) { self = sel_registerName(value) } public var hashValue: Int { return ptr.hashValue } } extension Selector : Equatable, Hashable {} public func ==(lhs: Selector, rhs: Selector) -> Bool { return sel_isEqual(lhs, rhs) } public struct NSZone { public var pointer : OpaquePointer } internal func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool { return ObjCBool(x) } internal func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool { return x.boolValue } public func ~=(x: NSObject, y: NSObject) -> Bool { return true } extension NSObject : Equatable, Hashable { public var hashValue: Int { return hash } } public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) }
9c7d6cb06e0a3d463b1f761c55672dda
19
75
0.677551
false
false
false
false
proxyco/RxBluetoothKit
refs/heads/master
Source/RestoredState.swift
mit
1
// // RestoredState.swift // RxBluetoothKit // // Created by Kacper Harasim on 21.05.2016. // Copyright © 2016 Polidea. All rights reserved. // import Foundation import CoreBluetooth /** Convenience class which helps reading state of restored BluetoothManager */ #if os(iOS) public struct RestoredState { /** Restored state dictionary */ public let restoredStateData: [String:AnyObject] public unowned let bluetoothManager: BluetoothManager /** Creates restored state information based on CoreBluetooth's dictionary - parameter restoredState: Core Bluetooth's restored state data - parameter bluetoothManager: `BluetoothManager` instance of which state has been restored. */ init(restoredStateDictionary: [String:AnyObject], bluetoothManager: BluetoothManager) { self.restoredStateData = restoredStateDictionary self.bluetoothManager = bluetoothManager } /** Array of `Peripheral` objects which have been restored. These are peripherals that were connected to the central manager (or had a connection pending) at the time the app was terminated by the system. */ public var peripherals: [Peripheral] { let objects = restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } return arrayOfAnyObjects.flatMap { $0 as? CBPeripheral } .map { RxCBPeripheral(peripheral: $0) } .map { Peripheral(manager: bluetoothManager, peripheral: $0) } } /** Dictionary that contains all of the peripheral scan options that were being used by the central manager at the time the app was terminated by the system. */ public var scanOptions: [String : AnyObject]? { return restoredStateData[CBCentralManagerRestoredStatePeripheralsKey] as? [String : AnyObject] } /** Array of `Service` objects which have been restored. These are all the services the central manager was scanning for at the time the app was terminated by the system. */ public var services: [Service] { let objects = restoredStateData[CBCentralManagerRestoredStateScanServicesKey] as? [AnyObject] guard let arrayOfAnyObjects = objects else { return [] } return arrayOfAnyObjects.flatMap { $0 as? CBService } .map { RxCBService(service: $0) } .map { Service(peripheral: Peripheral(manager: bluetoothManager, peripheral: RxCBPeripheral(peripheral: $0.service.peripheral)), service: $0) } } } #endif
8530218d4e33480c4e15bf7bffcb6823
39.421875
205
0.708156
false
false
false
false
yangyouyong0/SwiftLearnLog
refs/heads/master
CiChang/CiChang/ViewController.swift
apache-2.0
1
// // ViewController.swift // CiChang // // Created by yangyouyong on 15/7/8. // Copyright © 2015年 yangyouyong. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{ var bookArray = Array<CCBook>() var tableView:UITableView? // tableView // @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.setupView() self.requestData() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } internal func setupView() { self.tableView = UITableView(frame: CGRectMake(0, 0, CGRectGetHeight(self.view.bounds), CGRectGetHeight(self.view.bounds)), style: .Plain) self.view.addSubview(self.tableView!) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "bookCell") } internal func requestData() { let urlStr = "http://cichang.hjapi.com/v2/book/?pageIndex=0&pageSize=100&sort=popular" // let url = NSURL(string: urlStr) // let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { // (data, response, error) in // if data != nil { // do { // let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary // print("jsonData \(jsonData)") // // } catch { // // report error // print("noData,\(error)") // }// // }else{ // print("noData,\(error)") // } // } // task!.resume() // do { // let jsonData = try NSJSONSerialization.JSONObjectWithData(data as! NSData, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary // print("jsonData \(jsonData)") // } catch { // // report error // print("noData,\(error)") // }// Alamofire.request(.GET, URLString: urlStr).response { (_, _, data, error) in if data != nil { if (JSON(data: data as! NSData) != nil){ let json = JSON(data: data as! NSData) let items = json["data"]["items"] for value in items{ let (_ , dict) = value as (String,JSON) let book = CCBook().initWithDict(dict.object as! [String : AnyObject]) print(dict.object) print("value is \(book)") self.bookArray.append(book) } print("bookArray") print(self.bookArray) self.tableView!.reloadData() } }else{ print("noData,\(error)") } } } /* // 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. } */ // MARK: - TableViewDelegate&DataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("bookCell", forIndexPath: indexPath) let book:CCBook = self.bookArray[indexPath.row] cell.textLabel?.text = book.name // Alamofire.request(.GET, URLString: book.coverImageUrl!).response { // (_, _, data, error) in // if data != nil { // let image = UIImage(data: data as! NSData) // cell.imageView?.image = image // } // } // let imageUrl :NSURL = NSURL() // let imageData :NSData = NSData(contentsOfURL: ) // cell.coverImage.image = UIImage(data: NSData(contentsOfURL:NSURL.URLWithString(book.coverImageUrl!)!)!)!)! // var nsd = NSData(contentsOfURL:NSURL.URLWithString("http://ww2.sinaimg.cn/bmiddle/632dab64jw1ehgcjf2rd5j20ak07w767.jpg")) // Configure the cell... return cell } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.bookArray.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 68 } }
cd8c9a6e3bdbc2466a20a52a1dd0becc
37.847328
162
0.57025
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Orders/HBCIAccountStatementOrder.swift
gpl-2.0
1
// // HBCIAccountStatementOrder.swift // HBCI4Swift // // Created by Frank Emminghaus on 22.03.16. // Copyright © 2016 Frank Emminghaus. All rights reserved. // import Foundation public struct HBCIAccountStatementOrderPar { public var supportsNumber:Bool; public var needsReceipt:Bool; public var supportsLimit:Bool; public var formats:Array<HBCIAccountStatementFormat>; } open class HBCIAccountStatementOrder: HBCIOrder { public let account:HBCIAccount; open var number:Int? open var year:Int? open var format:HBCIAccountStatementFormat? // result open var statements = Array<HBCIAccountStatement>(); public init?(message: HBCICustomMessage, account:HBCIAccount) { self.account = account; super.init(name: "AccountStatement", message: message); //adjustNeedsTanForPSD2(); if self.segment == nil { return nil; } } open func enqueue() ->Bool { // check if order is supported if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) { logInfo(self.name + " is not supported for account " + account.number); return false; } var values = Dictionary<String,Any>(); // check if SEPA version is supported (only globally for bank - // later we check if account supports this as well if segment.version >= 7 { // we have the SEPA version if account.iban == nil || account.bic == nil { logInfo("Account has no IBAN or BIC information"); return false; } values = ["KTV.bic":account.bic!, "KTV.iban":account.iban!]; } else { values = ["KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode]; if account.subNumber != nil { values["KTV.subnumber"] = account.subNumber! } } if let idx = self.number { values["idx"] = idx; } if let year = self.year { values["year"] = year; } if let format = self.format { values["format"] = String(format.rawValue); } if !segment.setElementValues(values) { logInfo("AccountStatementOrder values could not be set"); return false; } // add to message return msg.addOrder(self); } override open func updateResult(_ result:HBCIResultMessage) { super.updateResult(result); for seg in resultSegments { if let statement = HBCIAccountStatement(segment: seg) { statements.append(statement); } } } open class func getParameters(_ user:HBCIUser) ->HBCIAccountStatementOrderPar? { guard let (elem, seg) = self.getParameterElement(user, orderName: "AccountStatement") else { return nil; } guard let supportsNumber = elem.elementValueForPath("canindex") as? Bool else { logInfo("AccountStatementParameters: mandatory parameter canindex missing"); logInfo(seg.description); return nil; } guard let needsReceipt = elem.elementValueForPath("needreceipt") as? Bool else { logInfo("AccountStatementParameters: mandatory parameter needreceipt missing"); logInfo(seg.description); return nil; } guard let supportsLimit = elem.elementValueForPath("canmaxentries") as? Bool else { logInfo("AccountStatementParameters: mandatory parameter supportsLimit missing"); logInfo(seg.description); return nil; } var formats = Array<HBCIAccountStatementFormat>(); if let fm = elem.elementValuesForPath("format") as? [String] { for formatString in fm { if let format = convertAccountStatementFormat(formatString) { formats.append(format); } } } return HBCIAccountStatementOrderPar(supportsNumber: supportsNumber, needsReceipt: needsReceipt, supportsLimit: supportsLimit, formats: formats); } }
d2631abafa732ef01fc518e1009c3bcf
33.416
152
0.598791
false
false
false
false
swiftix/swift
refs/heads/master
test/SILGen/objc_properties.swift
apache-2.0
1
// RUN: %target-swift-frontend %s -emit-silgen -emit-verbose-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import | %FileCheck %s // REQUIRES: objc_interop import Foundation class A { @objc dynamic var prop: Int @objc dynamic var computedProp: Int { get { return 5 } set {} } // Regular methods go through the @objc property accessors. // CHECK-LABEL: sil hidden @_T015objc_properties1AC6method{{[_0-9a-zA-Z]*}}F // CHECK: objc_method {{.*}} #A.prop func method(_ x: Int) { prop = x method(prop) } // Initializers and destructors always directly access stored properties, even // when they are @objc. // CHECK-LABEL: sil hidden @_T015objc_properties1AC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: class_method {{.*}} #A.prop init() { prop = 5 method(prop) prop = 6 } // rdar://15858869 - However, direct access only applies to (implicit or // explicit) 'self' ivar references, not ALL ivar refs. // CHECK-LABEL: sil hidden @_T015objc_properties1AC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0(%0 : $A, %1 : $Int, %2 : $A): // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] %2 : $A init(other : A, x : Int) { // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[SELF_A:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $A, #A.prop // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[SELF_A]] : $*Int // CHECK: assign %1 to [[WRITE]] // CHECK: end_access [[WRITE]] : $*Int // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] prop = x // CHECK: objc_method // CHECK: apply other.prop = x } // CHECK-LABEL: sil hidden @_T015objc_properties1ACfd : $@convention(method) (@guaranteed A) -> @owned Builtin.NativeObject { // CHECK-NOT: class_method {{.*}} #A.prop // CHECK: } deinit { prop = 7 method(prop) } } // CHECK-LABEL: sil hidden @_T015objc_properties11testPropGet{{[_0-9a-zA-Z]*}}F func testPropGet(_ a: A) -> Int { // CHECK: objc_method [[OBJ:%[0-9]+]] : $A, #A.prop!getter.1.foreign : (A) -> () -> Int, $@convention(objc_method) (A) -> Int return a.prop } // CHECK-LABEL: sil hidden @_T015objc_properties11testPropSet{{[_0-9a-zA-Z]*}}F func testPropSet(_ a: A, i: Int) { // CHECK: objc_method [[OBJ:%[0-9]+]] : $A, #A.prop!setter.1.foreign : (A) -> (Int) -> (), $@convention(objc_method) (Int, A) -> () a.prop = i } // CHECK-LABEL: sil hidden @_T015objc_properties19testComputedPropGet{{[_0-9a-zA-Z]*}}F func testComputedPropGet(_ a: A) -> Int { // CHECK: objc_method [[OBJ:%[0-9]+]] : $A, #A.computedProp!getter.1.foreign : (A) -> () -> Int, $@convention(objc_method) (A) -> Int return a.computedProp } // CHECK-LABEL: sil hidden @_T015objc_properties19testComputedPropSet{{[_0-9a-zA-Z]*}}F func testComputedPropSet(_ a: A, i: Int) { // CHECK: objc_method [[OBJ:%[0-9]+]] : $A, #A.computedProp!setter.1.foreign : (A) -> (Int) -> (), $@convention(objc_method) (Int, A) -> () a.computedProp = i } // 'super' property references. class B : A { @objc override var computedProp: Int { // CHECK-LABEL: sil hidden @_T015objc_properties1BC12computedPropSivg : $@convention(method) (@guaranteed B) -> Int get { // CHECK: objc_super_method [[SELF:%[0-9]+]] : $B, #A.computedProp!getter.1.foreign : (A) -> () -> Int, $@convention(objc_method) (A) -> Int return super.computedProp } // CHECK-LABEL: sil hidden @_T015objc_properties1BC12computedPropSivs : $@convention(method) (Int, @guaranteed B) -> () set(value) { // CHECK: objc_super_method [[SELF:%[0-9]+]] : $B, #A.computedProp!setter.1.foreign : (A) -> (Int) -> (), $@convention(objc_method) (Int, A) -> () super.computedProp = value } } } // Test the @NSCopying attribute. class TestNSCopying { // CHECK-LABEL: sil hidden [transparent] @_T015objc_properties13TestNSCopyingC8propertySo8NSStringCvs : $@convention(method) (@owned NSString, @guaranteed TestNSCopying) -> () // CHECK: bb0([[ARG0:%.*]] : $NSString, [[ARG1:%.*]] : $TestNSCopying): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: objc_method [[BORROWED_ARG0]] : $NSString, #NSString.copy!1.foreign @NSCopying var property : NSString @NSCopying var optionalProperty : NSString? @NSCopying var uncheckedOptionalProperty : NSString! @NSCopying weak var weakProperty : NSString? = nil // @NSCopying unowned var unownedProperty : NSString? = nil init(s : NSString) { property = s } } // <rdar://problem/16663515> IBOutlet not adjusting getter/setter when making a property implicit unchecked optional @objc class TestComputedOutlet : NSObject { var _disclosedView : TestComputedOutlet! = .none @IBOutlet var disclosedView : TestComputedOutlet! { get { return _disclosedView } set { _disclosedView = newValue } } func foo() { _disclosedView != nil ? () : self.disclosedView.foo() } } class Singleton : NSObject { // CHECK-DAG: sil hidden @_T015objc_properties9SingletonC14sharedInstanceACvgZ : $@convention(method) (@thick Singleton.Type) -> @owned Singleton // CHECK-DAG: sil hidden [thunk] @_T015objc_properties9SingletonC14sharedInstanceACvgZTo : $@convention(objc_method) (@objc_metatype Singleton.Type) -> @autoreleased Singleton { static let sharedInstance = Singleton() // CHECK-DAG: sil hidden @_T015objc_properties9SingletonC1iSivgZ : $@convention(method) (@thick Singleton.Type) -> Int // CHECK-DAG: sil hidden [thunk] @_T015objc_properties9SingletonC1iSivgZTo : $@convention(objc_method) (@objc_metatype Singleton.Type) -> Int static let i = 2 // CHECK-DAG: sil hidden @_T015objc_properties9SingletonC1jSSvgZ : $@convention(method) (@thick Singleton.Type) -> @owned String // CHECK-DAG: sil hidden [thunk] @_T015objc_properties9SingletonC1jSSvgZTo : $@convention(objc_method) (@objc_metatype Singleton.Type) -> @autoreleased NSString // CHECK-DAG: sil hidden @_T015objc_properties9SingletonC1jSSvsZ : $@convention(method) (@owned String, @thick Singleton.Type) -> () // CHECK-DAG: sil hidden [thunk] @_T015objc_properties9SingletonC1jSSvsZTo : $@convention(objc_method) (NSString, @objc_metatype Singleton.Type) -> () static var j = "Hello" // CHECK-DAG: sil hidden [thunk] @_T015objc_properties9SingletonC1kSdvgZTo : $@convention(objc_method) (@objc_metatype Singleton.Type) -> Double // CHECK-DAG: sil hidden @_T015objc_properties9SingletonC1kSdvgZ : $@convention(method) (@thick Singleton.Type) -> Double static var k: Double { return 7.7 } } class HasUnmanaged : NSObject { // CHECK-LABEL: sil hidden [thunk] @_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvgTo // CHECK: bb0([[CLS:%.*]] : $HasUnmanaged): // CHECK: [[CLS_COPY:%.*]] = copy_value [[CLS]] // CHECK: [[BORROWED_CLS_COPY:%.*]] = begin_borrow [[CLS_COPY]] // CHECK: [[NATIVE:%.+]] = function_ref @_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvg // CHECK: [[RESULT:%.+]] = apply [[NATIVE]]([[BORROWED_CLS_COPY]]) // CHECK: end_borrow [[BORROWED_CLS_COPY]] from [[CLS_COPY]] // CHECK-NOT: {{(retain|release)}} // CHECK: destroy_value [[CLS_COPY]] : $HasUnmanaged // CHECK-NOT: {{(retain|release)}} // CHECK: return [[RESULT]] : $Optional<Unmanaged<AnyObject>> // CHECK: } // end sil function '_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvgTo' // CHECK-LABEL: sil hidden [thunk] @_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvsTo // CHECK: bb0([[NEW_VALUE:%.*]] : $Optional<Unmanaged<AnyObject>>, [[SELF:%.*]] : $HasUnmanaged): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $HasUnmanaged // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[NATIVE:%.+]] = function_ref @_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvs // CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]([[NEW_VALUE]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] : $HasUnmanaged // CHECK-NEXT: return [[RESULT:%.*]] // CHECK: } // end sil function '_T015objc_properties12HasUnmanagedC3refs0D0VyyXlGSgvsTo' @objc var ref: Unmanaged<AnyObject>? } @_silgen_name("autoreleasing_user") func useAutoreleasingUnsafeMutablePointer(_ a: AutoreleasingUnsafeMutablePointer<NSObject>) class NonObjCClassWithObjCProperty { var property: NSObject init(_ newValue: NSObject) { property = newValue } // CHECK-LABEL: sil hidden @_T015objc_properties016NonObjCClassWithD9CPropertyC11usePropertyyyF : $@convention(method) (@guaranteed NonObjCClassWithObjCProperty) -> () { // CHECK: bb0([[ARG:%.*]] : $NonObjCClassWithObjCProperty): // CHECK: [[MATERIALIZE_FOR_SET:%.*]] = class_method [[ARG]] : $NonObjCClassWithObjCProperty, #NonObjCClassWithObjCProperty.property!materializeForSet.1 // CHECK: [[TUPLE:%.*]] = apply [[MATERIALIZE_FOR_SET]]({{.*}}, {{.*}}, [[ARG]]) // CHECK: [[RAW_POINTER:%.*]] = tuple_extract [[TUPLE]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 0 // CHECK: [[OBJECT:%.*]] = pointer_to_address [[RAW_POINTER]] : $Builtin.RawPointer to [strict] $*NSObject // CHECK: [[OBJECT_DEP:%.*]] = mark_dependence [[OBJECT]] : $*NSObject on [[ARG]] // CHECK: [[LOADED_OBJECT:%.*]] = load_borrow [[OBJECT_DEP]] // CHECK: [[UNMANAGED_OBJECT:%.*]] = ref_to_unmanaged [[LOADED_OBJECT]] : $NSObject to $@sil_unmanaged NSObject // CHECK: end_borrow [[LOADED_OBJECT]] from [[OBJECT_DEP]] func useProperty() { useAutoreleasingUnsafeMutablePointer(&property) } } // <rdar://problem/21544588> crash when overriding non-@objc property with @objc property. class NonObjCBaseClass : NSObject { @nonobjc var property: Int { get { return 0 } set {} } } @objc class ObjCSubclass : NonObjCBaseClass { @objc override var property: Int { get { return 1 } set {} } } // CHECK-LABEL: sil hidden [thunk] @_T015objc_properties12ObjCSubclassC8propertySivgTo // CHECK-LABEL: sil hidden [thunk] @_T015objc_properties12ObjCSubclassC8propertySivsTo // Make sure lazy properties that witness @objc protocol requirements are // correctly formed // // <https://bugs.swift.org/browse/SR-1825> @objc protocol HasProperty { @objc var window: NSObject? { get set } } class HasLazyProperty : NSObject, HasProperty { func instanceMethod() -> NSObject? { return nil } lazy var window = self.instanceMethod() } // CHECK-LABEL: sil hidden @_T015objc_properties15HasLazyPropertyC6windowSo8NSObjectCSgvg : $@convention(method) (@guaranteed HasLazyProperty) -> @owned Optional<NSObject> { // CHECK: class_method %0 : $HasLazyProperty, #HasLazyProperty.instanceMethod!1 : (HasLazyProperty) -> () -> NSObject? // CHECK: return
b9a3ededb9d957fb9044436b265185cb
41.932
179
0.665518
false
true
false
false
TENDIGI/Obsidian-UI-iOS
refs/heads/master
src/BasicTabBar.swift
mit
1
// // BasicTabBar.swift // Alfredo // // Created by Nick Lee on 8/21/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // // I'm not very proud of this class... import UIKit public final class BasicTabBar: BaseTabBar { // MARK: Initialization public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { backgroundColor = backgroundColor ?? UIColor.white } /// The accent color, used for the selected tab text and indicator public override var tintColor: UIColor! { didSet { layoutButtons() setNeedsDisplay() } } /// The text color used for non-selected tabs public var textColor: UIColor = UIColor(red:0.14, green:0.14, blue:0.15, alpha:1) { didSet { layoutButtons() setNeedsDisplay() } } /// The height of the selected tab indicator public var indicatorHeight: CGFloat = 3 { didSet { setNeedsDisplay() } } /// The font used for the tab text public var tabFont = UIFont.systemFont(ofSize: UIFont.systemFontSize) { didSet { layoutButtons() } } // MARK: Layout fileprivate func layoutButtons() { guard delegate != nil else { return } subviews.forEach { $0.removeFromSuperview() } let tabNames = delegate.tabNames let buttons = tabNames.map { (title) -> UIButton in let b = UIButton(type: .custom) b.setTitle(title, for: UIControlState()) b.addTarget(self, action: #selector(BasicTabBar.selectTabButton(_:)), for: .touchUpInside) b.titleLabel?.font = self.tabFont b.setTitleColor(self.textColor, for: UIControlState()) b.setTitleColor(self.tintColor, for: .selected) b.setTitleColor(self.tintColor, for: .highlighted) return b } let buttonSize = ceil(width / CGFloat(tabNames.count)) var x: CGFloat = 0 for (i, b) in buttons.enumerated() { b.x = x b.y = 0 b.width = buttonSize b.height = height b.tag = i x += buttonSize } buttons.forEach { self.addSubview($0) } selectTab(delegate.selectedTabIndex) } // MARK: BaseTabBar overrides /// :nodoc: public override func layout() { super.layout() layoutButtons() } /// :nodoc: public override func selectTab(_ index: Int) { if let buttons = (subviews as? [UIButton])?.sorted(by: { $0.x < $1.x }) { for (i, b) in buttons.enumerated() { b.isSelected = (i == index) } } setNeedsDisplay() } public override func frameForTab(_ index: Int) -> CGRect { if let buttons = (subviews as? [UIButton])?.sorted(by: { $0.x < $1.x }) { for (i, b) in buttons.enumerated() { if i == index { return b.frame } } } return super.frameForTab(index) } // MARK: Actions @objc private func selectTabButton(_ button: UIButton) { delegate.selectTab(button.tag) } // MARK: UIView Overrides /// :nodoc: public override func draw(_ rect: CGRect) { super.draw(rect) let buttonWidth = rect.width / CGFloat(delegate.tabNames.count) tintColor.setFill() let fillRect = CGRect(x: buttonWidth * CGFloat(delegate.selectedTabIndex), y: rect.height - indicatorHeight, width: buttonWidth, height: indicatorHeight) UIRectFill(fillRect) } /// :nodoc: public override func layoutSubviews() { super.layoutSubviews() layoutButtons() } }
0c254eca7f5ed79c4f91cc580d5c46b0
24.844156
161
0.561558
false
false
false
false
Eliothu/WordPress-iOS
refs/heads/buildAndLearn5.5
WordPress/Classes/Extensions/UIViewController+Helpers.swift
gpl-2.0
18
import Foundation extension UIViewController { public func isViewOnScreen() -> Bool { let visibleAsRoot = view.window?.rootViewController == self let visibleAsTopOnStack = navigationController?.topViewController == self && view.window != nil let visibleAsPresented = view.window?.rootViewController?.presentedViewController == self return visibleAsRoot || visibleAsTopOnStack || visibleAsPresented } }
1213626184d62f88d7ae1c63e612ce5b
34.384615
103
0.706522
false
false
false
false
kentaiwami/FiNote
refs/heads/master
ios/FiNote/FiNote/Social/ByAge/SocialByAgeViewController.swift
mit
1
// // SocialByAgeViewController.swift // FiNote // // Created by 岩見建汰 on 2018/01/29. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit import NVActivityIndicatorView import SwiftyJSON import Alamofire import AlamofireImage import StatusProvider import KeychainAccess class SocialByAgeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITabBarControllerDelegate, StatusController { var contentView: UIView! var latestView: UIView! var scrollView = UIScrollView() var refresh_controll = UIRefreshControl() var movies: [[MovieByAge.Data]] = [[]] var preViewName = "Social" fileprivate let utility = Utility() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.clear let keychain = Keychain() if (try! keychain.get("birthyear"))! == "" { let status = Status(title: "No View", description: "誕生年を登録していないため閲覧することができません。\nユーザ情報画面にて誕生年を登録すると閲覧することができます。") show(status: status) }else { CallGetByAgeAPI() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.navigationItem.title = "年代別ランキング" self.tabBarController?.delegate = self } @objc func refresh(sender: UIRefreshControl) { refresh_controll.beginRefreshing() CallGetByAgeAPI() } func CallGetByAgeAPI() { let urlString = API.base.rawValue+API.v1.rawValue+API.movie.rawValue+API.byage.rawValue let activityData = ActivityData(message: "Get Data", type: .lineScaleParty) NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData, nil) DispatchQueue(label: "get-byage").async { Alamofire.request(urlString, method: .get).responseJSON { (response) in self.refresh_controll.endRefreshing() NVActivityIndicatorPresenter.sharedInstance.stopAnimating(nil) guard let res = response.result.value else{return} let obj = JSON(res) print("***** API results *****") print(obj) print("***** API results *****") self.movies.removeAll() if self.utility.isHTTPStatus(statusCode: response.response?.statusCode) { // 結果をパース let dictionaryValue = obj["results"].dictionaryValue for key in stride(from: 10, to: 60, by: 10) { // 10,20...ごとに配列を取得 let arrayValue = dictionaryValue[String(key)]?.arrayValue // title, overview, poster, countごとにまとめた配列を取得 let data_array = MovieByAge().GetDataArray(json: arrayValue!) self.movies.append(data_array) } self.DrawViews() }else { self.utility.showStandardAlert(title: "Error", msg: obj.arrayValue[0].stringValue, vc: self) } } } } func DrawViews() { InitScrollView() CreateSection(text: "10代", isTop: true) CreateCollectionView(tag: 1) for i in 2...5 { CreateSection(text: "\(i)0代", isTop: false) CreateCollectionView(tag: i) } contentView.bottom(to: latestView, offset: 20) } func InitScrollView() { scrollView.removeFromSuperview() refresh_controll = UIRefreshControl() scrollView = UIScrollView() scrollView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height) scrollView.refreshControl = refresh_controll refresh_controll.addTarget(self, action: #selector(self.refresh(sender:)), for: .valueChanged) self.view.addSubview(scrollView) scrollView.top(to: self.view) scrollView.leading(to: self.view) scrollView.trailing(to: self.view) scrollView.bottom(to: self.view) contentView = UIView() scrollView.addSubview(contentView) contentView.top(to: scrollView) contentView.leading(to: scrollView) contentView.trailing(to: scrollView) contentView.bottom(to: scrollView) contentView.width(to: scrollView) latestView = contentView } func CreateSection(text: String, isTop: Bool) { let label = UILabel(frame: CGRect.zero) label.text = text label.font = UIFont(name: Font.helveticaneue_B.rawValue, size: 20) contentView.addSubview(label) label.leading(to: contentView, offset: 20) if isTop { label.top(to: latestView, offset: 20) }else { label.topToBottom(of: latestView, offset: 20) } latestView = label } func CreateCollectionView(tag: Int) { let count_space = 35 as CGFloat let w = 150 as CGFloat let h = w*1.5 + count_space let margin = 16 as CGFloat let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: w, height: h) layout.minimumInteritemSpacing = margin layout.minimumLineSpacing = margin layout.sectionInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin) layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.register(SocialByAgeCell.self, forCellWithReuseIdentifier: "MyCell") collectionView.delegate = self collectionView.dataSource = self collectionView.tag = tag collectionView.backgroundColor = UIColor.clear contentView.addSubview(collectionView) collectionView.topToBottom(of: latestView, offset: 10) collectionView.leading(to: contentView, offset: 20 - margin) collectionView.width(to: contentView) collectionView.height(h) latestView = collectionView } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = collectionView.tag - 1 let title = "\(collectionView.tag*10)代 \(indexPath.row+1)位\n\(movies[index][indexPath.row].title)" var release_date = "" if movies[index][indexPath.row].release_date != "" { release_date = "公開日:\(movies[index][indexPath.row].release_date)\n\n" } utility.showStandardAlert(title: title, msg: release_date + movies[index][indexPath.row].overview, vc: self) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let index = collectionView.tag - 1 return movies[index].count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : SocialByAgeCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath) as! SocialByAgeCell let index = collectionView.tag - 1 cell.poster.af_setImage( withURL: URL(string: API.poster_base.rawValue+movies[index][indexPath.row].poster)!, placeholderImage: UIImage(named: "no_image") ) cell.user_count?.text = String(movies[index][indexPath.row].count) return cell } func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { if viewController.restorationIdentifier! == "Social" && preViewName == "Social" { scrollView.scroll(to: .top, animated: true) } preViewName = "Social" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
ac5ce854afadd15ecdca15f998fae4c8
36.855814
151
0.612483
false
false
false
false
miracl/amcl
refs/heads/master
version3/swift/fp8.swift
apache-2.0
2
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // fp8.swift // // Created by Michael Scott on 07/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* Finite Field arithmetic Fp^8 functions */ /* FP8 elements are of the form a+ib, where i is sqrt(sqrt(-1+sqrt(-1))) */ public struct FP8 { private var a:FP4 private var b:FP4 /* constructors */ init() { a=FP4() b=FP4() } init(_ c:Int) { a=FP4(c) b=FP4() } init(_ x:FP8) { a=FP4(x.a) b=FP4(x.b) } init(_ c:FP4,_ d:FP4) { a=FP4(c) b=FP4(d) } init(_ c:FP4) { a=FP4(c) b=FP4() } /* reduce all components of this mod Modulus */ mutating func reduce() { a.reduce() b.reduce() } /* normalise all components of this mod Modulus */ mutating func norm() { a.norm() b.norm() } /* test this==0 ? */ func iszilch() -> Bool { return a.iszilch() && b.iszilch() } mutating func cmove(_ g:FP8,_ d:Int) { a.cmove(g.a,d) b.cmove(g.b,d) } /* test this==1 ? */ func isunity() -> Bool { let one=FP4(1); return a.equals(one) && b.iszilch() } /* test is w real? That is in a+ib test b is zero */ func isreal() -> Bool { return b.iszilch(); } /* extract real part a */ func real() -> FP4 { return a; } func geta() -> FP4 { return a; } /* extract imaginary part b */ func getb() -> FP4 { return b; } mutating func set_fp4s(_ c: FP4,_ d: FP4) { a.copy(c) b.copy(d) } mutating func set_fp4(_ c: FP4) { a.copy(c) b.zero() } mutating func set_fp4h(_ c: FP4) { b.copy(c) a.zero() } /* test self=x? */ func equals(_ x:FP8) -> Bool { return a.equals(x.a) && b.equals(x.b) } /* copy self=x */ mutating func copy(_ x:FP8) { a.copy(x.a) b.copy(x.b) } /* set this=0 */ mutating func zero() { a.zero() b.zero() } /* set this=1 */ mutating func one() { a.one() b.zero() } /* set self=-self */ mutating func neg() { norm() var m=FP4(a) var t=FP4() m.add(b) m.neg() t.copy(m); t.add(b) b.copy(m) b.add(a) a.copy(t) norm() } /* self=conjugate(self) */ mutating func conj() { b.neg(); norm() } /* this=-conjugate(this) */ mutating func nconj() { a.neg(); norm() } mutating func adds(_ x: FP4) { a.add(x) } /* self+=x */ mutating func add(_ x:FP8) { a.add(x.a) b.add(x.b) } /* self-=x */ mutating func sub(_ x:FP8) { var m=FP8(x) m.neg() add(m) } /* self-=x */ mutating func rsub(_ x: FP8) { neg() add(x) } /* self*=s where s is FP4 */ mutating func pmul(_ s:FP4) { a.mul(s) b.mul(s) } /* self*=s where s is FP2 */ mutating func qmul(_ s:FP2) { a.pmul(s) b.pmul(s) } /* self*=s where s is FP */ mutating func tmul(_ s:FP) { a.qmul(s) b.qmul(s) } /* self*=c where c is int */ mutating func imul(_ c:Int) { a.imul(c) b.imul(c) } /* self*=self */ mutating func sqr() { var t1=FP4(a) var t2=FP4(b) var t3=FP4(a) t3.mul(b) t1.add(b) t2.times_i() t2.add(a) t1.norm(); t2.norm() a.copy(t1) a.mul(t2) t2.copy(t3) t2.times_i() t2.add(t3); t2.norm() t2.neg() a.add(t2) b.copy(t3) b.add(t3) norm() } /* self*=y */ mutating func mul(_ y:FP8) { var t1=FP4(a) var t2=FP4(b) var t3=FP4() var t4=FP4(b) t1.mul(y.a) t2.mul(y.b) t3.copy(y.b) t3.add(y.a) t4.add(a) t3.norm(); t4.norm() t4.mul(t3) t3.copy(t1) t3.neg() t4.add(t3) t4.norm() t3.copy(t2) t3.neg() b.copy(t4) b.add(t3) t2.times_i() a.copy(t2) a.add(t1) norm(); } /* convert this to hex string */ func toString() -> String { return ("["+a.toString()+","+b.toString()+"]") } func toRawString() -> String { return ("["+a.toRawString()+","+b.toRawString()+"]") } /* self=1/self */ mutating func inverse() { //norm(); var t1=FP4(a) var t2=FP4(b) t1.sqr() t2.sqr() t2.times_i(); t2.norm() t1.sub(t2); t1.norm() t1.inverse() a.mul(t1) t1.neg(); t1.norm() b.mul(t1) } /* self*=i where i = sqrt(-1+sqrt(-1)) */ mutating func times_i() { var s=FP4(b) let t=FP4(a) s.times_i() a.copy(s) b.copy(t) norm() } mutating func times_i2() { a.times_i() b.times_i() } /* self=self^p using Frobenius */ mutating func frob(_ f:FP2) { var ff=FP2(f); ff.sqr(); ff.mul_ip(); ff.norm() a.frob(ff) b.frob(ff) b.pmul(f) b.times_i() } /* self=self^e */ func pow(_ e:BIG) -> FP8 { var w=FP8(self) w.norm() var z=BIG(e) var r=FP8(1) z.norm() while (true) { let bt=z.parity() z.fshr(1) if bt==1 {r.mul(w)} if z.iszilch() {break} w.sqr() } r.reduce() return r } /* XTR xtr_a function */ mutating func xtr_A(_ w:FP8,_ y:FP8,_ z:FP8) { var r=FP8(w) var t=FP8(w) r.sub(y); r.norm() r.pmul(a) t.add(y); t.norm() t.pmul(b) t.times_i() copy(r) add(t) add(z) norm() } /* XTR xtr_d function */ mutating func xtr_D() { var w=FP8(self) sqr(); w.conj() w.add(w); w.norm(); sub(w) reduce() } /* r=x^n using XTR method on traces of FP24s */ func xtr_pow(_ n:BIG) -> FP8 { var a=FP8(3) var b=FP8(self) var c=FP8(b) c.xtr_D() var t=FP8() var r=FP8() var sf=FP8(self) let par=n.parity() var v=BIG(n); v.norm(); v.fshr(1) if par==0 {v.dec(1); v.norm()} let nb=v.nbits() var i=nb-1 while i>=0 { if (v.bit(UInt(i)) != 1) { t.copy(b) sf.conj() c.conj() b.xtr_A(a,sf,c) sf.conj() c.copy(t) c.xtr_D() a.xtr_D() } else { t.copy(a); t.conj() a.copy(b) a.xtr_D() b.xtr_A(c,sf,t) c.xtr_D() } i-=1 } if par==0 {r.copy(c)} else {r.copy(b)} r.reduce() return r } /* r=ck^a.cl^n using XTR double exponentiation method on traces of FP24s. See Stam thesis. */ func xtr_pow2(_ ck:FP8,_ ckml:FP8,_ ckm2l:FP8,_ a:BIG,_ b:BIG) -> FP8 { var e=BIG(a) var d=BIG(b) e.norm(); d.norm() var w=BIG(0) var cu=FP8(ck) // can probably be passed in w/o copying var cv=FP8(self) var cumv=FP8(ckml) var cum2v=FP8(ckm2l) var r=FP8() var t=FP8() var f2:Int=0 while d.parity()==0 && e.parity()==0 { d.fshr(1); e.fshr(1); f2 += 1; } while (BIG.comp(d,e) != 0) { if BIG.comp(d,e)>0 { w.copy(e); w.imul(4); w.norm() if BIG.comp(d,w)<=0 { w.copy(d); d.copy(e) e.rsub(w); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cum2v.conj() cumv.copy(cv) cv.copy(cu) cu.copy(t) } else if d.parity()==0 { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } else if e.parity()==1 { d.sub(e); d.norm() d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cu.xtr_D() cum2v.copy(cv) cum2v.xtr_D() cum2v.conj() cv.copy(t) } else { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } } if BIG.comp(d,e)<0 { w.copy(d); w.imul(4); w.norm() if BIG.comp(e,w)<=0 { e.sub(d); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cumv.copy(cu) cu.copy(t) } else if e.parity()==0 { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } else if d.parity()==1 { w.copy(e) e.copy(d) w.sub(d); w.norm() d.copy(w); d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cumv.conj() cum2v.copy(cu) cum2v.xtr_D() cum2v.conj() cu.copy(cv) cu.xtr_D() cv.copy(t) } else { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } } } r.copy(cv) r.xtr_A(cu,cumv,cum2v) for _ in 0 ..< f2 {r.xtr_D()} r=r.xtr_pow(d) return r } /* self/=2 */ mutating func div2() { a.div2() b.div2() } mutating func div_i() { var u=FP4(a) let v=FP4(b) u.div_i() a.copy(v) b.copy(u) } mutating func div_i2() { a.div_i() b.div_i() } mutating func div_2i() { var u=FP4(a) var v=FP4(b) u.div_2i() v.add(v); v.norm() a.copy(v) b.copy(u) } /* sqrt(a+ib) = sqrt(a+sqrt(a*a-n*b*b)/2)+ib/(2*sqrt(a+sqrt(a*a-n*b*b)/2)) */ /* returns true if this is QR */ mutating func sqrt() -> Bool { if iszilch() {return true} var aa=FP4(a) var s=FP4(b) var t=FP4(a) if s.iszilch() { if t.sqrt() { a.copy(t) b.zero() } else { t.div_i() _=t.sqrt() b.copy(t) a.zero() } return true } s.sqr() a.sqr() s.times_i() s.norm() aa.sub(s) s.copy(aa) if !s.sqrt() { return false } aa.copy(t); aa.add(s); aa.norm(); aa.div2() if !aa.sqrt() { aa.copy(t); aa.sub(s); aa.norm(); aa.div2() if !a.sqrt() { return false } } t.copy(b) s.copy(aa); s.add(aa) s.inverse() t.mul(s) a.copy(aa) b.copy(t) return true } }
7d352228bbf63770d21d04d70491a298
19.926756
97
0.376786
false
false
false
false
buyiyang/iosstar
refs/heads/master
iOSStar/Scenes/Discover/CustomView/SellingIntroCell.swift
gpl-3.0
3
// // SellingIntroCell.swift // iOSStar // // Created by J-bb on 17/7/8. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class SellingIntroCell: SellingBaseCell { @IBOutlet weak var jobLabel: UILabel! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var doDetail: UIButton! @IBOutlet weak var backImageView: UIImageView! @IBOutlet weak var iconImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() backImageView.contentMode = .scaleAspectFill backImageView.clipsToBounds = true } override func setPanicModel(model: PanicBuyInfoModel?) { guard model != nil else { return } nickNameLabel.text = model?.star_name backImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.back_pic_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil) iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.head_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil) jobLabel.text = model?.work } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
f4d4f69681c2b285bf65f5741501ecc0
33.552632
190
0.693069
false
false
false
false
AnarchyTools/atfoundation
refs/heads/master
src/filesystem/path.swift
apache-2.0
1
// Copyright (c) 2016 Anarchy Tools Contributors. // // 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. #if os(Linux) import Glibc #else import Darwin #endif /// Abstraction for filesystem paths public struct Path { /// split path components public let components: [String] /// is this an absolute or relative path public let isAbsolute: Bool /// delimiter between path components public var delimiter: Character /// Initialize with a string, the string is split /// into components by the rules of the current platform /// /// - Parameter string: The string to parse public init(_ string: String, delimiter: Character = "/") { self.delimiter = delimiter var components = string.split(character: self.delimiter) if components[0] == "" { self.isAbsolute = true components.remove(at: 0) } else { self.isAbsolute = false } self.components = components } /// Initialize with path components /// /// - Parameter components: Array of path component strings /// - Parameter absolute: Boolean, defines if the path is absolute public init(components: [String], absolute: Bool = false) { self.components = components self.isAbsolute = absolute self.delimiter = "/" } /// Initialize empty path /// /// - Parameter absolute: If set to true the empty path is equal to /// the root path, else it equals the current path public init(absolute: Bool = false) { self.components = [] self.isAbsolute = absolute self.delimiter = "/" } /// Create a new path instance by appending a component /// /// - Parameter component: path component to append /// - Returns: new Path instance public func appending(_ component: String) -> Path { var components = self.components components.append(component) return Path(components: components, absolute: self.isAbsolute) } /// Create a new path instance by removing the last path component /// /// - Returns: New path instance cropped by the last path component public func removingLastComponent() -> Path { var components = self.components components.removeLast() return Path(components: components, absolute: self.isAbsolute) } /// Create a new path instance by removing the first path component /// /// - Returns: New path instance cropped by the first path component, /// implies conversion to relative path public func removingFirstComponent() -> Path { var components = self.components components.remove(at: 0) return Path(components: components, absolute: false) } /// Create a new path instance by joining two paths /// /// - Parameter path: other path to append to this instance. /// If the other path is absolute the result /// is the other path without this instance. public func join(_ path: Path) -> Path { if path.isAbsolute { return Path(components: path.components, absolute: true) } else { var myComponents = self.components myComponents += path.components return Path(components: myComponents, absolute: self.isAbsolute) } } /// Create a path instance that defines a relative path to another path /// /// - Parameter path: the path to calculate a relative path to /// - Returns: new path instance that is a relative path to `path`. /// If this instance is not absolute the result will be `nil` public func relativeTo(path: Path) -> Path? { if !self.isAbsolute || !path.isAbsolute { return nil } let maxCount = min(self.components.count, path.components.count) var up = 0 var same = 0 for idx in 0..<maxCount { let c1 = self.components[idx] let c2 = path.components[idx] if c1 != c2 { up = maxCount - idx break } else { same = idx } } var newComponents = [String]() if same < up { for _ in 0..<(up - same + 1) { newComponents.append("..") } } for idx in (same + 1)..<self.components.count { newComponents.append(self.components[idx]) } return Path(components:newComponents, absolute: false) } /// Return the dirname of a path /// /// - Returns: new path instance with only the dir name public func dirname() -> Path { return self.removingLastComponent() } /// Return the file name of a path /// /// - Returns: file name string public func basename() -> String { return self.components.last! } /// Return absolute path to the user's home directory /// /// - Returns: absolute path to user's homee directory or `nil` if /// that's not available public static func homeDirectory() -> Path? { let home = getenv("HOME") if let h = home { if let s = String(validatingUTF8: h) { return Path(s) } } return nil } /// Return path to the temp directory /// /// - Returns: path instance with temp directory public static func tempDirectory() -> Path { // TODO: temp dirs for other platforms return Path("/tmp") } } public func ==(lhs: Path, rhs: Path) -> Bool { if lhs.components.count != rhs.components.count || lhs.isAbsolute != rhs.isAbsolute { return false } for i in 0..<lhs.components.count { if lhs.components[i] != rhs.components[i] { return false } } return true } public func +(lhs: Path, rhs: String) -> Path { return lhs.join(Path(rhs)) } public func +(lhs: Path, rhs: Path) -> Path { return lhs.join(rhs) } public func +=(lhs: inout Path, rhs: String) { lhs = lhs.join(Path(rhs)) } public func +=(lhs: inout Path, rhs: Path) { lhs = lhs.join(rhs) } extension Path: CustomStringConvertible { /// Convert path back to a String public var description: String { if self.components.count == 0 { if self.isAbsolute { return "\(self.delimiter)" } else { return "." } } var result = String.join(parts: components, delimiter: self.delimiter) if self.isAbsolute { result = "\(self.delimiter)" + result } return result } }
0e519abf6d8ae9c7c9e62193963ca69a
30.465217
89
0.594113
false
false
false
false
daviwiki/Gourmet_Swift
refs/heads/master
Gourmet/GourmetModel/Interactors/GetBalance.swift
mit
1
// // GetAccountInfo.swift // Gourmet // // Created by David Martinez on 08/12/2016. // Copyright © 2016 Atenea. All rights reserved. // import Foundation public protocol GetBalanceListener : NSObjectProtocol { func onSuccess (balance : Balance) func onError () } public class GetBalance : NSObject, GetBalanceOfflineListener, GetBalanceOnlineListener { private var getBalanceOffline : GetBalanceOffline! private var getBalanceOnline : GetBalanceOnline! private var storeBalance : StoreBalance! private weak var listener : GetBalanceListener? private var account : Account! public init(getBalanceOffline : GetBalanceOffline, getBalanceOnline : GetBalanceOnline, storeBalance : StoreBalance) { super.init() self.getBalanceOffline = getBalanceOffline self.getBalanceOnline = getBalanceOnline self.storeBalance = storeBalance getBalanceOffline.setListener(listener: self) getBalanceOnline.setListener(listener: self) } public func setListener (listener : GetBalanceListener) { self.listener = listener } public func execute (account : Account) { self.account = account getBalanceOffline.execute() } // MARK: GetBalanceOfflineListener public func onFinish(getBalanceOffline: GetBalanceOffline, balance: Balance?) { guard listener != nil else { return } if (balance != nil) { listener!.onSuccess(balance: balance!) } getBalanceOnline.execute(account: account) } // MARK: GetBalanceOnlineListener public func onFinish(getBalanceOnline: GetBalanceOnline, balance: Balance?) { guard listener != nil else { return } if (balance != nil) { DispatchQueue.main.async { self.listener!.onSuccess(balance: balance!) } storeBalance.execute(balance: balance!) } else { DispatchQueue.main.async { self.listener!.onError() } } } }
ac3b5c2f91da2b5bb9706aef1906d27a
27.051948
89
0.626852
false
false
false
false
Yalantis/Koloda
refs/heads/master
Example/Koloda/ViewController.swift
mit
3
// // ViewController.swift // Koloda // // Created by Eugene Andreyev on 4/23/15. // Copyright (c) 2015 Eugene Andreyev. All rights reserved. // import UIKit import Koloda private var numberOfCards: Int = 5 class ViewController: UIViewController { @IBOutlet weak var kolodaView: KolodaView! fileprivate var dataSource: [UIImage] = { var array: [UIImage] = [] for index in 0..<numberOfCards { array.append(UIImage(named: "Card_like_\(index + 1)")!) } return array }() // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() kolodaView.dataSource = self kolodaView.delegate = self self.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal } // MARK: IBActions @IBAction func leftButtonTapped() { kolodaView?.swipe(.left) } @IBAction func rightButtonTapped() { kolodaView?.swipe(.right) } @IBAction func undoButtonTapped() { kolodaView?.revertAction() } } // MARK: KolodaViewDelegate extension ViewController: KolodaViewDelegate { func kolodaDidRunOutOfCards(_ koloda: KolodaView) { let position = kolodaView.currentCardIndex for i in 1...4 { dataSource.append(UIImage(named: "Card_like_\(i)")!) } kolodaView.insertCardAtIndexRange(position..<position + 4, animated: true) } func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) { UIApplication.shared.openURL(URL(string: "https://yalantis.com/")!) } } // MARK: KolodaViewDataSource extension ViewController: KolodaViewDataSource { func kolodaNumberOfCards(_ koloda: KolodaView) -> Int { return dataSource.count } func kolodaSpeedThatCardShouldDrag(_ koloda: KolodaView) -> DragSpeed { return .default } func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView { return UIImageView(image: dataSource[Int(index)]) } func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> OverlayView? { return Bundle.main.loadNibNamed("OverlayView", owner: self, options: nil)?[0] as? OverlayView } }
b0b892e0b44c3a21a8a53c14f2c5f3f3
23.73913
101
0.630053
false
false
false
false
hilen/TSWeChat
refs/heads/master
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UICollectionView+TSExtension.swift
mit
3
// // UICollectionView+TSExtension.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 8/5/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation import UIKit public extension UICollectionView { /** Last indexPath in section - parameter section: section - returns: NSIndexPath */ func ts_lastIndexPathInSection(_ section: Int) -> IndexPath? { return IndexPath(row: self.numberOfItems(inSection: section)-1, section: section) } /// Last indexPath in UICollectionView var ts_lastIndexPath: IndexPath? { if (self.ts_totalItems - 1) > 0 { return IndexPath(row: self.ts_totalItems-1, section: self.numberOfSections) } else { return nil } } /// Total items in UICollectionView var ts_totalItems: Int { var i = 0 var rowCount = 0 while i < self.numberOfSections { rowCount += self.numberOfItems(inSection: i) i += 1 } return rowCount } /** Scroll to the bottom - parameter animated: animated */ func ts_scrollToBottom(_ animated: Bool) { let section = self.numberOfSections - 1 let row = self.numberOfItems(inSection: section) - 1 if section < 0 || row < 0 { return } let path = IndexPath(row: row, section: section) let offset = contentOffset.y self.scrollToItem(at: path, at: .top, animated: animated) let delay = (animated ? 0.1 : 0.0) * Double(NSEC_PER_SEC) let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { () -> Void in if self.contentOffset.y != offset { self.ts_scrollToBottom(false) } }) } /** Reload data without flashing */ func ts_reloadWithoutFlashing() { UIView.setAnimationsEnabled(false) CATransaction.begin() CATransaction.setDisableActions(true) self.reloadData() CATransaction.commit() UIView.setAnimationsEnabled(true) } /** Fetch indexPaths of UICollectionView's visibleCells - returns: NSIndexPath Array */ func ts_visibleIndexPaths() -> [IndexPath] { var list = [IndexPath]() for cell in self.visibleCells { if let indexPath = self.indexPath(for: cell) { list.append(indexPath) } } return list } /** Fetch indexPaths of UICollectionView's rect - returns: NSIndexPath Array */ func ts_indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect) if (allLayoutAttributes?.count ?? 0) == 0 {return []} var indexPaths: [IndexPath] = [] indexPaths.reserveCapacity(allLayoutAttributes!.count) for layoutAttributes in allLayoutAttributes! { let indexPath = layoutAttributes.indexPath indexPaths.append(indexPath) } return indexPaths } /** Reload data with completion block - parameter completion: completion block */ func ts_reloadData(_ completion: @escaping ()->()) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } }
06f47f13ca2150b34593a7963fe42f49
27.293651
109
0.591304
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
iOS/Account/NewsBlurAccountViewController.swift
mit
1
// // NewsBlurAccountViewController.swift // NetNewsWire // // Created by Anh-Quang Do on 3/9/20. // Copyright (c) 2020 Ranchero Software. All rights reserved. // import UIKit import Account import Secrets import RSWeb import SafariServices class NewsBlurAccountViewController: UITableViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var cancelBarButtonItem: UIBarButtonItem! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var showHideButton: UIButton! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var footerLabel: UILabel! weak var account: Account? weak var delegate: AddAccountDismissDelegate? override func viewDidLoad() { super.viewDidLoad() setupFooter() activityIndicator.isHidden = true usernameTextField.delegate = self passwordTextField.delegate = self if let account = account, let credentials = try? account.retrieveCredentials(type: .newsBlurBasic) { actionButton.setTitle(NSLocalizedString("Update Credentials", comment: "Update Credentials"), for: .normal) actionButton.isEnabled = true usernameTextField.text = credentials.username passwordTextField.text = credentials.secret } else { actionButton.setTitle(NSLocalizedString("Add Account", comment: "Add Account"), for: .normal) } NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: usernameTextField) NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextField.textDidChangeNotification, object: passwordTextField) tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader") } private func setupFooter() { footerLabel.text = NSLocalizedString("Sign in to your NewsBlur account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a NewsBlur account?", comment: "NewsBlur") } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView headerView.imageView.image = AppAssets.image(for: .newsBlur) return headerView } else { return super.tableView(tableView, viewForHeaderInSection: section) } } @IBAction func cancel(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func showHidePassword(_ sender: Any) { if passwordTextField.isSecureTextEntry { passwordTextField.isSecureTextEntry = false showHideButton.setTitle("Hide", for: .normal) } else { passwordTextField.isSecureTextEntry = true showHideButton.setTitle("Show", for: .normal) } } @IBAction func action(_ sender: Any) { guard let username = usernameTextField.text else { showError(NSLocalizedString("Username required.", comment: "Credentials Error")) return } // When you fill in the email address via auto-complete it adds extra whitespace let trimmedUsername = username.trimmingCharacters(in: .whitespaces) guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .newsBlur, username: trimmedUsername) else { showError(NSLocalizedString("There is already a NewsBlur account with that username created.", comment: "Duplicate Error")) return } let password = passwordTextField.text ?? "" startAnimatingActivityIndicator() disableNavigation() let basicCredentials = Credentials(type: .newsBlurBasic, username: trimmedUsername, secret: password) Account.validateCredentials(type: .newsBlur, credentials: basicCredentials) { result in self.stopAnimatingActivityIndicator() self.enableNavigation() switch result { case .success(let sessionCredentials): if let sessionCredentials = sessionCredentials { if self.account == nil { self.account = AccountManager.shared.createAccount(type: .newsBlur) } do { do { try self.account?.removeCredentials(type: .newsBlurBasic) try self.account?.removeCredentials(type: .newsBlurSessionId) } catch {} try self.account?.storeCredentials(basicCredentials) try self.account?.storeCredentials(sessionCredentials) self.account?.refreshAll() { result in switch result { case .success: break case .failure(let error): self.presentError(error) } } self.dismiss(animated: true, completion: nil) self.delegate?.dismiss() } catch { self.showError(NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")) } } else { self.showError(NSLocalizedString("Invalid username/password combination.", comment: "Credentials Error")) } case .failure(let error): self.showError(error.localizedDescription) } } } @IBAction func signUpWithProvider(_ sender: Any) { let url = URL(string: "https://newsblur.com")! let safari = SFSafariViewController(url: url) safari.modalPresentationStyle = .currentContext self.present(safari, animated: true, completion: nil) } @objc func textDidChange(_ note: Notification) { actionButton.isEnabled = !(usernameTextField.text?.isEmpty ?? false) } private func showError(_ message: String) { presentError(title: "Error", message: message) } private func enableNavigation() { self.cancelBarButtonItem.isEnabled = true self.actionButton.isEnabled = true } private func disableNavigation() { cancelBarButtonItem.isEnabled = false actionButton.isEnabled = false } private func startAnimatingActivityIndicator() { activityIndicator.isHidden = false activityIndicator.startAnimating() } private func stopAnimatingActivityIndicator() { self.activityIndicator.isHidden = true self.activityIndicator.stopAnimating() } } extension NewsBlurAccountViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
928f8b44467f74e08afc2b730a8fe654
32.119171
239
0.751252
false
false
false
false
Shopify/mobile-buy-sdk-ios
refs/heads/main
Buy/Generated/Storefront/UnitPriceMeasurementMeasuredType.swift
mit
1
// // UnitPriceMeasurementMeasuredType.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The accepted types of unit of measurement. public enum UnitPriceMeasurementMeasuredType: String { /// Unit of measurements representing areas. case area = "AREA" /// Unit of measurements representing lengths. case length = "LENGTH" /// Unit of measurements representing volumes. case volume = "VOLUME" /// Unit of measurements representing weights. case weight = "WEIGHT" case unknownValue = "" } }
35b2c29c3af2cd1e1418dd5e918003ca
36.108696
81
0.739895
false
false
false
false
moozzyk/SignalR-Client-Swift
refs/heads/master
Tests/SignalRClientTests/Constants.swift
mit
1
// // Constants.swift // SignalRClientTests // // Created by Pawel Kadluczka on 10/1/18. // Copyright © 2018 Pawel Kadluczka. All rights reserved. // import Foundation let BASE_URL = "http://localhost:5000" let ECHO_URL = URL(string: "\(BASE_URL)/echo")! let ECHO_WEBSOCKETS_URL = URL(string: "\(BASE_URL)/echoWebSockets")! let ECHO_LONGPOLLING_URL = URL(string: "\(BASE_URL)/echoLongPolling")! let ECHO_NOTRANSPORTS_URL = URL(string: "\(BASE_URL)/echoNoTransports")! let TESTHUB_URL = URL(string: "\(BASE_URL)/testhub")! let TESTHUB_WEBSOCKETS_URL = URL(string: "\(BASE_URL)/testhubWebSockets")! let TESTHUB_LONGPOLLING_URL = URL(string: "\(BASE_URL)/testhubLongPolling")! // Used by most tests that don't depend on a specific transport directly let TARGET_ECHO_URL = ECHO_URL // ECHO_URL or ECHO_WEBSOCKETS_URL or ECHO_LONGPOLLING_URL let TARGET_TESTHUB_URL = TESTHUB_URL // TESTHUB_URL or TESTHUB_WEBSOCKETS_URL or TESTHUB_LONGPOLLING_URL
bf0af786c14fae38a58465a7653c081a
38.625
104
0.73081
false
true
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/AssistantV2/Models/LogMessageSource.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2021. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** An object that identifies the dialog element that generated the error message. */ public enum LogMessageSource: Codable, Equatable { case dialogNode(LogMessageSourceDialogNode) case action(LogMessageSourceAction) case step(LogMessageSourceStep) case handler(LogMessageSourceHandler) private struct GenericLogMessageSource: Codable, Equatable { var type: String private enum CodingKeys: String, CodingKey { case type = "type" } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let genericInstance = try? container.decode(GenericLogMessageSource.self) { switch genericInstance.type { case "dialog_node": if let val = try? container.decode(LogMessageSourceDialogNode.self) { self = .dialogNode(val) return } case "action": if let val = try? container.decode(LogMessageSourceAction.self) { self = .action(val) return } case "step": if let val = try? container.decode(LogMessageSourceStep.self) { self = .step(val) return } case "handler": if let val = try? container.decode(LogMessageSourceHandler.self) { self = .handler(val) return } default: // falling through to throw decoding error break } } throw DecodingError.typeMismatch(LogMessageSource.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Decoding failed for all associated types")) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .dialogNode(let dialog_node): try container.encode(dialog_node) case .action(let action): try container.encode(action) case .step(let step): try container.encode(step) case .handler(let handler): try container.encode(handler) } } }
9108439ee50d2f8db5c3ae9873ed3aa2
33.348837
157
0.598849
false
false
false
false
OscarSwanros/swift
refs/heads/master
stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableCollectionType.swift
apache-2.0
6
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import StdlibUnittest internal enum IndexSelection { case start case middle case end case last internal func index<C : Collection>(in c: C) -> C.Index { switch self { case .start: return c.startIndex case .middle: return c.index(c.startIndex, offsetBy: c.count / 2) case .end: return c.endIndex case .last: return c.index(c.startIndex, offsetBy: c.count - 1) } } } public struct ReplaceSubrangeTest { public let collection: [OpaqueValue<Int>] public let newElements: [OpaqueValue<Int>] public let rangeSelection: RangeSelection public let expected: [Int] public let closedExpected: [Int]? // Expected array for closed ranges public let loc: SourceLoc internal init( collection: [Int], newElements: [Int], rangeSelection: RangeSelection, expected: [Int], closedExpected: [Int]? = nil, file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.rangeSelection = rangeSelection self.expected = expected self.closedExpected = closedExpected self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data") } } internal struct AppendTest { let collection: [OpaqueValue<Int>] let newElement: OpaqueValue<Int> let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElement: Int, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElement = OpaqueValue(newElement) self.expected = expected self.loc = SourceLoc(file, line, comment: "append() test data") } } internal struct AppendContentsOfTest { let collection: [OpaqueValue<Int>] let newElements: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElements: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "append() test data") } } internal struct InsertTest { let collection: [OpaqueValue<Int>] let newElement: OpaqueValue<Int> let indexSelection: IndexSelection let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElement: Int, indexSelection: IndexSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElement = OpaqueValue(newElement) self.indexSelection = indexSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "insert() test data") } } internal struct InsertContentsOfTest { let collection: [OpaqueValue<Int>] let newElements: [OpaqueValue<Int>] let indexSelection: IndexSelection let expected: [Int] let loc: SourceLoc internal init( collection: [Int], newElements: [Int], indexSelection: IndexSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.newElements = newElements.map(OpaqueValue.init) self.indexSelection = indexSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "insert(contentsOf:at:) test data") } } internal struct RemoveAtIndexTest { let collection: [OpaqueValue<Int>] let indexSelection: IndexSelection let expectedRemovedElement: Int let expectedCollection: [Int] let loc: SourceLoc internal init( collection: [Int], indexSelection: IndexSelection, expectedRemovedElement: Int, expectedCollection: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.indexSelection = indexSelection self.expectedRemovedElement = expectedRemovedElement self.expectedCollection = expectedCollection self.loc = SourceLoc(file, line, comment: "remove(at:) test data") } } internal struct RemoveLastNTest { let collection: [OpaqueValue<Int>] let numberToRemove: Int let expectedCollection: [Int] let loc: SourceLoc internal init( collection: [Int], numberToRemove: Int, expectedCollection: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.numberToRemove = numberToRemove self.expectedCollection = expectedCollection self.loc = SourceLoc(file, line, comment: "removeLast(n: Int) test data") } } public struct RemoveSubrangeTest { public let collection: [OpaqueValue<Int>] public let rangeSelection: RangeSelection public let expected: [Int] public let loc: SourceLoc internal init( collection: [Int], rangeSelection: RangeSelection, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.rangeSelection = rangeSelection self.expected = expected self.loc = SourceLoc(file, line, comment: "removeSubrange() test data") } } internal struct RemoveAllTest { let collection: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( collection: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "removeAll() test data") } } internal struct ReserveCapacityTest { let collection: [OpaqueValue<Int>] let requestedCapacity: Int let loc: SourceLoc internal init( collection: [Int], requestedCapacity: Int, file: String = #file, line: UInt = #line ) { self.collection = collection.map(OpaqueValue.init) self.requestedCapacity = requestedCapacity self.loc = SourceLoc(file, line, comment: "removeAll() test data") } } internal struct OperatorPlusTest { let lhs: [OpaqueValue<Int>] let rhs: [OpaqueValue<Int>] let expected: [Int] let loc: SourceLoc internal init( lhs: [Int], rhs: [Int], expected: [Int], file: String = #file, line: UInt = #line ) { self.lhs = lhs.map(OpaqueValue.init) self.rhs = rhs.map(OpaqueValue.init) self.expected = expected self.loc = SourceLoc(file, line, comment: "`func +` test data") } } let removeLastTests: [RemoveLastNTest] = [ RemoveLastNTest( collection: [1010], numberToRemove: 0, expectedCollection: [1010] ), RemoveLastNTest( collection: [1010], numberToRemove: 1, expectedCollection: [] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 0, expectedCollection: [1010, 2020, 3030, 4040, 5050] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 1, expectedCollection: [1010, 2020, 3030, 4040] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 2, expectedCollection: [1010, 2020, 3030] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 3, expectedCollection: [1010, 2020] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 4, expectedCollection: [1010] ), RemoveLastNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 5, expectedCollection: [] ), ] let appendContentsOfTests: [AppendContentsOfTest] = [ AppendContentsOfTest( collection: [], newElements: [], expected: []), AppendContentsOfTest( collection: [1010], newElements: [], expected: [1010]), AppendContentsOfTest( collection: [1010, 2020, 3030, 4040], newElements: [], expected: [1010, 2020, 3030, 4040]), AppendContentsOfTest( collection: [], newElements: [1010], expected: [1010]), AppendContentsOfTest( collection: [1010], newElements: [2020], expected: [1010, 2020]), AppendContentsOfTest( collection: [1010], newElements: [2020, 3030, 4040], expected: [1010, 2020, 3030, 4040]), AppendContentsOfTest( collection: [1010, 2020, 3030, 4040], newElements: [5050, 6060, 7070, 8080], expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]), ] // Also used in RangeReplaceable.swift.gyb to test `replaceSubrange()` // overloads with the countable range types. public let replaceRangeTests: [ReplaceSubrangeTest] = [ ReplaceSubrangeTest( collection: [], newElements: [], rangeSelection: .emptyRange, expected: []), ReplaceSubrangeTest( collection: [], newElements: [1010], rangeSelection: .emptyRange, expected: [1010]), ReplaceSubrangeTest( collection: [], newElements: [1010, 2020, 3030], rangeSelection: .emptyRange, expected: [1010, 2020, 3030]), ReplaceSubrangeTest( collection: [4040], newElements: [1010, 2020, 3030], rangeSelection: .leftEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [1010, 2020, 3030]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [4040], rangeSelection: .leftEdge, expected: [4040, 1010, 2020, 3030], closedExpected: [4040, 2020, 3030]), ReplaceSubrangeTest( collection: [1010], newElements: [2020, 3030, 4040], rangeSelection: .rightEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [2020, 3030, 4040]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [4040], rangeSelection: .rightEdge, expected: [1010, 2020, 3030, 4040], closedExpected: [1010, 2020, 4040]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 1), expected: [1010, 9090, 2020, 3030, 4040, 5050], closedExpected: [1010, 9090, 3030, 4040, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 2), expected: [1010, 9090, 3030, 4040, 5050], closedExpected: [1010, 9090, 4040, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 3), expected: [1010, 9090, 4040, 5050], closedExpected: [1010, 9090, 5050]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 4), expected: [1010, 9090, 5050], closedExpected: [1010, 9090]), ReplaceSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], newElements: [9090], rangeSelection: .offsets(1, 5), expected: [1010, 9090]), ReplaceSubrangeTest( collection: [1010, 2020, 3030], newElements: [8080, 9090], rangeSelection: .offsets(1, 2), expected: [1010, 8080, 9090, 3030], closedExpected: [1010, 8080, 9090]), ] public let removeRangeTests: [RemoveSubrangeTest] = [ RemoveSubrangeTest( collection: [], rangeSelection: .emptyRange, expected: []), RemoveSubrangeTest( collection: [1010], rangeSelection: .middle, expected: []), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040], rangeSelection: .leftHalf, expected: [3030, 4040]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040], rangeSelection: .rightHalf, expected: [1010, 2020]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050], rangeSelection: .middle, expected: [1010, 5050]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .leftHalf, expected: [4040, 5050, 6060]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .rightHalf, expected: [1010, 2020, 3030]), RemoveSubrangeTest( collection: [1010, 2020, 3030, 4040, 5050, 6060], rangeSelection: .middle, expected: [1010, 6060]), ] extension TestSuite { /// Adds a set of tests for `RangeReplaceableCollection`. /// /// - parameter makeCollection: a factory function that creates a collection /// instance with provided elements. /// /// This facility can be used to test collection instances that can't be /// constructed using APIs in the protocol (for example, `Array`s that wrap /// `NSArray`s). public func addRangeReplaceableCollectionTests< C : RangeReplaceableCollection, CollectionWithEquatableElement : RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Iterator.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, collectionIsBidirectional: Bool = false ) where CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, collectionIsBidirectional: collectionIsBidirectional ) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // init() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).init()/semantics") { let c = C() expectEqualSequence([], c.map { extractValue($0).value }) } //===----------------------------------------------------------------------===// // init(Sequence) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).init(Sequence)/semantics") { for test in appendContentsOfTests { let c = C(test.newElements.map(wrapValue)) expectEqualSequence( test.newElements.map { $0.value }, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // replaceSubrange() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).replaceSubrange()/range/semantics") { for test in replaceRangeTests { var c = makeWrappedCollection(test.collection) let rangeToReplace = test.rangeSelection.range(in: c) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.replaceSubrange(rangeToReplace, with: newElements) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).replaceSubrange()/closedRange/semantics") { for test in replaceRangeTests { guard let closedExpected = test.closedExpected else { continue } var c = makeWrappedCollection(test.collection) let rangeToReplace = test.rangeSelection.closedRange(in: c) let newElements = makeWrappedCollection(test.newElements) c.replaceSubrange(rangeToReplace, with: newElements) expectEqualSequence( closedExpected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // append() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).append()/semantics") { let tests: [AppendTest] = [ AppendTest( collection: [], newElement: 1010, expected: [1010]), AppendTest( collection: [1010], newElement: 2020, expected: [1010, 2020]), AppendTest( collection: [1010, 2020, 3030, 4040, 5050, 6060, 7070], newElement: 8080, expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElement = wrapValue(test.newElement) c.append(newElement) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // append(contentsOf:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).append(contentsOf:)/semantics") { for test in appendContentsOfTests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.append(contentsOf: newElements) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).OperatorPlusEquals") { for test in appendContentsOfTests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c += newElements expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // insert() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).insert()/semantics") { let tests: [InsertTest] = [ InsertTest( collection: [], newElement: 1010, indexSelection: IndexSelection.start, expected: [1010]), InsertTest( collection: [2020], newElement: 1010, indexSelection: .start, expected: [1010, 2020]), InsertTest( collection: [1010], newElement: 2020, indexSelection: .end, expected: [1010, 2020]), InsertTest( collection: [2020, 3030, 4040, 5050], newElement: 1010, indexSelection: .start, expected: [1010, 2020, 3030, 4040, 5050]), InsertTest( collection: [1010, 2020, 3030, 4040], newElement: 5050, indexSelection: .end, expected: [1010, 2020, 3030, 4040, 5050]), InsertTest( collection: [1010, 2020, 4040, 5050], newElement: 3030, indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElement = wrapValue(test.newElement) c.insert(newElement, at: test.indexSelection.index(in: c)) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // insert(contentsOf:at:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).insert(contentsOf:at:)/semantics") { let tests: [InsertContentsOfTest] = [ InsertContentsOfTest( collection: [], newElements: [], indexSelection: IndexSelection.start, expected: []), InsertContentsOfTest( collection: [], newElements: [1010], indexSelection: .start, expected: [1010]), InsertContentsOfTest( collection: [], newElements: [1010, 2020, 3030, 4040], indexSelection: .start, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [2020], newElements: [1010], indexSelection: .start, expected: [1010, 2020]), InsertContentsOfTest( collection: [1010], newElements: [2020], indexSelection: .end, expected: [1010, 2020]), InsertContentsOfTest( collection: [4040], newElements: [1010, 2020, 3030], indexSelection: .start, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [1010], newElements: [2020, 3030, 4040], indexSelection: .end, expected: [1010, 2020, 3030, 4040]), InsertContentsOfTest( collection: [1010, 2020, 4040, 5050], newElements: [3030], indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050]), InsertContentsOfTest( collection: [4040, 5050, 6060], newElements: [1010, 2020, 3030], indexSelection: .start, expected: [1010, 2020, 3030, 4040, 5050, 6060]), InsertContentsOfTest( collection: [1010, 2020, 3030], newElements: [4040, 5050, 6060], indexSelection: .end, expected: [1010, 2020, 3030, 4040, 5050, 6060]), InsertContentsOfTest( collection: [1010, 2020, 3030, 7070, 8080, 9090], newElements: [4040, 5050, 6060], indexSelection: .middle, expected: [1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]), ] for test in tests { var c = makeWrappedCollection(test.collection) let newElements = MinimalCollection(elements: test.newElements.map(wrapValue)) c.insert(contentsOf: newElements, at: test.indexSelection.index(in: c)) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // remove(at:) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).remove(at:)/semantics") { let tests: [RemoveAtIndexTest] = [ RemoveAtIndexTest( collection: [1010], indexSelection: .start, expectedRemovedElement: 1010, expectedCollection: []), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .start, expectedRemovedElement: 1010, expectedCollection: [2020, 3030]), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .middle, expectedRemovedElement: 2020, expectedCollection: [1010, 3030]), RemoveAtIndexTest( collection: [1010, 2020, 3030], indexSelection: .last, expectedRemovedElement: 3030, expectedCollection: [1010, 2020]), ] for test in tests { var c = makeWrappedCollection(test.collection) let removedElement = c.remove(at: test.indexSelection.index(in: c)) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqual( test.expectedRemovedElement, extractValue(removedElement).value, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // removeFirst() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/semantics") { for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let removedElement = c.removeFirst() expectEqual(test.collection.first, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeFirst()/empty/semantics") { var c = makeWrappedCollection(Array<OpaqueValue<Int>>()) expectCrashLater() _ = c.removeFirst() // Should trap. } //===----------------------------------------------------------------------===// // removeFirst(n: Int) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") { for test in removeFirstTests { var c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) c.removeFirst(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the collection", stackTrace: SourceLocStack().with(test.loc) ) } } self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") { var c = makeWrappedCollection(Array<OpaqueValue<Int>>()) expectCrashLater() c.removeFirst(1) // Should trap. } self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() c.removeFirst(-1) // Should trap. } self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020, 3030].map(OpaqueValue.init)) expectCrashLater() c.removeFirst(5) // Should trap. } //===----------------------------------------------------------------------===// // removeSubrange() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeSubrange()/range/semantics") { for test in removeRangeTests { var c = makeWrappedCollection(test.collection) let rangeToRemove = test.rangeSelection.range(in: c) c.removeSubrange(rangeToRemove) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).replaceSubrange()/closedRange/semantics") { for test in removeRangeTests.filter({ !$0.rangeSelection.isEmpty }) { var c = makeWrappedCollection(test.collection) let rangeToRemove = test.rangeSelection.closedRange(in: c) c.removeSubrange(rangeToRemove) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // removeAll() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeAll()/semantics") { let tests: [RemoveAllTest] = [ RemoveAllTest( collection: [], expected: []), RemoveAllTest( collection: [1010], expected: []), RemoveAllTest( collection: [1010, 2020, 3030, 4040, 5050], expected: []), ] for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll() expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll(keepingCapacity: false) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } for test in tests { var c = makeWrappedCollection(test.collection) c.removeAll(keepingCapacity: true) expectEqualSequence( test.expected, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // reserveCapacity() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).reserveCapacity()/semantics") { let tests: [ReserveCapacityTest] = [ ReserveCapacityTest( collection: [], requestedCapacity: 0), ReserveCapacityTest( collection: [], requestedCapacity: 3), ReserveCapacityTest( collection: [], requestedCapacity: 100), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 0), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 3), ReserveCapacityTest( collection: [ 1010 ], requestedCapacity: 100), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 0), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 3), ReserveCapacityTest( collection: [ 1010, 2020, 3030 ], requestedCapacity: 100), ] for test in tests { var c = makeWrappedCollection(test.collection) c.reserveCapacity(numericCast(test.requestedCapacity)) expectEqualSequence( test.collection.map { $0.value }, c.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // + operator //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).OperatorPlus") { let tests: [OperatorPlusTest] = [ OperatorPlusTest( lhs: [], rhs: [], expected: []), OperatorPlusTest( lhs: [], rhs: [ 1010 ], expected: [ 1010 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [], expected: [ 1010 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [ 2020 ], expected: [ 1010, 2020 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [], expected: [ 1010, 2020, 3030 ]), OperatorPlusTest( lhs: [], rhs: [ 1010, 2020, 3030 ], expected: [ 1010, 2020, 3030 ]), OperatorPlusTest( lhs: [ 1010 ], rhs: [ 2020, 3030, 4040 ], expected: [ 1010, 2020, 3030, 4040 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [ 4040 ], expected: [ 1010, 2020, 3030, 4040 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030, 4040 ], rhs: [ 5050, 6060, 7070 ], expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]), OperatorPlusTest( lhs: [ 1010, 2020, 3030 ], rhs: [ 4040, 5050, 6060, 7070 ], expected: [ 1010, 2020, 3030, 4040, 5050, 6060, 7070 ]), ] // RangeReplaceableCollection + Sequence for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalSequence(elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // Sequence + RangeReplaceableCollection for test in tests { let lhs = MinimalSequence(elements: test.lhs.map(wrapValue)) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + Collection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalCollection(elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + same RangeReplaceableCollection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // RangeReplaceableCollection + MinimalRangeReplaceableCollection for test in tests { let lhs = makeWrappedCollection(test.lhs) let rhs = MinimalRangeReplaceableCollection( elements: test.rhs.map(wrapValue)) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } // MinimalRangeReplaceableCollection + RangeReplaceableCollection for test in tests { let lhs = MinimalRangeReplaceableCollection( elements: test.lhs.map(wrapValue)) let rhs = makeWrappedCollection(test.rhs) let result = lhs + rhs expectEqualSequence( test.expected, result.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.lhs.map { $0.value }, lhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.rhs.map { $0.value }, rhs.map { extractValue($0).value }, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// } // addRangeReplaceableCollectionTests public func addRangeReplaceableBidirectionalCollectionTests< C : BidirectionalCollection & RangeReplaceableCollection, CollectionWithEquatableElement : BidirectionalCollection & RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Iterator.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1 ) where CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addRangeReplaceableCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, collectionIsBidirectional: true ) addBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) //===----------------------------------------------------------------------===// // removeLast() //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/semantics") { for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { var c = makeWrappedCollection(test.collection) let removedElement = c.removeLast() expectEqual( test.collection.last!.value, extractValue(removedElement).value, stackTrace: SourceLocStack().with(test.loc)) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast()/whereIndexIsBidirectional/empty/semantics") { var c = makeWrappedCollection([]) expectCrashLater() _ = c.removeLast() // Should trap. } //===----------------------------------------------------------------------===// // removeLast(n: Int) //===----------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/semantics") { for test in removeLastTests { var c = makeWrappedCollection(test.collection) c.removeLast(test.numberToRemove) expectEqualSequence( test.expectedCollection, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the collection", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/empty/semantics") { var c = makeWrappedCollection([]) expectCrashLater() c.removeLast(1) // Should trap. } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeNegative/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() c.removeLast(-1) // Should trap. } self.test("\(testNamePrefix).removeLast(n: Int)/whereIndexIsBidirectional/removeTooMany/semantics") { var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) expectCrashLater() c.removeLast(3) // Should trap. } //===----------------------------------------------------------------------===// } // addRangeReplaceableBidirectionalCollectionTests public func addRangeReplaceableRandomAccessCollectionTests< C : RandomAccessCollection & RangeReplaceableCollection, CollectionWithEquatableElement : RandomAccessCollection & RangeReplaceableCollection >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Iterator.Element]) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1 ) where CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addRangeReplaceableBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) addRandomAccessCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset) testNamePrefix += String(describing: C.Type.self) // No extra checks for collections with random access traversal so far. } // addRangeReplaceableRandomAccessCollectionTests }
0b537d7eff3254292b89ec6184a6be93
30.211826
127
0.633133
false
true
false
false
aojet/Aojet
refs/heads/master
Sources/Aojet/function/Identifiable.swift
mit
1
// // Identifiable.swift // Aojet // // Created by Qihe Bian on 8/29/16. // Copyright © 2016 Qihe Bian. All rights reserved. // import Foundation public typealias Identifier = NSUUID public protocol Identifiable { var objectId: Identifier { get } } public protocol IdentifierHashable: Identifiable, Hashable { } public extension Identifiable { static func generateObjectId() -> Identifier { return Identifier() } } public extension IdentifierHashable { var hashValue: Int { get { return objectId.hashValue } } } public func ==<T>(lhs: T, rhs: T) -> Bool where T:IdentifierHashable { return lhs.objectId == rhs.objectId }
db2546712f84a36c14a2eec342208bff
16.918919
70
0.695324
false
false
false
false
apple/swift-corelibs-foundation
refs/heads/main
Sources/FoundationNetworking/URLSession/TaskRegistry.swift
apache-2.0
1
// Foundation/URLSession/TaskRegistry.swift - URLSession & libcurl // // 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 // // ----------------------------------------------------------------------------- /// /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import SwiftFoundation #else import Foundation #endif @_implementationOnly import CoreFoundation import Dispatch extension URLSession { /// This helper class keeps track of all tasks, and their behaviours. /// /// Each `URLSession` has a `TaskRegistry` for its running tasks. The /// *behaviour* defines what action is to be taken e.g. upon completion. /// The behaviour stores the completion handler for tasks that are /// completion handler based. /// /// - Note: This must **only** be accessed on the owning session's work queue. class _TaskRegistry { /// Completion handler for `URLSessionDataTask`, and `URLSessionUploadTask`. typealias DataTaskCompletion = (Data?, URLResponse?, Error?) -> Void /// Completion handler for `URLSessionDownloadTask`. typealias DownloadTaskCompletion = (URL?, URLResponse?, Error?) -> Void /// What to do upon events (such as completion) of a specific task. enum _Behaviour { /// Call the `URLSession`s delegate case callDelegate /// Default action for all events, except for completion. case dataCompletionHandler(DataTaskCompletion) /// Default action for all events, except for completion. case downloadCompletionHandler(DownloadTaskCompletion) } fileprivate var tasks: [Int: URLSessionTask] = [:] fileprivate var behaviours: [Int: _Behaviour] = [:] fileprivate var tasksFinishedCallback: (() -> Void)? } } extension URLSession._TaskRegistry { /// Add a task /// /// - Note: This must **only** be accessed on the owning session's work queue. func add(_ task: URLSessionTask, behaviour: _Behaviour) { let identifier = task.taskIdentifier guard identifier != 0 else { fatalError("Invalid task identifier") } guard tasks.index(forKey: identifier) == nil else { if tasks[identifier] === task { fatalError("Trying to re-insert a task that's already in the registry.") } else { fatalError("Trying to insert a task, but a different task with the same identifier is already in the registry.") } } tasks[identifier] = task behaviours[identifier] = behaviour } /// Remove a task /// /// - Note: This must **only** be accessed on the owning session's work queue. func remove(_ task: URLSessionTask) { let identifier = task.taskIdentifier guard identifier != 0 else { fatalError("Invalid task identifier") } guard let tasksIdx = tasks.index(forKey: identifier) else { fatalError("Trying to remove task, but it's not in the registry.") } tasks.remove(at: tasksIdx) guard let behaviourIdx = behaviours.index(forKey: identifier) else { fatalError("Trying to remove task's behaviour, but it's not in the registry.") } behaviours.remove(at: behaviourIdx) guard let allTasksFinished = tasksFinishedCallback else { return } if self.isEmpty { allTasksFinished() } } func notify(on tasksCompletion: @escaping () -> Void) { tasksFinishedCallback = tasksCompletion } var isEmpty: Bool { return tasks.isEmpty } var allTasks: [URLSessionTask] { return tasks.map { $0.value } } } extension URLSession._TaskRegistry { /// The behaviour that's registered for the given task. /// /// - Note: It is a programming error to pass a task that isn't registered. /// - Note: This must **only** be accessed on the owning session's work queue. func behaviour(for task: URLSessionTask) -> _Behaviour { guard let b = behaviours[task.taskIdentifier] else { fatalError("Trying to access a behaviour for a task that in not in the registry.") } return b } }
bad8942132bd498ffc6e73bc50967bc8
38.798319
128
0.623311
false
false
false
false