repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SwiftReactive/SugarRecord
SugarRecord/Source/Foundation/Version/VersionProvider.swift
6
1328
import Foundation internal class VersionProvider: NSObject { // MARK: - Constants internal static let apiReleasesUrl: String = "https://api.github.com/repos/carambalabs/sugarrecord/releases" // MARK: - Internal internal func framework() -> String! { if let version = Bundle(for: VersionProvider.classForCoder()).object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String { return version } return nil } internal func github(_ completion: @escaping (String) -> Void) { let request: URLRequest = URLRequest(url: URL(string: VersionProvider.apiReleasesUrl)!) let session = URLSession(configuration: URLSessionConfiguration.default) session.dataTask(with: request, completionHandler: { (data, response, error) in if let data = data { let json: AnyObject? = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? if let array = json as? [[String: AnyObject]], let lastVersion = array.first, let versionTag: String = lastVersion["tag_name"] as? String { completion(versionTag) } } }).resume() session.finishTasksAndInvalidate() } }
mit
18a3fea4af04c127aad79ee3bdf5c7d9
39.242424
156
0.642319
5.127413
false
true
false
false
YifengBai/YuDou
YuDou/YuDou/Classes/Home/View/CycleScrollView.swift
1
5078
// // CycleScrollView.swift // YuDou // // Created by Bemagine on 2017/1/23. // Copyright © 2017年 bemagine. All rights reserved. // import UIKit private let CycleViewCollectionId = "CycleViewCollectionId" class CycleScrollView: UIView { var timer : Timer? fileprivate lazy var collectionView : UICollectionView = { [weak self] in let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let colleV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) colleV.backgroundColor = ThemColor colleV.delegate = self colleV.dataSource = self colleV.isPagingEnabled = true colleV.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CycleViewCollectionId) colleV.showsVerticalScrollIndicator = false colleV.showsHorizontalScrollIndicator = false return colleV }() fileprivate lazy var pageControl : UIPageControl = { [weak self] in let pageControl = UIPageControl(frame: CGRect.zero) pageControl.currentPageIndicatorTintColor = ThemColor pageControl.pageIndicatorTintColor = UIColor(r: 240, g: 240, b: 240) pageControl.contentHorizontalAlignment = .center return pageControl }() var slideArray : [SlideModel]? { didSet { guard let slide = slideArray else { return } collectionView.reloadData() pageControl.numberOfPages = slide.count let indexPath = IndexPath(item: slide.count * 200, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) removeCycleTimer() addCycleTimer() } } override init(frame: CGRect) { super.init(frame: frame) self.collectionView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) (self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = frame.size self.pageControl.frame = CGRect(x: 0, y: frame.height-20, width: frame.width, height: 20) self.addSubview(self.collectionView) self.addSubview(self.pageControl) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CycleScrollView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let count = slideArray?.count else { return 0 } return count * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CycleViewCollectionId, for: indexPath) let data = slideArray?[indexPath.item % slideArray!.count] for subv in cell.contentView.subviews { subv.removeFromSuperview() } let imageView = UIImageView(frame: cell.contentView.bounds) let url = URL(string: (data?.pic_url)!) imageView.kf.setImage(with: url, placeholder: UIImage(named: "Img_default")) cell.contentView.addSubview(imageView) return cell } } extension CycleScrollView : UICollectionViewDelegate { } extension CycleScrollView { func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1.获取滚动的偏移量 let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 pageControl.currentPage = Int((offsetX) / scrollView.bounds.width) % slideArray!.count } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } // MARK: - 对定时器的操作方法 extension CycleScrollView { fileprivate func addCycleTimer() { timer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .commonModes) } fileprivate func removeCycleTimer () { timer?.invalidate() // 从运行循环中移除 timer = nil } @objc fileprivate func scrollToNext() { // 1.获取滚动的偏移量 let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width // 2.滚动该位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
mit
d6ac55e9ce3939a92360cddb30b3e10d
29.481707
124
0.635927
5.375269
false
false
false
false
meticulo3366/PNChart-Swift
PNChartSwift/PNBarChart/PNBarChart.swift
1
12695
// // PNBarChart.swift // PNChart-Swift // // Created by kevinzhow on 6/6/14. // Copyright (c) 2014 Catch Inc. All rights reserved. // import UIKit import QuartzCore public enum AnimationType { case Default case Waterfall } public class PNBarChart: UIView { // MARK: Variables public var xLabels: NSArray = [] { didSet{ if showLabel { xLabelWidth = (self.frame.size.width - chartMargin * 2.0) / CGFloat(self.xLabels.count) } } } var labels: NSMutableArray = [] var yLabels: NSArray = [] public var yValues: NSArray = [] { didSet{ if (yMaxValue != nil) { yValueMax = yMaxValue }else{ self.getYValueMax(yValues) } xLabelWidth = (self.frame.size.width - chartMargin * 2.0) / CGFloat(yValues.count) } } var bars: NSMutableArray = [] public var xLabelWidth:CGFloat! public var yValueMax: CGFloat! public var strokeColor: UIColor = PNGreenColor public var strokeColors: NSArray = [] public var xLabelHeight:CGFloat = 11.0 public var yLabelHeight:CGFloat = 20.0 /* chartMargin changes chart margin */ public var yChartLabelWidth:CGFloat = 18.0 /* yLabelFormatter will format the ylabel text */ var yLabelFormatter = ({(index: CGFloat) -> NSString in return "" }) /* chartMargin changes chart margin */ public var chartMargin:CGFloat = 15.0 /* showLabel if the Labels should be deplay */ public var showLabel = true /* showChartBorder if the chart border Line should be deplay */ public var showChartBorder = false /* chartBottomLine the Line at the chart bottom */ public var chartBottomLine:CAShapeLayer = CAShapeLayer() /* chartLeftLine the Line at the chart left */ public var chartLeftLine:CAShapeLayer = CAShapeLayer() /* barRadius changes the bar corner radius */ public var barRadius:CGFloat = 0.0 /* barWidth changes the width of the bar */ public var barWidth:CGFloat! /* labelMarginTop changes the width of the bar */ public var labelMarginTop: CGFloat = 0 /* barBackgroundColor changes the bar background color */ public var barBackgroundColor:UIColor = UIColor.grayColor() /* labelTextColor changes the bar label text color */ public var labelTextColor: UIColor = PNGreyColor /* labelFont changes the bar label font */ public var labelFont: UIFont = UIFont.systemFontOfSize(11.0) /* xLabelSkip define the label skip number */ public var xLabelSkip:Int = 1 /* yLabelSum define the label skip number */ public var yLabelSum:Int = 4 /* yMaxValue define the max value of the chart */ public var yMaxValue:CGFloat! /* yMinValue define the min value of the chart */ public var yMinValue:CGFloat! /* animationType defines the type of animation for the bars Default (All bars at once) / Waterfall (bars in sequence) */ public var animationType : AnimationType = .Default public var delegate:PNChartDelegate! /** * This method will call and stroke the line in animation */ // MARK: Functions public func strokeChart() { self.viewCleanupForCollection(labels) if showLabel{ //Add x labels var labelAddCount:Int = 0 for var index:Int = 0; index < xLabels.count; ++index { labelAddCount += 1 if labelAddCount == xLabelSkip { var labelText:NSString = xLabels[index] as! NSString var label:PNChartLabel = PNChartLabel(frame: CGRectZero) label.font = labelFont label.textColor = labelTextColor label.textAlignment = NSTextAlignment.Center label.text = labelText as String label.sizeToFit() var labelXPosition:CGFloat = ( CGFloat(index) * xLabelWidth + chartMargin + xLabelWidth / 2.0 ) label.center = CGPointMake(labelXPosition, self.frame.size.height - xLabelHeight - chartMargin + label.frame.size.height / 2.0 + labelMarginTop) labelAddCount = 0 labels.addObject(label) self.addSubview(label) } } //Add y labels var yLabelSectionHeight:CGFloat = (self.frame.size.height - chartMargin * 2.0 - xLabelHeight) / CGFloat(yLabelSum) for var index:Int = 0; index < yLabelSum; ++index { var labelText:NSString = yLabelFormatter((yValueMax * ( CGFloat(yLabelSum - index) / CGFloat(yLabelSum) ) )) var label:PNChartLabel = PNChartLabel(frame: CGRectMake(0,yLabelSectionHeight * CGFloat(index) + chartMargin - yLabelHeight/2.0, yChartLabelWidth, yLabelHeight)) label.font = labelFont label.textColor = labelTextColor label.textAlignment = NSTextAlignment.Right label.text = labelText as String labels.addObject(label) self.addSubview(label) } } self.viewCleanupForCollection(bars) //Add bars var chartCavanHeight:CGFloat = frame.size.height - chartMargin * 2 - xLabelHeight var index:Int = 0 for valueObj: AnyObject in yValues{ var valueString = valueObj as! NSNumber var value:CGFloat = CGFloat(valueString.floatValue) var grade = value / yValueMax var bar:PNBar! var barXPosition:CGFloat! if barWidth > 0 { barXPosition = CGFloat(index) * xLabelWidth + chartMargin + (xLabelWidth / 2.0) - (barWidth / 2.0) }else{ barXPosition = CGFloat(index) * xLabelWidth + chartMargin + xLabelWidth * 0.25 if showLabel { barWidth = xLabelWidth * 0.5 } else { barWidth = xLabelWidth * 0.6 } } bar = PNBar(frame: CGRectMake(barXPosition, //Bar X position frame.size.height - chartCavanHeight - xLabelHeight - chartMargin, //Bar Y position barWidth, // Bar witdh chartCavanHeight)) //Bar height //Change Bar Radius bar.barRadius = barRadius //Change Bar Background color bar.backgroundColor = barBackgroundColor //Bar StrokColor First if strokeColor != UIColor.blackColor() { bar.barColor = strokeColor }else{ bar.barColor = self.barColorAtIndex(index) } if(self.animationType == .Waterfall) { var indexDouble : Double = Double(index) // Time before each bar starts animating var barStartTime = indexDouble-(0.9*indexDouble) bar.startAnimationTime = barStartTime } //Height Of Bar bar.grade = grade //For Click Index bar.tag = index bars.addObject(bar) addSubview(bar) index += 1 } //Add chart border lines if showChartBorder{ chartBottomLine = CAShapeLayer() chartBottomLine.lineCap = kCALineCapButt chartBottomLine.fillColor = UIColor.whiteColor().CGColor chartBottomLine.lineWidth = 1.0 chartBottomLine.strokeEnd = 0.0 var progressline:UIBezierPath = UIBezierPath() progressline.moveToPoint(CGPointMake(chartMargin, frame.size.height - xLabelHeight - chartMargin)) progressline.addLineToPoint(CGPointMake(frame.size.width - chartMargin, frame.size.height - xLabelHeight - chartMargin)) progressline.lineWidth = 1.0 progressline.lineCapStyle = kCGLineCapSquare chartBottomLine.path = progressline.CGPath chartBottomLine.strokeColor = PNLightGreyColor.CGColor; var pathAnimation:CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = 0.5 pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathAnimation.fromValue = 0.0 pathAnimation.toValue = 1.0 chartBottomLine.addAnimation(pathAnimation, forKey:"strokeEndAnimation") chartBottomLine.strokeEnd = 1.0; layer.addSublayer(chartBottomLine) //Add left Chart Line chartLeftLine = CAShapeLayer() chartLeftLine.lineCap = kCALineCapButt chartLeftLine.fillColor = UIColor.whiteColor().CGColor chartLeftLine.lineWidth = 1.0 chartLeftLine.strokeEnd = 0.0 var progressLeftline:UIBezierPath = UIBezierPath() progressLeftline.moveToPoint(CGPointMake(chartMargin, frame.size.height - xLabelHeight - chartMargin)) progressLeftline.addLineToPoint(CGPointMake(chartMargin, chartMargin)) progressLeftline.lineWidth = 1.0 progressLeftline.lineCapStyle = kCGLineCapSquare chartLeftLine.path = progressLeftline.CGPath chartLeftLine.strokeColor = PNLightGreyColor.CGColor var pathLeftAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd") pathLeftAnimation.duration = 0.5 pathLeftAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathLeftAnimation.fromValue = 0.0 pathLeftAnimation.toValue = 1.0 chartLeftLine.addAnimation(pathAnimation, forKey:"strokeEndAnimation") chartLeftLine.strokeEnd = 1.0 layer.addSublayer(chartLeftLine) } } func barColorAtIndex(index:Int) -> UIColor { if (self.strokeColors.count == self.yValues.count) { return self.strokeColors[index] as! UIColor } else { return self.strokeColor as UIColor } } func viewCleanupForCollection( array:NSMutableArray ) { if array.count > 0 { for object:AnyObject in array{ var view = object as! UIView view.removeFromSuperview() } array.removeAllObjects() } } func getYValueMax(yLabels:NSArray) { var max:CGFloat = CGFloat(yLabels.valueForKeyPath("@max.floatValue") as! Float) if max == 0 { yValueMax = yMinValue }else{ yValueMax = max } } public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { touchPoint(touches, withEvent: event) super.touchesBegan(touches as Set<NSObject>, withEvent: event) } func touchPoint(touches: NSSet!, withEvent event: UIEvent!){ var touch:UITouch = touches.anyObject() as! UITouch var touchPoint = touch.locationInView(self) var subview:UIView = hitTest(touchPoint, withEvent: nil)! self.delegate?.userClickedOnBarCharIndex(subview.tag) } // MARK: Init override public init(frame: CGRect) { super.init(frame: frame) barBackgroundColor = PNLightGreyColor clipsToBounds = true } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
1ef3bda649cc6d8cd4ec8a13c5230931
30.423267
177
0.556676
5.692825
false
false
false
false
cactis/SwiftEasyKit
Source/Classes/ProgressView.swift
1
2195
//// //// ProgressView.swift //// Created by ctslin on 3/3/16. // //import UIKit //import KDCircularProgress // //open class ProgressView: DefaultView { // public var complete = UIImageView() // public var progress: KDCircularProgress! // public var percentage: CGFloat { // didSet { // animateToAngle(seconds: 0.8) // } // } // // public func animateToAngle(seconds: Double) { // delayedJob(seconds) { () -> () in // let angle = Double(self.percentage * 360) // self.progress.animate(toAngle: Double(angle), duration: 0.5, completion: { (success) in // // }) // // } // } // // public init(percentage: CGFloat = 0) { // self.percentage = percentage // super.init(frame: .zero) // } // // override open func layoutUI() { // super.layoutUI() //// if percentage < 1 { // progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: width, height: height)) // layout([progress]) //// } else { // complete.image = UIImage.init(named: "complete") // layout([complete]) //// } // } // // override open func styleUI() { // super.styleUI() // // progress.startAngle = -90 // progress.progressThickness = 0.16 // progress.trackThickness = progress.progressThickness // progress.clockwise = true // progress.center = center // progress.gradientRotateSpeed = 1 // progress.roundedCorners = false // progress.glowMode = .noGlow // progress.angle = Double(percentage * CGFloat(360)) // progress.trackColor = UIColor.clear // progress.set(colors: UIColor.yellow.tinyDarker(), UIColor.orange, UIColor.red.tinyLighter(), UIColor.purple, UIColor.magenta, UIColor.green.tinyDarker()) // } // // override open func layoutSubviews() { // super.layoutSubviews() // if percentage < 1 { // let p = -1 * width * 0.15 // progress.fillSuperview(left: p, right: p, top: p, bottom: p) // progress.trackColor = UIColor.lightGray.lighter() // } else { // let q: CGFloat = -6 // complete.fillSuperview(left: q, right: q, top: q, bottom: q) // } // } // // required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //}
mit
ccc3c55b4698f5a6c4415698ce4717e2
29.068493
159
0.621412
3.440439
false
false
false
false
renyufei8023/WeiBo
Pods/UIColor_Hex_Swift/HEXColor/UIColorExtension.swift
3
5144
// // UIColorExtension.swift // HEXColor // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit /** MissingHashMarkAsPrefix: "Invalid RGB string, missing '#' as prefix" UnableToScanHexValue: "Scan hex error" MismatchedHexStringLength: "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8" */ public enum UIColorInputError : ErrorType { case MissingHashMarkAsPrefix, UnableToScanHexValue, MismatchedHexStringLength } extension UIColor { /** The shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ public convenience init(hex3: UInt16, alpha: CGFloat = 1) { let divisor = CGFloat(15) let red = CGFloat((hex3 & 0xF00) >> 8) / divisor let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor let blue = CGFloat( hex3 & 0x00F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ public convenience init(hex4: UInt16) { let divisor = CGFloat(15) let red = CGFloat((hex4 & 0xF000) >> 12) / divisor let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor let alpha = CGFloat( hex4 & 0x000F ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. */ public convenience init(hex6: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor let blue = CGFloat( hex6 & 0x0000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ public convenience init(hex8: UInt32) { let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor let alpha = CGFloat( hex8 & 0x000000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, throws error. - parameter rgba: String value. */ public convenience init(rgba_throws rgba: String) throws { guard rgba.hasPrefix("#") else { throw UIColorInputError.MissingHashMarkAsPrefix } guard let hexString: String = rgba.substringFromIndex(rgba.startIndex.advancedBy(1)), var hexValue: UInt32 = 0 where NSScanner(string: hexString).scanHexInt(&hexValue) else { throw UIColorInputError.UnableToScanHexValue } switch (hexString.characters.count) { case 3: self.init(hex3: UInt16(hexValue)) case 4: self.init(hex4: UInt16(hexValue)) case 6: self.init(hex6: hexValue) case 8: self.init(hex8: hexValue) default: throw UIColorInputError.MismatchedHexStringLength } } /** The rgba string representation of color with alpha of the form #RRGGBBAA/#RRGGBB, fails to default color. - parameter rgba: String value. */ public convenience init(rgba: String, defaultColor: UIColor = UIColor.clearColor()) { guard let color = try? UIColor(rgba_throws: rgba) else { self.init(CGColor: defaultColor.CGColor) return } self.init(CGColor: color.CGColor) } /** Hex string of a UIColor instance. - parameter rgba: Whether the alpha should be included. */ public func hexString(includeAlpha: Bool) -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) if (includeAlpha) { return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255)) } else { return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255)) } } public override var description: String { return self.hexString(true) } public override var debugDescription: String { return self.hexString(true) } }
mit
e6b5ead774864bec7b6d79e5093c001e
33.52349
110
0.592341
4
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
03-YFPageViewDemo/YFPageViewDemo/YFPageView/YFTitleView.swift
1
7576
// // YFTitleView.swift // YFPageViewDemo // // Created by Allison on 2017/4/27. // Copyright © 2017年 Allison. All rights reserved. // import UIKit protocol YFTitleViewDelegate : class { func titleView(_ titleView : YFTitleView, targetIndex : Int) } class YFTitleView: UIView { weak var delegate : YFTitleViewDelegate? fileprivate var titlesArr : [String] fileprivate var style : YFPageStyle fileprivate lazy var titleLabelsArr : [UILabel] = [UILabel]() fileprivate var currentIndex :Int = 0 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor bottomLine.frame.size.height = self.style.bottomLineHeight return bottomLine }() init(frame: CGRect,titles:[String],style:YFPageStyle) { self.titlesArr = titles self.style = style super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension YFTitleView { fileprivate func setupUI() { //1.将UIScorllView添加到view中 addSubview(scrollView) //2.将titleLabel添加到UIScorllView中 setupTitleLabels() //3.设置titleLabel的frame setupTitleLabelsFrame() // 4.设置BottomLine setupBottomLine() } private func setupBottomLine() { // 1.判断是否需要显示底部线段 guard style.isShowBottomLine else { return } // 2.将bottomLine添加到titleView中 scrollView.addSubview(bottomLine) // 3.设置frame bottomLine.frame.origin.x = titleLabelsArr.first!.frame.origin.x bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight bottomLine.frame.size.width = titleLabelsArr.first!.bounds.width } private func setupTitleLabels(){ for (i ,title) in titlesArr.enumerated() { // 1.创建Label let titleLabel = UILabel() // 2.设置label的属性 titleLabel.text = title titleLabel.font = UIFont.systemFont(ofSize: style.fontSize) titleLabel.tag = i titleLabel.textAlignment = .center titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor // 3.添加到父控件中 scrollView.addSubview(titleLabel) // 4.保存label titleLabelsArr.append(titleLabel) //给UILabel添加点击手势 let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:))) titleLabel.addGestureRecognizer(tapGes) titleLabel.isUserInteractionEnabled = true } } private func setupTitleLabelsFrame() { let count = titlesArr.count for (i, label) in titleLabelsArr.enumerated() { var w : CGFloat = 0 let h : CGFloat = bounds.height var x : CGFloat = 0 let y : CGFloat = 0 if style.isScrollEnable { // 可以滚动 w = (titlesArr[i] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil).width if i == 0 { x = style.itemMargin * 0.5 } else { let preLabel = titleLabelsArr[i - 1] x = preLabel.frame.maxX + style.itemMargin } } else { // 不能滚动 w = bounds.width / CGFloat(count) x = w * CGFloat(i) } label.frame = CGRect(x: x, y: y, width: w, height: h) } scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabelsArr.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero } } // MARK:- 监听事件 extension YFTitleView { @objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer) { //1.取出用户点击的View let targetLabel = tapGes.view as! UILabel //2.调整title adjustTitleLabel(targetIndex: targetLabel.tag) //3.通知ContentView进行调整 delegate?.titleView(self, targetIndex: currentIndex) // 4.调整BottomLine if style.isShowBottomLine { bottomLine.frame.origin.x = targetLabel.frame.origin.x bottomLine.frame.size.width = targetLabel.frame.width } } fileprivate func adjustTitleLabel(targetIndex : Int) { if targetIndex == currentIndex { return } //1.取出label let targetLabel = titleLabelsArr[targetIndex] let sourceLabel = titleLabelsArr[currentIndex] //2.切换文字的颜色 sourceLabel.textColor = style.normalColor targetLabel.textColor = style.selectColor //3.记录下值 currentIndex = targetLabel.tag //5.调整位置 -- 选中的按钮居中 if style.isScrollEnable { var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5 if offsetX < 0 { offsetX = 0 } if offsetX > scrollView.contentSize.width - scrollView.bounds.width { offsetX = scrollView.contentSize.width - scrollView.bounds.width } scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } } //MARK:-遵循YFContentViewDelegate 滑动contentView标签调整 extension YFTitleView : YFContentViewDelegate{ func contentView(_ contentView: YFContentView, targetIndex: Int) { adjustTitleLabel(targetIndex: targetIndex) } func contentView(_ contentView: YFContentView, targetIndex: Int, progress: CGFloat) { print(progress) //1.取出label let sourceLabel = titleLabelsArr[currentIndex] let targetLabel = titleLabelsArr[targetIndex] //2.颜色渐变 let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor) let selectRGB = style.selectColor.getRGB() let normalRGB = style.normalColor.getRGB() sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress) targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress) // 3.渐变BottomLine if style.isShowBottomLine { let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let deltaW = targetLabel.frame.width - sourceLabel.frame.width bottomLine.frame.origin.x = sourceLabel.frame.origin.x + deltaX * progress bottomLine.frame.size.width = sourceLabel.frame.width + deltaW * progress } } }
mit
124e56c094df6270579b53561cdebb4b
29.252066
212
0.593498
4.956669
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/SCSConstants.swift
1
1239
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // SCSConstants.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** import Foundation struct SCSFontsName { static let defaultFontName = "Helvetica" } struct SCSFontSizes { static let defaultFontSize: Float = 16.0 } struct SCSColorsHEX { static let backgroundBrush: UInt32 = 0xFF1c1c1e static let seriesBackgroundBrush: UInt32 = 0xFF1c1c1e static let majorPen: UInt32 = 0xFF323539 static let gridBandPen: UInt32 = 0xE1202123 static let minorPen: UInt32 = 0xFF232426 static let textColor: UInt32 = 0xFFDCb3af }
mit
3dd03676e54c3811d7ce055d5688521e
35.382353
85
0.651294
4.276817
false
false
false
false
kaji001/GnomesBook
GnomesBook/Gnome.swift
1
1648
// // Gnome.swift // GnomesBook // // Created by Mario Martinez on 18/6/16. // Copyright © 2016 Brastlewark Town. All rights reserved. // import UIKit import Alamofire final class Gnome: ResponseObjectSerializable, ResponseCollectionSerializable { let id: Int let name: String let surname: String let fullName: String let thumbnail: String let age: Int let weight: Float let height: Float let hairColor: String let professions: Array<String> let friends: Array<String> init() { self.id = 0 self.name = "" self.surname = "" self.fullName = "" self.thumbnail = "" self.age = 0 self.weight = 0.0 self.height = 0.0 self.hairColor = "" self.professions = Array<String>() self.friends = Array<String>() } init?(response: NSHTTPURLResponse, representation: AnyObject) { self.id = representation["id"] as! Int let fullName = representation["name"] as! String var fullNameArr = fullName.componentsSeparatedByString(" ") self.name = fullNameArr[1] self.surname = fullNameArr[0] self.fullName = fullName self.thumbnail = representation["thumbnail"] as! String self.age = representation["age"] as! Int self.weight = representation["weight"] as! Float self.height = representation["height"] as! Float self.hairColor = representation["hair_color"] as! String self.professions = representation["professions"] as! Array self.friends = representation["friends"] as! Array } }
gpl-3.0
e889fddc057b2ab8993bd5a83ef4a6ed
27.396552
79
0.617486
4.3687
false
false
false
false
KempinGe/LiveBroadcast
LIveBroadcast/LIveBroadcast/classes/Home/View/GKBRecomendGameViewCell.swift
1
1330
// // GKBRecomendGameViewCell.swift // LIveBroadcast // // Created by KempinGe on 2016/12/12. // Copyright © 2016年 盖凯宾. All rights reserved. // import UIKit import Kingfisher class GKBRecomendGameViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! var gameAnchorRoom : GKBGroupModel? { didSet{ titleLabel.text = gameAnchorRoom?.tag_name guard let AnchorRoom = gameAnchorRoom else { return } if AnchorRoom.icon_url == "" { imageView.image = UIImage(named: "home_more_btn") } guard let url = URL(string: AnchorRoom.icon_url) else { return } imageView.kf.setImage(with: url) // imageView.kf.setImage(with: <#T##Resource?#>, placeholder: <#T##Image?#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> ()#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> ()#>) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code imageView.layer.cornerRadius = 18 imageView.layer.masksToBounds = true } }
mit
1906c3aff616020b09528881a7cc0111
32.871795
328
0.62377
4.462838
false
false
false
false
BennyHarv3/habitica-ios
HabitRPG/TableviewCells/YesterdailyTaskCell.swift
1
2297
// // File.swift // Habitica // // Created by Phillip on 08.06.17. // Copyright © 2017 Phillip Thelen. All rights reserved. // import UIKit class YesterdailyTaskCell: UITableViewCell { @IBOutlet weak var wrapperView: UIView! @IBOutlet weak var checkbox: HRPGCheckBoxView! @IBOutlet weak var titleTextView: UILabel! @IBOutlet weak var checklistStackview: UIStackView! var onChecklistItemChecked: ((ChecklistItem) -> Void)? var checklistItems: [ChecklistItem]? override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none self.wrapperView.layer.borderWidth = 1 self.wrapperView.layer.borderColor = UIColor.lightGray.cgColor } func configure(task: Task) { checkbox.configure(for: task) titleTextView.text = task.text?.unicodeEmoji checklistStackview.subviews.forEach { view in view.removeFromSuperview() } guard let checklist = task.checklist else { return } checklistItems = checklist.array as? [ChecklistItem] for item in checklist { if let view = UIView.fromNib(nibName: "YesterdailyChecklistItem"), let checklistItem = item as? ChecklistItem { let label = view.viewWithTag(2) as? UILabel label?.text = checklistItem.text.unicodeEmoji let checkbox = view.viewWithTag(1) as? HRPGCheckBoxView checkbox?.configure(for: checklistItem, for: task) checkbox?.backgroundColor = UIColor.gray700() checklistStackview.addArrangedSubview(view) let recognizer = UITapGestureRecognizer(target: self, action:#selector(YesterdailyTaskCell.handleChecklistTap(recognizer:))) view.addGestureRecognizer(recognizer) } } } override func layoutSubviews() { super.layoutSubviews() } func handleChecklistTap(recognizer: UITapGestureRecognizer) { for (index, view) in checklistStackview.arrangedSubviews.enumerated() where view == recognizer.view { if let checked = self.onChecklistItemChecked, let item = checklistItems?[index] { checked(item) } return } } }
gpl-3.0
5be57af21a06b97cc0ba0b03fbc90335
33.268657
140
0.641115
4.991304
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Tests/DealerComponentTests/Presenter Tests/Test Doubles/CapturingDealerDetailScene.swift
1
7823
import DealerComponent import EurofurenceModel import UIKit class CapturingDealerDetailScene: UIViewController, DealerDetailScene, DealerDetailItemComponentFactory { private(set) var delegate: DealerDetailSceneDelegate? func setDelegate(_ delegate: DealerDetailSceneDelegate) { self.delegate = delegate } private(set) var boundNumberOfComponents: Int? private(set) var binder: DealerDetailSceneBinder? func bind(numberOfComponents: Int, using binder: DealerDetailSceneBinder) { boundNumberOfComponents = numberOfComponents self.binder = binder } typealias Component = AnyObject private(set) var boundDealerSummaryComponent: CapturingDealerDetailSummaryComponent? func makeDealerSummaryComponent(configureUsing block: (DealerDetailSummaryComponent) -> Void) -> Component { let component = CapturingDealerDetailSummaryComponent() block(component) boundDealerSummaryComponent = component return component } private(set) var boundLocationAndAvailabilityComponent: CapturingDealerLocationAndAvailabilityComponent? func makeDealerLocationAndAvailabilityComponent( configureUsing block: (DealerLocationAndAvailabilityComponent) -> Void ) -> Component { let component = CapturingDealerLocationAndAvailabilityComponent() block(component) boundLocationAndAvailabilityComponent = component return component } private(set) var boundAboutTheArtistComponent: CapturingAboutTheArtistComponent? func makeAboutTheArtistComponent(configureUsing block: (DealerAboutTheArtistComponent) -> Void) -> Component { let component = CapturingAboutTheArtistComponent() block(component) boundAboutTheArtistComponent = component return component } private(set) var boundAboutTheArtComponent: CapturingAboutTheArtComponent? func makeAboutTheArtComponent(configureUsing block: (AboutTheArtComponent) -> Void) -> Component { let component = CapturingAboutTheArtComponent() block(component) boundAboutTheArtComponent = component return component } } extension CapturingDealerDetailScene { @discardableResult func bindComponent(at index: Int) -> Component? { return binder?.bindComponent(at: index, using: self) } func simulateShareButtonTapped(_ sender: Any) { delegate?.dealerDetailSceneDidTapShareButton(sender) } } class CapturingDealerDetailSummaryComponent: DealerDetailSummaryComponent { private(set) var capturedOnWebsiteSelected: (() -> Void)? func onWebsiteSelected(perform block: @escaping () -> Void) { capturedOnWebsiteSelected = block } private(set) var capturedOnTwitterSelected: (() -> Void)? func onTwitterSelected(perform block: @escaping () -> Void) { capturedOnTwitterSelected = block } private(set) var capturedOnTelegramSelected: (() -> Void)? func onTelegramSelected(perform block: @escaping () -> Void) { capturedOnTelegramSelected = block } private(set) var capturedArtistImagePNGData: Data? func showArtistArtworkImageWithPNGData(_ data: Data) { capturedArtistImagePNGData = data } private(set) var didHideArtistArtwork = false func hideArtistArtwork() { didHideArtistArtwork = true } private(set) var capturedDealerTitle: String? func setDealerTitle(_ title: String) { capturedDealerTitle = title } private(set) var capturedDealerSubtitle: String? func showDealerSubtitle(_ subtitle: String) { capturedDealerSubtitle = subtitle } private(set) var didHideSubtitle = false func hideDealerSubtitle() { didHideSubtitle = true } private(set) var capturedDealerCategories: String? func setDealerCategories(_ categories: String) { capturedDealerCategories = categories } private(set) var capturedDealerShortDescription: String? func showDealerShortDescription(_ shortDescription: String) { capturedDealerShortDescription = shortDescription } private(set) var didHideShortDescription = false func hideDealerShortDescription() { didHideShortDescription = true } private(set) var capturedDealerWebsite: String? func showDealerWebsite(_ website: String) { capturedDealerWebsite = website } private(set) var didHideWebsite = false func hideDealerWebsite() { didHideWebsite = true } private(set) var capturedDealerTwitterHandle: String? func showDealerTwitterHandle(_ twitterHandle: String) { capturedDealerTwitterHandle = twitterHandle } private(set) var didHideTwitterHandle = false func hideTwitterHandle() { didHideTwitterHandle = true } private(set) var capturedDealerTelegramHandle: String? func showDealerTelegramHandle(_ telegramHandle: String) { capturedDealerTelegramHandle = telegramHandle } private(set) var didHideTelegramHandle = false func hideTelegramHandle() { didHideTelegramHandle = true } } class CapturingDealerLocationAndAvailabilityComponent: DealerLocationAndAvailabilityComponent { private(set) var capturedTitle: String? func setComponentTitle(_ title: String) { capturedTitle = title } private(set) var capturedMapPNGGraphicData: Data? func showMapPNGGraphicData(_ data: Data) { capturedMapPNGGraphicData = data } private(set) var capturedLimitedAvailabilityWarning: String? func showDealerLimitedAvailabilityWarning(_ warning: String) { capturedLimitedAvailabilityWarning = warning } private(set) var capturedLocatedInAfterDarkDealersDenMessage: String? func showLocatedInAfterDarkDealersDenMessage(_ message: String) { capturedLocatedInAfterDarkDealersDenMessage = message } private(set) var didHideMap = false func hideMap() { didHideMap = true } private(set) var didHideLimitedAvailbilityWarning = false func hideLimitedAvailbilityWarning() { didHideLimitedAvailbilityWarning = true } private(set) var didHideAfterDarkDenNotice = false func hideAfterDarkDenNotice() { didHideAfterDarkDenNotice = true } } class CapturingAboutTheArtistComponent: DealerAboutTheArtistComponent { private(set) var capturedTitle: String? func setAboutTheArtistTitle(_ title: String) { capturedTitle = title } private(set) var capturedArtistDescription: String? func setArtistDescription(_ artistDescription: String) { capturedArtistDescription = artistDescription } } class CapturingAboutTheArtComponent: AboutTheArtComponent { private(set) var capturedTitle: String? func setComponentTitle(_ title: String) { capturedTitle = title } private(set) var capturedAboutTheArt: String? func showAboutTheArtDescription(_ aboutTheArt: String) { capturedAboutTheArt = aboutTheArt } private(set) var didHideAboutTheArtDescription = false func hideAboutTheArtDescription() { didHideAboutTheArtDescription = true } private(set) var capturedArtPreviewImagePNGData: Data? func showArtPreviewImagePNGData(_ artPreviewImagePNGData: Data) { capturedArtPreviewImagePNGData = artPreviewImagePNGData } private(set) var didHideArtPreview = false func hideArtPreviewImage() { didHideArtPreview = true } private(set) var capturedArtPreviewCaption: String? func showArtPreviewCaption(_ caption: String) { capturedArtPreviewCaption = caption } private(set) var didHideArtPreviewCaption = false func hideArtPreviewCaption() { didHideArtPreviewCaption = true } }
mit
66344d92c2848ddf178c3ddab68c5666
30.417671
114
0.726192
5.718567
false
false
false
false
prey/prey-ios-client
Prey/Classes/ReportPhoto.swift
1
23410
// // ReportPhoto.swift // Prey // // Created by Javier Cala Uribe on 26/05/16. // Copyright © 2016 Prey, Inc. All rights reserved. // import Foundation import AVFoundation import UIKit protocol PhotoServiceDelegate { func photoReceived(_ photos:NSMutableDictionary) } class ReportPhoto: NSObject { // MARK: Properties // Check device authorization var isDeviceAuthorized : Bool { let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) return (authStatus == AVAuthorizationStatus.authorized) ? true : false } // Check camera number var isTwoCameraAvailable : Bool { let videoDevices = AVCaptureDevice.devices(for: AVMediaType.video) return (videoDevices.count > 1) ? true : false } // Photo array var photoArray = NSMutableDictionary() var waitForRequest = false // ReportPhoto Delegate var delegate: PhotoServiceDelegate? // Session Device let sessionDevice:AVCaptureSession // Session Queue let sessionQueue:DispatchQueue // Device Input var videoDeviceInput:AVCaptureDeviceInput? // MARK: Init // Init camera session override init() { // Create AVCaptureSession sessionDevice = AVCaptureSession() // Set session to PresetLow if sessionDevice.canSetSessionPreset(AVCaptureSession.Preset.low) { sessionDevice.sessionPreset = AVCaptureSession.Preset.low } // In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, // or connections from multiple threads at the same time. // Why not do all of this on the main queue? // AVCaptureSession.startRunning() is a blocking call which can take a long time. We dispatch session setup // to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive). sessionQueue = DispatchQueue(label: "session queue", attributes: []) } // Start Session func startSession() { } // Stop Session func stopSession() { } // MARK: Functions // Remove observer func removeObserver() { NotificationCenter.default.removeObserver(self) } // Set shutter sound off func setShutterSoundOff() { var soundID:SystemSoundID = 0 let pathFile = Bundle.main.path(forResource: "shutter", ofType: "aiff") let shutterFile = URL(fileURLWithPath: pathFile!) AudioServicesCreateSystemSoundID((shutterFile as CFURL), &soundID) AudioServicesPlaySystemSound(soundID) } // Set Flash Off func setFlashModeOff(_ device:AVCaptureDevice) { if (device.hasFlash && device.isFlashModeSupported(AVCaptureDevice.FlashMode.off)) { // Set AVCaptureFlashMode do { try device.lockForConfiguration() device.flashMode = AVCaptureDevice.FlashMode.off device.unlockForConfiguration() } catch let error { PreyLogger("AVCaptureFlashMode error: \(error.localizedDescription)") } } } // Observer Key @objc func sessionRuntimeError(notification: NSNotification) { PreyLogger("Capture session runtime error") self.delegate?.photoReceived(self.photoArray) } @objc func sessionWasInterrupted(notification: NSNotification) { PreyLogger("Capture session interrupted") self.delegate?.photoReceived(self.photoArray) } // Return AVCaptureDevice class func deviceWithPosition(_ position:AVCaptureDevice.Position) -> AVCaptureDevice? { // Get devices array let devicesArray = AVCaptureDevice.devices(for: AVMediaType.video) // Search for device for device in devicesArray { if device.position == position { return device } } return nil } } // ==== // MARK: ReportPhotoiOS10 // ==== @available(iOS 10.0, *) class ReportPhotoiOS10: ReportPhoto, AVCapturePhotoCaptureDelegate { // MARK: Properties private var isFirstPhoto = true // Photo Output private let photoOutput = AVCapturePhotoOutput() // MARK: Init // Start Session override func startSession() { sessionQueue.async { self.getFirstPhoto() } } // Stop Session override func stopSession() { sessionQueue.async { // Remove current device input self.sessionDevice.beginConfiguration() // Remove session input if let deviceInput = self.videoDeviceInput { if !self.sessionDevice.canAddInput(deviceInput) { self.sessionDevice.removeInput(deviceInput) } } // Remove session output if !self.sessionDevice.canAddOutput(self.photoOutput) { self.sessionDevice.removeOutput(self.photoOutput) } // Set session to PresetLow if self.sessionDevice.canSetSessionPreset(AVCaptureSession.Preset.low) { self.sessionDevice.sessionPreset = AVCaptureSession.Preset.low } // Disable wide-gamut color self.sessionDevice.automaticallyConfiguresCaptureDeviceForWideColor = false // End session config self.sessionDevice.commitConfiguration() // Stop session self.sessionDevice.stopRunning() } } // MARK: Functions // Get first photo func getFirstPhoto() { // Check error with device guard let videoDevice = ReportPhoto.deviceWithPosition(AVCaptureDevice.Position.back) else { PreyLogger("Error with AVCaptureDevice") self.delegate?.photoReceived(self.photoArray) return } // Set AVCaptureDeviceInput do { self.videoDeviceInput = try AVCaptureDeviceInput(device:videoDevice) // Check videoDeviceInput guard let videoDevInput = self.videoDeviceInput else { PreyLogger("Error videoDeviceInput") self.delegate?.photoReceived(self.photoArray) return } // Add session input guard self.sessionDevice.canAddInput(videoDevInput) else { PreyLogger("Error add session input") self.delegate?.photoReceived(self.photoArray) return } self.sessionDevice.addInput(videoDevInput) } catch let error { PreyLogger("AVCaptureDeviceInput error: \(error.localizedDescription)") self.delegate?.photoReceived(self.photoArray) return } // Add session output guard self.sessionDevice.canAddOutput(self.photoOutput) else { PreyLogger("Error add session output") self.delegate?.photoReceived(self.photoArray) return } self.sessionDevice.addOutput(self.photoOutput) // Disable wide-gamut color self.sessionDevice.automaticallyConfiguresCaptureDeviceForWideColor = false // Start session self.sessionDevice.startRunning() // KeyObserver NotificationCenter.default.addObserver(self, selector: #selector(self.sessionRuntimeError), name: .AVCaptureSessionRuntimeError, object: self.sessionDevice) NotificationCenter.default.addObserver(self, selector: #selector(self.sessionWasInterrupted), name: .AVCaptureSessionWasInterrupted, object: self.sessionDevice) // Delay let timeValue = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) self.sessionQueue.asyncAfter(deadline: timeValue, execute: { () -> Void in // Capture a still image self.takePicture(true) }) } // Get second photo func getSecondPhoto() { // Set captureDevice guard let videoDevice = ReportPhoto.deviceWithPosition(AVCaptureDevice.Position.front) else { PreyLogger("Error with AVCaptureDevice") self.delegate?.photoReceived(self.photoArray) return } // Set AVCaptureDeviceInput do { let frontDeviceInput = try AVCaptureDeviceInput(device:videoDevice) // Remove current device input self.sessionDevice.beginConfiguration() if let deviceInput = self.videoDeviceInput { self.sessionDevice.removeInput(deviceInput) } // Add session input guard self.sessionDevice.canAddInput(frontDeviceInput) else { PreyLogger("Error add session input") self.delegate?.photoReceived(self.photoArray) return } self.sessionDevice.addInput(frontDeviceInput) self.videoDeviceInput = frontDeviceInput // Set session to PresetLow if self.sessionDevice.canSetSessionPreset(AVCaptureSession.Preset.low) { self.sessionDevice.sessionPreset = AVCaptureSession.Preset.low } // Disable wide-gamut color self.sessionDevice.automaticallyConfiguresCaptureDeviceForWideColor = false // End session config self.sessionDevice.commitConfiguration() // Delay let timeValue = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) self.sessionQueue.asyncAfter(deadline: timeValue, execute: { () -> Void in // Capture a still image self.takePicture(false) }) } catch let error { PreyLogger("AVCaptureDeviceInput error: \(error.localizedDescription)") self.delegate?.photoReceived(self.photoArray) } } // Capture a still image func takePicture(_ isFirstPhoto:Bool) { self.isFirstPhoto = isFirstPhoto // Set flash off if let deviceInput = self.videoDeviceInput { self.setFlashModeOff(deviceInput.device) } // Capture a still image guard let videoConnection = self.photoOutput.connection(with: AVMediaType.video) else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } guard videoConnection.isEnabled else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } guard videoConnection.isActive else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } let photoSettings = AVCapturePhotoSettings() self.photoOutput.capturePhoto(with: photoSettings, delegate: self) } @available(iOS 11.0, *) func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { guard error == nil else { PreyLogger("Error AVCapturePhotoOutput") self.delegate?.photoReceived(self.photoArray) return } guard let imageData = photo.fileDataRepresentation() else { PreyLogger("Error CMSampleBuffer to NSData") self.delegate?.photoReceived(self.photoArray) return } self.saveImagePhotoArray(imageData: imageData) } func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { guard error == nil else { PreyLogger("Error CMSampleBuffer") self.delegate?.photoReceived(self.photoArray) return } // Change SampleBuffer to NSData guard let sampleBuffer = photoSampleBuffer else { PreyLogger("Error CMSampleBuffer") self.delegate?.photoReceived(self.photoArray) return } guard let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: nil) else { PreyLogger("Error CMSampleBuffer to NSData") self.delegate?.photoReceived(self.photoArray) return } self.saveImagePhotoArray(imageData: imageData) } // Save image to Photo Array func saveImagePhotoArray(imageData: Data) { guard let image = UIImage(data: imageData) else { PreyLogger("Error NSData to UIImage") self.delegate?.photoReceived(self.photoArray) return } if self.isFirstPhoto { self.photoArray.removeAllObjects() self.photoArray.setObject(image, forKey: "picture" as NSCopying) } else { self.photoArray.setObject(image, forKey: "screenshot" as NSCopying) } // Check if two camera available if self.isTwoCameraAvailable && self.isFirstPhoto { self.sessionQueue.async { self.getSecondPhoto() } } else { // Send Photo Array to Delegate self.delegate?.photoReceived(self.photoArray) } } } // ==== // MARK: ReportPhotoiOS8 // ==== class ReportPhotoiOS8: ReportPhoto { // MARK: Properties // Image Output @objc dynamic var stillImageOutput = AVCaptureStillImageOutput() // MARK: Init // Start Session override func startSession() { sessionQueue.async { self.getFirstPhoto() } } // Stop Session override func stopSession() { sessionQueue.async { // Remove current device input self.sessionDevice.beginConfiguration() // Remove session input if let deviceInput = self.videoDeviceInput { if !self.sessionDevice.canAddInput(deviceInput) { self.sessionDevice.removeInput(deviceInput) } } // Remove session output if !self.sessionDevice.canAddOutput(self.stillImageOutput) { self.sessionDevice.removeOutput(self.stillImageOutput) } // Set session to PresetLow if self.sessionDevice.canSetSessionPreset(AVCaptureSession.Preset.low) { self.sessionDevice.sessionPreset = AVCaptureSession.Preset.low } // End session config self.sessionDevice.commitConfiguration() // Stop session self.sessionDevice.stopRunning() } } // MARK: Functions // Get first photo func getFirstPhoto() { // Check error with device guard let videoDevice = ReportPhoto.deviceWithPosition(AVCaptureDevice.Position.back) else { PreyLogger("Error with AVCaptureDevice") self.delegate?.photoReceived(self.photoArray) return } // Set AVCaptureDeviceInput do { self.videoDeviceInput = try AVCaptureDeviceInput(device:videoDevice) // Check videoDeviceInput guard let videoDevInput = self.videoDeviceInput else { PreyLogger("Error videoDeviceInput") self.delegate?.photoReceived(self.photoArray) return } // Add session input guard self.sessionDevice.canAddInput(videoDevInput) else { PreyLogger("Error add session input") self.delegate?.photoReceived(self.photoArray) return } self.sessionDevice.addInput(videoDevInput) } catch let error { PreyLogger("AVCaptureDeviceInput error: \(error.localizedDescription)") self.delegate?.photoReceived(self.photoArray) return } // Add session output guard self.sessionDevice.canAddOutput(self.stillImageOutput) else { PreyLogger("Error add session output") self.delegate?.photoReceived(self.photoArray) return } self.stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] self.sessionDevice.addOutput(self.stillImageOutput) // Start session self.sessionDevice.startRunning() // KeyObserver NotificationCenter.default.addObserver(self, selector: #selector(self.sessionRuntimeError), name: .AVCaptureSessionRuntimeError, object: self.sessionDevice) NotificationCenter.default.addObserver(self, selector: #selector(self.sessionWasInterrupted), name: .AVCaptureSessionWasInterrupted, object: self.sessionDevice) // Delay let timeValue = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) self.sessionQueue.asyncAfter(deadline: timeValue, execute: { () -> Void in // Capture a still image self.takePicture(true) }) } // Get second photo func getSecondPhoto() { // Set captureDevice guard let videoDevice = ReportPhoto.deviceWithPosition(AVCaptureDevice.Position.front) else { PreyLogger("Error with AVCaptureDevice") self.delegate?.photoReceived(self.photoArray) return } // Set AVCaptureDeviceInput do { let frontDeviceInput = try AVCaptureDeviceInput(device:videoDevice) // Remove current device input self.sessionDevice.beginConfiguration() if let deviceInput = self.videoDeviceInput { self.sessionDevice.removeInput(deviceInput) } // Add session input guard self.sessionDevice.canAddInput(frontDeviceInput) else { PreyLogger("Error add session input") self.delegate?.photoReceived(self.photoArray) return } self.sessionDevice.addInput(frontDeviceInput) self.videoDeviceInput = frontDeviceInput // Set session to PresetLow if self.sessionDevice.canSetSessionPreset(AVCaptureSession.Preset.low) { self.sessionDevice.sessionPreset = AVCaptureSession.Preset.low } // End session config self.sessionDevice.commitConfiguration() // Delay let timeValue = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) self.sessionQueue.asyncAfter(deadline: timeValue, execute: { () -> Void in // Capture a still image self.takePicture(false) }) } catch let error { PreyLogger("AVCaptureDeviceInput error: \(error.localizedDescription)") self.delegate?.photoReceived(self.photoArray) } } // Capture a still image func takePicture(_ isFirstPhoto:Bool) { // Set flash off if let deviceInput = self.videoDeviceInput { self.setFlashModeOff(deviceInput.device) } // Capture a still image guard let videoConnection = self.stillImageOutput.connection(with: AVMediaType.video) else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } guard videoConnection.isEnabled else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } guard videoConnection.isActive else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } // Check current state guard self.stillImageOutput.isCapturingStillImage == false else { // Error: return to delegate self.delegate?.photoReceived(self.photoArray) return } // Capture image self.stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler:self.checkPhotoCapture(isFirstPhoto)) } // Completion Handler to Photo Capture func checkPhotoCapture(_ isFirstPhoto:Bool) -> (CMSampleBuffer?, Error?) -> Void { let actionPhotoCapture: (CMSampleBuffer?, Error?) -> Void = { (sampleBuffer, error) in guard error == nil else { PreyLogger("Error CMSampleBuffer") self.delegate?.photoReceived(self.photoArray) return } // Change SampleBuffer to NSData guard let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer!) else { PreyLogger("Error CMSampleBuffer to NSData") self.delegate?.photoReceived(self.photoArray) return } // Save image to Photo Array guard let image = UIImage(data: imageData) else { PreyLogger("Error NSData to UIImage") self.delegate?.photoReceived(self.photoArray) return } if isFirstPhoto { self.photoArray.removeAllObjects() self.photoArray.setObject(image, forKey: "picture" as NSCopying) } else { self.photoArray.setObject(image, forKey: "screenshot" as NSCopying) } // Check if two camera available if self.isTwoCameraAvailable && isFirstPhoto { self.sessionQueue.async { self.getSecondPhoto() } } else { // Send Photo Array to Delegate self.delegate?.photoReceived(self.photoArray) } } return actionPhotoCapture } }
gpl-3.0
ab3d43d97bab5c2f7bbc8cd10b56ca14
34.361027
292
0.580717
6.086583
false
false
false
false
ZhipingYang/UUChatSwift
UUChatTableViewSwift/ChatTableViewController.swift
1
7340
// // ViewController.swift // UUChatTableViewSwift // // Created by XcodeYang on 8/13/15. // Copyright © 2015 XcodeYang. All rights reserved. // import UIKit private let leftCellId = "UUChatLeftMessageCell" private let rightCellId = "UUChatRightMessageCell" class ChatTableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var chatTableView: UITableView! var inputBackView: UUInputView! var dataArray: [AnyObject]! var inputViewConstraint: NSLayoutConstraint? = nil override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardFrameChanged:"), name: UIKeyboardWillChangeFrameNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } //TODO: This method seems like would fix the problem of cells layout when Orientation changed. override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { //chatTableView.reloadData() self.view.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() self.dataArray = UUChatModel.creatRandomArray(count: 10) initBaseViews() chatTableView.registerClass(UUChatLeftMessageCell.classForKeyedArchiver(), forCellReuseIdentifier: leftCellId) chatTableView.registerClass(UUChatRightMessageCell.classForKeyedArchiver(), forCellReuseIdentifier: rightCellId) chatTableView.estimatedRowHeight = 100 } func initBaseViews() { self.title = "UUChat - Swift2" navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Stop, target: self, action: Selector("backAction")) navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Search, target: self, action: nil) inputBackView = UUInputView() self.view.addSubview(inputBackView) //TODO: I don't know how to get constraint from snapkit's methods. //It doesn't works. why.why.why... //https://github.com/SnapKit/SnapKit/tree/feature/protocol-api#1-references //inputViewConstraint = make.bottom.equalTo(view).constraint // temporary method inputViewConstraint = NSLayoutConstraint( item: inputBackView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0 ) inputBackView.snp_makeConstraints { (make) -> Void in make.leading.trailing.equalTo(self.view) } view.addConstraint(inputViewConstraint!) inputBackView.sendMessage( imageBlock: { [weak self](image:UIImage, textView:UITextView) -> Void in self!.dataArray.append(UUChatModel.creatMessageFromMeByImage(image)) self!.chatTableView.reloadData() self!.chatTableView.scrollToBottom(animation: true) }, textBlock: { [weak self](text:String, textView:UITextView) -> Void in self!.dataArray.append(UUChatModel.creatMessageFromMeByText(text)) self!.chatTableView.reloadData() self!.chatTableView.scrollToBottom(animation: true) }, voiceBlock: { [weak self](voice:NSData, textView:UITextView) -> Void in }) chatTableView = UITableView.init(frame: CGRectZero, style: .Plain) chatTableView.dataSource = self chatTableView.delegate = self chatTableView.separatorStyle = UITableViewCellSeparatorStyle.None chatTableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive chatTableView.estimatedRowHeight = 60 self.view.addSubview(chatTableView) chatTableView.snp_makeConstraints { (make) -> Void in make.top.leading.trailing.equalTo(self.view) make.bottom.equalTo(inputBackView.snp_top) } chatTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) } // private method func backAction(){ if navigationController?.viewControllers.count>1 { self.navigationController?.popViewControllerAnimated(true) } else { self.dismissViewControllerAnimated(true, completion: nil) } } @objc func keyboardFrameChanged(notification: NSNotification) { let dict = NSDictionary(dictionary: notification.userInfo!) let keyboardValue = dict.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue let bottomDistance = mainScreenSize().height - keyboardValue.CGRectValue().origin.y let duration = Double(dict.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber) UIView.animateWithDuration(duration, animations: { self.inputViewConstraint!.constant = -bottomDistance self.view.layoutIfNeeded() }, completion: { (value: Bool) in self.chatTableView.scrollToBottom(animation: true) }) } private func mainScreenSize() -> CGSize { return UIScreen.mainScreen().bounds.size } // tableview delegate & dataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let model = dataArray[indexPath.row] as! UUChatModel if model.from == .Me { let cell:UUChatRightMessageCell = tableView.dequeueReusableCellWithIdentifier(rightCellId) as! UUChatRightMessageCell cell.configUIWithModel(model) return cell } else { let cell:UUChatLeftMessageCell = tableView.dequeueReusableCellWithIdentifier(leftCellId) as! UUChatLeftMessageCell cell.configUIWithModel(model) return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.view.endEditing(true) } // action @IBAction func sendImage(btn:UIButton) { self.view.endEditing(true) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) let libraryAction = UIAlertAction(title: "本地相册", style: .Default) { (action:UIAlertAction) -> Void in } let takePhotoAction = UIAlertAction(title: "拍照", style: .Default) { (action:UIAlertAction) -> Void in } let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alert.addAction(cancelAction) alert.addAction(libraryAction) alert.addAction(takePhotoAction) self.presentViewController(alert, animated: true, completion: nil) } }
mit
aa566bc86461c52de6a239034cdf8c6a
37.767196
165
0.659615
5.48018
false
false
false
false
manavgabhawala/swift
test/Generics/deduction.swift
2
10569
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Deduction of generic arguments //===----------------------------------------------------------------------===// func identity<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> T { return value } func identity2<T>(_ value: T) -> Int { return 0 } struct X { } struct Y { } func useIdentity(_ x: Int, y: Float, i32: Int32) { var x2 = identity(x) var y2 = identity(y) // Deduction that involves the result type x2 = identity(17) var i32_2 : Int32 = identity(17) // Deduction where the result type and input type can get different results var xx : X, yy : Y xx = identity(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} } // FIXME: Crummy diagnostic! func twoIdentical<T>(_ x: T, _ y: T) -> T {} func useTwoIdentical(_ xi: Int, yi: Float) { var x = xi, y = yi x = twoIdentical(x, x) y = twoIdentical(y, y) x = twoIdentical(x, 1) x = twoIdentical(1, x) y = twoIdentical(1.0, y) y = twoIdentical(y, 1.0) twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func mySwap<T>(_ x: inout T, _ y: inout T) { let tmp = x x = y y = tmp } func useSwap(_ xi: Int, yi: Float) { var x = xi, y = yi mySwap(&x, &x) mySwap(&y, &y) mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} // expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}} mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func takeTuples<T, U>(_: (T, U), _: (U, T)) { } func useTuples(_ x: Int, y: Float, z: (Float, Int)) { takeTuples((x, y), (y, x)) takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} // FIXME: Use 'z', which requires us to fix our tuple-conversion // representation. } func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {} func passFunction(_ f: (Int) -> Float, x: Int, y: Float) { acceptFunction(f, x, y) acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}} func testReturnTuple(_ x: Int, y: Float) { returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}} var _ : (Int, Float) = returnTuple(x) var _ : (Float, Float) = returnTuple(y) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) { confusingArgAndParam(g, f) confusingArgAndParam(f, g) } func acceptUnaryFn<T, U>(_ f: (T) -> U) { } func acceptUnaryFnSame<T>(_ f: (T) -> T) { } func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { } func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { } func unaryFnIntInt(_: Int) -> Int {} func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}} func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}} // Variable forms of the above functions var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt func passOverloadSet() { // Passing a non-generic function to a generic function acceptUnaryFn(unaryFnIntInt) acceptUnaryFnSame(unaryFnIntInt) // Passing an overloaded function set to a generic function // FIXME: Yet more terrible diagnostics. acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}} acceptUnaryFnSame(unaryFnOvl) // Passing a variable of function type to a generic function acceptUnaryFn(unaryFnIntIntVar) acceptUnaryFnSame(unaryFnIntIntVar) // Passing a variable of function type to a generic function to an inout parameter acceptUnaryFnRef(&unaryFnIntIntVar) acceptUnaryFnSameRef(&unaryFnIntIntVar) acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}} } func acceptFnFloatFloat(_ f: (Float) -> Float) {} func acceptFnDoubleDouble(_ f: (Double) -> Double) {} func passGeneric() { acceptFnFloatFloat(identity) acceptFnFloatFloat(identity2) } //===----------------------------------------------------------------------===// // Simple deduction for generic member functions //===----------------------------------------------------------------------===// struct SomeType { func identity<T>(_ x: T) -> T { return x } func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}} func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}} func returnAs<T>() -> T {} } func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) { var st = sti, i = ii, f = fi i = st.identity(i) f = st.identity(f) i = st.identity2(i) f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}} i = st.returnAs() f = st.returnAs() acceptFnFloatFloat(st.identity) acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}} acceptFnDoubleDouble(st.identity2) } struct StaticFuncs { static func chameleon<T>() -> T {} func chameleon2<T>() -> T {} } struct StaticFuncsGeneric<U> { // FIXME: Nested generics are very broken // static func chameleon<T>() -> T {} } func chameleon<T>() -> T {} func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) { var x: Int16 x = StaticFuncs.chameleon() x = sf.chameleon2() // FIXME: Nested generics are very broken // x = sfi.chameleon() // typealias SFI = StaticFuncsGeneric<Int> // x = SFI.chameleon() _ = x } //===----------------------------------------------------------------------===// // Deduction checking for constraints //===----------------------------------------------------------------------===// protocol IsBefore { func isBefore(_ other: Self) -> Bool } func min2<T : IsBefore>(_ x: T, _ y: T) -> T { if y.isBefore(x) { return y } return x } extension Int : IsBefore { func isBefore(_ other: Int) -> Bool { return self < other } } func callMin(_ x: Int, y: Int, a: Float, b: Float) { _ = min2(x, y) min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}} } func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} func callRangeOfIsBefore(_ ia: [Int], da: [Double]) { rangeOfIsBefore(ia.makeIterator()) rangeOfIsBefore(da.makeIterator()) // expected-error{{type 'Double' does not conform to protocol 'IsBefore'}} } func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {} // expected-note@-1 {{requirement specified as 'A.Element' == 'B.Element' [with A = IndexingIterator<[Int]>, B = IndexingIterator<[Double]>]}} func compareIterators() { var a: [Int] = [] var b: [Double] = [] testEqualIterElementTypes(a.makeIterator(), b.makeIterator()) // expected-error {{'<A, B where A : IteratorProtocol, B : IteratorProtocol, A.Element == B.Element> (A, B) -> ()' requires the types 'Int' and 'Double' be equivalent}} } protocol P_GI { associatedtype Y } class C_GI : P_GI { typealias Y = Double } class GI_Diff {} func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {} // expected-note@-1 {{requirement specified as 'T.Y' : 'GI_Diff' [with T = C_GI]}} genericInheritsA(C_GI()) // expected-error {{<T where T : P_GI, T.Y : GI_Diff> (T) -> ()' requires that 'C_GI.Y' (aka 'Double') inherit from 'GI_Diff'}} //===----------------------------------------------------------------------===// // Deduction for member operators //===----------------------------------------------------------------------===// protocol Addable { static func +(x: Self, y: Self) -> Self } func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T { u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} return x+y } //===----------------------------------------------------------------------===// // Deduction for bound generic types //===----------------------------------------------------------------------===// struct MyVector<T> { func size() -> Int {} } func getVectorSize<T>(_ v: MyVector<T>) -> Int { return v.size() } func ovlVector<T>(_ v: MyVector<T>) -> X {} func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {} func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) { var i : Int i = getVectorSize(vi) i = getVectorSize(vf) getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}} var x : X, y : Y x = ovlVector(vi) x = ovlVector(vf) var vvi : MyVector<MyVector<Int>> y = ovlVector(vvi) var yy = ovlVector(vvi) yy = y y = yy } // <rdar://problem/15104554> postfix operator <*> protocol MetaFunction { associatedtype Result static postfix func <*> (_: Self) -> Result? } protocol Bool_ {} struct False : Bool_ {} struct True : Bool_ {} postfix func <*> <B:Bool_>(_: Test<B>) -> Int? { return .none } postfix func <*> (_: Test<True>) -> String? { return .none } class Test<C: Bool_> : MetaFunction { typealias Result = Int } // picks first <*> typealias Inty = Test<True>.Result var iy : Inty = 5 // okay, because we picked the first <*> var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}} // rdar://problem/20577950 class DeducePropertyParams { let badSet: Set = ["Hello"] } // SR-69 struct A {} func foo() { for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}} } let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}} let oi : Int? = 5 let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}} }
apache-2.0
fd870f05acc622952d8265892bafcf97
32.028125
232
0.602138
3.689005
false
false
false
false
Pursuit92/antlr4
runtime/Swift/Antlr4/org/antlr/v4/runtime/Parser.swift
4
38705
/* 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 is all the parsing support code essentially; most of it is error recovery stuff. */ //public abstract class Parser : Recognizer<Token, ParserATNSimulator> { import Foundation open class Parser: Recognizer<ParserATNSimulator> { public static let EOF: Int = -1 public static var ConsoleError = true //false public class TraceListener: ParseTreeListener { var host: Parser init(_ host: Parser) { self.host = host } public func enterEveryRule(_ ctx: ParserRuleContext) throws { let ruleName = host.getRuleNames()[ctx.getRuleIndex()] let lt1 = try host._input.LT(1)!.getText()! print("enter \(ruleName), LT(1)=\(lt1)") } public func visitTerminal(_ node: TerminalNode) { print("consume \(node.getSymbol()) rule \(host.getRuleNames()[host._ctx!.getRuleIndex()])") } public func visitErrorNode(_ node: ErrorNode) { } public func exitEveryRule(_ ctx: ParserRuleContext) throws { let ruleName = host.getRuleNames()[ctx.getRuleIndex()] let lt1 = try host._input.LT(1)!.getText()! print("exit \(ruleName), LT(1)=\(lt1)") } } public class TrimToSizeListener: ParseTreeListener { public static let INSTANCE: TrimToSizeListener = TrimToSizeListener() public func enterEveryRule(_ ctx: ParserRuleContext) { } public func visitTerminal(_ node: TerminalNode) { } public func visitErrorNode(_ node: ErrorNode) { } public func exitEveryRule(_ ctx: ParserRuleContext) { //TODO: check necessary // if (ctx.children is ArrayList) { // (ctx.children as ArrayList<?>).trimToSize(); // } } } /** * This field maps from the serialized ATN string to the deserialized {@link org.antlr.v4.runtime.atn.ATN} with * bypass alternatives. * * @see org.antlr.v4.runtime.atn.ATNDeserializationOptions#isGenerateRuleBypassTransitions() */ //private let bypassAltsAtnCache : Dictionary<String, ATN> = // WeakHashMap<String, ATN>(); MapTable<NSString, ATN> private let bypassAltsAtnCache: HashMap<String, ATN> = HashMap<String, ATN>() /** * The error handling strategy for the parser. The default value is a new * instance of {@link org.antlr.v4.runtime.DefaultErrorStrategy}. * * @see #getErrorHandler * @see #setErrorHandler */ public var _errHandler: ANTLRErrorStrategy = DefaultErrorStrategy() /** * The input stream. * * @see #getInputStream * @see #setInputStream */ public var _input: TokenStream! internal var _precedenceStack: Stack<Int> = { var precedenceStack = Stack<Int>() precedenceStack.push(0) return precedenceStack }() /** * The {@link org.antlr.v4.runtime.ParserRuleContext} object for the currently executing rule. * This is always non-null during the parsing process. */ public var _ctx: ParserRuleContext? = nil /** * Specifies whether or not the parser should construct a parse tree during * the parsing process. The default value is {@code true}. * * @see #getBuildParseTree * @see #setBuildParseTree */ internal var _buildParseTrees: Bool = true /** * When {@link #setTrace}{@code (true)} is called, a reference to the * {@link org.antlr.v4.runtime.Parser.TraceListener} is stored here so it can be easily removed in a * later call to {@link #setTrace}{@code (false)}. The listener itself is * implemented as a parser listener so this field is not directly used by * other parser methods. */ private var _tracer: TraceListener? /** * The list of {@link org.antlr.v4.runtime.tree.ParseTreeListener} listeners registered to receive * events during the parse. * * @see #addParseListener */ public var _parseListeners: Array<ParseTreeListener>? /** * The number of syntax errors reported during parsing. This value is * incremented each time {@link #notifyErrorListeners} is called. */ internal var _syntaxErrors: Int = 0 public init(_ input: TokenStream) throws { self._input = input super.init() try setInputStream(input) } /** reset the parser's state */ public func reset() throws { if (getInputStream() != nil) { try getInputStream()!.seek(0) } _errHandler.reset(self) _ctx = nil _syntaxErrors = 0 setTrace(false) _precedenceStack.clear() _precedenceStack.push(0) // getInterpreter(); if let interpreter = _interp { interpreter.reset() } } /** * Match current input symbol against {@code ttype}. If the symbol type * matches, {@link org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch} and {@link #consume} are * called to complete the match process. * * <p>If the symbol type does not match, * {@link org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline} is called on the current error * strategy to attempt recovery. If {@link #getBuildParseTree} is * {@code true} and the token index of the symbol returned by * {@link org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to * the parse tree by calling {@link org.antlr.v4.runtime.ParserRuleContext#addErrorNode}.</p> * * @param ttype the token type to match * @return the matched symbol * @throws org.antlr.v4.runtime.RecognitionException if the current input symbol did not match * {@code ttype} and the error strategy could not recover from the * mismatched symbol *///; RecognitionException @discardableResult public func match(_ ttype: Int) throws -> Token { var t: Token = try getCurrentToken() if t.getType() == ttype { _errHandler.reportMatch(self) try consume() } else { t = try _errHandler.recoverInline(self) if _buildParseTrees && t.getTokenIndex() == -1 { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx!.addErrorNode(t) } } return t } /** * Match current input symbol as a wildcard. If the symbol type matches * (i.e. has a value greater than 0), {@link org.antlr.v4.runtime.ANTLRErrorStrategy#reportMatch} * and {@link #consume} are called to complete the match process. * * <p>If the symbol type does not match, * {@link org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline} is called on the current error * strategy to attempt recovery. If {@link #getBuildParseTree} is * {@code true} and the token index of the symbol returned by * {@link org.antlr.v4.runtime.ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to * the parse tree by calling {@link org.antlr.v4.runtime.ParserRuleContext#addErrorNode}.</p> * * @return the matched symbol * @throws org.antlr.v4.runtime.RecognitionException if the current input symbol did not match * a wildcard and the error strategy could not recover from the mismatched * symbol *///; RecognitionException @discardableResult public func matchWildcard() throws -> Token { var t: Token = try getCurrentToken() if t.getType() > 0 { _errHandler.reportMatch(self) try consume() } else { t = try _errHandler.recoverInline(self) if _buildParseTrees && t.getTokenIndex() == -1 { // we must have conjured up a new token during single token insertion // if it's not the current symbol _ctx!.addErrorNode(t) } } return t } /** * Track the {@link org.antlr.v4.runtime.ParserRuleContext} objects during the parse and hook * them up using the {@link org.antlr.v4.runtime.ParserRuleContext#children} list so that it * forms a parse tree. The {@link org.antlr.v4.runtime.ParserRuleContext} returned from the start * rule represents the root of the parse tree. * * <p>Note that if we are not building parse trees, rule contexts only point * upwards. When a rule exits, it returns the context but that gets garbage * collected if nobody holds a reference. It points upwards but nobody * points at it.</p> * * <p>When we build parse trees, we are adding all of these contexts to * {@link org.antlr.v4.runtime.ParserRuleContext#children} list. Contexts are then not candidates * for garbage collection.</p> */ public func setBuildParseTree(_ buildParseTrees: Bool) { self._buildParseTrees = buildParseTrees } /** * Gets whether or not a complete parse tree will be constructed while * parsing. This property is {@code true} for a newly constructed parser. * * @return {@code true} if a complete parse tree will be constructed while * parsing, otherwise {@code false} */ public func getBuildParseTree() -> Bool { return _buildParseTrees } /** * Trim the internal lists of the parse tree during parsing to conserve memory. * This property is set to {@code false} by default for a newly constructed parser. * * @param trimParseTrees {@code true} to trim the capacity of the {@link org.antlr.v4.runtime.ParserRuleContext#children} * list to its size after a rule is parsed. */ public func setTrimParseTree(_ trimParseTrees: Bool) { if trimParseTrees { if getTrimParseTree() { return } addParseListener(TrimToSizeListener.INSTANCE) } else { removeParseListener(TrimToSizeListener.INSTANCE) } } /** * @return {@code true} if the {@link org.antlr.v4.runtime.ParserRuleContext#children} list is trimmed * using the default {@link org.antlr.v4.runtime.Parser.TrimToSizeListener} during the parse process. */ public func getTrimParseTree() -> Bool { return !getParseListeners().filter({ $0 === TrimToSizeListener.INSTANCE }).isEmpty } public func getParseListeners() -> Array<ParseTreeListener> { let listeners: Array<ParseTreeListener>? = _parseListeners if listeners == nil { return Array<ParseTreeListener>() } return listeners! } /** * Registers {@code listener} to receive events during the parsing process. * * <p>To support output-preserving grammar transformations (including but not * limited to left-recursion removal, automated left-factoring, and * optimized code generation), calls to listener methods during the parse * may differ substantially from calls made by * {@link org.antlr.v4.runtime.tree.ParseTreeWalker#DEFAULT} used after the parse is complete. In * particular, rule entry and exit events may occur in a different order * during the parse than after the parser. In addition, calls to certain * rule entry methods may be omitted.</p> * * <p>With the following specific exceptions, calls to listener events are * <em>deterministic</em>, i.e. for identical input the calls to listener * methods will be the same.</p> * * <ul> * <li>Alterations to the grammar used to generate code may change the * behavior of the listener calls.</li> * <li>Alterations to the command line options passed to ANTLR 4 when * generating the parser may change the behavior of the listener calls.</li> * <li>Changing the version of the ANTLR Tool used to generate the parser * may change the behavior of the listener calls.</li> * </ul> * * @param listener the listener to add * * @throws NullPointerException if {@code} listener is {@code null} */ public func addParseListener(_ listener: ParseTreeListener) { if _parseListeners == nil { _parseListeners = Array<ParseTreeListener>() } self._parseListeners!.append(listener) } /** * Remove {@code listener} from the list of parse listeners. * * <p>If {@code listener} is {@code null} or has not been added as a parse * listener, this method does nothing.</p> * * @see #addParseListener * * @param listener the listener to remove */ public func removeParseListener(_ listener: ParseTreeListener?) { if _parseListeners != nil { if !_parseListeners!.filter({ $0 === listener }).isEmpty { _parseListeners = _parseListeners!.filter({ $0 !== listener }) if _parseListeners!.isEmpty { _parseListeners = nil } } // if (_parseListeners.remove(listener)) { // if (_parseListeners.isEmpty) { // _parseListeners = nil; // } // } } } /** * Remove all parse listeners. * * @see #addParseListener */ public func removeParseListeners() { _parseListeners = nil } /** * Notify any parse listeners of an enter rule event. * * @see #addParseListener */ public func triggerEnterRuleEvent() throws { if let _parseListeners = _parseListeners, let _ctx = _ctx { for listener: ParseTreeListener in _parseListeners { try listener.enterEveryRule(_ctx) _ctx.enterRule(listener) } } } /** * Notify any parse listeners of an exit rule event. * * @see #addParseListener */ public func triggerExitRuleEvent() throws { // reverse order walk of listeners if let _parseListeners = _parseListeners, let _ctx = _ctx { var i: Int = _parseListeners.count - 1 while i >= 0 { let listener: ParseTreeListener = _parseListeners[i] _ctx.exitRule(listener) try listener.exitEveryRule(_ctx) i -= 1 } } } /** * Gets the number of syntax errors reported during parsing. This value is * incremented each time {@link #notifyErrorListeners} is called. * * @see #notifyErrorListeners */ public func getNumberOfSyntaxErrors() -> Int { return _syntaxErrors } override open func getTokenFactory() -> TokenFactory { //<AnyObject> return _input.getTokenSource().getTokenFactory() } /** Tell our token source and error strategy about a new way to create tokens. */ override open func setTokenFactory(_ factory: TokenFactory) { //<AnyObject> _input.getTokenSource().setTokenFactory(factory) } /** * The ATN with bypass alternatives is expensive to create so we create it * lazily. * * @throws UnsupportedOperationException if the current parser does not * implement the {@link #getSerializedATN()} method. */ public func getATNWithBypassAlts() -> ATN { let serializedAtn: String = getSerializedATN() var result: ATN? = bypassAltsAtnCache[serializedAtn] synced(bypassAltsAtnCache) { [unowned self] in if result == nil { let deserializationOptions: ATNDeserializationOptions = ATNDeserializationOptions() try! deserializationOptions.setGenerateRuleBypassTransitions(true) result = try! ATNDeserializer(deserializationOptions).deserialize(Array(serializedAtn.characters)) self.bypassAltsAtnCache[serializedAtn] = result! } } return result! } /** * The preferred method of getting a tree pattern. For example, here's a * sample use: * * <pre> * ParseTree t = parser.expr(); * ParseTreePattern p = parser.compileParseTreePattern("&lt;ID&gt;+0", MyParser.RULE_expr); * ParseTreeMatch m = p.match(t); * String id = m.get("ID"); * </pre> */ public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int) throws -> ParseTreePattern { if let tokenStream = getTokenStream() { let tokenSource: TokenSource = tokenStream.getTokenSource() if tokenSource is Lexer { let lexer: Lexer = tokenSource as! Lexer return try compileParseTreePattern(pattern, patternRuleIndex, lexer) } } throw ANTLRError.unsupportedOperation(msg: "Parser can't discover a lexer to use") } /** * The same as {@link #compileParseTreePattern(String, int)} but specify a * {@link org.antlr.v4.runtime.Lexer} rather than trying to deduce it from this parser. */ public func compileParseTreePattern(_ pattern: String, _ patternRuleIndex: Int, _ lexer: Lexer) throws -> ParseTreePattern { let m: ParseTreePatternMatcher = ParseTreePatternMatcher(lexer, self) return try m.compile(pattern, patternRuleIndex) } public func getErrorHandler() -> ANTLRErrorStrategy { return _errHandler } public func setErrorHandler(_ handler: ANTLRErrorStrategy) { self._errHandler = handler } override open func getInputStream() -> IntStream? { return getTokenStream() } override public final func setInputStream(_ input: IntStream) throws { try setTokenStream(input as! TokenStream) } public func getTokenStream() -> TokenStream? { return _input } /** Set the token stream and reset the parser. */ public func setTokenStream(_ input: TokenStream) throws { //TODO self._input = nil; self._input = nil; try reset() self._input = input } /** Match needs to return the current input symbol, which gets put * into the label for the associated token ref; e.g., x=ID. */ public func getCurrentToken() throws -> Token { return try _input.LT(1)! } public final func notifyErrorListeners(_ msg: String) throws { try notifyErrorListeners(getCurrentToken(), msg, nil) } public func notifyErrorListeners(_ offendingToken: Token, _ msg: String, _ e: AnyObject?) { _syntaxErrors += 1 var line: Int = -1 var charPositionInLine: Int = -1 line = offendingToken.getLine() charPositionInLine = offendingToken.getCharPositionInLine() let listener: ANTLRErrorListener = getErrorListenerDispatch() listener.syntaxError(self, offendingToken, line, charPositionInLine, msg, e) } /** * Consume and return the {@linkplain #getCurrentToken current symbol}. * * <p>E.g., given the following input with {@code A} being the current * lookahead symbol, this function moves the cursor to {@code B} and returns * {@code A}.</p> * * <pre> * A B * ^ * </pre> * * If the parser is not in error recovery mode, the consumed symbol is added * to the parse tree using {@link org.antlr.v4.runtime.ParserRuleContext#addChild(org.antlr.v4.runtime.Token)}, and * {@link org.antlr.v4.runtime.tree.ParseTreeListener#visitTerminal} is called on any parse listeners. * If the parser <em>is</em> in error recovery mode, the consumed symbol is * added to the parse tree using * {@link org.antlr.v4.runtime.ParserRuleContext#addErrorNode(org.antlr.v4.runtime.Token)}, and * {@link org.antlr.v4.runtime.tree.ParseTreeListener#visitErrorNode} is called on any parse * listeners. */ @discardableResult public func consume() throws -> Token { let o: Token = try getCurrentToken() if o.getType() != Parser.EOF { try getInputStream()!.consume() } guard let _ctx = _ctx else { return o } let hasListener: Bool = _parseListeners != nil && !_parseListeners!.isEmpty if _buildParseTrees || hasListener { if _errHandler.inErrorRecoveryMode(self) { let node: ErrorNode = _ctx.addErrorNode(o) if let _parseListeners = _parseListeners { for listener: ParseTreeListener in _parseListeners { listener.visitErrorNode(node) } } } else { let node: TerminalNode = _ctx.addChild(o) if let _parseListeners = _parseListeners { for listener: ParseTreeListener in _parseListeners { listener.visitTerminal(node) } } } } return o } internal func addContextToParseTree() { // add current context to parent if we have a parent if let parent = _ctx?.parent as? ParserRuleContext { parent.addChild(_ctx!) } } /** * Always called by generated parsers upon entry to a rule. Access field * {@link #_ctx} get the current context. */ public func enterRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws { setState(state) _ctx = localctx _ctx!.start = try _input.LT(1) if _buildParseTrees { addContextToParseTree() } } public func exitRule() throws { guard let ctx = _ctx else { return } ctx.stop = try _input.LT(-1) // trigger event on _ctx, before it reverts to parent if _parseListeners != nil { try triggerExitRuleEvent() } setState(ctx.invokingState) _ctx = ctx.parent as? ParserRuleContext } public func enterOuterAlt(_ localctx: ParserRuleContext, _ altNum: Int) throws { localctx.setAltNumber(altNum) // if we have new localctx, make sure we replace existing ctx // that is previous child of parse tree if _buildParseTrees && _ctx! !== localctx { if let parent = _ctx?.parent as? ParserRuleContext { parent.removeLastChild() parent.addChild(localctx) } } _ctx = localctx if _parseListeners != nil { try triggerEnterRuleEvent() } } /** * Get the precedence level for the top-most precedence rule. * * @return The precedence level for the top-most precedence rule, or -1 if * the parser context is not nested within a precedence rule. */ public final func getPrecedence() -> Int { if _precedenceStack.isEmpty { return -1 } return _precedenceStack.peek() ?? -1 } /** * @deprecated Use * {@link #enterRecursionRule(org.antlr.v4.runtime.ParserRuleContext, int, int, int)} instead. */ ////@Deprecated public func enterRecursionRule(_ localctx: ParserRuleContext, _ ruleIndex: Int) throws { try enterRecursionRule(localctx, getATN().ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0) } public func enterRecursionRule(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int, _ precedence: Int) throws { setState(state) _precedenceStack.push(precedence) _ctx = localctx _ctx!.start = try _input.LT(1) if _parseListeners != nil { try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules } } /** Like {@link #enterRule} but for recursive rules. * Make the current context the child of the incoming localctx. */ public func pushNewRecursionContext(_ localctx: ParserRuleContext, _ state: Int, _ ruleIndex: Int) throws { let previous: ParserRuleContext = _ctx! previous.parent = localctx previous.invokingState = state previous.stop = try _input.LT(-1) _ctx = localctx _ctx!.start = previous.start if _buildParseTrees { _ctx!.addChild(previous) } if _parseListeners != nil { try triggerEnterRuleEvent() // simulates rule entry for left-recursive rules } } public func unrollRecursionContexts(_ _parentctx: ParserRuleContext?) throws { _precedenceStack.pop() _ctx!.stop = try _input.LT(-1) let retctx: ParserRuleContext = _ctx! // save current ctx (return value) // unroll so _ctx is as it was before call to recursive method if _parseListeners != nil { while let ctxWrap = _ctx , ctxWrap !== _parentctx { try triggerExitRuleEvent() _ctx = ctxWrap.parent as? ParserRuleContext } } else { _ctx = _parentctx } // hook into tree retctx.parent = _parentctx if _buildParseTrees && _parentctx != nil { // add return ctx into invoking rule's tree _parentctx!.addChild(retctx) } } public func getInvokingContext(_ ruleIndex: Int) -> ParserRuleContext? { var p: ParserRuleContext? = _ctx while let pWrap = p { if pWrap.getRuleIndex() == ruleIndex { return pWrap } p = pWrap.parent as? ParserRuleContext } return nil } public func getContext() -> ParserRuleContext? { return _ctx } public func setContext(_ ctx: ParserRuleContext) { _ctx = ctx } override open func precpred(_ localctx: RuleContext?, _ precedence: Int) -> Bool { return precedence >= _precedenceStack.peek()! } public func inContext(_ context: String) -> Bool { // TODO: useful in parser? return false } /** Given an AmbiguityInfo object that contains information about an * ambiguous decision event, return the list of ambiguous parse trees. * An ambiguity occurs when a specific token sequence can be recognized * in more than one way by the grammar. These ambiguities are detected only * at decision points. * * The list of trees includes the actual interpretation (that for * the minimum alternative number) and all ambiguous alternatives. * The actual interpretation is always first. * * This method reuses the same physical input token stream used to * detect the ambiguity by the original parser in the first place. * This method resets/seeks within but does not alter originalParser. * The input position is restored upon exit from this method. * Parsers using a {@link org.antlr.v4.runtime.UnbufferedTokenStream} may not be able to * perform the necessary save index() / seek(saved_index) operation. * * The trees are rooted at the node whose start..stop token indices * include the start and stop indices of this ambiguity event. That is, * the trees returns will always include the complete ambiguous subphrase * identified by the ambiguity event. * * Be aware that this method does NOT notify error or parse listeners as * it would trigger duplicate or otherwise unwanted events. * * This uses a temporary ParserATNSimulator and a ParserInterpreter * so we don't mess up any statistics, event lists, etc... * The parse tree constructed while identifying/making ambiguityInfo is * not affected by this method as it creates a new parser interp to * get the ambiguous interpretations. * * Nodes in the returned ambig trees are independent of the original parse * tree (constructed while identifying/creating ambiguityInfo). * * @since 4.5.1 * * @param originalParser The parser used to create ambiguityInfo; it * is not modified by this routine and can be either * a generated or interpreted parser. It's token * stream *is* reset/seek()'d. * @param ambiguityInfo The information about an ambiguous decision event * for which you want ambiguous parse trees. * @param startRuleIndex The start rule for the entire grammar, not * the ambiguous decision. We re-parse the entire input * and so we need the original start rule. * * @return The list of all possible interpretations of * the input for the decision in ambiguityInfo. * The actual interpretation chosen by the parser * is always given first because this method * retests the input in alternative order and * ANTLR always resolves ambiguities by choosing * the first alternative that matches the input. * * @throws org.antlr.v4.runtime.RecognitionException Throws upon syntax error while matching * ambig input. */ // public class func getAmbiguousParseTrees(originalParser : Parser, // _ ambiguityInfo : AmbiguityInfo, // _ startRuleIndex : Int) throws -> Array<ParserRuleContext> //; RecognitionException // { // var trees : Array<ParserRuleContext> = Array<ParserRuleContext>(); // var saveTokenInputPosition : Int = originalParser.getTokenStream().index(); // //try { // // Create a new parser interpreter to parse the ambiguous subphrase // var parser : ParserInterpreter; // if ( originalParser is ParserInterpreter ) { // parser = ParserInterpreter( originalParser as! ParserInterpreter); // } // else { // var serializedAtn : [Character] = ATNSerializer.getSerializedAsChars(originalParser.getATN()); // var deserialized : ATN = ATNDeserializer().deserialize(serializedAtn); // parser = ParserInterpreter(originalParser.getGrammarFileName(), // originalParser.getVocabulary(), // originalParser.getRuleNames() , // deserialized, // originalParser.getTokenStream()); // } // // // Make sure that we don't get any error messages from using this temporary parser // parser.removeErrorListeners(); // parser.removeParseListeners(); // parser.getInterpreter()!.setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION); // // // get ambig trees // var alt : Int = ambiguityInfo.ambigAlts.nextSetBit(0); // while alt>=0 { // // re-parse entire input for all ambiguous alternatives // // (don't have to do first as it's been parsed, but do again for simplicity // // using this temp parser.) // parser.reset(); // parser.getTokenStream().seek(0); // rewind the input all the way for re-parsing // parser.overrideDecision = ambiguityInfo.decision; // parser.overrideDecisionInputIndex = ambiguityInfo.startIndex; // parser.overrideDecisionAlt = alt; // var t : ParserRuleContext = parser.parse(startRuleIndex); // var ambigSubTree : ParserRuleContext = // Trees.getRootOfSubtreeEnclosingRegion(t, ambiguityInfo.startIndex, ambiguityInfo.stopIndex)!; // trees.append(ambigSubTree); // alt = ambiguityInfo.ambigAlts.nextSetBit(alt+1); // } // //} // defer { // originalParser.getTokenStream().seek(saveTokenInputPosition); // } // // return trees; // } /** * Checks whether or not {@code symbol} can follow the current state in the * ATN. The behavior of this method is equivalent to the following, but is * implemented such that the complete context-sensitive follow set does not * need to be explicitly constructed. * * <pre> * return getExpectedTokens().contains(symbol); * </pre> * * @param symbol the symbol type to check * @return {@code true} if {@code symbol} can follow the current state in * the ATN, otherwise {@code false}. */ public func isExpectedToken(_ symbol: Int) throws -> Bool { // return getInterpreter().atn.nextTokens(_ctx); let atn: ATN = getInterpreter().atn var ctx: ParserRuleContext? = _ctx let s: ATNState = atn.states[getState()]! var following: IntervalSet = try atn.nextTokens(s) if following.contains(symbol) { return true } // System.out.println("following "+s+"="+following); if !following.contains(CommonToken.EPSILON) { return false } while let ctxWrap = ctx , ctxWrap.invokingState >= 0 && following.contains(CommonToken.EPSILON) { let invokingState: ATNState = atn.states[ctxWrap.invokingState]! let rt: RuleTransition = invokingState.transition(0) as! RuleTransition following = try atn.nextTokens(rt.followState) if following.contains(symbol) { return true } ctx = ctxWrap.parent as? ParserRuleContext } if following.contains(CommonToken.EPSILON) && symbol == CommonToken.EOF { return true } return false } /** * Computes the set of input symbols which could follow the current parser * state and context, as given by {@link #getState} and {@link #getContext}, * respectively. * * @see org.antlr.v4.runtime.atn.ATN#getExpectedTokens(int, org.antlr.v4.runtime.RuleContext) */ public func getExpectedTokens() throws -> IntervalSet { return try getATN().getExpectedTokens(getState(), getContext()!) } public func getExpectedTokensWithinCurrentRule() throws -> IntervalSet { let atn: ATN = getInterpreter().atn let s: ATNState = atn.states[getState()]! return try atn.nextTokens(s) } /** Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found. */ public func getRuleIndex(_ ruleName: String) -> Int { let ruleIndex: Int? = getRuleIndexMap()[ruleName] if ruleIndex != nil { return ruleIndex! } return -1 } public func getRuleContext() -> ParserRuleContext? { return _ctx } /** Return List&lt;String&gt; of the rule names in your parser instance * leading up to a call to the current rule. You could override if * you want more details such as the file/line info of where * in the ATN a rule is invoked. * * This is very useful for error messages. */ public func getRuleInvocationStack() -> Array<String> { return getRuleInvocationStack(_ctx) } public func getRuleInvocationStack(_ p: RuleContext?) -> Array<String> { var p = p var ruleNames: [String] = getRuleNames() var stack: Array<String> = Array<String>() while let pWrap = p { // compute what follows who invoked us let ruleIndex: Int = pWrap.getRuleIndex() if ruleIndex < 0 { stack.append("n/a") } else { stack.append(ruleNames[ruleIndex]) } p = pWrap.parent } return stack } /** For debugging and other purposes. */ public func getDFAStrings() -> Array<String> { var s: Array<String> = Array<String>() guard let _interp = _interp else { return s } synced(_interp.decisionToDFA as AnyObject) { [unowned self] in for d in 0..<_interp.decisionToDFA.count { let dfa: DFA = _interp.decisionToDFA[d] s.append(dfa.toString(self.getVocabulary())) } } return s } /** For debugging and other purposes. */ public func dumpDFA() { guard let _interp = _interp else { return } synced(_interp.decisionToDFA as AnyObject) { [unowned self] in var seenOne: Bool = false for d in 0..<_interp.decisionToDFA.count { let dfa: DFA = _interp.decisionToDFA[d] if !dfa.states.isEmpty { if seenOne { print("") } print("Decision \(dfa.decision):") print(dfa.toString(self.getVocabulary()), terminator: "") seenOne = true } } } } public func getSourceName() -> String { return _input.getSourceName() } override open func getParseInfo() -> ParseInfo? { let interp: ParserATNSimulator? = getInterpreter() if interp is ProfilingATNSimulator { return ParseInfo(interp as! ProfilingATNSimulator) } return nil } /** * @since 4.3 */ public func setProfile(_ profile: Bool) { let interp: ParserATNSimulator = getInterpreter() let saveMode: PredictionMode = interp.getPredictionMode() if profile { if !(interp is ProfilingATNSimulator) { setInterpreter(ProfilingATNSimulator(self)) } } else { if interp is ProfilingATNSimulator { let sim: ParserATNSimulator = ParserATNSimulator(self, getATN(), interp.decisionToDFA, interp.getSharedContextCache()!) setInterpreter(sim) } } getInterpreter().setPredictionMode(saveMode) } /** During a parse is sometimes useful to listen in on the rule entry and exit * events as well as token matches. This is for quick and dirty debugging. */ public func setTrace(_ trace: Bool) { if !trace { removeParseListener(_tracer) _tracer = nil } else { if _tracer != nil { removeParseListener(_tracer!) } else { _tracer = TraceListener(self) } addParseListener(_tracer!) } } /** * Gets whether a {@link org.antlr.v4.runtime.Parser.TraceListener} is registered as a parse listener * for the parser. * * @see #setTrace(boolean) */ public func isTrace() -> Bool { return _tracer != nil } }
bsd-3-clause
ee830f732b75e760ec3dd44f03e78f63
35.004651
125
0.611187
4.644228
false
false
false
false
debugsquad/nubecero
nubecero/View/OnboardForm/VOnboardFormSender.swift
1
2634
import UIKit class VOnboardFormSender:UIView { private weak var controller:COnboardForm! private let kCornerRadius:CGFloat = 4 private let kButtonWidth:CGFloat = 100 private let kButtonRight:CGFloat = 20 convenience init(controller:COnboardForm) { self.init() clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor(white:1, alpha:0.9) self.controller = controller let border:UIView = UIView() border.isUserInteractionEnabled = false border.translatesAutoresizingMaskIntoConstraints = false border.backgroundColor = UIColor(white:0, alpha:0.05) let button:UIButton = UIButton() button.clipsToBounds = true button.backgroundColor = UIColor.complement button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = kCornerRadius button.setTitleColor(UIColor.white, for:UIControlState.normal) button.setTitleColor(UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) button.setTitle(controller.model.buttonMessage, for:UIControlState.normal) button.titleLabel!.font = UIFont.medium(size:14) button.layer.cornerRadius = kCornerRadius button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(border) addSubview(button) let views:[String:UIView] = [ "border":border, "button":button] let metrics:[String:CGFloat] = [ "buttonWidth":kButtonWidth, "buttonRight":kButtonRight] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[border]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[border(1)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:[button(buttonWidth)]-(buttonRight)-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-6-[button]-5-|", options:[], metrics:metrics, views:views)) } //MARK: actions func actionButton(sender button:UIButton) { controller.send() } }
mit
963479ea6d945f72c910c32c0465d3a6
33.207792
89
0.616932
5.522013
false
false
false
false
orta/SignalKit
SignalKit/Extensions/UIKit/UILabel+Signal.swift
1
869
// // UILabel+Signal.swift // SignalKit // // Created by Yanko Dimitrov on 8/16/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import UIKit public extension SignalType where Item == String { /** Bind a String value to the text property of UILabel */ public func bindTo(textIn label: UILabel) -> Self { addObserver { [weak label] in label?.text = $0 } return self } } public extension SignalType where Item == NSAttributedString { /** Bind a NSAttributedString to the atrributedText property of UILabel */ public func bindTo(attributedTextIn label: UILabel) -> Self { addObserver { [weak label] in label?.attributedText = $0 } return self } }
mit
76de87f4a5f1009edd8bddc8a25f2a7d
19.186047
75
0.556452
4.96
false
false
false
false
weichsel/ZIPFoundation
Tests/ZIPFoundationTests/ZIPFoundationReadingTests.swift
1
12531
// // ZIPFoundationReadingTests.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import XCTest @testable import ZIPFoundation extension ZIPFoundationTests { func testExtractUncompressedFolderEntries() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { // Test extracting to memory var checksum = try archive.extract(entry, bufferSize: 32, consumer: { _ in }) XCTAssert(entry.checksum == checksum) // Test extracting to file var fileURL = self.createDirectory(for: #function) fileURL.appendPathComponent(entry.path) checksum = try archive.extract(entry, to: fileURL) XCTAssert(entry.checksum == checksum) let fileManager = FileManager() XCTAssertTrue(fileManager.itemExists(at: fileURL)) if entry.type == .file { let fileData = try Data(contentsOf: fileURL) let checksum = fileData.crc32(checksum: 0) XCTAssert(checksum == entry.checksum) } } catch { XCTFail("Failed to unzip uncompressed folder entries") } } } func testExtractCompressedFolderEntries() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { // Test extracting to memory var checksum = try archive.extract(entry, bufferSize: 128, consumer: { _ in }) XCTAssert(entry.checksum == checksum) // Test extracting to file var fileURL = self.createDirectory(for: #function) fileURL.appendPathComponent(entry.path) checksum = try archive.extract(entry, to: fileURL) XCTAssert(entry.checksum == checksum) let fileManager = FileManager() XCTAssertTrue(fileManager.itemExists(at: fileURL)) if entry.type != .directory { let fileData = try Data(contentsOf: fileURL) let checksum = fileData.crc32(checksum: 0) XCTAssert(checksum == entry.checksum) } } catch { XCTFail("Failed to unzip compressed folder entries") } } } func testExtractUncompressedDataDescriptorArchive() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { let checksum = try archive.extract(entry, consumer: { _ in }) XCTAssert(entry.checksum == checksum) } catch { XCTFail("Failed to unzip data descriptor archive") } } } func testExtractCompressedDataDescriptorArchive() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { let checksum = try archive.extract(entry, consumer: { _ in }) XCTAssert(entry.checksum == checksum) } catch { XCTFail("Failed to unzip data descriptor archive") } } } func testExtractPreferredEncoding() { let encoding = String.Encoding.utf8 let archive = self.archive(for: #function, mode: .read, preferredEncoding: encoding) XCTAssertTrue(archive.checkIntegrity()) let imageEntry = archive["data/pic👨‍👩‍👧‍👦🎂.jpg"] XCTAssertNotNil(imageEntry) let textEntry = archive["data/Benoît.txt"] XCTAssertNotNil(textEntry) } func testExtractMSDOSArchive() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { let checksum = try archive.extract(entry, consumer: { _ in }) XCTAssert(entry.checksum == checksum) } catch { XCTFail("Failed to unzip MSDOS archive") } } } func testExtractErrorConditions() { let archive = self.archive(for: #function, mode: .read) XCTAssertNotNil(archive) guard let fileEntry = archive["testZipItem.png"] else { XCTFail("Failed to obtain test asset from archive.") return } XCTAssertNotNil(fileEntry) do { _ = try archive.extract(fileEntry, to: archive.url) } catch let error as CocoaError { XCTAssert(error.code == CocoaError.fileWriteFileExists) } catch { XCTFail("Unexpected error while trying to extract entry to existing URL.") return } guard let linkEntry = archive["testZipItemLink"] else { XCTFail("Failed to obtain test asset from archive.") return } do { let longFileName = String(repeating: ProcessInfo.processInfo.globallyUniqueString, count: 100) var overlongURL = URL(fileURLWithPath: NSTemporaryDirectory()) overlongURL.appendPathComponent(longFileName) _ = try archive.extract(fileEntry, to: overlongURL) } catch let error as CocoaError { XCTAssert(error.code == CocoaError.fileNoSuchFile) } catch { XCTFail("Unexpected error while trying to extract entry to invalid URL.") return } XCTAssertNotNil(linkEntry) do { _ = try archive.extract(linkEntry, to: archive.url) } catch let error as CocoaError { XCTAssert(error.code == CocoaError.fileWriteFileExists) } catch { XCTFail("Unexpected error while trying to extract link entry to existing URL.") return } } func testCorruptFileErrorConditions() { let archiveURL = self.resourceURL(for: #function, pathExtension: "zip") let fileManager = FileManager() let destinationFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: archiveURL.path) let destinationFile: FILEPointer = fopen(destinationFileSystemRepresentation, "r+b") do { fseek(destinationFile, 64, SEEK_SET) // We have to inject a large enough zeroes block to guarantee that libcompression // detects the failure when reading the stream _ = try Data.write(chunk: Data(count: 512*1024), to: destinationFile) fclose(destinationFile) guard let archive = Archive(url: archiveURL, accessMode: .read) else { XCTFail("Failed to read archive.") return } guard let entry = archive["data.random"] else { XCTFail("Failed to read entry.") return } _ = try archive.extract(entry, consumer: { _ in }) } catch let error as Data.CompressionError { XCTAssert(error == Data.CompressionError.corruptedData) } catch { XCTFail("Unexpected error while testing an archive with corrupt entry data.") } } func testCorruptSymbolicLinkErrorConditions() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { var tempFileURL = URL(fileURLWithPath: NSTemporaryDirectory()) tempFileURL.appendPathComponent(ProcessInfo.processInfo.globallyUniqueString) _ = try archive.extract(entry, to: tempFileURL) } catch let error as Archive.ArchiveError { XCTAssert(error == .invalidEntryPath) } catch { XCTFail("Unexpected error while trying to extract entry with invalid symbolic link.") } } } func testInvalidCompressionMethodErrorConditions() { let archive = self.archive(for: #function, mode: .read) for entry in archive { do { _ = try archive.extract(entry, consumer: { (_) in }) } catch let error as Archive.ArchiveError { XCTAssert(error == .invalidCompressionMethod) } catch { XCTFail("Unexpected error while trying to extract entry with invalid compression method link.") } } } func testExtractEncryptedArchiveErrorConditions() { let archive = self.archive(for: #function, mode: .read) var entriesRead = 0 for _ in archive { entriesRead += 1 } // We currently don't support encryption so we expect failed initialization for entry objects. XCTAssert(entriesRead == 0) } func testExtractInvalidBufferSizeErrorConditions() { let archive = self.archive(for: #function, mode: .read) let entry = archive["text.txt"]! XCTAssertThrowsError(try archive.extract(entry, to: URL(fileURLWithPath: ""), bufferSize: 0, skipCRC32: true)) let archive2 = self.archive(for: #function, mode: .read) let entry2 = archive2["text.txt"]! XCTAssertThrowsError(try archive2.extract(entry2, bufferSize: 0, skipCRC32: true, consumer: { _ in })) } func testExtractUncompressedEmptyFile() { // We had a logic error, where completion handlers for empty entries were not called // Ensure that this edge case works var didCallCompletion = false let archive = self.archive(for: #function, mode: .read) guard let entry = archive["empty.txt"] else { XCTFail("Failed to extract entry."); return } do { _ = try archive.extract(entry) { (data) in XCTAssertEqual(data.count, 0) didCallCompletion = true } } catch { XCTFail("Unexpected error while trying to extract empty file of uncompressed archive.") } XCTAssert(didCallCompletion) } func testExtractUncompressedEntryCancelation() { let archive = self.archive(for: #function, mode: .read) guard let entry = archive["original"] else { XCTFail("Failed to extract entry."); return } let progress = archive.makeProgressForReading(entry) do { var readCount = 0 _ = try archive.extract(entry, bufferSize: 1, progress: progress) { (data) in readCount += data.count if readCount == 4 { progress.cancel() } } } catch let error as Archive.ArchiveError { XCTAssert(error == Archive.ArchiveError.cancelledOperation) XCTAssertEqual(progress.fractionCompleted, 0.5, accuracy: .ulpOfOne) } catch { XCTFail("Unexpected error while trying to cancel extraction.") } } func testExtractCompressedEntryCancelation() { let archive = self.archive(for: #function, mode: .read) guard let entry = archive["random"] else { XCTFail("Failed to extract entry."); return } let progress = archive.makeProgressForReading(entry) do { var readCount = 0 _ = try archive.extract(entry, bufferSize: 256, progress: progress) { (data) in readCount += data.count if readCount == 512 { progress.cancel() } } } catch let error as Archive.ArchiveError { XCTAssert(error == Archive.ArchiveError.cancelledOperation) XCTAssertEqual(progress.fractionCompleted, 0.5, accuracy: .ulpOfOne) } catch { XCTFail("Unexpected error while trying to cancel extraction.") } } func testProgressHelpers() { let tempPath = NSTemporaryDirectory() var nonExistantURL = URL(fileURLWithPath: tempPath) nonExistantURL.appendPathComponent("invalid.path") let archive = self.archive(for: #function, mode: .update) XCTAssert(archive.totalUnitCountForAddingItem(at: nonExistantURL) == -1) } func testDetectEntryType() { let archive = self.archive(for: #function, mode: .read) let expectedData: [String: Entry.EntryType] = [ "META-INF/": .directory, "META-INF/container.xml": .file ] for entry in archive { XCTAssertEqual(entry.type, expectedData[entry.path]) } } }
mit
bfa54b86e89fd55c05f78b07840f9b66
40.693333
118
0.592901
5.057825
false
true
false
false
carlospaelinck/pokebattle
PokéBattle/MainViewController.swift
1
879
// // ViewController.swift // PokéBattle // // Created by Carlos Paelinck on 4/11/16. // Copyright © 2016 Carlos Paelinck. All rights reserved. // import Cocoa class MainViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } override func viewWillAppear() { super.viewWillAppear() preferredContentSize = NSSize(width: 640, height: 480) guard let window = view.window else { return } window.titlebarAppearsTransparent = true window.movableByWindowBackground = true window.styleMask = window.styleMask | NSFullSizeContentViewWindowMask window.title = "" } }
mit
4a8cedb7b4835b0fd9ff3a3cbc56f396
23.361111
77
0.646522
4.845304
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Option/ReformaCrossing/Node/VOptionReformaCrossingStop.swift
1
1255
import SpriteKit class VOptionReformaCrossingStop:ViewGameNode<MOptionReformaCrossing> { override init(controller:ControllerGame<MOptionReformaCrossing>) { let texture:MGameTexture = controller.model.textures.stop super.init( controller:controller, texture:texture) isUserInteractionEnabled = true alpha = 0 } required init?(coder:NSCoder) { return nil } override func positionStart() { guard let modelTexture:MGameTexture = modelTexture else { return } let sceneWidth:CGFloat = MGame.sceneSize.width let sceneWidth_2:CGFloat = sceneWidth / 2.0 let height_2:CGFloat = modelTexture.height_2 position = CGPoint(x:sceneWidth_2, y:height_2) } override func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?) { controller.model.playerStop() } //MARK: public func animateStop() { let action:SKAction = controller.model.actions.actionStopAnimation run(action) } func restoreStand() { texture = modelTexture?.texture } }
mit
6343f89b84619635683440b7efd55f3c
21.818182
75
0.585657
5.040161
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Abstract/MOptionWhistlesVsZombiesActionsFactory.swift
1
3995
import SpriteKit extension MOptionWhistlesVsZombiesActions { private static let kSonicReleaseFrameDuration:TimeInterval = 0.1 private static let kSonicBoomFrameDuration:TimeInterval = 0.1 private static let kSonicCollisionFrameDuration:TimeInterval = 0.1 private static let kWhistleExplodeFrameDuration:TimeInterval = 0.1 private static let kZombieSonicColourTransition:TimeInterval = 0.2 private static let kZombieSonicColourDuration:TimeInterval = 0.5 private static let kZombieWalkingFrameDuration:TimeInterval = 0.4 private static let kZombieDefeatedFrameDuration:TimeInterval = 0.2 private static let kZombieDefeatedFadeOut:TimeInterval = 1 private static let kZombieColourBlendFactor:CGFloat = 0.8 class func factorySonicReleaseAnimation(texture:MGameTextureAnimated) -> SKAction { let action:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kSonicReleaseFrameDuration, resize:false, restore:false) return action } class func factorySonicBoomAnimation(texture:MGameTextureAnimated) -> SKAction { let animation:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kSonicBoomFrameDuration, resize:false, restore:false) let repeatForever:SKAction = SKAction.repeatForever( animation) return repeatForever } class func factorySonicCollisionAnimation(texture:MGameTextureAnimated) -> SKAction { let action:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kSonicCollisionFrameDuration, resize:true, restore:false) return action } class func factoryWhistleExplodeAnimation(texture:MGameTextureAnimated) -> SKAction { let action:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kWhistleExplodeFrameDuration, resize:false, restore:false) return action } class func factoryZombieSonicHitAnimation() -> SKAction { let colour:UIColor = UIColor(red:1, green:0, blue:0, alpha:0.8) let actionAddColour:SKAction = SKAction.colorize( with:colour, colorBlendFactor:kZombieColourBlendFactor, duration:kZombieSonicColourTransition) let actionWait:SKAction = SKAction.wait( forDuration:kZombieSonicColourDuration) let actionRemoveColour:SKAction = SKAction.colorize( with:colour, colorBlendFactor:0, duration:kZombieSonicColourTransition) let actions:[SKAction] = [ actionAddColour, actionWait, actionRemoveColour] let sequence:SKAction = SKAction.sequence(actions) return sequence } class func factoryZombieWalkingAnimation(texture:MGameTextureAnimated) -> SKAction { let animation:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kZombieWalkingFrameDuration, resize:false, restore:false) let repeatForever:SKAction = SKAction.repeatForever( animation) return repeatForever } class func factoryZombieDefeatedAnimation(texture:MGameTextureAnimated) -> SKAction { let animation:SKAction = SKAction.animate( with:texture.textures, timePerFrame:kZombieDefeatedFrameDuration, resize:false, restore:false) let fadeOut:SKAction = SKAction.fadeOut( withDuration:kZombieDefeatedFadeOut) let actions:[SKAction] = [ animation, fadeOut] let sequence:SKAction = SKAction.sequence(actions) return sequence } }
mit
181b3ec0f7d3c5ecd517a0481b980a3f
32.571429
87
0.646558
5.642655
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Common/SJSegmentedScrollView/Classes/SJSegmentTab.swift
1
3721
// // SJSegmentTab.swift // Pods // // Created by Subins on 22/11/16. // Copyright © 2016 Subins Jose. 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 typealias DidSelectSegmentAtIndex = (_ segment: SJSegmentTab?,_ index: Int,_ animated: Bool) -> Void open class SJSegmentTab: UIView { let kSegmentViewTagOffset = 100 let button = UIButton(type: .custom) var didSelectSegmentAtIndex: DidSelectSegmentAtIndex? var isSelected = false { didSet { button.isSelected = isSelected } } convenience init(title: String) { self.init(frame: CGRect.zero) setTitle(title) } convenience init(view: UIView) { self.init(frame: CGRect.zero) insertSubview(view, at: 0) view.removeConstraints(view.constraints) addConstraintsToView(view) } required override public init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false button.frame = bounds button.addTarget(self, action: #selector(SJSegmentTab.onSegmentButtonPress(_:)), for: .touchUpInside) addSubview(button) addConstraintsToView(button) } func addConstraintsToView(_ view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": view]) let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": view]) addConstraints(verticalConstraints) addConstraints(horizontalConstraints) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func setTitle(_ title: String) { button.setTitle(title, for: .normal) } open func titleColor(_ color: UIColor) { button.setTitleColor(color, for: .normal) } open func titleFont(_ font: UIFont) { button.titleLabel?.font = font } func onSegmentButtonPress(_ sender: AnyObject) { let index = tag - kSegmentViewTagOffset NotificationCenter.default.post(name: Notification.Name(rawValue: "DidChangeSegmentIndex"), object: index) if didSelectSegmentAtIndex != nil { didSelectSegmentAtIndex!(self, index, true) } } }
mit
c2e38159bbda5457d892b6658f2a5f9b
33.766355
107
0.656452
4.621118
false
false
false
false
lorentey/swift
test/Constraints/operator.swift
4
5817
// RUN: %target-typecheck-verify-swift // Test constraint simplification of chains of binary operators. // <https://bugs.swift.org/browse/SR-1122> do { let a: String? = "a" let b: String? = "b" let c: String? = "c" let _: String? = a! + b! + c! let x: Double = 1 _ = x + x + x let sr3483: Double? = 1 _ = sr3483! + sr3483! + sr3483! let sr2636: [String: Double] = ["pizza": 10.99, "ice cream": 4.99, "salad": 7.99] _ = sr2636["pizza"]! _ = sr2636["pizza"]! + sr2636["salad"]! _ = sr2636["pizza"]! + sr2636["salad"]! + sr2636["ice cream"]! } // Use operators defined within a type. struct S0 { static func +(lhs: S0, rhs: S0) -> S0 { return lhs } } func useS0(lhs: S0, rhs: S0) { _ = lhs + rhs } // Use operators defined within a generic type. struct S0b<T> { static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() } } func useS0b(s1i: S0b<Int>, s: String) { var s1s = s1i + s s1s = S0b<String>() _ = s1s } // Use operators defined within a protocol extension. infix operator %%% infix operator %%%% protocol P1 { static func %%%(lhs: Self, rhs: Self) -> Bool } extension P1 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP1Directly<T : P1>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1 : P1 { static func %%%(lhs: S1, rhs: S1) -> Bool { return false } } func useP1Model(lhs: S1, rhs: S1) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S1b<T> : P1 { static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false } } func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Use operators defined within a protocol extension to satisfy a requirement. protocol P2 { static func %%%(lhs: Self, rhs: Self) -> Bool static func %%%%(lhs: Self, rhs: Self) -> Bool } extension P2 { static func %%%%(lhs: Self, rhs: Self) -> Bool { return !(lhs %%% rhs) } } func useP2Directly<T : P2>(lhs: T, rhs: T) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2 : P2 { static func %%%(lhs: S2, rhs: S2) -> Bool { return false } } func useP2Model(lhs: S2, rhs: S2) { _ = lhs %%% rhs _ = lhs %%%% rhs } struct S2b<T> : P2 { static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false } } func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) { _ = lhs %%% rhs _ = lhs %%%% rhs } func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) { _ = lhs %%% rhs _ = lhs %%%% rhs } // Using an extension of one protocol to satisfy another conformance. protocol P3 { } extension P3 { static func ==(lhs: Self, rhs: Self) -> Bool { return true } } struct S3 : P3, Equatable { } // rdar://problem/30220565 func shrinkTooFar(_ : Double, closure : ()->()) {} func testShrinkTooFar() { shrinkTooFar(0*0*0) {} } // rdar://problem/33759839 enum E_33759839 { case foo case bar(String) } let foo_33759839 = ["a", "b", "c"] let bar_33759839 = ["A", "B", "C"] let _: [E_33759839] = foo_33759839.map { .bar($0) } + bar_33759839.map { .bar($0) } + [E_33759839.foo] // Ok // rdar://problem/28688585 class B_28688585 { var value: Int init(value: Int) { self.value = value } func add(_ other: B_28688585) -> B_28688585 { return B_28688585(value: value + other.value) } } class D_28688585 : B_28688585 { } func + (lhs: B_28688585, rhs: B_28688585) -> B_28688585 { return lhs.add(rhs) } let var_28688585 = D_28688585(value: 1) _ = var_28688585 + var_28688585 + var_28688585 // Ok // rdar://problem/35740653 - Fix `LinkedExprAnalyzer` greedy operator linking struct S_35740653 { var v: Double = 42 static func value(_ value: Double) -> S_35740653 { return S_35740653(v: value) } static func / (lhs: S_35740653, rhs: S_35740653) -> Double { return lhs.v / rhs.v } } func rdar35740653(val: S_35740653) { let _ = 0...Int(val / .value(1.0 / 42.0)) // Ok } protocol P_37290898 {} struct S_37290898: P_37290898 {} func rdar37290898(_ arr: inout [P_37290898], _ element: S_37290898?) { arr += [element].compactMap { $0 } // Ok } // SR-8221 infix operator ??= func ??= <T>(lhs: inout T?, rhs: T?) {} var c: Int = 0 // expected-note {{change variable type to 'Int?' if it doesn't need to be declared as 'Int'}} c ??= 5 // expected-error{{inout argument could be set to a value with a type other than 'Int'; use a value declared as type 'Int?' instead}} func rdar46459603() { enum E { case foo(value: String) } let e = E.foo(value: "String") var arr = ["key": e] _ = arr.values == [e] // expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'Dictionary<String, E>.Values' and '[E]'}} // expected-note@-2 {{expected an argument list of type '(Self, Self)'}} _ = [arr.values] == [[e]] // expected-error@-1 {{value of protocol type 'Any' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols}} // expected-note@-2 {{requirement from conditional conformance of '[Any]' to 'Equatable'}} } // SR-10843 infix operator ^^^ func ^^^ (lhs: String, rhs: String) {} struct SR10843 { static func ^^^ (lhs: SR10843, rhs: SR10843) {} } func sr10843() { let s = SR10843() (^^^)(s, s) _ = (==)(0, 0) } // SR-10970 precedencegroup PowerPrecedence { lowerThan: BitwiseShiftPrecedence higherThan: AdditionPrecedence associativity: right } infix operator ^^ : PowerPrecedence extension Int { static func ^^ (lhs: Int, rhs: Int) -> Int { var result = 1 for _ in 1...rhs { result *= lhs } return result } } _ = 1 ^^ 2 ^^ 3 * 4 // expected-error {{adjacent operators are in unordered precedence groups 'PowerPrecedence' and 'MultiplicationPrecedence'}}
apache-2.0
9859ae39128bf7ae7b0a824ba707bc61
21.634241
144
0.595496
2.970889
false
false
false
false
cotkjaer/SilverbackFramework
SilverbackFramework/NSCalendar.swift
1
3218
// // NSCalendar.swift // SilverbackFramework // // Created by Christian Otkjær on 28/06/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation public extension NSCalendar { /// Returns the hour, minute, second, and nanoseconds of a given date. func getTimeFromDate(date: NSDate) -> (hour: Int, minute: Int, second: Int, nanosecond: Int) { var (hour, minute, second, nanosecond) = (0, 0, 0, 0) getHour(&hour, minute: &minute, second: &second, nanosecond: &nanosecond, fromDate: date) return (hour, minute, second, nanosecond) } /// Returns the era, year, month, and day of a given date. func getDateItemsFromDate(date: NSDate) -> (era: Int, year: Int, month: Int, day: Int) { var (era, year, month, day) = (0, 0, 0, 0) getEra(&era, year: &year, month: &month, day: &day, fromDate: date) return (era, year, month, day) } /// Returns the era, year for week-of-year calculations, week of year, and weekday of a given date. func getWeekItemsFromDate(date: NSDate) -> (era: Int, yearForWeekOfYear: Int, weekOfYear: Int, weekday: Int) { var (era, yearForWeekOfYear, weekOfYear, weekday) = (0, 0, 0, 0) getEra(&era, yearForWeekOfYear: &yearForWeekOfYear, weekOfYear: &weekOfYear, weekday: &weekday, fromDate: date) return (era, yearForWeekOfYear, weekOfYear, weekday) } /// Returns the start and length of the next weekend after the given date. Returns nil if the /// calendar or locale don't support weekends. func nextWeekendAfterDate(date: NSDate) -> (startDate: NSDate, interval: NSTimeInterval)? { var startDate: NSDate? var interval: NSTimeInterval = 0 if nextWeekendStartDate(&startDate, interval: &interval, options: [], afterDate: date), let startDate = startDate { return (startDate, interval) } return nil } /// Returns the start and length of the weekend before the given date. Returns nil if the /// calendar or locale don't support weekends. func nextWeekendBeforeDate(date: NSDate) -> (startDate: NSDate, interval: NSTimeInterval)? { var startDate: NSDate? var interval: NSTimeInterval = 0 if nextWeekendStartDate(&startDate, interval: &interval, options: .SearchBackwards, afterDate: date), let startDate = startDate { return (startDate, interval) } return nil } /// Returns the start and length of the weekend containing the given date. Returns nil if the /// given date isn't in a weekend or if the calendar or locale don't support weekends. func rangeOfWeekendContainingDate(date: NSDate) -> (startDate: NSDate, interval: NSTimeInterval)? { var startDate: NSDate? var interval: NSTimeInterval = 0 if rangeOfWeekendStartDate(&startDate, interval: &interval, containingDate: date), let startDate = startDate { return (startDate, interval) } return nil } }
mit
0d8414404021c40f8f087b5bc9320a77
35.977011
119
0.623445
4.542373
false
false
false
false
jongwonwoo/learningswift
Swift 3 Functional Programming/Enumerations and Pattern Matching.playground/Contents.swift
1
2589
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" enum HttpError: Int { case badRequest = 400 case unauthorized = 401 case forbidden = 403 } let possibleError = HttpError(rawValue: 400) let unknownError = HttpError(rawValue: 500) enum Dimension { case us(Double, Double) case metric(Double, Double) } let sizeMetric = Dimension.metric(5.0, 4.0) // sum, product, recursion types enum NHLTeam { case canadiens case senators case rangers case penguins case blackHawks case capitals } enum MLSTeam { case montreal case toronto case newYork case columbus case losAngeles case seattle } struct HockeyAndSoccerTeams { var hockey: NHLTeam var soccer: MLSTeam } let team = HockeyAndSoccerTeams(hockey: .capitals, soccer: .toronto) team.hockey team.hockey.hashValue team.soccer.hashValue enum HockeyAndSoccerTeamsEnumVersion { case Value(hockey: NHLTeam, soccer: MLSTeam) } let teamEnumVersion = HockeyAndSoccerTeamsEnumVersion.Value(hockey: .capitals, soccer: .toronto) switch teamEnumVersion { case let .Value(hockey, soccer): print("\(hockey), \(soccer)") } enum Tree { case empty case leaf(Int) indirect case node(Tree, Tree) } let ourTree = Tree.node(Tree.leaf(1), Tree.node(Tree.leaf(2), Tree.leaf(3))) func searchTree(_ search: Int, tree: Tree) -> Bool { switch tree { case .leaf(let x): return x == search case .node(let l, let r): return searchTree(search, tree: l) || searchTree(search, tree: r) default: return false } } let isFound = searchTree(2, tree: ourTree) // pattern matching for _ in 1...5 { print("underscore") } let anOptionalString: String? = nil switch anOptionalString { case _?: print("some") case nil: print("none") } let name = "john" let age: Int? = 27 let address: String? = nil switch (name, age, address) { case (let name, _?, _?): print(name) default: print("oops") } let anyValue: Any = 1 switch anyValue { case is Int: print(anyValue) case let ourValue as Int: print(ourValue + 3) default: print("here") } let position = (3, 5) switch position { case (0, 0): print("the origin") case (-4...4, -6...6): print("\(position.0), \(position.1) is near the origin") default: print("\(position.0), \(position.1)") } func ~=(pattern:String, value: Int) -> Bool { return pattern == "\(value)" } switch position { case ("0", "0"): print("the origin") default: print("\(position.0), \(position.1)") }
mit
6b4069065b299507b78b0a1849d7f533
16.855172
96
0.654693
3.314981
false
false
false
false
eoger/firefox-ios
Client/Telemetry/UnifiedTelemetry.swift
1
10025
/* 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 Shared import Telemetry // // 'Unified Telemetry' is the name for Mozilla's telemetry system // class UnifiedTelemetry { private func migratePathComponentInDocumentsDirectory(_ pathComponent: String, to destinationSearchPath: FileManager.SearchPathDirectory) { guard let oldPath = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(pathComponent).path, FileManager.default.fileExists(atPath: oldPath) else { return } print("Migrating \(pathComponent) from ~/Documents to \(destinationSearchPath)") guard let newPath = try? FileManager.default.url(for: destinationSearchPath, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(pathComponent).path else { print("Unable to get destination path \(destinationSearchPath) to move \(pathComponent)") return } do { try FileManager.default.moveItem(atPath: oldPath, toPath: newPath) print("Migrated \(pathComponent) to \(destinationSearchPath) successfully") } catch let error as NSError { print("Unable to move \(pathComponent) to \(destinationSearchPath): \(error.localizedDescription)") } } init(profile: Profile) { migratePathComponentInDocumentsDirectory("MozTelemetry-Default-core", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("MozTelemetry-Default-mobile-event", to: .cachesDirectory) migratePathComponentInDocumentsDirectory("eventArray-MozTelemetry-Default-mobile-event.json", to: .cachesDirectory) NotificationCenter.default.addObserver(self, selector: #selector(uploadError), name: Telemetry.notificationReportError, object: nil) let telemetryConfig = Telemetry.default.configuration telemetryConfig.appName = "Fennec" telemetryConfig.userDefaultsSuiteName = AppInfo.sharedContainerIdentifier telemetryConfig.dataDirectory = .cachesDirectory telemetryConfig.updateChannel = AppConstants.BuildChannel.rawValue let sendUsageData = profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true telemetryConfig.isCollectionEnabled = sendUsageData telemetryConfig.isUploadEnabled = sendUsageData telemetryConfig.measureUserDefaultsSetting(forKey: "profile.blockPopups", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.saveLogins", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.showClipboardBar", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.settings.closePrivateTabs", withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASPocketStoriesVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASBookmarkHighlightsVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.ASRecentHighlightsVisible", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.normalbrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.privatebrowsing", withDefaultValue: true) telemetryConfig.measureUserDefaultsSetting(forKey: "profile.prefkey.trackingprotection.strength", withDefaultValue: "basic") telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.automaticSwitchIsOn.rawValue, withDefaultValue: false) telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.automaticSliderValue.rawValue, withDefaultValue: 0) telemetryConfig.measureUserDefaultsSetting(forKey: ThemeManagerPrefs.themeName.rawValue, withDefaultValue: "normal") let prefs = profile.prefs Telemetry.default.beforeSerializePing(pingType: CorePingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict // make a mutable copy if let newTabChoice = prefs.stringForKey(NewTabAccessors.PrefKey) { outputDict["defaultNewTabExperience"] = newTabChoice as AnyObject? } if let chosenEmailClient = prefs.stringForKey(PrefsKeys.KeyMailToOption) { outputDict["defaultMailClient"] = chosenEmailClient as AnyObject? } return outputDict } Telemetry.default.beforeSerializePing(pingType: MobileEventPingBuilder.PingType) { (inputDict) -> [String: Any?] in var outputDict = inputDict var settings: [String: String?] = inputDict["settings"] as? [String: String?] ?? [:] let searchEngines = SearchEngines(prefs: profile.prefs, files: profile.files) settings["defaultSearchEngine"] = searchEngines.defaultEngine.engineID ?? "custom" if let windowBounds = UIApplication.shared.keyWindow?.bounds { settings["windowWidth"] = String(describing: windowBounds.width) settings["windowHeight"] = String(describing: windowBounds.height) } outputDict["settings"] = settings // App Extension telemetry requires reading events stored in prefs, then clearing them from prefs. if let extensionEvents = profile.prefs.arrayForKey(PrefsKeys.AppExtensionTelemetryEventArray) as? [[String: String]], var pingEvents = outputDict["events"] as? [[Any?]] { profile.prefs.removeObjectForKey(PrefsKeys.AppExtensionTelemetryEventArray) extensionEvents.forEach { extensionEvent in let category = UnifiedTelemetry.EventCategory.appExtensionAction.rawValue let newEvent = TelemetryEvent(category: category, method: extensionEvent["method"] ?? "", object: extensionEvent["object"] ?? "") pingEvents.append(newEvent.toArray()) } outputDict["events"] = pingEvents } return outputDict } Telemetry.default.add(pingBuilderType: CorePingBuilder.self) Telemetry.default.add(pingBuilderType: MobileEventPingBuilder.self) } @objc func uploadError(notification: NSNotification) { guard !DeviceInfo.isSimulator(), let error = notification.userInfo?["error"] as? NSError else { return } Sentry.shared.send(message: "Upload Error", tag: SentryTag.unifiedTelemetry, severity: .info, description: error.debugDescription) } } // Enums for Event telemetry. extension UnifiedTelemetry { public enum EventCategory: String { case action = "action" case appExtensionAction = "app-extension-action" } public enum EventMethod: String { case add = "add" case background = "background" case cancel = "cancel" case change = "change" case delete = "delete" case drag = "drag" case drop = "drop" case foreground = "foreground" case open = "open" case press = "press" case scan = "scan" case share = "share" case tap = "tap" case view = "view" case applicationOpenUrl = "application-open-url" } public enum EventObject: String { case app = "app" case bookmark = "bookmark" case bookmarksPanel = "bookmarks-panel" case download = "download" case downloadLinkButton = "download-link-button" case downloadNowButton = "download-now-button" case downloadsPanel = "downloads-panel" case keyCommand = "key-command" case locationBar = "location-bar" case qrCodeText = "qr-code-text" case qrCodeURL = "qr-code-url" case readerModeCloseButton = "reader-mode-close-button" case readerModeOpenButton = "reader-mode-open-button" case readingListItem = "reading-list-item" case setting = "setting" case tab = "tab" case trackingProtectionStatistics = "tracking-protection-statistics" case trackingProtectionWhitelist = "tracking-protection-whitelist" case url = "url" case searchText = "searchText" } public enum EventValue: String { case activityStream = "activity-stream" case appMenu = "app-menu" case awesomebarResults = "awesomebar-results" case bookmarksPanel = "bookmarks-panel" case browser = "browser" case downloadCompleteToast = "download-complete-toast" case downloadsPanel = "downloads-panel" case homePanel = "home-panel" case homePanelTabButton = "home-panel-tab-button" case markAsRead = "mark-as-read" case markAsUnread = "mark-as-unread" case pageActionMenu = "page-action-menu" case readerModeToolbar = "reader-mode-toolbar" case readingListPanel = "reading-list-panel" case shareExtension = "share-extension" case shareMenu = "share-menu" case tabTray = "tab-tray" case topTabs = "top-tabs" } public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: EventValue, extras: [String: Any?]? = nil) { Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value.rawValue, extras: extras) } public static func recordEvent(category: EventCategory, method: EventMethod, object: EventObject, value: String? = nil, extras: [String: Any?]? = nil) { Telemetry.default.recordEvent(category: category.rawValue, method: method.rawValue, object: object.rawValue, value: value, extras: extras) } }
mpl-2.0
582d2e5e82aefdba70ea3a93a1e79313
51.213542
237
0.697057
5.24046
false
true
false
false
NicholasTD07/ToDoRedux
Sources/ToDoRedux/ToDos.swift
1
1074
public struct ToDos { public static let initial = ToDos.init(todos: []) public enum Box { case inbox case today case later case archive } internal struct ToDoInBox { let todo: ToDo let box: Box } internal let todos: [ToDoInBox] } extension ToDos { public var inbox: [ToDo] { return todos .filter { $0.box == .inbox } .map { $0.todo } } public var today: [ToDo] { return todos .filter { $0.box == .today } .map { $0.todo } } public var later: [ToDo] { return todos .filter { $0.box == .later } .map { $0.todo } } public var archive: [ToDo] { return todos .filter { $0.box == .archive } .map { $0.todo } } public var all: [ToDo] { return todos.map { $0.todo } } public var done: [ToDo] { return all.filter { $0.done } } public var schedueld: [ToDo] { return all.filter { $0.due != nil } } }
mit
99a88153aeea207bc6eded42f0e916be
20.48
53
0.478585
3.729167
false
false
false
false
khizkhiz/swift
test/Interpreter/SDK/Accelerate.swift
2
1910
// RUN: %target-run-simple-swift // REQUIRES: executable_test // // vU1024Divide() is only available on OS X. // REQUIRES: OS=macosx import Accelerate extension vU1024: IntegerLiteralConvertible, CustomStringConvertible, Equatable { public init(integerLiteral: Int) { var integerLiteral = integerLiteral self.init() memcpy(&self, &integerLiteral, sizeof(Int.self)) } init(_ int: Int) { self.init(integerLiteral: int) } public var description: String { if self == 0 { return "0" } var digits: [Character] = [] var intermediate = self var digit: vU1024 = 0 repeat { (intermediate, digit) = quorem(intermediate, 10) digits.append(Character(UnicodeScalar(Int(digit) + 48))) } while intermediate != 0 return String(digits.reversed()) } } extension Int { init(_ u1024: vU1024) { var u1024 = u1024 // NB: Doesn't overflow check self.init() memcpy(&self, &u1024, sizeof(Int.self)) } } func *(x: vU1024, y: vU1024) -> vU1024 { var x = x var y = y var result = vU1024() vU1024HalfMultiply(&x, &y, &result) return result } func quorem(x: vU1024, _ y: vU1024) -> (vU1024, vU1024) { var x = x var y = y var quo = vU1024() var rem = vU1024() vU1024Divide(&x, &y, &quo, &rem) return (quo, rem) } public func ==(x: vU1024, y: vU1024) -> Bool { var x = x var y = y return memcmp(&x, &y, sizeof(vU1024.self)) == 0 } func factorial(x: Int) -> vU1024 { var result: vU1024 = 1 for i in 1...x { result = result * vU1024(i) } return result } // CHECK: 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000 print(factorial(170))
apache-2.0
7e3cffc118cde6cab7a9e33675c7ccd2
23.177215
317
0.682723
3.178037
false
false
false
false
byvapps/ByvUtils
ByvUtils/Classes/UIImage+extension.swift
1
2072
// // UIImage+extension.swift // Pods // // Created by Adrian Apodaca on 17/2/17. // // import Foundation public extension UIImage { /// Returns a image that fills in newSize func resizedImageToSize(_ newSize: CGSize) -> UIImage { // Guard newSize is different guard self.size != newSize else { return self } UIGraphicsBeginImageContext(size) self.draw(in: CGRect(x:0, y:0, width:size.width, height:size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } /// Returns a resized image that fits in rectSize, keeping it's aspect ratio /// Note that the new image size is not rectSize, but within it. func resizedImageToMaxSize(_ maxSize: CGSize) -> UIImage { let widthFactor = size.width / maxSize.width let heightFactor = size.height / maxSize.height var resizeFactor = widthFactor if size.height > size.width { resizeFactor = heightFactor } let newSize = CGSize(width: size.width/resizeFactor, height: size.height/resizeFactor) let resized = resizedImageToSize(newSize) return resized } public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } func alpha(_ value:CGFloat)->UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(at: CGPoint.zero, blendMode: .normal, alpha: value) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
mit
d9d95b9a13672e8aaf4ed8036926f8cc
31.888889
94
0.640927
5.090909
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Message/Controller/BTMessageViewController.swift
1
6121
// // BTMessageViewController.swift // BanTang // // Created by 张灿 on 16/5/23. // Copyright © 2016年 张灿. All rights reserved. // import UIKit class BTMessageViewController: UIViewController { //标题滚动栏 var titleScrollView: UIScrollView = { var titlescroll = UIScrollView() titlescroll.frame = CGRect(x: 0, y: 64, width: UIScreen.mainScreen().bounds.width, height: 44) titlescroll.backgroundColor = UIColor.whiteColor() return titlescroll }() //容器滚动栏 var contentScrollView: UIScrollView = { var content = UIScrollView() content.frame = CGRect(x: 0, y: 108, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height - 108 - 49) content.pagingEnabled = true content.showsHorizontalScrollIndicator = false return content }() var underLine: UIView? // var selectBtn: UIButton? var titleBtns: [UIButton] = [UIButton]() override func viewDidLoad() { super.viewDidLoad() //设置导航栏标题,字体颜色等 setupNavTitle() setupScrollView() addAllChildVC() setupTitleView() view.backgroundColor = UIColor(red: 244 / 255.0, green: 244 / 255.0, blue: 244 / 255.0, alpha: 1.0) automaticallyAdjustsScrollViewInsets = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //设置导航栏标题,字体颜色等 func setupNavTitle() { navigationItem.title = "消息" navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(19), NSForegroundColorAttributeName: UIColor.darkGrayColor()] } } extension BTMessageViewController: UIScrollViewDelegate { //设置两个滚动代理 func setupScrollView() { titleScrollView.delegate = self view.addSubview(titleScrollView) contentScrollView.delegate = self view.addSubview(contentScrollView) } //添加所有子控制器 func addAllChildVC() { let vc1 = BTMessageChildBaseTVC() vc1.title = "喜欢/收藏" self.addChildViewController(vc1) let vc2 = BTMessageChildBaseTVC() vc2.title = "评论" self.addChildViewController(vc2) let vc3 = BTMessageChildBaseTVC() vc3.title = "通知" self.addChildViewController(vc3) } //设置标题栏 func setupTitleView() { let count: NSInteger = self.childViewControllers.count var x: CGFloat = 0 let y: CGFloat = 0 let w: CGFloat = UIScreen.mainScreen().bounds.width / CGFloat(count) let h: CGFloat = (titleScrollView.frame.size.height) for i in 0..<count { let vc = self.childViewControllers[i] let btn = UIButton(type: .Custom) btn.setTitle(vc.title, forState: .Normal) btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal) btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected) btn.tag = i btn.titleLabel?.font = UIFont.systemFontOfSize(15) x = CGFloat(i) * w btn.frame = CGRect(x: x, y: y, width: w, height: h) titleScrollView.addSubview(btn) btn.addTarget(self, action: #selector(BTMessageViewController.btnClick(_:)), forControlEvents: .TouchUpInside) titleBtns.append(btn) if i == 0 { btnClick(btn) underLine = UIView() underLine?.backgroundColor = UIColor.redColor() underLine?.frame.size.height = 3 underLine?.frame.size.width = 30 underLine?.frame.origin.y = titleScrollView.frame.size.height - 3 underLine?.center.x = btn.center.x titleScrollView.addSubview(underLine!) } } titleScrollView.contentSize = CGSize(width: w * CGFloat(count), height: 0) contentScrollView.contentSize = CGSize(width: UIScreen.mainScreen().bounds.width * CGFloat(count), height: 0) } //按钮点击 func btnClick(btn: UIButton) { let i = btn.tag // btnChange(btn) setupChildVC(i) UIView.animateWithDuration(0.25) { self.underLine?.center.x = btn.center.x } let x = CGFloat(i) * UIScreen.mainScreen().bounds.width contentScrollView.contentOffset = CGPoint(x: x, y: 0) } func setupChildVC(i: NSInteger) { let vc = childViewControllers[i] if (vc.view.superview != nil) { return } let x = CGFloat(i) * UIScreen.mainScreen().bounds.width vc.view.frame = CGRect(x: x, y: 0, width: contentScrollView.bounds.size.width, height: contentScrollView.bounds.size.height) contentScrollView.addSubview(vc.view) } // func btnChange(btn: UIButton) { // selectBtn = btn // UIView.animateWithDuration(0.25) { // // self.underLine?.center.x = btn.center.x // } // } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let page = contentScrollView.contentOffset.x / UIScreen.mainScreen().bounds.width // let btn = titleBtns[NSInteger(page)] // btnChange(btn) setupChildVC(NSInteger(page)) } //动态计算下划线位置 func scrollViewDidScroll(scrollView: UIScrollView) { let page = contentScrollView.contentOffset.x / UIScreen.mainScreen().bounds.width underLine?.center.x = BTscreenW / CGFloat(titleBtns.count) * 0.5 + page * BTscreenW / CGFloat(titleBtns.count) } }
apache-2.0
f31cdbfb4a1a08c5ee3b8183e15013ed
29.849741
173
0.585153
4.740446
false
false
false
false
ZICUNREN/MicroShopProject
MicroShop/MicroShop/Swift/GoodsViewController.swift
2
9657
// // GoodsViewController.swift // MicroShop // // Created by abc on 15/6/23. // Copyright (c) 2015年 App. All rights reserved. // import UIKit class GoodsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate{ @IBOutlet weak var tableiew: UITableView! @IBOutlet weak var hederView: UIView! @IBOutlet weak var typeView: UIView! @IBOutlet weak var searchbar: UISearchBar! @IBOutlet weak var class_btn: UIButton! @IBOutlet weak var order_nav: UISegmentedControl! var model:SYWebURLModel = SYWebURLModel() var tableData:[JSON] = [] var class_list_data:[JSON] = [] var getUrl = "\(HomeURL)\(Supply_Goods_URL)" var page = 1 var order:Int = 1 var name:String? var goods_class_id:Int? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "产品" self.tableiew.dataSource = self self.tableiew.delegate = self self.searchbar.delegate = self self.tableiew.separatorInset = UIEdgeInsetsZero self.tableiew.layoutMargins = UIEdgeInsetsZero self.tableiew.tableHeaderView = hederView self.tableiew.addHeaderWithCallback { () -> Void in self.reLoad() } self.tableiew.addFooterWithCallback { () -> Void in self.nextPage() } SVProgressHUD.showLoad("加载中") model = SYGettingWebURLData.sharedManager().getWebURLData(); reLoad() } func reLoad(){ page = 1 var authcode = OCToSwift.sharedManager().userToken() getUrl = "\(getUrl)&authcode=\(authcode)&order=\(order)&p=\(page)" if let pre_name = name{ getUrl = "\(getUrl)&name=\(pre_name)" } if let pre_class_id = goods_class_id{ getUrl = "\(getUrl)&class=\(pre_class_id)" } NetworkInterface.shareInstance().requestForGet(getUrl, complete: { (re:[NSObject : AnyObject]!) -> Void in SVProgressHUD.dismiss() let json = JSON(re) if let class_data = json["data"]["class_list"].array{ self.class_list_data = class_data } if let data = json["data"]["list"].array{ self.tableData = data self.tableiew.reloadData() self.tableiew.endRefreshing() }else{ self.tableiew.loadAll() } }) { (error:NSError!) -> Void in self.tableiew.endRefreshing() } } func nextPage(){ page = page+1 var authcode = OCToSwift.sharedManager().userToken() getUrl = "\(getUrl)&authcode=\(authcode)&order=\(order)&p=\(page)" if let pre_name = name{ getUrl = "\(getUrl)&name=\(pre_name)" } if let pre_class_id = goods_class_id{ getUrl = "\(getUrl)&class=\(pre_class_id)" } NetworkInterface.shareInstance().requestForGet(getUrl, complete: { (re:[NSObject : AnyObject]!) -> Void in let json = JSON(re) if let class_data = json["data"]["class_list"].array{ self.class_list_data = class_data } if let data = json["data"]["list"].array{ self.tableData = self.tableData+data self.tableiew.reloadData() self.tableiew.endRefreshing() if data.count <= 0{ self.tableiew.loadAll() } }else{ self.tableiew.loadAll() } }) { (error:NSError!) -> Void in self.tableiew.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 45 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return typeView } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let rowData = tableData[indexPath.row] let cell:GoodsTableViewCell? = self.tableiew.dequeueReusableCellWithIdentifier("goodscell") as? GoodsTableViewCell cell?.zf?.tag = indexPath.row cell?.sj?.tag = indexPath.row let is_sell:Int = rowData["is_sell"].intValue if is_sell == 1{ cell?.sj.setTitle("已上架", forState: UIControlState.Normal) cell?.sj.setBackgroundImage(UIImage(named: "gray_btn"), forState: UIControlState.Normal) }else{ cell?.sj.setTitle("上架", forState: UIControlState.Normal) cell?.sj.setBackgroundImage(UIImage(named: "red_btn"), forState: UIControlState.Normal) } cell?.goods_name?.text = rowData["goods_name"].string! let price = rowData["goods_price"].string! cell?.goods_price?.text = "¥\(price)" let commission = rowData["goods_commission"].string! cell?.goods_commission?.text = "佣金:\(commission)" let sales = rowData["goods_sales"].string! cell?.goods_sales?.text = "销量:\(sales)" cell?.cover?.layer.cornerRadius = 3 cell?.cover?.sd_setImageWithURL(NSURL(string: rowData["cover"].string!)) cell?.separatorInset = UIEdgeInsetsZero cell?.layoutMargins = UIEdgeInsetsZero return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableiew.deselectRowAtIndexPath(indexPath, animated: true) var rowData = tableData[indexPath.row] let goods_id:Int = rowData["goods_id"].intValue var url = model.Spread_Good_Detail let mainStoryboard = UIStoryboard(name: "Html", bundle: NSBundle.mainBundle()) let vc : SYGeneralHtmlViewController = mainStoryboard.instantiateViewControllerWithIdentifier("generalHtmlVC") as! SYGeneralHtmlViewController vc.hidesBottomBarWhenPushed = true vc.url = "\(url)&good_id=\(goods_id)" vc.navTitle = "产品详情" self.navigationController?.pushViewController(vc, animated: 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. } */ func searchBarSearchButtonClicked(searchBar: UISearchBar) { var name = searchBar.text searchBar.resignFirstResponder() if let name_str = name{ self.name = name_str SVProgressHUD.showLoad("搜索中") self.reLoad() } } @IBAction func order_click(sender: AnyObject) { var select:Int = sender.selectedSegmentIndex+1 if select != order{ order = select SVProgressHUD.showLoad("加载中") self.reLoad() } } @IBAction func zf_click(sender: UIButton) { var row:Int = sender.tag var rowData = tableData[row] var goods_id:String? = rowData["goods_id"].string! println(goods_id) OCToSwift.sharedManager().requestAddSell(goods_id) } @IBAction func sj_click(sender: UIButton) { var row:Int = sender.tag var rowData = tableData[row] let goods_id:Int = rowData["goods_id"].intValue let is_sell:Int = rowData["is_sell"].intValue if is_sell == 0{ let authcode = OCToSwift.sharedManager().userToken() let url = "\(HomeURL)\(Spread_Add_Sell)&authcode=\(authcode)&goods_id=\(goods_id)" NetworkInterface.shareInstance().requestForGet(url, complete: { (re) -> Void in SVProgressHUD.alertSuccess("上架成功") sender.setTitle("已上架", forState: UIControlState.Normal) sender.setBackgroundImage(UIImage(named: "gray_btn"), forState: UIControlState.Normal) }, error: { (error) -> Void in SVProgressHUD.alertError("上架失败") }) } } }
apache-2.0
47208fda87f529d8333877b5c6eeec90
27.694611
150
0.532241
5.265934
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Weather Station Meteorology Details Scene/Table Cells/Weather Station Meteorology Details Atmospheric Details/WeatherStationMeteorologyDetailsAtmosphericDetailsCell.swift
1
10890
// // WeatherStationCurrentInformationAtmosphericDetailsCell.swift // NearbyWeather // // Created by Erik Maximilian Martens on 15.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension WeatherStationMeteorologyDetailsAtmosphericDetailsCell { struct Definitions { static let symbolWidth: CGFloat = 20 } } // MARK: - Class Definition final class WeatherStationMeteorologyDetailsAtmosphericDetailsCell: UITableViewCell, BaseCell { // swiftlint:disable:this type_name typealias CellViewModel = WeatherStationMeteorologyDetailsAtmosphericDetailsCellViewModel private typealias CellContentInsets = Constants.Dimensions.Spacing.ContentInsets private typealias CellInterelementSpacing = Constants.Dimensions.Spacing.InterElementSpacing // MARK: - UIComponents private lazy var cloudCoverageSymbolImageView = Factory.ImageView.make(fromType: .symbol(systemImageName: "cloud")) private lazy var cloudCoverageDescriptionLabel = Factory.Label.make(fromType: .body(text: R.string.localizable.cloud_coverage(), textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var cloudCoverageLabel = Factory.Label.make(fromType: .subtitle(alignment: .right)) private lazy var humiditySymbolImageView = Factory.ImageView.make(fromType: .symbol(systemImageName: "humidity")) private lazy var humidityDescriptionLabel = Factory.Label.make(fromType: .body(text: R.string.localizable.humidity(), textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var humidityLabel = Factory.Label.make(fromType: .subtitle(alignment: .right)) private lazy var airPressureSymbolImageView = Factory.ImageView.make(fromType: .symbol(systemImageName: "gauge")) private lazy var airPressureDescriptionLabel = Factory.Label.make(fromType: .body(text: R.string.localizable.air_pressure(), textColor: Constants.Theme.Color.ViewElement.Label.titleDark)) private lazy var airPressureLabel = Factory.Label.make(fromType: .subtitle(alignment: .right)) // MARK: - Assets private var disposeBag = DisposeBag() // MARK: - Properties var cellViewModel: CellViewModel? // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutUserInterface() setupAppearance() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Cell Life Cycle func configure(with cellViewModel: BaseCellViewModelProtocol?) { guard let cellViewModel = cellViewModel as? WeatherStationMeteorologyDetailsAtmosphericDetailsCellViewModel else { return } self.cellViewModel = cellViewModel cellViewModel.observeEvents() bindContentFromViewModel(cellViewModel) bindUserInputToViewModel(cellViewModel) } } // MARK: - ViewModel Bindings extension WeatherStationMeteorologyDetailsAtmosphericDetailsCell { func bindContentFromViewModel(_ cellViewModel: CellViewModel) { cellViewModel.cellModelDriver .drive(onNext: { [setContent] in setContent($0) }) .disposed(by: disposeBag) } } // MARK: - Cell Composition private extension WeatherStationMeteorologyDetailsAtmosphericDetailsCell { func setContent(for cellModel: WeatherStationMeteorologyDetailsAtmosphericDetailsCellModel) { cloudCoverageLabel.text = cellModel.cloudCoverageString humidityLabel.text = cellModel.humidityString airPressureLabel.text = cellModel.airPressureString } func layoutUserInterface() { // line 1 contentView.addSubview(cloudCoverageSymbolImageView, constraints: [ cloudCoverageSymbolImageView.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), cloudCoverageSymbolImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .medium)), cloudCoverageSymbolImageView.widthAnchor.constraint(equalToConstant: Definitions.symbolWidth), cloudCoverageSymbolImageView.heightAnchor.constraint(equalTo: cloudCoverageSymbolImageView.widthAnchor) ]) contentView.addSubview(cloudCoverageDescriptionLabel, constraints: [ cloudCoverageDescriptionLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), cloudCoverageDescriptionLabel.leadingAnchor.constraint(equalTo: cloudCoverageSymbolImageView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), cloudCoverageDescriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), cloudCoverageDescriptionLabel.centerYAnchor.constraint(equalTo: cloudCoverageSymbolImageView.centerYAnchor) ]) contentView.addSubview(cloudCoverageLabel, constraints: [ cloudCoverageLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), cloudCoverageLabel.leadingAnchor.constraint(equalTo: cloudCoverageDescriptionLabel.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), cloudCoverageLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .medium)), cloudCoverageLabel.widthAnchor.constraint(equalTo: cloudCoverageDescriptionLabel.widthAnchor, multiplier: 4/5), cloudCoverageLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), cloudCoverageLabel.centerYAnchor.constraint(equalTo: cloudCoverageDescriptionLabel.centerYAnchor), cloudCoverageLabel.centerYAnchor.constraint(equalTo: cloudCoverageSymbolImageView.centerYAnchor) ]) // line 2 contentView.addSubview(humiditySymbolImageView, constraints: [ humiditySymbolImageView.topAnchor.constraint(greaterThanOrEqualTo: cloudCoverageSymbolImageView.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), humiditySymbolImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .medium)), humiditySymbolImageView.widthAnchor.constraint(equalToConstant: Definitions.symbolWidth), humiditySymbolImageView.heightAnchor.constraint(equalTo: humiditySymbolImageView.widthAnchor) ]) contentView.addSubview(humidityDescriptionLabel, constraints: [ humidityDescriptionLabel.topAnchor.constraint(equalTo: cloudCoverageDescriptionLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), humidityDescriptionLabel.leadingAnchor.constraint(equalTo: humiditySymbolImageView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), humidityDescriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), humidityDescriptionLabel.centerYAnchor.constraint(equalTo: humiditySymbolImageView.centerYAnchor) ]) contentView.addSubview(humidityLabel, constraints: [ humidityLabel.topAnchor.constraint(equalTo: cloudCoverageLabel.bottomAnchor, constant: CellContentInsets.top(from: .medium)), humidityLabel.leadingAnchor.constraint(equalTo: humidityDescriptionLabel.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), humidityLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .medium)), humidityLabel.widthAnchor.constraint(equalTo: humidityDescriptionLabel.widthAnchor, multiplier: 4/5), humidityLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), humidityLabel.centerYAnchor.constraint(equalTo: humidityDescriptionLabel.centerYAnchor), humidityLabel.centerYAnchor.constraint(equalTo: humiditySymbolImageView.centerYAnchor) ]) // line 3 contentView.addSubview(airPressureSymbolImageView, constraints: [ airPressureSymbolImageView.topAnchor.constraint(greaterThanOrEqualTo: humiditySymbolImageView.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), airPressureSymbolImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .medium)), airPressureSymbolImageView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), airPressureSymbolImageView.widthAnchor.constraint(equalToConstant: Definitions.symbolWidth), airPressureSymbolImageView.centerYAnchor.constraint(equalTo: airPressureSymbolImageView.centerYAnchor) ]) contentView.addSubview(airPressureDescriptionLabel, constraints: [ airPressureDescriptionLabel.topAnchor.constraint(equalTo: humidityDescriptionLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), airPressureDescriptionLabel.leadingAnchor.constraint(equalTo: airPressureSymbolImageView.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), airPressureDescriptionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), airPressureDescriptionLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), airPressureDescriptionLabel.centerYAnchor.constraint(equalTo: airPressureSymbolImageView.centerYAnchor) ]) contentView.addSubview(airPressureLabel, constraints: [ airPressureLabel.topAnchor.constraint(equalTo: humidityLabel.bottomAnchor, constant: CellInterelementSpacing.yDistance(from: .medium)), airPressureLabel.leadingAnchor.constraint(equalTo: airPressureDescriptionLabel.trailingAnchor, constant: CellInterelementSpacing.xDistance(from: .small)), airPressureLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .medium)), airPressureLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), airPressureLabel.widthAnchor.constraint(equalTo: airPressureDescriptionLabel.widthAnchor, multiplier: 4/5), airPressureLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), airPressureLabel.centerYAnchor.constraint(equalTo: airPressureDescriptionLabel.centerYAnchor), airPressureLabel.centerYAnchor.constraint(equalTo: airPressureSymbolImageView.centerYAnchor) ]) } func setupAppearance() { selectionStyle = .none backgroundColor = .clear contentView.backgroundColor = Constants.Theme.Color.ViewElement.primaryBackground } }
mit
909d54361e520d0036423ab62e494a67
59.160221
193
0.809165
6.049444
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/WordPressTest/RecentSitesServiceTests.swift
2
1461
import XCTest @testable import WordPress class RecentSitesServiceTests: XCTestCase { func testEmptyByDefault() { let service = newService() XCTAssertEqual(service.recentSites.count, 0) } func testRecentSitesLimited() { let service = newService() service.touch(site: "site1") service.touch(site: "site2") service.touch(site: "site3") service.touch(site: "site4") XCTAssertEqual(service.recentSites, ["site4", "site3", "site2"]) } func testDoesNotDuplicate() { let service = newService() service.touch(site: "site1") service.touch(site: "site2") service.touch(site: "site1") XCTAssertEqual(service.recentSites, ["site1", "site2"]) } func testMigratesLastBlogUsed() { let database = EphemeralKeyValueDatabase() database.set("site1", forKey: "LastUsedBlogURLDefaultsKey") let service = RecentSitesService(database: database) XCTAssertEqual(service.recentSites, ["site1"]) } private func newService() -> RecentSitesService { return RecentSitesService(database: EphemeralKeyValueDatabase()) } func testTouchSiteSendsNotification() { expectation(forNotification: RecentSitesService.RecentSitesChanged, object: nil, handler: nil) let service = newService() service.touch(site: "site1") waitForExpectations(timeout: 0.01, handler: nil) } }
gpl-2.0
9b7a51e0f4b596a5db0ea52c641c4e31
32.204545
102
0.659138
4.537267
false
true
false
false
regexident/XCConfig
xccfg/main.swift
1
634
// // main.swift // xccfg // // Created by Vincent Esche on 6/21/15. // Copyright (c) 2015 Vincent Esche. All rights reserved. // import Foundation func printHelp(filePath: String) { println("usage: \(filePath.lastPathComponent) FILE.xcconfig") } let arguments = Process.arguments if (arguments.count != 2) || (arguments[1] == "--help") || (arguments[1] == "-h") { printHelp(arguments[0]) } else { let parser = XCConfigParser() let filePath = arguments[1] let fileURL = NSURL(fileURLWithPath: filePath) if let xcconfig = XCConfig(fileURL: fileURL!) { println(xcconfig) } else { println("Could not read file.") } }
bsd-3-clause
ffbf4240ab516db77b12d27cf324b9d0
21.642857
83
0.676656
3.218274
false
true
false
false
goktugyil/EZSwiftExtensions
Sources/StringExtensions.swift
1
21286
// // StringExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // // swiftlint:disable line_length // swiftlint:disable trailing_whitespace #if os(OSX) import AppKit #endif #if os(iOS) || os(tvOS) import UIKit #endif extension String { /// EZSE: Init string with a base64 encoded string init ? (base64: String) { let pad = String(repeating: "=", count: base64.length % 4) let base64Padded = base64 + pad if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) { self.init(decodedString) return } return nil } /// EZSE: base64 encoded of string var base64: String { let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue) let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } /// EZSE: Cut string from integerIndex to the end public subscript(integerIndex: Int) -> Character { let index = self.index(startIndex, offsetBy: integerIndex) return self[index] } /// EZSE: Cut string from range public subscript(integerRange: Range<Int>) -> String { let start = self.index(startIndex, offsetBy: integerRange.lowerBound) let end = self.index(startIndex, offsetBy: integerRange.upperBound) return String(self[start..<end]) } /// EZSE: Cut string from closedrange public subscript(integerClosedRange: ClosedRange<Int>) -> String { return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)] } /// EZSE: Character count public var length: Int { return self.count } /// EZSE: Counts number of instances of the input inside String public func count(_ substring: String) -> Int { return components(separatedBy: substring).count - 1 } /// EZSE: Capitalizes first character of String public mutating func capitalizeFirst() { guard self.count > 0 else { return } self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized) } /// EZSE: Capitalizes first character of String, returns a new string public func capitalizedFirst() -> String { guard self.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized) return result } /// EZSE: Uppercases first 'count' characters of String public mutating func uppercasePrefix(_ count: Int) { guard self.count > 0 && count > 0 else { return } self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) } /// EZSE: Uppercases first 'count' characters of String, returns a new string public func uppercasedPrefix(_ count: Int) -> String { guard self.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) return result } /// EZSE: Uppercases last 'count' characters of String public mutating func uppercaseSuffix(_ count: Int) { guard self.count > 0 && count > 0 else { return } self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) } /// EZSE: Uppercases last 'count' characters of String, returns a new string public func uppercasedSuffix(_ count: Int) -> String { guard self.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) return result } /// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex) public mutating func uppercase(range: CountableRange<Int>) { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard self.count > 0 && (0..<length).contains(from) else { return } self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased()) } /// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string public func uppercased(range: CountableRange<Int>) -> String { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard self.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased()) return result } /// EZSE: Lowercases first character of String public mutating func lowercaseFirst() { guard self.count > 0 else { return } self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) } /// EZSE: Lowercases first character of String, returns a new string public func lowercasedFirst() -> String { guard self.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) return result } /// EZSE: Lowercases first 'count' characters of String public mutating func lowercasePrefix(_ count: Int) { guard self.count > 0 && count > 0 else { return } self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased()) } /// EZSE: Lowercases first 'count' characters of String, returns a new string public func lowercasedPrefix(_ count: Int) -> String { guard self.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased()) return result } /// EZSE: Lowercases last 'count' characters of String public mutating func lowercaseSuffix(_ count: Int) { guard self.count > 0 && count > 0 else { return } self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) } /// EZSE: Lowercases last 'count' characters of String, returns a new string public func lowercasedSuffix(_ count: Int) -> String { guard self.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) return result } /// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex) public mutating func lowercase(range: CountableRange<Int>) { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard self.count > 0 && (0..<length).contains(from) else { return } self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased()) } /// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string public func lowercased(range: CountableRange<Int>) -> String { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard self.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased()) return result } /// EZSE: Counts whitespace & new lines @available(*, deprecated: 1.6, renamed: "isBlank") public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool { let characterSet = CharacterSet.whitespacesAndNewlines let newText = self.trimmingCharacters(in: characterSet) return newText.isEmpty } /// EZSE: Checks if string is empty or consists only of whitespace and newline characters public var isBlank: Bool { let trimmed = trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty } /// EZSE: Trims white space and new line characters public mutating func trim() { self = self.trimmed() } /// EZSE: Trims white space and new line characters, returns a new string public func trimmed() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } /// EZSE: Position of begining character of substing public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int { if subString.isEmpty { return -1 } var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards if caseInsensitive { searchOption.insert(NSString.CompareOptions.caseInsensitive) } if let range = self.range(of: subString, options: searchOption), !range.isEmpty { return self.distance(from: self.startIndex, to: range.lowerBound) } return -1 } /// EZSE: split string using a spearator string, returns an array of string public func split(_ separator: String) -> [String] { return self.components(separatedBy: separator).filter { !$0.trimmed().isEmpty } } /// EZSE: split string with delimiters, returns an array of string public func split(_ characters: CharacterSet) -> [String] { return self.components(separatedBy: characters).filter { !$0.trimmed().isEmpty } } /// EZSE : Returns count of words in string public var countofWords: Int { let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options()) return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0 } /// EZSE : Returns count of paragraphs in string public var countofParagraphs: Int { let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options()) let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: str.length)) ?? -1) + 1 } internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? { let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location) let to16 = utf16.index(from16, offsetBy: nsRange.length) if let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) { return from ..< to } return nil } /// EZSE: Find matches of regular expression in string public func matchesForRegexInText(_ regex: String!) -> [String] { let regex = try? NSRegularExpression(pattern: regex, options: []) let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? [] return results.map { String(self[self.rangeFromNSRange($0.range)!]) } } /// EZSE: Checks if String contains Email public var isEmail: Bool { let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length)) return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto") } /// EZSE: Returns if String is a number public func isNumber() -> Bool { return NumberFormatter().number(from: self) != nil ? true : false } /// EZSE: Extracts URLS from String public var extractURLs: [URL] { var urls: [URL] = [] let detector: NSDataDetector? do { detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } catch _ as NSError { detector = nil } let text = self if let detector = detector { detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), using: { (result: NSTextCheckingResult?, _, _) -> Void in if let result = result, let url = result.url { urls.append(url) } }) } return urls } /// EZSE: Checking if String contains input with comparing options public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool { return self.range(of: find, options: compareOption) != nil } /// EZSE: Converts String to Int public func toInt() -> Int? { if let num = NumberFormatter().number(from: self) { return num.intValue } else { return nil } } /// EZSE: Converts String to Double public func toDouble() -> Double? { if let num = NumberFormatter().number(from: self) { return num.doubleValue } else { return nil } } /// EZSE: Converts String to Float public func toFloat() -> Float? { if let num = NumberFormatter().number(from: self) { return num.floatValue } else { return nil } } /// EZSE: Converts String to Bool public func toBool() -> Bool? { let trimmedString = trimmed().lowercased() if trimmedString == "true" || trimmedString == "false" { return (trimmedString as NSString).boolValue } return nil } ///EZSE: Returns the first index of the occurency of the character in String public func getIndexOf(_ char: Character) -> Int? { for (index, c) in self.enumerated() where c == char { return index } return nil } /// EZSE: Converts String to NSString public var toNSString: NSString { return self as NSString } #if os(iOS) ///EZSE: Returns bold NSAttributedString public func bold() -> NSAttributedString { let boldString = NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) return boldString } #endif #if os(iOS) ///EZSE: Returns underlined NSAttributedString public func underline() -> NSAttributedString { let underlineString = NSAttributedString(string: self, attributes: [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]) return underlineString } #endif #if os(iOS) ///EZSE: Returns italic NSAttributedString public func italic() -> NSAttributedString { let italicString = NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) return italicString } #endif #if os(iOS) ///EZSE: Returns hight of rendered string public func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat { var attrib: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font] if lineBreakMode != nil { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode! attrib.updateValue(paragraphStyle, forKey: NSAttributedStringKey.paragraphStyle) } let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude)) return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrib, context: nil).height) } #endif #if os(iOS) || os(tvOS) ///EZSE: Returns NSAttributedString public func color(_ color: UIColor) -> NSAttributedString { let colorString = NSMutableAttributedString(string: self, attributes: [NSAttributedStringKey.foregroundColor: color]) return colorString } ///EZSE: Returns NSAttributedString public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString { var start = 0 var ranges: [NSRange] = [] while true { let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start)) if range.location == NSNotFound { break } else { ranges.append(range) start = range.location + range.length } } let attrText = NSMutableAttributedString(string: self) for range in ranges { attrText.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) } return attrText } #endif /// EZSE: Checks if String contains Emoji public func includesEmoji() -> Bool { for i in 0...length { let c: unichar = (self as NSString).character(at: i) if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) { return true } } return false } #if os(iOS) /// EZSE: copy string to pasteboard public func addToPasteboard() { let pasteboard = UIPasteboard.general pasteboard.string = self } #endif // EZSE: URL encode a string (percent encoding special chars) public func urlEncoded() -> String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } // EZSE: URL encode a string (percent encoding special chars) mutating version mutating func urlEncode() { self = urlEncoded() } // EZSE: Removes percent encoding from string public func urlDecoded() -> String { return removingPercentEncoding ?? self } // EZSE : Mutating versin of urlDecoded mutating func urlDecode() { self = urlDecoded() } } extension String { init(_ value: Float, precision: Int) { let nFormatter = NumberFormatter() nFormatter.numberStyle = .decimal nFormatter.maximumFractionDigits = precision self = nFormatter.string(from: NSNumber(value: value))! } init(_ value: Double, precision: Int) { let nFormatter = NumberFormatter() nFormatter.numberStyle = .decimal nFormatter.maximumFractionDigits = precision self = nFormatter.string(from: NSNumber(value: value))! } } /// EZSE: Pattern matching of strings via defined functions public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool { return pattern(value) } /// EZSE: Can be used in switch-case public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool { return { (value: String) -> Bool in value.hasPrefix(prefix) } } /// EZSE: Can be used in switch-case public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool { return { (value: String) -> Bool in value.hasSuffix(suffix) } }
mit
1ccfafac5b59ccc51290f5f8bd4726c9
39.934615
206
0.628065
4.822383
false
false
false
false
huchenme/TSAnimations
MapLocationAnimation/MapLocationAnimation/ViewController.swift
1
2173
// // ViewController.swift // MapLocationAnimation // // Created by Hu Chen on 10/5/16. // Copyright © 2016 Hu Chen. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { // MARK: - Types struct Constants { struct MapViewIdentifiers { static let sonarAnnotationView = "sonarAnnotationView" } } // MARK: - Properties @IBOutlet weak var mapView: MKMapView! let regionRadius: CLLocationDistance = 3000 let latitude = 40.758873 let longitude = -73.985134 // MARK: - View Life Cycle override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let initialLocation = CLLocation(latitude: latitude, longitude: longitude) centerMapOnLocation(initialLocation) let annotation = Annotation(coodinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), title: nil, subtitle: nil) mapView.addAnnotation(annotation) } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } // Reuse the annotation if possible. var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.MapViewIdentifiers.sonarAnnotationView) if annotationView == nil { annotationView = SonarAnnotationView(annotation: annotation, reuseIdentifier: Constants.MapViewIdentifiers.sonarAnnotationView) } else { annotationView!.annotation = annotation } return annotationView } // MARK: - Convenience func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius) mapView.setRegion(coordinateRegion, animated: false) } // MARK: - Status Bar override func prefersStatusBarHidden() -> Bool { return true } }
mit
d8c9930157a23834d24a2937951ef5de
27.96
139
0.658379
5.761273
false
false
false
false
Schatzjason/cs212
LectureCode/Three-Delegates/TextFields/EmojiTextFieldDelegate.swift
1
2284
// // EmojiTextFieldDelegate.swift // TextFields // // Created by Jason on 11/11/14. // Copyright (c) 2014 CCSF. All rights reserved. // import Foundation import UIKit class EmojiTextFieldDelegate : NSObject, UITextFieldDelegate { var translations = [String : String]() override init() { super.init() translations["heart"] = "\u{0001F496}" translations["fish"] = "\u{E522}" translations["bird"] = "\u{E523}" translations["frog"] = "\u{E531}" translations["bear"] = "\u{E527}" translations["dog"] = "\u{E052}" translations["cat"] = "\u{E04F}" } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var replacedAnEmoji = false var emojiStringRange: NSRange // Construct the text that will be in the field if this change is accepted var newText: NSString = textField.text! as NSString newText = newText.replacingCharacters(in: range, with: string) as NSString // For each dictionary entry in translations, pull out a string to search for // and an emoji to replace it with for (emojiString, emoji) in translations { // Search for all occurances of key (ie. "dog"), and replace with emoji (ie. 🐶) repeat { emojiStringRange = newText.range(of: emojiString, options: NSString.CompareOptions.caseInsensitive) // found one if emojiStringRange.location != NSNotFound { newText = newText.replacingCharacters(in: emojiStringRange, with: emoji) as NSString replacedAnEmoji = true } } while emojiStringRange.location != NSNotFound } // If we have replaced an emoji, then we directly edit the text field // Otherwise we allow the proposed edit. if replacedAnEmoji { textField.text = newText as String return false } else { return true } } func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } }
mit
d3f726e3dd8aa9b8ffd85285bc30bf48
32.057971
129
0.584393
5.068889
false
false
false
false
hfutrell/MetalMemoryBandwidth
Mac/MetalMemoryBandwidth/main.swift
1
6353
// // main.swift // MetalMemoryBandwidth // // Created by Holmes Futrell on 6/17/16. // Copyright © 2016 Holmes Futrell. All rights reserved. // import Foundation import MetalKit func randomFloat() -> Float { return Float(arc4random()) / Float(UINT32_MAX); } func computeSumCPU(array1 array1 : [Float], array2 : [Float], inout sumArray : [Float], N : Int) { for i in 0..<N { sumArray[i] = array1[i] + array2[i]; } } func generateLibrary(device: MTLDevice) -> MTLLibrary { let library : MTLLibrary?; do { let source : String = try String(contentsOfFile: "./addFunction.metal" ) library = try device.newLibraryWithSource(source, options: nil) // do we need compile options? } catch _ { print("error creating library ..."); library = nil } return library! } func computeSumMetal(array1 array1 : [Float], array2 : [Float], inout sumArray : [Float], N : Int) { let devices: [MTLDevice] = MTLCopyAllDevices(); for device in devices { print(device); } let defaultDevice : MTLDevice = MTLCreateSystemDefaultDevice()!; print("default device = ", defaultDevice); // create the buffers let resourceOptions: MTLResourceOptions = MTLResourceOptions.StorageModeManaged let arrayBuffer1 = defaultDevice.newBufferWithBytes(array1, length: N * sizeof(Float), options: resourceOptions) let arrayBuffer2 = defaultDevice.newBufferWithBytes(array2, length: N * sizeof(Float), options: resourceOptions) let sumBuffer = defaultDevice.newBufferWithBytes(sumArray, length: N * sizeof(Float), options: resourceOptions) // create the library let library: MTLLibrary = generateLibrary(defaultDevice) let myAdditionFunction: MTLFunction = library.newFunctionWithName("myAddFunction")!; // create compute pipeline state let computePipelineState: MTLComputePipelineState? do { computePipelineState = try defaultDevice.newComputePipelineStateWithFunction(myAdditionFunction); } catch _ { print("error with compute pipeline state ..."); return; } let commandQueue = defaultDevice.newCommandQueue(); let threadsPerThreadgroup: MTLSize = MTLSizeMake(256, 1, 1) // a decent guess let threadGroups: MTLSize = MTLSizeMake(N / threadsPerThreadgroup.width, 1, 1) print("generating command buffers ...") let timeStart = NSDate() let generateCommandBuffersStart: NSDate = NSDate() let iterations = 500 var lastCommandBuffer: MTLCommandBuffer? = nil for i in 0..<iterations { let commandBuffer = commandQueue.commandBuffer(); let commandEncoder = commandBuffer.computeCommandEncoder(); // 1. Call the setComputePipelineState(_:) method with the MTLComputePipelineState object that contains the compute function that will be executed. commandEncoder.setComputePipelineState(computePipelineState!); // 2 Specify resources that hold the input data (or output destination) for the compute function. Set the location (index) of each resource in its corresponding argument table. commandEncoder.setBuffer(arrayBuffer1, offset: 0, atIndex: 0); commandEncoder.setBuffer(arrayBuffer2, offset: 0, atIndex: 1); commandEncoder.setBuffer(sumBuffer, offset: 0, atIndex: 2); // 3. Call the dispatchThreadgroups(_:threadsPerThreadgroup:) method to encode the compute function with a specified number of threadgroups for the grid and the number of threads per threadgroup. commandEncoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerThreadgroup) // 4. Call endEncoding() to finish encoding the compute commands onto the command buffer. commandEncoder.endEncoding(); commandBuffer.enqueue(); if ( i == iterations-1) { lastCommandBuffer = commandBuffer // last command buffer gets a blit encoder // to synchronize on the sum memory // otherwise the CPU can't read it let blitCommandEncoder = commandBuffer.blitCommandEncoder() blitCommandEncoder.synchronizeResource(sumBuffer) blitCommandEncoder.endEncoding(); } commandBuffer.commit(); // causes the command buffer to be executed as soon as possible commandBuffer.waitUntilScheduled() } print("took ", NSDate().timeIntervalSinceDate(generateCommandBuffersStart), " seconds"); lastCommandBuffer!.waitUntilCompleted(); print("command buffer complete."); if (lastCommandBuffer!.status == MTLCommandBufferStatus.Error) { if (lastCommandBuffer!.error != nil) { print("command buffer failed with error: ", lastCommandBuffer!.error) } else { print("command buffer failed") } return } let timeInterval: Double = NSDate().timeIntervalSinceDate(timeStart) let bytesPerSecond : Double = (Double(iterations * 3 * N * sizeof(Float))) / Double(timeInterval) let gBytesPerSecond : Double = bytesPerSecond / 1024.0 / 1024.0 / 1024.0 print("took ", timeInterval, " seconds") print("bytes per second: ", bytesPerSecond) print("GB per second: ", gBytesPerSecond) let output : UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>(sumBuffer.contents()) sumArray = Array(UnsafeBufferPointer(start: output, count: N)); } // create an array of random floats var N : Int = 1024 * 1024 * 32; print("Running test with N = ", N); var floatArray1 = [Float](count: N, repeatedValue: 0.0); var floatArray2 = [Float](count: N, repeatedValue: 0.0); var sumArray = [Float](count: N, repeatedValue: 0.0); for i in 0..<N { floatArray1[i] = randomFloat(); } for i in 0..<N { floatArray2[i] = randomFloat(); } // compute sum computeSumMetal(array1: floatArray1, array2: floatArray2, sumArray: &sumArray, N: N); // verify sum var success = true; for i in 0..<N { if sumArray[i] != floatArray1[i] + floatArray2[i] { print("sum failed at index", i, "(got ", sumArray[i], ", expected ", floatArray1[i] + floatArray2[i], ")"); success = false; break; } } if success { print("success"); }
mit
375ee46f45f4f9c4f07ed3081567f4a6
34.892655
203
0.668293
4.712166
false
false
false
false
Boss-XP/ChatToolBar
BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatToolBar/BXPChatFaceView/BXPChatFaceView.swift
1
9866
// // BXPChatFaceView.swift // BXPChatToolBar // // Created by 向攀 on 17/1/13. // Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved. // import UIKit private let kFooterViewHeight: CGFloat = 50 private let kViewMargin: CGFloat = 20 private let kCountsPerPage: NSInteger = 20 private let kEmojiImageKey = "emoji" private let kDeleteEmojiImageKey = "chat_face_delete" @objc protocol BXPChatFaceViewDelegate: NSObjectProtocol { @objc optional func chatFaceView(_ chatFaceView: BXPChatFaceView, didSelected item: BXPFaceItemModel) -> Void @objc optional func chatFaceViewDidClikcedDeleteItem(_ chatFaceView: BXPChatFaceView) -> Void @objc optional func chatFaceViewDidSendButton(_ chatFaceView: BXPChatFaceView) -> Void } class BXPChatFaceView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let emojiCellIdentifier = "chat.face.cell.emoji" let deleteCellIdentifier = "chat.face.cell.delete" var faceImages = [Any]()//[Any]?.self weak var delegate: BXPChatFaceViewDelegate? override init(frame: CGRect) { super.init(frame: frame) let path = Bundle.main.path(forResource: "ChatSystemFaceConfig.plist", ofType: nil) let faces = (NSArray(contentsOfFile: path!) as! Array<Any>) //(NSArray(contentsOfFile: path!) as! Array<Any>) for (_, value) in faces.enumerated() { let dict = value as! Dictionary<String, Any> let emojiIndex = dict["emojiIndex"] as? NSNumber let itemModel = BXPFaceItemModel() itemModel.imageIndex = emojiIndex ?? 0 // faceImages += [emojiIndex ?? 0] faceImages += [itemModel] // faceImages.append([emojiIndex]) } var frameValue = frame frameValue.size.height = 216; self.frame = frameValue; setupBottomView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() addSubview(collectionView) addSubview(pageControl) makeConstrainsForPageControl() } func setupBottomView() -> Void { let height: CGFloat = 35 let bottomView = UIView(frame: CGRect(x: 0, y: self.bounds.size.height - height, width: UIScreen.main.bounds.size.width, height: height)) bottomView.backgroundColor = UIColor.white addSubview(bottomView) let width: CGFloat = 66 let edgeInset:CGFloat = (width - height) * 0.5 let emojiButton = UIButton(frame: CGRect(x: 0, y: 0, width: width, height: height)) emojiButton.setImage(UIImage(named: kEmojiImageKey), for: UIControlState.normal) emojiButton.imageEdgeInsets = UIEdgeInsetsMake(0, edgeInset, 0, edgeInset) emojiButton.backgroundColor = UIColor(red: 242/255.0, green: 244/255.0, blue: 248/255.0, alpha: 1.0) bottomView.addSubview(emojiButton) let sendButton = UIButton(frame: CGRect(x: UIScreen.main.bounds.size.width - width, y: 0, width: width, height: height)) sendButton.setTitle("发送", for: UIControlState.normal) sendButton.setTitleColor(UIColor.white, for: UIControlState.normal) sendButton.backgroundColor = UIColor(red: 0/255.0, green: 198/255.0, blue: 129/255.0, alpha: 1.0) sendButton.addTarget(self, action: #selector(self.sendButtonClicked), for: UIControlEvents.touchUpInside) bottomView.addSubview(sendButton) } private lazy var collectionView: UICollectionView = { var frame: CGRect = self.bounds frame.size.height -= 35; let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.horizontal layout.minimumLineSpacing = 0; layout.minimumInteritemSpacing = 0; layout.sectionInset = UIEdgeInsetsMake(8, 10, 23, 10) let tempCollectionView = UICollectionView(frame: frame, collectionViewLayout: layout) tempCollectionView.backgroundColor = UIColor(red: 242/255.0, green: 244/255.0, blue: 248/255.0, alpha: 1.0) tempCollectionView.dataSource = self tempCollectionView.delegate = self // tempCollectionView.isPrefetchingEnabled = false tempCollectionView.isPagingEnabled = true tempCollectionView.showsHorizontalScrollIndicator = false tempCollectionView.register(BXPChatFaceCollectionViewCell.self, forCellWithReuseIdentifier: self.emojiCellIdentifier) tempCollectionView.register(BXPChatFaceCollectionViewCell.self, forCellWithReuseIdentifier: self.deleteCellIdentifier) return tempCollectionView }() lazy var pageControl: UIPageControl = { let tempPage = UIPageControl() tempPage.pageIndicatorTintColor = UIColor.init(red: 135/255, green: 136/255, blue: 142/255, alpha: 1.0) tempPage.currentPageIndicatorTintColor = UIColor.init(red: 29/255, green: 29/255, blue: 36/255, alpha: 1.0) tempPage.currentPage = 0 tempPage.numberOfPages = Int(self.faceImages.count / kCountsPerPage) tempPage.isHidden = !(tempPage.numberOfPages > 1) tempPage.translatesAutoresizingMaskIntoConstraints = false return tempPage }() func makeConstrainsForPageControl() -> Void { let centerXConstraint = NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: collectionView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0) let topConstraint = NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: collectionView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -20) let heightConstraint = NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 15) let widthConstraint = NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 50) self.addConstraints([centerXConstraint, topConstraint]) pageControl.addConstraints([heightConstraint, widthConstraint]) } // MARK: - Events Response func sendButtonClicked() -> Void { if (delegate != nil) && (delegate?.responds(to: #selector(BXPChatFaceViewDelegate.chatFaceViewDidSendButton(_:))))! { delegate?.chatFaceViewDidSendButton!(self) } } // MARK: - UICollectionViewDelegate, UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return Int(faceImages.count / kCountsPerPage) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return Int(kCountsPerPage + 1) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row == kCountsPerPage { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: deleteCellIdentifier, for: indexPath) as! BXPChatFaceCollectionViewCell cell.setupDeleteItemWithImage(image: UIImage(named: kDeleteEmojiImageKey)!) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: emojiCellIdentifier, for: indexPath) as! BXPChatFaceCollectionViewCell let itemModel = faceImages[indexPath.row + kCountsPerPage * indexPath.section] as! BXPFaceItemModel cell.setupFaceImageWithImage(image: itemModel.faceImage) return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == kCountsPerPage { if (delegate != nil) && (delegate?.responds(to: #selector(BXPChatFaceViewDelegate.chatFaceViewDidClikcedDeleteItem(_:))))! { delegate?.chatFaceViewDidClikcedDeleteItem!(self) } return } if (delegate != nil) && (delegate?.responds(to: #selector(BXPChatFaceViewDelegate.chatFaceViewDidClikcedDeleteItem(_:))))! { let itemModel = faceImages[indexPath.row + kCountsPerPage * indexPath.section] as! BXPFaceItemModel delegate?.chatFaceView!(self, didSelected: itemModel) } } // MARK: - UICollectionViewDelegateFlowLayout let sizeW: CGFloat = (UIScreen.main.bounds.size.width - kViewMargin) / 7.0 let sizeH: CGFloat = (216 - kViewMargin - kFooterViewHeight) / 3 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: sizeW, height: sizeH) } // MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { UIView.animate(withDuration: 0.15, animations: { self.pageControl.currentPage = Int(scrollView.contentOffset.x / self.bounds.size.width) }) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { UIView.animate(withDuration: 0.15, animations: { self.pageControl.currentPage = Int(scrollView.contentOffset.x / self.bounds.size.width) }) } } }
apache-2.0
4f6e1b8d7b1bfec89d97fd294e4b046e
44.625
240
0.686859
5.122141
false
false
false
false
manderson-productions/RompAround
RompAround/MapSquare.swift
1
3515
// // MapSquare.swift // RompAround // // Created by Mark Anderson on 10/10/15. // Copyright © 2015 manderson-productions. All rights reserved. // import SpriteKit enum MapSquare: Int { case Ground = 0 case Wall = 1 case Destructable = 2 case Enemy = 3 case Player = 4 case Loot = 5 case Empty = 6 var name: String { return "\(self)" } } extension MapSquare { var color: SKColor { switch self { case .Ground: return SKColor.grayColor() case .Wall: return SKColor.darkGrayColor() case .Destructable: return SKColor.purpleColor() case .Enemy: return SKColor.orangeColor() case .Player: return SKColor.redColor() case .Loot: return SKColor.blueColor() case .Empty: return SKColor.blackColor() } } // TODO: We don't necessarily need the level, gridx and gridY but may in the future func entryAction(forSprite sprite:SKSpriteNode, inLevel level:LevelData, atGridX gridX:Int, gridY:Int) -> SKAction? { let duration = 0.1 sprite.alpha = 0 switch self { case .Player, .Enemy: sprite.setScale(4.0) return SKAction.sequence([SKAction.waitForDuration(0.2), SKAction.group([SKAction.scaleTo(1.0, duration: duration), SKAction.fadeAlphaTo(1.0, duration: duration)])]) default: return SKAction.fadeAlphaTo(1.0, duration: duration) } } func spriteForSquare(inLevel level:LevelData, atGridX gridX:Int=0, gridY:Int=0) -> SKSpriteNode? { if self == .Empty { return nil } let sprite: SKSpriteNode switch self { case .Player: sprite = PlayerSprite(color: color, size: CGSize(width: level.squareSize, height: level.squareSize)) case .Enemy: sprite = EnemySprite(type: .Goblin, health: nil, attack: nil, defense: nil, movement: nil, size: CGSize(width: level.squareSize, height: level.squareSize)) case .Loot: sprite = LootSprite(color: color, size: CGSize(width: level.squareSize, height: level.squareSize)) default: sprite = SKSpriteNode(color: color, size: CGSize(width: level.squareSize, height: level.squareSize)) } switch self { case .Empty, .Ground, .Wall, .Destructable: sprite.zPosition = LevelScene.WorldLayer.BelowCharacter.cgFloat case .Player, .Loot, .Enemy: sprite.zPosition = LevelScene.WorldLayer.Character.cgFloat } sprite.position = CGPoint(x: gridX * level.squareSize, y: gridY * level.squareSize) sprite.name = name //Any special entry animation? if let initialAction = entryAction(forSprite: sprite, inLevel: level, atGridX: gridX, gridY: gridY){ sprite.runAction(initialAction) } //If we are something that should be overlayed over the ground then create a ground sprite //and yourself as a child switch self{ case .Empty, .Ground, .Wall: return sprite default: let groundSprite = MapSquare.Ground.spriteForSquare(inLevel: level, atGridX: gridX, gridY: gridY) sprite.position = CGPointZero groundSprite?.addChild(sprite) return groundSprite } } }
apache-2.0
6d66c4dbb111cb867e9d75d80af9d2fe
32.160377
177
0.594195
4.436869
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Class/FirstVC/Controllers/SwiftScan/SwiftScanViewController.swift
1
13559
// // SwiftScanViewController.swift // MyTools // // Created by gongrong on 2017/5/19. // Copyright © 2017年 zhangk. All rights reserved. // import UIKit class SwiftScanViewController: BaseViewController , UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate { var tableView: UITableView! var arrayItems:Array<Array<String>> = [ ["模拟qq扫码界面","qqStyle"], ["模仿支付宝扫码区域","ZhiFuBaoStyle"], ["模仿微信扫码区域","weixinStyle"], ["无边框,内嵌4个角","InnerStyle"], ["4个角在矩形框线上,网格动画","OnStyle"], ["自定义颜色","changeColor"], ["只识别框内","recoCropRect"], ["改变尺寸","changeSize"], ["条形码效果","notSquare"], ["二维码/条形码生成","myCode"], ["相册","openLocalPhotoAlbum"] ]; override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height)) self.title = "swift 扫一扫" tableView.delegate = self tableView.dataSource = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath) // Configure the cell... cell.textLabel?.text = arrayItems[indexPath.row].first return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //objc_msgSend对应方法好像没有 let sel = NSSelectorFromString(arrayItems[indexPath.row].last!) if responds(to: sel) { perform(sel) } tableView.deselectRow(at: indexPath as IndexPath, animated: true) } //MARK: ----模仿qq扫码界面--------- func qqStyle() { print("qqStyle") let vc = QQScanViewController(); var style = LBXScanViewStyle() style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") vc.scanStyle = style hidesBottomBarWhenPushed=true self.navigationController?.pushViewController(vc, animated: true) } //MARK: ---模仿支付宝------ func ZhiFuBaoStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 60; style.xScanRetangleOffset = 30; if UIScreen.main.bounds.size.height <= 480 { //3.5inch 显示的扫码缩小 style.centerUpOffset = 40; style.xScanRetangleOffset = 20; } style.color_NotRecoginitonArea = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.4) style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 2.0; style.photoframeAngleW = 16; style.photoframeAngleH = 16; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net") let vc = LBXScanViewController(); vc.scanStyle = style vc.arrayCodeType = LBXScanWrapper.defaultMetaDataObjectTypes() hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } func createImageWithColor(color:UIColor)->UIImage { let rect=CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0); UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); context!.setFillColor(color.cgColor); context!.fill(rect); let theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage!; } //MARK: -------条形码扫码界面 --------- func notSquare() { //设置扫码区域参数 //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 4; style.photoframeAngleW = 28; style.photoframeAngleH = 16; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineStill; style.animationImage = createImageWithColor(color: UIColor.red) //非正方形 //设置矩形宽高比 style.whRatio = 4.3/2.18; //离左边和右边距离 style.xScanRetangleOffset = 30; let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: ----无边框,内嵌4个角 ----- func InnerStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 3; style.photoframeAngleW = 18; style.photoframeAngleH = 18; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: ---无边框,内嵌4个角------ func weixinStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner; style.photoframeLineW = 2; style.photoframeAngleW = 18; style.photoframeAngleH = 18; style.isNeedShowRetangle = false; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0) style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_Scan_weixin_Line") let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: ----框内区域识别 func recoCropRect() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 80; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net") let vc = LBXScanViewController(); vc.scanStyle = style vc.isOpenInterestRect = true //TODO:待设置框内识别 hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: -----4个角在矩形框线上,网格动画 func OnStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net"); let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: -------自定义4个角及矩形框颜色 func changeColor() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green"); //4个角的颜色 style.colorAngle = UIColor(red: 65.0/255.0, green: 174.0/255.0, blue: 57.0/255.0, alpha: 1.0) //矩形框颜色 style.colorRetangleLine = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 1.0) //非矩形框区域颜色 style.color_NotRecoginitonArea = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 0.2) let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: ------改变扫码区域位置 func changeSize() { //设置扫码区域参数 var style = LBXScanViewStyle() //矩形框向上移动 style.centerUpOffset = 60; //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 100; style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On; style.photoframeLineW = 6; style.photoframeAngleW = 24; style.photoframeAngleH = 24; style.isNeedShowRetangle = true; style.anmiationStyle = LBXScanViewAnimationStyle.LineMove; //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController(); vc.scanStyle = style hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } //MARK: -------- 相册 func openLocalPhotoAlbum() { let picker = UIImagePickerController() picker.sourceType = UIImagePickerControllerSourceType.photoLibrary picker.delegate = self; // picker.allowsEditing = true present(picker, animated: true, completion: nil) } //MARK: -----相册选择图片识别二维码 (条形码没有找到系统方法) private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { picker.dismiss(animated: true, completion: nil) var image:UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage if (image == nil ) { image = info[UIImagePickerControllerOriginalImage] as? UIImage } if(image == nil) { return } if(image != nil) { let arrayResult = LBXScanWrapper.recognizeQRImage(image: image!) if arrayResult.count > 0 { let result = arrayResult[0]; showMsg(title: result.strBarCodeType, message: result.strScanned) return } } showMsg(title: "", message: "识别失败") } func showMsg(title:String?,message:String?) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "知道了", style: UIAlertActionStyle.default) { (alertAction) -> Void in } alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } func myCode() { let vc = MyCodeViewController() hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } }
mit
aa3885c6cb49c47765f9a5d224819fa5
29.985437
159
0.597446
5.155897
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/TableviewCells/Social/SystemMessageTableViewCell.swift
1
1075
// // SystemMessageTableViewCell.swift // Habitica // // Created by Phillip Thelen on 16.02.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import UIKit import Habitica_Models class SystemMessageTableViewCell: UITableViewCell { @IBOutlet weak var messageWrapper: UIView! @IBOutlet weak var messageTextView: UITextView! @IBOutlet weak var leftMarginConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() messageTextView.textContainerInset = UIEdgeInsets.zero } @objc func configure(chatMessage: ChatMessageProtocol) { messageTextView.text = chatMessage.text?.unicodeEmoji.replacingOccurrences(of: "`", with: "") applyTheme(theme: ThemeService.shared.theme) } func applyTheme(theme: Theme) { backgroundColor = theme.windowBackgroundColor contentView.backgroundColor = theme.windowBackgroundColor messageTextView.textColor = theme.tintColor messageWrapper.borderColor = theme.separatorColor } }
gpl-3.0
a0157696d6745cb6fd7dd00b4a990877
28.833333
101
0.708566
5.316832
false
false
false
false
priya273/stockAnalyzer
Stock Analyzer/Stock Analyzer/DeleteStockTableCell.swift
1
1029
// // DeleteStockTableCell.swift // Stock Analyzer // // Created by Naga sarath Thodime on 11/4/15. // Copyright © 2015 Priyadarshini Ragupathy. All rights reserved. // import UIKit class DeleteStockTableCell: UITableViewCell { @IBOutlet weak var labelSymbol: UILabel! @IBOutlet weak var labelName: UILabel! var symbol : String = "" { didSet { if(symbol != oldValue) { labelSymbol.text = symbol; } } } var name : String = "" { didSet { if(name != oldValue) { labelName.text = name; } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
dbdae4959dbf7fc16fb5b771f5a67859
18.396226
66
0.512646
4.715596
false
false
false
false
nicemohawk/nmf-ios
nmf/DataStore.swift
1
6999
// // DataStore.swift // nmf // // Created by Daniel Pagan on 4/15/16. // Copyright © 2017 Nelsonville Music Festival. All rights reserved. // import Foundation import SwiftSDK private let dataStoreSingleton = DataStore() //extension Fault : Error { // //} class DataStore: NSObject { static let archiveURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! lazy var scheduleItems: [ScheduleItem] = { NSKeyedUnarchiver.setClass(ScheduleItem.self, forClassName: "NMF.Schedule") return NSKeyedUnarchiver.unarchiveObject(withFile: DataStore.archiveURL.appendingPathComponent("schedule").path) as? [ScheduleItem] ?? [ScheduleItem]() }() lazy var artistItems: [Artist] = { NSKeyedUnarchiver.setClass(Artist.self, forClassName: "NMF.Artists") return NSKeyedUnarchiver.unarchiveObject(withFile: DataStore.archiveURL.appendingPathComponent("artists").path) as? [Artist] ?? [Artist]() }() class var sharedInstance: DataStore { return dataStoreSingleton } func saveData() { print( "saved schedule: \(NSKeyedArchiver.archiveRootObject(scheduleItems, toFile: DataStore.archiveURL.appendingPathComponent("schedule").path))") print("saved artists: \(NSKeyedArchiver.archiveRootObject(artistItems, toFile: DataStore.archiveURL.appendingPathComponent("artists").path))") } func updateScheduleItems(_ completion: @escaping (Error?) -> Void) -> Void { let backendless = Backendless.shared func pageAllScheduleData(queryBuilder: DataQueryBuilder) { backendless.data.of(ScheduleItem.self).find(queryBuilder: queryBuilder, responseHandler: { (scheduleItemsCollection: [Any]?) in if scheduleItemsCollection?.count != 0 { guard let items = scheduleItemsCollection as? [ScheduleItem] else { print("Unable to convert scheduleItemsCollection (type: \(type(of:scheduleItemsCollection?.first))) to \(type(of:ScheduleItem.self)) array.") return } self.mergeScheduleItems(items) queryBuilder.prepareNextPage() pageAllScheduleData(queryBuilder: queryBuilder) } else { // finished paging results completion(nil) } }, errorHandler: { (fault) in print(fault) completion(fault) }) } self.removeOldItems() let scheduleBuilder = DataQueryBuilder() scheduleBuilder.pageSize = 100 pageAllScheduleData(queryBuilder: scheduleBuilder) } func updateArtistItems(_ completion: @escaping (Error?) -> Void) -> Void { let backendless = Backendless.shared func pageAllArtistData(queryBuilder: DataQueryBuilder) { backendless.data.of(Artist.self).find( queryBuilder: queryBuilder, responseHandler: { (artistsItemsCollection: [Any]?) in if artistsItemsCollection?.count != 0 { guard let artists = artistsItemsCollection as? [Artist] else { print("unable to convert artistsItemsCollection to Artist array") return } // artists.forEach { $0.updated = true } self.mergeArtists(artists) queryBuilder.prepareNextPage() pageAllArtistData(queryBuilder: queryBuilder) } else { completion(nil) } }, errorHandler: { (fault) in print(fault) completion(fault) }) } let artistBuilder = DataQueryBuilder() artistBuilder.pageSize = 100 pageAllArtistData(queryBuilder: artistBuilder) } func getArtistByName(_ artistName: String, completion: @escaping (Artist?, Error?) -> Void) -> Void { let backendless = Backendless.shared let artistsQueryBuilder = DataQueryBuilder() artistsQueryBuilder.whereClause = "ArtistName = '\(artistName)'" backendless.data.of(Artist.self).find(queryBuilder: artistsQueryBuilder, responseHandler: { (artistsItemsCollection: [Any]?) in let foundArtist = artistsItemsCollection?.first as? Artist completion(foundArtist, nil) }, errorHandler: { (fault) in self.artistItems = [] print(fault) completion(nil, fault) }) } func removeOutOfDateScheduleItems() { // remove schedule items that have not been updated scheduleItems = scheduleItems.filter { item in if item._updated { item._updated = false return true } return false } } func removeOutOfDateArtists() { // remove artists that haven't been updated artistItems = artistItems.filter { item in if item._updated { item._updated = false return true } return false } } func removeOldItems() { let currentYear = Calendar.current.component(.year, from: Date()) var itemsToRemove = [ScheduleItem]() for item in scheduleItems { if let date = item.startTime, Calendar.current.component(.year, from: date) < currentYear { itemsToRemove.append(item) } } scheduleItems = scheduleItems.filter { itemsToRemove.contains($0) == false } } func mergeScheduleItems(_ newItems: [ScheduleItem]) { for newItem in newItems { var foundItem = false for item in scheduleItems where newItem.objectId == item.objectId { item.update(newItem) foundItem = true break } if foundItem == false { newItem._updated = true scheduleItems.append(newItem) } } } func mergeArtists(_ newArtists: [Artist]) { for newArtist in newArtists { var foundItem = false for artist in artistItems where newArtist.objectId == artist.objectId { artist.update(newArtist) foundItem = true break } if foundItem == false { newArtist._updated = true artistItems.append(newArtist) } } } }
apache-2.0
b9944fa9b5b6324e804708d140e0056d
33.136585
165
0.550872
5.817124
false
false
false
false
GraphKit/GraphKit
Sources/ManagedNode.swift
5
8953
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * 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 CoreData @objc(ManagedNode) internal class ManagedNode: ManagedObject { @NSManaged internal var nodeClass: Int @NSManaged internal var type: String @NSManaged internal var createdDate: Date @NSManaged internal var propertySet: Set<ManagedProperty> @NSManaged internal var tagSet: Set<ManagedTag> @NSManaged internal var groupSet: Set<ManagedGroup> /// A reference to the Nodes unique ID. var id: String { guard let moc = managedObjectContext else { fatalError("[Graph Error: Cannot obtain permanent objectID]") } return performAndWait { [unowned moc] `self` in do { try moc.obtainPermanentIDs(for: [self]) } catch let e as NSError { fatalError("[Graph Error: Cannot obtain permanent objectID - \(e.localizedDescription)]") } return "\(self.nodeClass)" + self.type + self.objectID.uriRepresentation().lastPathComponent } } /// A reference to the tags. var tags: [String] { return performAndWait { node in node.tagSet.map { $0.name } } ?? [] } /// A reference to the groups. var groups: [String] { return performAndWait { node in node.groupSet.map { $0.name } } ?? [] } /// A reference to the properties. internal var properties: [String: Any] { return performAndWait { node in node.propertySet.reduce(into: [String: Any]()) { $0[$1.name] = $1.object } } ?? [:] } /** Initializer that accepts an identifier, a type, and a NSManagedObjectContext. - Parameter identifier: A model identifier. - Parameter type: A reference to the Node type. - Parameter managedObjectContext: A reference to the NSManagedObejctContext. */ convenience init(identifier: String, type: String, managedObjectContext: NSManagedObjectContext) { self.init(entity: NSEntityDescription.entity(forEntityName: identifier, in: managedObjectContext)!, insertInto: managedObjectContext) self.type = type createdDate = Date() propertySet = [] tagSet = [] groupSet = [] } /** Adds a tag to the ManagedNode. - Parameter tag: An Array of Strings. */ internal func add(tags: [String]) { guard let moc = managedObjectContext else { return } performAndWait { [unowned moc] node in for name in tags { guard !node.has(tags: name) else { continue } Swift.type(of: self).createTag(name: name, node: node, managedObjectContext: moc) } } } /** Removes a tag from the ManagedNode. - Parameter tags: An Array of Strings. */ internal func remove(tags: [String]) { performAndWait { node in tags.forEach { name in node.tagSet.forEach { if let t = Swift.type(of: self).asTag($0), name == t.name { t.delete() } } } } } /** Adds the ManagedNode to a given group. - Parameter to groups: An Array of Strings. */ internal func add(to groups: [String]) { guard let moc = managedObjectContext else { return } performAndWait { [unowned moc] node in for name in groups { guard !node.member(of: name) else { continue } Swift.type(of: self).createGroup(name: name, node: node, managedObjectContext: moc) } } } /** Removes the ManagedNode from a given group. - Parameter from groups: An Array of Strings. */ internal func remove(from groups: [String]) { performAndWait { node in groups.forEach { name in node.groupSet.forEach { if let g = Swift.type(of: self).asGroup($0), name == g.name { g.delete() } } } } } /// Generic creation of the managed tag type. internal class func createTag(name: String, node: ManagedNode, managedObjectContext: NSManagedObjectContext) { fatalError("Must be implemented by subclasses") } /// Generic cast to the managed tag type. internal class func asTag(_ tag: ManagedTag) -> ManagedTag? { fatalError("Must be implemented by subclasses") } /// Generic creation of the managed group type. internal class func createGroup(name: String, node: ManagedNode, managedObjectContext: NSManagedObjectContext) { fatalError("Must be implemented by subclasses") } /// Generic cast to the managed group type. internal class func asGroup(_ group: ManagedGroup) -> ManagedGroup? { fatalError("Must be implemented by subclasses") } /// Generic creation of the managed property type. internal class func createProperty(name: String, object: Any, node: ManagedNode, managedObjectContext: NSManagedObjectContext) { fatalError("Must be implemented by subclasses") } /// Generic cast to the managed property type. internal class func asProperty(_ property: ManagedProperty) -> ManagedProperty? { fatalError("Must be implemented by subclasses") } /** Access properties using the subscript operator. - Parameter name: A property name value. - Returns: The optional Any value. */ subscript(name: String) -> Any? { get { return performAndWait { node in node.propertySet.first { $0.name == name }?.object } } set(value) { performAndWait { action in let property = action.propertySet.first { Swift.type(of: self).asProperty($0)?.name == name } guard let object = value else { property?.delete() return } guard let p = property else { guard let moc = managedObjectContext else { return } Swift.type(of: self).createProperty(name: name, object: object, node: action, managedObjectContext: moc) return } p.object = object } } } /** Checks if the ManagedNode has a given tag. - Parameter tag: A tag name. - Returns: A boolean of the result, true if has the given tag, false otherwise. */ func has(tags: String...) -> Bool { return has(tags: tags) } /** Checks if the ManagedNode has a the given tags. - Parameter tags: An Array of Strings. - Parameter using condition: A SearchCondition value. - Returns: A boolean of the result, true if has the tags, false otherwise. */ func has(tags: [String], using condition: SearchCondition = .and) -> Bool { let t = Set(self.tags) let tags = Set(tags) switch condition { case .and: return tags.isSubset(of: t) case .or: return tags.contains(where: t.contains) } } /** Checks if the ManagedNode is a member of a group. - Parameter of groups: A list of Strings. - Returns: A boolean of the result, true if a member, false otherwise. */ func member(of groups: String...) -> Bool { return member(of: groups) } /** Checks if the ManagedNode is a member of a group. - Parameter of groups: An Array of Strings. - Parameter using condition: A SearchCondition value. - Returns: A boolean of the result, true if a member, false otherwise. */ func member(of groups: [String], using condition: SearchCondition = .and) -> Bool { let g = Set(self.groups) let groups = Set(groups) switch condition { case .and: return groups.isSubset(of: g) case .or: return groups.contains(where: g.contains) } } } extension ManagedNode: Comparable { static public func ==(left: ManagedNode, right: ManagedNode) -> Bool { return left.id == right.id } public static func <(left: ManagedNode, right: ManagedNode) -> Bool { return left.id < right.id } }
agpl-3.0
86463ce3806e5424a411eaaaac19d553
28.943144
137
0.644253
4.416872
false
false
false
false
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Applications/Timetable/EditClassTableViewController.swift
1
19455
// // EditClassTableViewController.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 24/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import UIKit class EditClassTableViewController: UITableViewController, UITextFieldDelegate, AlertMessageDelegate, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var dayPicker: UIPickerView! @IBOutlet weak var notificationSwitch: UISwitch! @IBOutlet weak var timePicker: UIDatePicker! @IBOutlet weak var notifcationPicker: UIDatePicker! @IBOutlet weak var moduleName: UITextField! @IBOutlet weak var classRoom: UITextField! @IBOutlet weak var classLecture: UITextField! @IBOutlet weak var classGroups: UITextField! @IBOutlet weak var notificationLabel: UILabel! @IBOutlet weak var deleteLabel: UILabel! @IBOutlet weak var saveLabel: UILabel! var sectionTitles = [String]() var notificationPicked : Bool = false var timerPicked : Bool = false var dayPicked : Bool = false var indexPathSel : IndexPath? //var currentClass = Timetable() var allTimestables = [AllTimetables]() var dayNo : Int = 0 var updateDayNo : Int = 0 var notifOn : Int = 1 let database = Database() let notificationManager = NotificationManager() var classRow : Int = 0 var deleteClass : Bool = false var isEditMode = false var dayPickerDataSource = [String]() var connectivityHandler: ConnectivityHandler? override func viewDidLoad() { super.viewDidLoad() self.connectivityHandler = (UIApplication.shared.delegate as? AppDelegate)?.connectivityHandler self.updateDayNo = self.dayNo dayPickerDataSource.append("Monday") dayPickerDataSource.append("Tuesday") dayPickerDataSource.append("Wednesday") dayPickerDataSource.append("Thursday") dayPickerDataSource.append("Friday") dayPickerDataSource.append("Saturday") dayPickerDataSource.append("Sunday") sectionTitles.append("Class Details") sectionTitles.append(" ") //Notifications sectionTitles.append("Class Time") sectionTitles.append("Class Day") sectionTitles.append( " " ) //save sectionTitles.append( " " ) //delete self.tableView.tableFooterView = UIView() self.tableView.backgroundColor = UIColor.groupTableViewBackground //UIColor(red: 204/255, green: 204/255, blue: 204/255, alpha: 1.0) self.classLecture.delegate = self self.classRoom.delegate = self self.classGroups.delegate = self self.dayPicker.dataSource = self self.dayPicker.delegate = self var startTime = "00:00" var endTime = "00:00" let dayNo = self.dayPickerDataSource[self.dayNo] var notifHr = 0 var notifMin = 5 if self.classRow >= 0 { isEditMode = true let myClass = self.database.getClass(classID: self.allTimestables[self.dayNo].timetable[self.classRow].id) self.notificationPicked = ( myClass.notifOn > 0 ) self.updateDayNo = self.dayNo self.moduleName.text = self.allTimestables[self.dayNo].timetable[self.classRow].name self.classLecture.text = self.allTimestables[self.dayNo].timetable[self.classRow].lecture self.classRoom.text = self.allTimestables[self.dayNo].timetable[self.classRow].room self.classGroups.text = self.allTimestables[self.dayNo].timetable[self.classRow].groups startTime = self.allTimestables[self.dayNo].timetable[self.classRow].timeStart.convertToCurrentTimeFormat() endTime = self.allTimestables[self.dayNo].timetable[self.classRow].timeEnd.convertToCurrentTimeFormat() (notifHr, notifMin) = self.minToHoursMinutes(minutes: self.allTimestables[self.dayNo].timetable[self.classRow].notifOn ) } self.notificationSwitch.isOn = self.notificationPicked var indexPath = IndexPath(row: 0, section: 1 ) indexPath = IndexPath(row: 0, section: 2 ) var cell = self.tableView.cellForRow(at: indexPath) cell?.textLabel?.text = "Start" cell?.detailTextLabel?.text = startTime indexPath = IndexPath(row: 1, section: 2 ) cell = self.tableView.cellForRow(at: indexPath) cell?.textLabel?.text = "End" cell?.detailTextLabel?.text = endTime indexPath = IndexPath(row: 0, section: 3) cell = self.tableView.cellForRow(at: indexPath) cell?.textLabel?.text = dayNo let components = NSDateComponents() components.setValue(notifMin, forComponent: .minute) components.setValue(notifHr, forComponent: .hour) self.notifcationPicker.date = NSCalendar.current.date(from: components as DateComponents)! //self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func minToHoursMinutes (minutes : Int) -> (Int, Int) { return (minutes / 60, (minutes % 60)) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 6 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitles[section] } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows switch section { case 0 : return 4 case 1 : return ( self.notificationPicked == true ? 2 : 1 ) case 2 : return ( self.timerPicked == true ? 3 : 2 ) case 3 : return ( self.dayPicked == true ? 2 : 1) case 4 : return 1 case 5 : return 1 default : return 0 } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.indexPathSel = indexPath if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 0 { self.notificationPicked = ( self.notificationPicked == false ? true : false ) self.notificationSwitch.isOn = self.notificationPicked self.tableView.reloadData() } else if (indexPath as NSIndexPath).section == 2 && ( (indexPath as NSIndexPath).row == 0 || (indexPath as NSIndexPath).row == 1 ) { self.timerPicked = ( self.timerPicked == false ? true : false ) self.tableView.reloadData() } else if (indexPath as NSIndexPath).section == 3 && (indexPath as NSIndexPath).row == 0 { self.dayPicked = ( self.dayPicked == false ? true : false ) self.tableView.reloadData() } else if (indexPath as NSIndexPath).section == 4 && (indexPath as NSIndexPath).row == 0 { self.deleteCurrrentClass() } else if (indexPath as NSIndexPath).section == 5 && (indexPath as NSIndexPath).row == 0 { self.saveCurrentClass() } } @IBAction func timePicker(_ sender: AnyObject) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let strDate = dateFormatter.string(from: self.timePicker.date) let cell = self.tableView.cellForRow(at: self.indexPathSel!) cell?.detailTextLabel?.text = strDate } func sendClassToConnectivityHandler() { let today = Date() if(today.weekDayIndex() == self.dayNo) { if let connectivityHandler = self.connectivityHandler { var timetables = self.allTimestables[self.dayNo].timetable if(self.classRow < 0) { self.classRow = 0 } let timetable = self.allTimestables[self.dayNo].timetable[self.classRow] if(timetable.markDeleted) { timetables.remove(at: self.classRow) } let jsonObject = MyJSONMapper.toJSON(timetables: timetables) connectivityHandler.session.sendMessage(["refresh" : jsonObject], replyHandler: nil) { (error) in NSLog("%@", "Error sending message: \(error)") } } } } func saveCurrentClass() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" var indexPath = IndexPath(row: 0, section: 2 ) var cell = self.tableView.cellForRow(at: indexPath) let timeStart = (cell?.detailTextLabel?.text)!.convertTo24hrFomat() indexPath = IndexPath(row: 1, section: 2 ) cell = self.tableView.cellForRow(at: indexPath) let timeEnd = (cell?.detailTextLabel?.text)!.convertTo24hrFomat() indexPath = IndexPath(row: 0, section: 3) cell = self.tableView.cellForRow(at: indexPath) let dayIndex = self.dayPickerDataSource.index(of: cell!.textLabel!.text! ) let startTime = dateFormatter.date(from: timeStart) let endTime = dateFormatter.date(from: timeEnd) if startTime! < endTime! { var notifytime = 0 if self.notificationPicked { let hr = self.notifcationPicker.date.hour() let min = self.notifcationPicker.date.minute() notifytime = ( hr * 60) + min } if self.isEditMode { self.allTimestables[self.dayNo].timetable[self.classRow].name = self.moduleName.text! self.allTimestables[self.dayNo].timetable[self.classRow].lecture = self.classLecture.text! self.allTimestables[self.dayNo].timetable[self.classRow].room = self.classRoom.text! self.allTimestables[self.dayNo].timetable[self.classRow].groups = self.classGroups.text! self.allTimestables[self.dayNo].timetable[self.classRow].notifOn = notifytime self.allTimestables[self.dayNo].timetable[self.classRow].name = self.moduleName.text! self.allTimestables[self.dayNo].timetable[self.classRow].dayNo = self.updateDayNo self.allTimestables[self.dayNo].timetable[self.classRow].timeStart = timeStart self.allTimestables[self.dayNo].timetable[self.classRow].timeEnd = timeEnd self.allTimestables[self.dayNo].timetable[self.classRow].dayNo = dayIndex! self.database.updateTimetable(timetable: self.allTimestables[self.dayNo].timetable[self.classRow]) //if day changed then delete previous and add new if dayIndex != self.dayNo { PrintLn.strLine(functionName: "changeClassDay", message: dayNo) self.allTimestables[self.dayNo].timetable[self.classRow].dayNo = dayNo self.allTimestables[self.dayNo].timetable[self.classRow].markDeleted = true self.updateDayNo = dayNo let classChange = Timetable() classChange.id = self.allTimestables[self.dayNo].timetable[self.classRow].id classChange.groups = self.classGroups.text! classChange.lecture = self.classLecture.text! classChange.name = self.moduleName.text! classChange.notifOn = notifytime classChange.timeStart = timeStart classChange.timeEnd = timeEnd classChange.weeks = self.allTimestables[self.dayNo].timetable[self.classRow].weeks classChange.markDeleted = false classChange.dayNo = dayIndex! self.allTimestables[dayIndex!].timetable.append(classChange) } } else { let curTimetable = Class() curTimetable.id = -1 curTimetable.day = self.updateDayNo curTimetable.name = self.moduleName.text ?? "" curTimetable.lecture = self.classLecture.text ?? "" curTimetable.room = self.classRoom.text ?? "" curTimetable.timeStart = timeStart curTimetable.timeEnd = timeEnd curTimetable.weeks = "" curTimetable.groups = self.classGroups.text ?? "" curTimetable.notifOn = notifytime let id = self.database.saveClass( myClass: curTimetable) let newClass = Timetable() newClass.id = id newClass.lecture = curTimetable.lecture newClass.timeStart = curTimetable.timeStart newClass.timeEnd = curTimetable.timeEnd newClass.dayNo = curTimetable.day newClass.name = curTimetable.name newClass.groups = curTimetable.groups newClass.room = curTimetable.room newClass.notifOn = notifytime self.allTimestables[self.dayNo].timetable.append(newClass) } self.sendClassToConnectivityHandler() self.updateNotifications() //self.updateClass = true self.performSegue(withIdentifier: "unwindSegue", sender: self) } else { let showAlert = ShowAlert() showAlert.alertDelegate = self let messageArr = ["OK"] let timeErrorMessage = "End time is less than start time" showAlert.presentAlert(curView: self, title: "Error", message: timeErrorMessage, buttons: messageArr) } } func updateNotifications() { self.notificationManager.cancelAllNotifications() self.notificationManager.createAllNotifications(myTimetable: self.allTimestables) } func deleteCurrrentClass() { self.database.deleteClass( classID: self.allTimestables[self.dayNo].timetable[self.classRow].id) self.deleteClass = true self.allTimestables[self.dayNo].timetable[self.classRow].markDeleted = true self.updateNotifications() self.sendClassToConnectivityHandler() self.performSegue(withIdentifier: "unwindSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindSegue" { PrintLn.strLine(functionName: "segue", message: "going back") if let destinationVC = segue.destination as? DayTableViewController { destinationVC.dayTimetable = self.allTimestables } } } func deleteBreaks() { if self.allTimestables.count > 0 { for index in (0...self.allTimestables.count-1).reversed() { if self.allTimestables[self.dayNo].timetable[index].id == -1 { print("Delete") print(index) self.allTimestables.remove(at: index) } } } /*if self.dayTimetable.count > 1 { self.checkForBreaks() } else { self.tableView.reloadData() }*/ } // override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // // // let cell = tableView.dequeueReusableCell(withIdentifier: "editCell", for: indexPath) // // cell.contentView.backgroundColor = UIColor.black // return cell // } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension EditClassTableViewController { // MARK: UIPickerView DataSource and Delegate Methods @objc(numberOfComponentsInPickerView:) func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.dayPickerDataSource.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let cell = self.tableView.cellForRow(at: indexPathSel!) cell?.textLabel?.text = self.dayPickerDataSource[row] self.dayPicked = false self.tableView.reloadData() } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.dayPickerDataSource[row] } } extension EditClassTableViewController { //MARK: - TextView Delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } } //MARK : AlertMessageDelegate extension EditClassTableViewController { func buttonPressRequest(result: Int) { } }
mit
d41d9c9e119b3beb37e06778602c97d4
36.996094
148
0.599722
5.306601
false
false
false
false
AlexanderMazaletskiy/RealmObjectEditor
Realm Object Editor/Document.swift
1
2550
// // Document.swift // Realm Object Editor // // Created by Ahmed Ali on 12/26/14. // Copyright (c) 2014 Ahmed Ali. All rights reserved. // import Cocoa class Document: NSDocument { var vc : EditorViewController! var windowController: NSWindowController! var entities = [EntityDescriptor]() override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) // Add any code here that needs to be executed once the windowController has loaded the document's window. } override class func autosavesInPlace() -> Bool { return true } override func makeWindowControllers() { // Returns the Storyboard that contains your Document window. let storyboard = NSStoryboard(name: "Main", bundle: nil) windowController = storyboard.instantiateControllerWithIdentifier("Editor Window Controller") as! NSWindowController if let v = windowController.contentViewController as? EditorViewController{ vc = v vc.entities = entities } self.addWindowController(windowController) } override func dataOfType(typeName: String) throws -> NSData { var outError: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil) var arrayOfDictionaries = [NSDictionary]() for entityObject in vc.entities{ let entity = entityObject as EntityDescriptor arrayOfDictionaries.append(entity.toDictionary()) } let data: NSData? do { data = try NSJSONSerialization.dataWithJSONObject(arrayOfDictionaries, options: []) } catch let error as NSError { outError = error data = nil } if let value = data { return value } throw outError } override func readFromData(data: NSData, ofType typeName: String) throws { let outError: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil) if let arrayOfDictionaries = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [NSDictionary]{ for dictionary in arrayOfDictionaries{ entities.append(EntityDescriptor(dictionary: dictionary)) } return } throw outError } }
mit
24e6faec5e5f56dc6607f905fdef17cb
28.651163
124
0.623922
5.543478
false
false
false
false
allenngn/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
90679
/* 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 Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire private let log = XCGLogger.defaultInstance() private let OKString = NSLocalizedString("OK", comment: "OK button") private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button") private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let KVOURL = "URL" private let KVOCanGoBack = "canGoBack" private let KVOCanGoForward = "canGoForward" private struct BrowserViewControllerUX { private static let BackgroundColor = UIConstants.AppBackgroundColor private static let ShowHeaderTapAreaHeight: CGFloat = 32 private static let BookmarkStarAnimationDuration: Double = 0.5 private static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { private var urlBar: URLBarView! private var readerModeBar: ReaderModeBarView? private var statusBarOverlay: UIView! private var toolbar: BrowserToolbar? private var homePanelController: HomePanelViewController? private var searchController: SearchViewController? private var webViewContainer: UIView! private let uriFixup = URIFixup() private var screenshotHelper: ScreenshotHelper! private var homePanelIsInline = false private var searchLoader: SearchLoader! private let snackBars = UIView() private let auralProgress = AuralProgressBar() // location label actions private var pasteGoAction: AccessibleAction! private var pasteAction: AccessibleAction! private var copyAddressAction: AccessibleAction! private weak var tabTrayController: TabTrayController! private let profile: Profile private let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them private var header: UIView! private var footer: UIView! private var footerBackground: UIView! private var topTouchArea: UIButton! private var scrollController = BrowserScrollingController() private var keyboardState: KeyboardState? let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"] // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: BrowserToolbarProtocol { return toolbar ?? urlBar } init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager super.init(nibName: nil, bundle: nil) didInit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } private func didInit() { screenshotHelper = BrowserScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override func preferredStatusBarStyle() -> UIStatusBarStyle { if header == nil { return UIStatusBarStyle.LightContent } if header.transform.ty == 0 { return UIStatusBarStyle.LightContent } return UIStatusBarStyle.Default } func shouldShowToolbarForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .Compact && previousTraitCollection.horizontalSizeClass != .Regular } private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) { let showToolbar = shouldShowToolbarForTraitCollection(newCollection) urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.browserToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = BrowserToolbar() toolbar?.browserToolbarDelegate = self footerBackground = wrapInEffect(toolbar!, parent: footer) } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading ?? false) } } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) updateToolbarStateForTraitCollection(newCollection) // WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user // performs a device rotation. Since scrolling calls // _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430) // this method nudges the web view's scroll view by a single pixel to force it to invalidate. if let scrollView = self.tabManager.selectedTab?.webView?.scrollView { let contentOffset = scrollView.contentOffset coordinator.animateAlongsideTransition({ context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true) self.scrollController.showToolbars(animated: false) }, completion: { context in scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false) }) } } func SELstatusBarFrameWillChange(notification: NSNotification) { if let statusBarFrame = notification.userInfo![UIApplicationStatusBarFrameUserInfoKey] as? NSValue { scrollController.showToolbars(animated: false) self.view.setNeedsUpdateConstraints() } } func SELtappedTopArea() { scrollController.showToolbars(animated: true) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELstatusBarFrameWillChange:", name: UIApplicationWillChangeStatusBarFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainer = UIView() view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.setTranslatesAutoresizingMaskIntoConstraints(false) urlBar.delegate = self urlBar.browserToolbarDelegate = self header = wrapInEffect(urlBar, parent: view, backgroundColor: nil) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.generalPasteboard().string { self.urlBar.updateURLBarText(pasteboardContents) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let urlString = self.urlBar.currentURL?.absoluteString { UIPasteboard.generalPasteboard().string = urlString } return true }) searchLoader = SearchLoader(history: profile.history, urlBar: urlBar) footer = UIView() self.view.addSubview(footer) footer.addSubview(snackBars) snackBars.backgroundColor = UIColor.clearColor() scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer self.updateToolbarStateForTraitCollection(self.traitCollection) } func loadQueuedTabs() { log.debug("Loading queued tabs.") // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. self.profile.queue.getQueuedTabs() >>== { c in log.debug("Queue. Count: \(c.count).") if c.count > 0 { var urls = [NSURL]() for (let r) in c { if let url = r?.url.asURL { log.debug("Queuing \(url).") urls.append(url) } } if !urls.isEmpty { dispatch_async(dispatch_get_main_queue()) { self.tabManager.addTabsForURLs(urls, zombie: false) } } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } } func startTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning() } func stopTrackingAccessibilityStatus() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil) auralProgress.hidden = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the browser so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0 } if tabManager.count == 0 && !AppConstants.IsRunningTest { // If we previously crashed, ask the user if they want to restore their tabs if FXCrashDetector.sharedDetector().hasCrashed() { let crashData = FXCrashDetector.sharedDetector().crashData as FXCrashDetectorData crashData.clearPreviousCrash() let alertView = UIAlertView( title: CrashPromptMessaging.CrashPromptTitle, message: CrashPromptMessaging.CrashPromptDescription, delegate: self, cancelButtonTitle: CrashPromptMessaging.CrashPromptNegative, otherButtonTitles: CrashPromptMessaging.CrashPromptAffirmative) alertView.show() } else { tabManager.restoreTabs() } } // If restoring tabs failed, was disabled, there was nothing to restore, or we're running tests, // create an initial about:home tab. if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } override func viewDidAppear(animated: Bool) { startTrackingAccessibilityStatus() presentIntroViewController() super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { stopTrackingAccessibilityStatus() } override func updateViewConstraints() { super.updateViewConstraints() statusBarOverlay.snp_remakeConstraints { make in make.left.right.equalTo(self.view) make.height.equalTo(UIApplication.sharedApplication().statusBarFrame.height) make.bottom.equalTo(header.snp_top) } topTouchArea.snp_remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } urlBar.snp_remakeConstraints { make in make.edges.equalTo(self.header) } header.snp_remakeConstraints { make in let topLayoutGuide = self.topLayoutGuide as! UIView scrollController.headerTopConstraint = make.top.equalTo(topLayoutGuide.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } header.setNeedsUpdateConstraints() readerModeBar?.snp_remakeConstraints { make in make.top.equalTo(self.header.snp_bottom).constraint make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp_remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp_bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp_bottom) } if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp_top) } else { make.bottom.equalTo(self.view) } } // Setup the bottom toolbar toolbar?.snp_remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(UIConstants.ToolbarHeight) } footer.snp_remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint make.top.equalTo(self.snackBars.snp_top) make.leading.trailing.equalTo(self.view) } adjustFooterSize(top: nil) footerBackground?.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(UIConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp_remakeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } else { make.bottom.equalTo(self.view.snp_bottom) } } } private func wrapInEffect(view: UIView, parent: UIView) -> UIView { return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor()) } private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView { let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) effect.setTranslatesAutoresizingMaskIntoConstraints(false) if let background = backgroundColor { view.backgroundColor = backgroundColor } effect.addSubview(view) parent.addSubview(effect) return effect } private func showHomePanelController(#inline: Bool) { homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 view.addSubview(homePanelController!.view) addChildViewController(homePanelController!) } var panelNumber = tabManager.selectedTab?.url?.fragment var numberArray = panelNumber?.componentsSeparatedByString("=") homePanelController?.selectedButtonIndex = numberArray?.last?.toInt() ?? 0 // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true self.stopTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) toolbar?.hidden = !inline view.setNeedsUpdateConstraints() } private func hideHomePanelController() { if let controller = homePanelController { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { finished in if finished { controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false self.toolbar?.hidden = false self.startTrackingAccessibilityStatus() UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active { self.showReaderModeBar(animated: false) } } }) } } private func updateInContentHomePanel(url: NSURL?) { if !urlBar.isEditing { if AboutUtils.isAboutHomeURL(url){ showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false)) } else { hideHomePanelController() } } } private func showSearchController() { if searchController != nil { return } urlBar.locationView.inputMode = .Search searchController = SearchViewController() searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true addChildViewController(searchController!) } private func hideSearchController() { if let searchController = searchController { searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil urlBar.locationView.inputMode = .URL homePanelController?.view?.hidden = false } } private func finishEditingAndSubmit(var url: NSURL, visitType: VisitType) { urlBar.currentURL = url urlBar.finishEditing() if let tab = tabManager.selectedTab, let nav = tab.loadRequest(NSURLRequest(URL: url)) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(url: String, title: String?) { let shareItem = ShareItem(url: url, title: title, favicon: nil) profile.bookmarks.shareItem(shareItem) animateBookmarkStar() // Dispatch to the main thread to update the UI dispatch_async(dispatch_get_main_queue()) { _ in self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } private func animateBookmarkStar() { let offset: CGFloat let button: UIButton! if let toolbar: BrowserToolbar = self.toolbar { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1 button = toolbar.bookmarkButton } else { offset = BrowserViewControllerUX.BookmarkStarAnimationOffset button = self.urlBar.bookmarkButton } let offToolbar = CGAffineTransformMakeTranslation(0, offset) UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: nil, animations: { () -> Void in button.transform = offToolbar var rotation = CABasicAnimation(keyPath: "transform.rotation") rotation.toValue = CGFloat(M_PI * 2.0) rotation.cumulative = true rotation.duration = BrowserViewControllerUX.BookmarkStarAnimationDuration + 0.075 rotation.repeatCount = 1.0 rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70 ,0.18 ,1.00) button.imageView?.layer.addAnimation(rotation, forKey: "rotateStar") }, completion: { finished in UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: nil, animations: { () -> Void in button.transform = CGAffineTransformIdentity }, completion: nil) }) } private func removeBookmark(url: String) { profile.bookmarks.removeByURL(url).uponQueue(dispatch_get_main_queue()) { res in if res.isSuccess { self.toolbar?.updateBookmarkStatus(false) self.urlBar.updateBookmarkStatus(false) } } } func SELBookmarkStatusDidChange(notification: NSNotification) { if let bookmark = notification.object as? BookmarkItem { if bookmark.url == urlBar.currentURL?.absoluteString { if let userInfo = notification.userInfo as? Dictionary<String, Bool>{ if let added = userInfo["added"]{ self.toolbar?.updateBookmarkStatus(added) self.urlBar.updateBookmarkStatus(added) } } } } } override func accessibilityPerformEscape() -> Bool { if urlBar.canCancel { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { let webView = object as! WKWebView if webView !== tabManager.selectedTab?.webView { return } switch keyPath { case KVOEstimatedProgress: let progress = change[NSKeyValueChangeNewKey] as! Float urlBar.updateProgressBar(progress) // when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running if progress != 1.0 || tabManager.selectedTab?.loading ?? false { auralProgress.progress = Double(progress) } case KVOLoading: let loading = change[NSKeyValueChangeNewKey] as! Bool toolbar?.updateReloadStatus(loading) urlBar.updateReloadStatus(loading) auralProgress.progress = loading ? 0 : nil case KVOURL: if let tab = tabManager.selectedTab where tab.webView === webView { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } updateInContentHomePanel(tab.url) } case KVOCanGoBack: let canGoBack = change[NSKeyValueChangeNewKey] as! Bool navigationToolbar.updateBackStatus(canGoBack) case KVOCanGoForward: let canGoForward = change[NSKeyValueChangeNewKey] as! Bool navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath)") } } private func isWhitelistedUrl(url: NSURL) -> Bool { for entry in WhiteListedUrls { if let match = url.absoluteString!.rangeOfString(entry, options: .RegularExpressionSearch) { return UIApplication.sharedApplication().canOpenURL(url) } } return false } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. private func updateURLBarDisplayURL(tab: Browser) { urlBar.currentURL = tab.displayURL let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false navigationToolbar.updatePageStatus(isWebPage: isPage) if let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.navigationToolbar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } } func openURLInNewTab(url: NSURL) { let tab = tabManager.addTab(request: NSURLRequest(URL: url)) tabManager.selectTab(tab) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(tab: Browser, navigation: WKNavigation?) -> VisitType? { if let navigation = navigation { if let ignored = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link } else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.Link } } } extension BrowserViewController: URLBarDelegate { func urlBarDidPressReload(urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(urlBar: URLBarView) { let tabTrayController = TabTrayController() tabTrayController.profile = profile tabTrayController.tabManager = tabManager tabTrayController.transitioningDelegate = self tabTrayController.modalPresentationStyle = .Custom if let tab = tabManager.selectedTab { tab.screenshot = screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1) } presentViewController(tabTrayController, animated: true, completion: nil) self.tabTrayController = tabTrayController } func dismissTabTrayController(#animated: Bool, completion: () -> Void) { if let tabTrayController = tabTrayController { tabTrayController.dismissViewControllerAnimated(animated) { completion() self.tabTrayController = nil } } } func urlBarDidPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool { if let tab = tabManager.selectedTab, url = tab.displayURL, absoluteString = url.absoluteString, result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) { switch result { case .Success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .Failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) log.error("readingList.createRecordWithURL(url: \"\(absoluteString)\", ...) failed with error: \(error)") } return true } UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.generalPasteboard().string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDidLongPressLocation(urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .Default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in }) longPressAlertController.addAction(cancelAction) if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true) } } } func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(urlBar: URLBarView, didSubmitText text: String) { var url = uriFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) } // If we still don't have a valid URL, something is broken. Give up. if url == nil { log.error("Error handling URL entry: \"\(text)\".") return } finishEditingAndSubmit(url!, visitType: VisitType.Typed) } func urlBarDidBeginEditing(urlBar: URLBarView) { // Pass the edit message along if we are already showing the home panel if let homePanelController = self.homePanelController where homePanelController.view.alpha == 1 { homePanelController.endEditing(nil) } else { showHomePanelController(inline: false) } } func urlBarDidEndEditing(urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.backList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { // See 1159373 - Disable long press back/forward for backforward list // let controller = BackForwardListViewController() // controller.listData = tabManager.selectedTab?.forwardList // controller.tabManager = tabManager // presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { isBookmarked in if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } }, failure: { err in log.error("Bookmark error: \(err).") } ) } else { log.error("Bookmark error: No tab is selected, or no URL in tab.") } } func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { } func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let selected = tabManager.selectedTab { if let url = selected.displayURL { var activityViewController = UIActivityViewController(activityItems: [selected.title ?? url.absoluteString!, url], applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari activityViewController.excludedActivityTypes = [UIActivityTypeAddToReadingList] activityViewController.completionWithItemsHandler = { _, completed, _, _ in if completed { if let selectedTab = self.tabManager.selectedTab { // We don't know what share action the user has chosen so we simply always // update the toolbar and reader mode bar to refelect the latest status. self.updateURLBarDisplayURL(selectedTab) self.updateReaderModeBar() } } } if let popoverPresentationController = activityViewController.popoverPresentationController { // Using the button for the sourceView here results in this not showing on iPads. popoverPresentationController.sourceView = toolbar ?? urlBar popoverPresentationController.sourceRect = button.frame ?? button.frame popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up popoverPresentationController.delegate = self } presentViewController(activityViewController, animated: true, completion: nil) } } } } extension BrowserViewController: BrowserDelegate { func browser(browser: Browser, didCreateWebView webView: WKWebView) { webViewContainer.insertSubview(webView, atIndex: 0) webView.snp_makeConstraints { make in make.edges.equalTo(self.webViewContainer) } // Observers that live as long as the tab. Make sure these are all cleared // in willDeleteWebView below! webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil) webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil) webView.UIDelegate = self let readerMode = ReaderMode(browser: browser) readerMode.delegate = self browser.addHelper(readerMode, name: ReaderMode.name()) let favicons = FaviconManager(browser: browser, profile: profile) browser.addHelper(favicons, name: FaviconManager.name()) // Temporarily disable password support until the new code lands let logins = LoginsHelper(browser: browser, profile: profile) browser.addHelper(logins, name: LoginsHelper.name()) let contextMenuHelper = ContextMenuHelper(browser: browser) contextMenuHelper.delegate = self browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() browser.addHelper(errorHelper, name: ErrorPageHelper.name()) } func browser(browser: Browser, willDeleteWebView webView: WKWebView) { webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) webView.removeObserver(self, forKeyPath: KVOLoading) webView.removeObserver(self, forKeyPath: KVOURL) webView.removeObserver(self, forKeyPath: KVOCanGoBack) webView.removeObserver(self, forKeyPath: KVOCanGoForward) webView.UIDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } private func findSnackbar(barToFind: SnackBar) -> Int? { let bars = snackBars.subviews for (index, bar) in enumerate(bars) { if bar === barToFind { return index } } return nil } private func adjustFooterSize(top: UIView? = nil) { snackBars.snp_remakeConstraints({ make in let bars = self.snackBars.subviews // if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom if bars.count > 0 { let view = bars[bars.count-1] as! UIView make.top.equalTo(view.snp_top) if let state = keyboardState { make.bottom.equalTo(-(state.intersectionHeightForView(self.view))) } else { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } } else { make.top.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } if traitCollection.horizontalSizeClass != .Regular { make.leading.trailing.equalTo(self.footer) self.snackBars.layer.borderWidth = 0 } else { make.centerX.equalTo(self.footer) make.width.equalTo(SnackBarUX.MaxWidth) self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor self.snackBars.layer.borderWidth = 1 } }) } // This removes the bar from its superview and updates constraints appropriately private func finishRemovingBar(bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints. if let index = findSnackbar(bar) { // If the bar being removed isn't on the top of the list let bars = snackBars.subviews if index < bars.count-1 { // Move the bar above this one var nextbar = bars[index+1] as! SnackBar nextbar.snp_updateConstraints { make in // If this wasn't the bottom bar, attach to the bar below it if index > 0 { let bar = bars[index-1] as! SnackBar nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint } else { // Otherwise, we attach it to the bottom of the snackbars nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint } } } } // Really remove the bar bar.removeFromSuperview() } private func finishAddingBar(bar: SnackBar) { snackBars.addSubview(bar) bar.snp_remakeConstraints({ make in // If there are already bars showing, add this on top of them let bars = self.snackBars.subviews // Add the bar on top of the stack // We're the new top bar in the stack, so make sure we ignore ourself if bars.count > 1 { let view = bars[bars.count - 2] as! UIView bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint } else { bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint } make.leading.trailing.equalTo(self.snackBars) }) } func showBar(bar: SnackBar, animated: Bool) { finishAddingBar(bar) adjustFooterSize(top: bar) bar.hide() view.layoutIfNeeded() UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.show() self.view.layoutIfNeeded() }) } func removeBar(bar: SnackBar, animated: Bool) { let index = findSnackbar(bar)! UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.hide() self.view.layoutIfNeeded() }) { success in // Really remove the bar self.finishRemovingBar(bar) // Adjust the footer size to only contain the bars self.adjustFooterSize() } } func removeAllBars() { let bars = snackBars.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.adjustFooterSize() } func browser(browser: Browser, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url, visitType: VisitType.Typed) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines let navController = UINavigationController(rootViewController: settingsNavigationController) self.presentViewController(navController, animated: true, completion: nil) } func searchViewControllerWillAppear(searchViewController: SearchViewController) { self.urlBar.locationView.editTextField.becomeFirstResponder() } } extension BrowserViewController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil // due to screwy handling within iOS, the scrollToTop handling does not work if there are // more than one scroll view in the view hierarchy // we therefore have to hide all the scrollViews that we are no actually interesting in interacting with // to ensure that scrollsToTop actually works wv.scrollView.hidden = true } if let tab = selected, webView = tab.webView { // if we have previously hidden this scrollview in order to make scrollsToTop work then // we should ensure that it is not hidden now that it is our foreground scrollView if webView.scrollView.hidden { webView.scrollView.hidden = false } updateURLBarDisplayURL(tab) scrollController.browser = selected webViewContainer.addSubview(webView) webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if let url = webView.URL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in log.error("Error getting bookmark status: \(err).") }) } else { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. webView.reload() } } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.url) } func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool) { // If we are restoring tabs then we update the count once at the end if !restoring { urlBar.updateTabCount(tabManager.count) } tab.browserDelegate = self } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(tabManager.count) // browserDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. } func tabManagerDidAddTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } func tabManagerDidRestoreTabs(tabManager: TabManager) { urlBar.updateTabCount(tabManager.count) } private func isWebPage(url: NSURL) -> Bool { let httpSchemes = ["http", "https"] if let scheme = url.scheme, index = find(httpSchemes, scheme) { return true } return false } } extension BrowserViewController: WKNavigationDelegate { func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.URL { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } } } private func openExternal(url: NSURL, prompt: Bool = true) { if prompt { // Ask the user if it's okay to open the url with UIApplication. let alert = UIAlertController( title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url), message: NSLocalizedString("This will open in another application", comment: "Opening an external app"), preferredStyle: UIAlertControllerStyle.Alert ) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction!) in })) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } else { UIApplication.sharedApplication().openURL(url) } } private func callExternal(url: NSURL) { if let phoneNumber = url.resourceSpecifier?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url) })) presentViewController(alert, animated: true, completion: nil) } } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.URL { if let scheme = url.scheme { switch scheme { case "about", "http", "https": if isWhitelistedUrl(url) { // If the url is whitelisted, we open it without prompting. openExternal(url, prompt: false) decisionHandler(WKNavigationActionPolicy.Cancel) } else { decisionHandler(WKNavigationActionPolicy.Allow) } case "tel": callExternal(url) decisionHandler(WKNavigationActionPolicy.Cancel) default: if UIApplication.sharedApplication().canOpenURL(url) { openExternal(url) } decisionHandler(WKNavigationActionPolicy.Cancel) } } } else { decisionHandler(WKNavigationActionPolicy.Cancel) } } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest { if let tab = tabManager[webView] { let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in if let credentials = res.successValue { completionHandler(.UseCredential, credentials.credentials) } else { completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil) } } } } else { completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil) } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let tab: Browser! = tabManager[webView] tab.expireSnackbars() if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = tab.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) // The screenshot immediately after didFinishNavigation is actually a screenshot of the // previous page, presumably due to some iOS bug. Adding a small delay seems to fix this, // and the current page gets captured as expected. let time = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * NSEC_PER_MSEC)) dispatch_after(time, dispatch_get_main_queue()) { if webView.URL != url { // The page changed during the delay, so we missed our chance to get a thumbnail. return } if let screenshot = self.screenshotHelper.takeScreenshot(tab, aspectRatio: CGFloat(ThumbnailCellUX.ImageAspectRatio), quality: 0.5) { let thumbnail = Thumbnail(image: screenshot) self.profile.thumbnails.set(url, thumbnail: thumbnail, complete: nil) } } // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } } } extension BrowserViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if let currentTab = tabManager.selectedTab { currentTab.screenshot = screenshotHelper.takeScreenshot(currentTab, aspectRatio: 0, quality: 1) } // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let tab = tabManager.addTab(request: navigationAction.request, configuration: configuration) tabManager.selectTab(tab) return tab.webView } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript alerts. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler() })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript confirm dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(false) })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String!) -> Void) { tabManager.selectTab(tabManager[webView]) // Show JavaScript input dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert) var input: UITextField! alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField!) in textField.text = defaultText input = textField }) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(input.text) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(nil) })) presentViewController(alertController, animated: true, completion: nil) } /// Invoked when an error occurs during a committed main frame navigation. func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { return } // Ignore the "Plug-in handled load" error. Which is more like a notification than an error. // Note that there are no constants in the SDK for the WebKit domain or error codes. if error.domain == "WebKitErrorDomain" && error.code == 204 { return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) { if let browser = tabManager[webView] where browser === tabManager.selectedTab { urlBar.currentURL = browser.displayURL } return } if let url = error.userInfo?["NSErrorFailingURLKey"] as? NSURL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) } } func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) { if navigationResponse.canShowMIMEType { decisionHandler(WKNavigationResponsePolicy.Allow) return } let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView) decisionHandler(WKNavigationResponsePolicy.Allow) } } extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === browser { log.debug("New readerModeState: \(state.rawValue)") urlBar.updateReaderModeState(state) } } func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) { self.showReaderModeBar(animated: true) browser.showContent(animated: true) } // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } } extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:AnyObject] = style.encode() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } } extension BrowserViewController : UIViewControllerTransitioningDelegate { func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: false) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: true) } } extension BrowserViewController : Transitionable { private func headerTransformToCellFrame(frame: CGRect) -> CGAffineTransform { let scale = frame.size.width / header.frame.size.width // Since the scale will happen in the center of the frame, we move this so the centers of the two frames overlap. let tx = frame.origin.x + frame.width/2 - (header.frame.origin.x + header.frame.width/2) let ty = frame.origin.y - header.frame.origin.y * scale * 2 // Move this up a little actually keeps it above the web page. I'm not sure what you want var transform = CGAffineTransformMakeTranslation(tx, ty) return CGAffineTransformScale(transform, scale, scale) } private func footerTransformToCellFrame(frame: CGRect) -> CGAffineTransform { let tx = frame.origin.x + frame.width/2 - (footer.frame.origin.x + footer.frame.width/2) var footerTransform = CGAffineTransformMakeTranslation(tx, -footer.frame.origin.y + frame.origin.y + frame.size.height - footer.frame.size.height) let footerScale = frame.size.width / footer.frame.size.width return CGAffineTransformScale(footerTransform, footerScale, footerScale) } func transitionablePreHide(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = true } } self.homePanelController?.view.hidden = true } func transitionablePreShow(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = true } } // Move over the transforms to reflect where the opening tab is coming from instead of where the previous tab was if let frame = options.cellFrame { header.transform = CGAffineTransformIdentity footer.transform = CGAffineTransformIdentity header.transform = headerTransformToCellFrame(frame) footer.transform = footerTransformToCellFrame(frame) } self.homePanelController?.view.hidden = true } func transitionableWillShow(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 1 header.transform = CGAffineTransformIdentity footer.transform = CGAffineTransformIdentity } func transitionableWillHide(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 0 if let frame = options.cellFrame { header.transform = headerTransformToCellFrame(frame) footer.transform = footerTransformToCellFrame(frame) } } func transitionableWillComplete(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's back on screen for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.hidden = false } } self.homePanelController?.view.hidden = false if options.toView === self { startTrackingAccessibilityStatus() } else { stopTrackingAccessibilityStatus() } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(#animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRectZero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(#animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView, let backList = webView.backForwardList.backList as? [WKBackForwardListItem], let forwardList = webView.backForwardList.forwardList as? [WKBackForwardListItem] { if let currentURL = webView.backForwardList.currentItem?.URL { if let readerModeURL = ReaderModeUtils.encodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == readerModeURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL { webView.goToBackForwardListItem(forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { ReaderModeCache.sharedInstance.put(currentURL, readabilityResult, error: nil) if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } } } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList as! [WKBackForwardListItem] let forwardList = webView.backForwardList.forwardList as! [WKBackForwardListItem] if let currentURL = webView.backForwardList.currentItem?.URL { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == originalURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == originalURL { webView.goToBackForwardListItem(forwardList.first!) } else { if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .Settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover let popoverPresentationController = readerModeStyleViewController.popoverPresentationController popoverPresentationController?.backgroundColor = UIColor.whiteColor() popoverPresentationController?.delegate = self popoverPresentationController?.sourceView = readerModeBar popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up self.presentViewController(readerModeStyleViewController, animated: true, completion: nil) } case .MarkAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .MarkAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .AddToReadingList: if let tab = tabManager.selectedTab, let url = tab.url where ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url), let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? readerModeBar.added = true } } case .RemoveFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false } } } } } private class BrowserScreenshotHelper: ScreenshotHelper { private weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? { if let url = tab.url { if url == UIConstants.AboutHomeURL { if let homePanel = controller?.homePanelController { return homePanel.view.screenshot(aspectRatio, quality: quality) } } else { let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0)) return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality) } } return nil } } extension BrowserViewController: IntroViewControllerDelegate { func presentIntroViewController(force: Bool = false) { if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if UIDevice.currentDevice().userInterfaceIdiom == .Pad { introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height) introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet } presentViewController(introViewController, animated: false) { self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey) } } } func introViewControllerDidFinish(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: nil) } func presentSignInViewController() { // TODO When bug 1161151 has been resolved we can jump directly to the sign in screen let settingsNavigationController = SettingsNavigationController() settingsNavigationController.profile = self.profile settingsNavigationController.tabManager = self.tabManager settingsNavigationController.modalPresentationStyle = .FormSheet self.presentViewController(settingsNavigationController, animated: true, completion: nil) } func introViewControllerDidRequestToLogin(introViewController: IntroViewController) { introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in self.presentSignInViewController() }) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var dialogTitle: String? if let url = elements.link { dialogTitle = url.absoluteString let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) in self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in self.tabManager.addTab(request: NSURLRequest(URL: url)) }) } actionSheetController.addAction(openNewTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString } actionSheetController.addAction(copyAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined { self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.Alert) let dismissAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) } accessDenied.addAction(settingsAction) self.presentViewController(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in let pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = url.absoluteString! // TODO: put the actual image on the clipboard } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16)) popoverPresentationController.permittedArrowDirections = .Any } actionSheetController.title = dialogTitle var cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil) actionSheetController.addAction(cancelAction) self.presentViewController(actionSheetController, animated: true, completion: nil) } private func getImage(url: NSURL, success: UIImage -> ()) { Alamofire.request(.GET, url) .validate(statusCode: 200..<300) .response { _, _, data, _ in if let data = data as? NSData, let image = UIImage(data: data) { success(image) } } } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state // if we are already showing snack bars, adjust them so they sit above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil // if we are showing snack bars, adjust them so they are no longer sitting above the keyboard if snackBars.subviews.count > 0 { adjustFooterSize(top: nil) } } } private struct CrashPromptMessaging { static let CrashPromptTitle = NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title") static let CrashPromptDescription = NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description") static let CrashPromptAffirmative = NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action") static let CrashPromptNegative = NSLocalizedString("No", comment: "Restore Tabs Negative Action") } extension BrowserViewController: UIAlertViewDelegate { private enum CrashPromptIndex: Int { case Cancel = 0 case Restore = 1 } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == CrashPromptIndex.Restore.rawValue { tabManager.restoreTabs() } // In case restore fails, launch at least one tab if tabManager.count == 0 { let tab = tabManager.addTab() tabManager.selectTab(tab) } } }
mpl-2.0
12dc3bb9e1382c9fc91863ac7aa141d8
44.181365
410
0.651739
5.866153
false
false
false
false
vector-im/vector-ios
Riot/Modules/Secrets/Setup/RecoveryPassphrase/SecretsSetupRecoveryPassphraseViewController.swift
1
12338
// File created from ScreenTemplate // $ createScreen.sh Test SecretsSetupRecoveryPassphrase /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class SecretsSetupRecoveryPassphraseViewController: UIViewController { // MARK: - Constants private enum Constants { static let animationDuration: TimeInterval = 0.3 } // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var securePassphraseImageView: UIImageView! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var formBackgroundView: UIView! @IBOutlet private weak var passphraseTitleLabel: UILabel! @IBOutlet private weak var passphraseTextField: UITextField! @IBOutlet private weak var passphraseVisibilityButton: UIButton! @IBOutlet private weak var passphraseAdditionalInfoView: UIView! @IBOutlet private weak var passphraseStrengthContainerView: UIView! @IBOutlet private weak var passphraseStrengthView: PasswordStrengthView! @IBOutlet private weak var passphraseAdditionalLabel: UILabel! @IBOutlet private weak var additionalInformationLabel: UILabel! @IBOutlet private weak var validateButton: RoundedButton! // MARK: Private private var viewModel: SecretsSetupRecoveryPassphraseViewModelType! private var cancellable: Bool! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var isFirstViewAppearing: Bool = true private var isPassphraseTextFieldEditedOnce: Bool = false private var currentViewData: SecretsSetupRecoveryPassphraseViewData? // MARK: - Setup class func instantiate(with viewModel: SecretsSetupRecoveryPassphraseViewModelType, cancellable: Bool) -> SecretsSetupRecoveryPassphraseViewController { let viewController = StoryboardScene.SecretsSetupRecoveryPassphraseViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.cancellable = cancellable viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.isFirstViewAppearing { self.isFirstViewAppearing = false } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.view.endEditing(true) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func setupViews() { if self.cancellable { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem } self.vc_removeBackTitle() self.title = VectorL10n.secretsSetupRecoveryPassphraseTitle self.scrollView.keyboardDismissMode = .interactive self.securePassphraseImageView.image = Asset.Images.secretsSetupPassphrase.image.withRenderingMode(.alwaysTemplate) self.passphraseTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) self.passphraseAdditionalInfoView.isHidden = true let visibilityImage = Asset.Images.revealPasswordButton.image.withRenderingMode(.alwaysTemplate) self.passphraseVisibilityButton.setImage(visibilityImage, for: .normal) self.additionalInformationLabel.text = VectorL10n.secretsSetupRecoveryPassphraseAdditionalInformation self.validateButton.setTitle(VectorL10n.continue, for: .normal) } private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.securePassphraseImageView.tintColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor self.formBackgroundView.backgroundColor = theme.backgroundColor self.passphraseTitleLabel.textColor = theme.textPrimaryColor theme.applyStyle(onTextField: self.passphraseTextField) let passphraseTitle: String if let viewData = self.currentViewData, case .confimPassphrase = viewData.mode { passphraseTitle = VectorL10n.secretsSetupRecoveryPassphraseConfirmPassphrasePlaceholder } else { passphraseTitle = VectorL10n.keyBackupSetupPassphrasePassphrasePlaceholder } self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: passphraseTitle, attributes: [.foregroundColor: theme.placeholderTextColor]) self.passphraseVisibilityButton.tintColor = theme.tintColor self.additionalInformationLabel.textColor = theme.textSecondaryColor self.validateButton.update(theme: theme) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func render(viewState: SecretsSetupRecoveryPassphraseViewState) { switch viewState { case .loaded(let viewData): self.renderLoaded(viewData: viewData) case .formUpdated(let viewData): self.renderFormUpdated(viewData: viewData) case .error(let error): self.render(error: error) } } private func renderLoaded(viewData: SecretsSetupRecoveryPassphraseViewData) { self.currentViewData = viewData let informationText: String let passphraseTitle: String let showPasswordStrength: Bool switch viewData.mode { case .newPassphrase(strength: let strength): informationText = VectorL10n.secretsSetupRecoveryPassphraseInformation passphraseTitle = VectorL10n.keyBackupSetupPassphrasePassphraseTitle showPasswordStrength = true self.passphraseStrengthView.strength = strength case .confimPassphrase: informationText = VectorL10n.secretsSetupRecoveryPassphraseConfirmInformation passphraseTitle = VectorL10n.secretsSetupRecoveryPassphraseConfirmPassphraseTitle showPasswordStrength = false } self.informationLabel.text = informationText self.passphraseTitleLabel.text = passphraseTitle self.passphraseStrengthContainerView.isHidden = !showPasswordStrength self.update(theme: self.theme) } private func renderFormUpdated(viewData: SecretsSetupRecoveryPassphraseViewData) { self.currentViewData = viewData if case .newPassphrase(strength: let strength) = viewData.mode { self.passphraseStrengthView.strength = strength } self.validateButton.isEnabled = viewData.isFormValid self.updatePassphraseAdditionalLabel(viewData: viewData) // Show passphrase additional info at first character entered if self.isPassphraseTextFieldEditedOnce == false, self.passphraseTextField.text?.isEmpty == false { self.isPassphraseTextFieldEditedOnce = true self.showPassphraseAdditionalInfo(animated: true) } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func showPassphraseAdditionalInfo(animated: Bool) { guard self.passphraseAdditionalInfoView.isHidden else { return } // Workaround to layout passphraseStrengthView corner radius self.passphraseStrengthView.setNeedsLayout() UIView.animate(withDuration: Constants.animationDuration) { self.passphraseAdditionalInfoView.isHidden = false } } private func updatePassphraseAdditionalLabel(viewData: SecretsSetupRecoveryPassphraseViewData) { let text: String let textColor: UIColor if viewData.isFormValid { switch viewData.mode { case .newPassphrase: text = VectorL10n.keyBackupSetupPassphrasePassphraseValid case .confimPassphrase: text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseValid } textColor = self.theme.tintColor } else { switch viewData.mode { case .newPassphrase: text = VectorL10n.keyBackupSetupPassphrasePassphraseInvalid case .confimPassphrase: text = VectorL10n.keyBackupSetupPassphraseConfirmPassphraseInvalid } textColor = self.theme.noticeColor } self.passphraseAdditionalLabel.text = text self.passphraseAdditionalLabel.textColor = textColor } // MARK: - Actions @IBAction private func passphraseVisibilityButtonAction(_ sender: Any) { guard self.isPassphraseTextFieldEditedOnce else { return } self.passphraseTextField.isSecureTextEntry.toggle() } @objc private func textFieldDidChange(_ textField: UITextField) { guard textField == self.passphraseTextField else { return } self.viewModel.process(viewAction: .updatePassphrase(textField.text)) } @IBAction private func validateButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .validate) } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - SecretsSetupRecoveryPassphraseViewModelViewDelegate extension SecretsSetupRecoveryPassphraseViewController: SecretsSetupRecoveryPassphraseViewModelViewDelegate { func secretsSetupRecoveryPassphraseViewModel(_ viewModel: SecretsSetupRecoveryPassphraseViewModelType, didUpdateViewState viewSate: SecretsSetupRecoveryPassphraseViewState) { self.render(viewState: viewSate) } }
apache-2.0
6abd15873056165b64ee047b132e240f
36.730887
178
0.688929
6.187563
false
false
false
false
powerytg/Accented
Accented/Core/API/APIService+Photos.swift
1
2600
// // APIService+Photos.swift // Accented // // Created by Tiangong You on 8/28/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import OAuthSwift extension APIService { func uploadPhoto(name : String, description : String, category : Category, privacy : Privacy, image : Data, success: (() -> Void)? = nil, failure : ((String) -> Void)? = nil) { let request = UploadPhotoRequest(name: name, description: description, category: category, privacy: privacy, image: image, success: success, failure: failure) let photoData = OAuthSwiftMultipartData(name: "file", data: image, fileName: "test_photo.jpg", mimeType: "image/jpeg") let nameData = OAuthSwiftMultipartData(name: "name", data: name.data(using: .utf8)!, fileName: nil, mimeType: "multipart/form-data") let descData = OAuthSwiftMultipartData(name: "description", data: description.data(using: .utf8)!, fileName: nil, mimeType: "multipart/form-data") let categoryData = OAuthSwiftMultipartData(name: "category", data: String(category.rawValue).data(using: .utf8)!, fileName: nil, mimeType: "multipart/form-data") let privacyData = OAuthSwiftMultipartData(name: "privacy", data: String(privacy.rawValue).data(using: .utf8)!, fileName: nil, mimeType: "multipart/form-data") let multiparts = [nameData, descData, categoryData, privacyData, photoData] _ = client.postMultiPartRequest(request.url, method: .POST, parameters: [String:String](), headers: nil, multiparts: multiparts, checkTokenExpiration: false, success: { (response) in request.handleSuccess(data: response.data, response: response.response) }, failure: { (error) in request.handleFailure(error) }) } func votePhoto(photoId : String, success: (() -> Void)? = nil, failure : ((String) -> Void)? = nil) { let request = VotePhotoRequest(photoId: photoId, success: success, failure: failure) post(request: request) } func deleteVote(photoId : String, success: (() -> Void)? = nil, failure : ((String) -> Void)? = nil) { let request = DeleteVotePhotoRequest(photoId: photoId, success: success, failure: failure) delete(request: request) } func reportPhoto(photoId : String, reason : ReportReason, details : String?, success: (() -> Void)? = nil, failure : ((String) -> Void)? = nil) { let request = ReportPhotoRequest(photoId: photoId, reason : reason, details : details, success: success, failure: failure) post(request: request) } }
mit
96881dd481cd4719c0c151d91d9b5675
56.755556
190
0.669488
4.165064
false
false
false
false
Great-Li-Xin/Xcode
Fake Tencent iOS/Fake Tencent iOS/ViewController.swift
1
7399
// // ViewController.swift // Fake Tencent iOS // // Created by 李欣 on 2017/9/26. // Copyright © 2017年 李欣. All rights reserved. // import UIKit import Dispatch class ViewController: UIViewController { /// TODO: 静态 UI //// 登陆界面 ///// 用户名 @IBOutlet weak var loginUsername: UITextField! ///// 密码 @IBOutlet weak var loginPassword: UITextField! //// 聊天界面 @IBOutlet weak var chatMsg: UITextField! @IBOutlet weak var chatView: UITextView! /// socket 服务端封装类对象 var socketServer: TcpSocketServer? /// socket 客户端类对象 var socketClient: TCPClient? /// 服务器地址设定 let remoteAddress = "127.0.0.1" // "139.129.46.224" /// 定义服务器端口 let remotePort: Int32 = serverPort override func viewDidLoad() { super.viewDidLoad() socketServer = TcpSocketServer() socketServer?.start() /// 初始化客户端,并连接服务器 processClientSocket() } /// 初始化客户端,并连接服务器 func processClientSocket() { socketClient = TCPClient(address: self.remoteAddress, port: self.remotePort) DispatchQueue.global(qos: .background).async { /// 用于读取并解析服务端发来的消息 func readMsg() -> [String: Any]? { /// 读取 Int32(4 Byte int) 类型 if let data = self.socketClient!.read(4) { let ndata = NSData(bytes: data, length: data.count) var len: Int32 = 0 ndata.getBytes(&len, length: data.count) if let buff = self.socketClient!.read(Int(len)) { let msgData = Data(bytes: buff, count: buff.count) let msgCmd = (try! JSONSerialization.jsonObject(with: msgData, options: .mutableContainers)) as! [String: Any] return msgCmd } } return nil } /// 连接服务器 let connectionStatus: Result = self.socketClient!.connect(timeout: 5) // if connectionStatus.isSuccess { // DispatchQueue.main.async { // self.alert(msg: "与服务器连接成功", after: {}) // } // // /// 发送用户名给服务器 // /// TODO: 登陆功能代替现在的随机生成 // // let msgToSend = ["cmd": "nickname", "nickname": "游客\(Int(arc4random() % 1000))"] // let msgToSend = ["cmd": "nickname", "nickname": self.loginUsername.text!] // self.sendMessage(msgToSend: msgToSend) // // /// 不断接受服务器发来的消息 // while true { // if let msg = readMsg() { // DispatchQueue.main.async { // self.processMessage(msg: msg) // } // } else { // DispatchQueue.main.async { // // self.disconnect // } // break // } // } // } else { // DispatchQueue.main.async { // var error: String = "" // switch connectionStatus.error as! SocketError { // case .queryFailed: // error = "队列服务器错误" // case .connectionClosed: // error = "连接关闭" // case .connectionTimeout: // error = "连接超时" // case .unknownError: // error = "unknownError" // default: // error = "未知错误" // } // self.alert(msg: error, after: {}) // } // } switch connectionStatus { case .success: DispatchQueue.main.async { self.alert(msg: "与服务器连接成功", after: {}) } /// 发送用户名给服务器 /// TODO: 登陆功能代替现在的随机生成 // let msgToSend = ["cmd": "nickname", "nickname": "游客\(Int(arc4random() % 1000))"] let msgToSend = ["cmd": "nickname", "nickname": self.loginUsername.text!] self.sendMessage(msgToSend: msgToSend) /// 不断接受服务器发来的消息 while true { if let msg = readMsg() { DispatchQueue.main.async { self.processMessage(msg: msg) } } else { DispatchQueue.main.async { // self.disconnect } break } } case .failure(let error): DispatchQueue.main.async { var errorString: String = "" switch connectionStatus.error as! SocketError { case .queryFailed: errorString = "队列服务器错误" case .connectionClosed: errorString = "连接关闭" case .connectionTimeout: errorString = "连接超时" case .unknownError: errorString = "未知错误" } self.alert(msg: errorString, after: {}) } } } } /// TODO: UI 函数 /// 聊天界面 “发送” 按钮点击 @IBAction func chatSend(_ sender: Any) { let content = chatMsg.text! let message = ["cmd": "msg", "content": content] self.sendMessage(msgToSend: message) chatMsg.text = nil } /// 发送消息 func sendMessage(msgToSend: [String: String]) { let msgData = try? JSONSerialization.data(withJSONObject: msgToSend, options: .prettyPrinted) var len: Int32 = Int32(msgData!.count) let data = Data(bytes: &len, count: 4) _ = self.socketClient!.send(data: data) _ = self.socketClient!.send(data: msgData!) } /// 处理服务器返回的消息 func processMessage(msg: [String: Any]) { let cmd: String = msg["cmd"] as! String switch (cmd) { case "msg": self.chatView.text = self.chatView.text + (msg["from"] as! String) + ": " + (msg["content"] as! String) + "\n" default: /// TODO: 开发本地聊天记录功能 print(msg) } } /// 弹出消息框 func alert(msg: String, after: () -> (Void)) { let alertController = UIAlertController(title: "", message: msg, preferredStyle: .alert) self.present(alertController, animated: true, completion: nil) /// 1.5 秒后自动消失 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) { alertController.dismiss(animated: false, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
3d54237d64892b82f63483bdf1cddbef
33.089552
134
0.469936
4.639133
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/BlogUploadDirTableViewController.swift
1
5320
// // BlogUploadDirTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/10. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit protocol BlogUploadDirDelegate { func blogUploadDirDone(controller: BlogUploadDirTableViewController, directory: String) } class BlogUploadDirTableViewController: BaseTableViewController { var directory = "" var delegate: BlogUploadDirDelegate? var field: UITextField? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = NSLocalizedString("Upload Dir", comment: "Upload Dir") self.tableView.backgroundColor = Color.tableBg if directory.hasPrefix("/") { directory = (directory as NSString).substringFromIndex(1) } self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:") } 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 Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TextFieldCell", forIndexPath: indexPath) as! UITableViewCell self.adjustCellLayoutMargins(cell) // Configure the cell... field = cell.viewWithTag(99) as? UITextField field?.keyboardType = UIKeyboardType.URL field?.text = directory field?.becomeFirstResponder() return cell } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var header = UIView(frame: CGRectMake(0.0, 0.0, self.tableView.frame.size.width, self.tableView(tableView, heightForHeaderInSection: 0))) var label = UILabel(frame: CGRectMake(10.0, 0.0, header.frame.size.width - 10.0 * 2, header.frame.size.height)) label.text = NSLocalizedString("Upload Directory", comment: "Upload Directory") label.textColor = Color.placeholderText label.font = UIFont.systemFontOfSize(15.0) header.addSubview(label) return header } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // 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 NO 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. } */ @IBAction func doneButtonPushed(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) if field != nil { var dir = field!.text if !dir.hasPrefix("/") { dir = "/" + dir } delegate?.blogUploadDirDone(self, directory: dir) } } }
mit
8ba352a7ae7e50f8c21548107734455d
35.675862
157
0.67563
5.366297
false
false
false
false
irshadqureshi/IQCacheResources
IQCacheResources/Classes/DiscardableJSON.swift
1
983
// // DiscardableJSON.swift // Pods // // Created by Irshad on 15/07/17. // // import Foundation open class DiscardableJSON: NSObject, NSDiscardableContent { private(set) public var json : [String: AnyObject]? var accessedCounter : UInt = 0 public init(json:[String: AnyObject]) { self.json = json } public func beginContentAccess() -> Bool { if json == nil { return false } accessedCounter += 1 return true } public func endContentAccess() { if accessedCounter > 0 { accessedCounter -= 1 } } public func discardContentIfPossible() { if accessedCounter == 0 { json = nil } } public func isContentDiscarded() -> Bool { return json == nil ? true : false } }
mit
c7f22f391bad6f54b96c4815dfd81035
15.948276
60
0.476094
5.041026
false
false
false
false
jegumhon/URWeatherView
URWeatherView/Filter/URRGBToneCurveFilter.swift
1
2181
// // URRGBToneCurveFilter.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 7.. // Copyright © 2017년 zigbang. All rights reserved. // import Foundation let URKernelShaderRGBToneCurve: String = "URKernelShaderRGBToneCurve.cikernel.fsh" open class URRGBToneCurveFilter: URFilter { required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Initialize CIFilter with **CGImage** and CIKernel shader params - parameters: - frame: The frame rectangle for the input image, measured in points. - cgImage: Core Image of the input image - inputValues: attributes for CIKernel. The format is like below. [red: CIImage, green: CIImage, blue: CIImage, original: CIImage] */ required public init(frame: CGRect, cgImage: CGImage, inputValues: [Any]) { super.init(frame: frame, cgImage: cgImage, inputValues: inputValues) self.loadCIColorKernel(from: URKernelShaderRGBToneCurve) guard inputValues.count == 4 else { return } self.customAttributes = inputValues } /** Initialize CIFilter with **CGImage** and CIKernel shader params - parameters: - frame: The frame rectangle for the input image, measured in points. - imageView: The UIImageView of the input image - inputValues: attributes for CIKernel. The format is like below. [red: CIImage, green: CIImage, blue: CIImage, original: CIImage] */ required public init(frame: CGRect, imageView: UIImageView, inputValues: [Any]) { super.init(frame: frame, imageView: imageView, inputValues: inputValues) self.loadCIColorKernel(from: URKernelShaderRGBToneCurve) guard inputValues.count >= 4 else { return } self.customAttributes = inputValues } override func applyFilter() -> CIImage { guard let resultImage: CIImage = (self.customKernel as! CIColorKernel).apply(extent: self.extent, arguments: self.customAttributes!) else { fatalError("Filtered Image merging is failed!!") } return resultImage } }
mit
5b67a17d2086d6c9c3e05fef0fac4323
34.704918
147
0.672635
4.683871
false
false
false
false
intelygenz/NetClient-iOS
Pods/RxSwift/RxSwift/Observables/Delay.swift
6
6309
// // Delay.swift // RxSwift // // Created by tarunon on 2016/02/09. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // import struct Foundation.Date extension ObservableType { /** Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the source by. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: the source Observable shifted in time by the specified delay. */ public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<E> { return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) } } final fileprivate class DelaySink<O: ObserverType> : Sink<O> , ObserverType { typealias E = O.E typealias Source = Observable<E> typealias DisposeKey = Bag<Disposable>.KeyType private let _lock = RecursiveLock() private let _dueTime: RxTimeInterval private let _scheduler: SchedulerType private let _sourceSubscription = SingleAssignmentDisposable() private let _cancelable = SerialDisposable() // is scheduled some action private var _active = false // is "run loop" on different scheduler running private var _running = false private var _errorEvent: Event<E>? = nil // state private var _queue = Queue<(eventTime: RxTime, event: Event<E>)>(capacity: 0) private var _disposed = false init(observer: O, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { _dueTime = dueTime _scheduler = scheduler super.init(observer: observer, cancel: cancel) } // All of these complications in this method are caused by the fact that // error should be propagated immediately. Error can be potentially received on different // scheduler so this process needs to be synchronized somehow. // // Another complication is that scheduler is potentially concurrent so internal queue is used. func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { _lock.lock() // { let hasFailed = _errorEvent != nil if !hasFailed { _running = true } _lock.unlock() // } if hasFailed { return } var ranAtLeastOnce = false while true { _lock.lock() // { let errorEvent = _errorEvent let eventToForwardImmediately = ranAtLeastOnce ? nil : _queue.dequeue()?.event let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !_queue.isEmpty ? _queue.peek().eventTime : nil if let _ = errorEvent { } else { if let _ = eventToForwardImmediately { } else if let _ = nextEventToScheduleOriginalTime { _running = false } else { _running = false _active = false } } _lock.unlock() // { if let errorEvent = errorEvent { self.forwardOn(errorEvent) self.dispose() return } else { if let eventToForwardImmediately = eventToForwardImmediately { ranAtLeastOnce = true self.forwardOn(eventToForwardImmediately) if case .completed = eventToForwardImmediately { self.dispose() return } } else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { let elapsedTime = _scheduler.now.timeIntervalSince(nextEventToScheduleOriginalTime) let interval = _dueTime - elapsedTime let normalizedInterval = interval < 0.0 ? 0.0 : interval scheduler.schedule((), dueTime: normalizedInterval) return } else { return } } } } func on(_ event: Event<E>) { if event.isStopEvent { _sourceSubscription.dispose() } switch event { case .error(_): _lock.lock() // { let shouldSendImmediately = !_running _queue = Queue(capacity: 0) _errorEvent = event _lock.unlock() // } if shouldSendImmediately { forwardOn(event) dispose() } default: _lock.lock() // { let shouldSchedule = !_active _active = true _queue.enqueue((_scheduler.now, event)) _lock.unlock() // } if shouldSchedule { _cancelable.disposable = _scheduler.scheduleRecursive((), dueTime: _dueTime, action: self.drainQueue) } } } func run(source: Observable<E>) -> Disposable { _sourceSubscription.setDisposable(source.subscribe(self)) return Disposables.create(_sourceSubscription, _cancelable) } } final fileprivate class Delay<Element>: Producer<Element> { private let _source: Observable<Element> private let _dueTime: RxTimeInterval private let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { _source = source _dueTime = dueTime _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DelaySink(observer: observer, dueTime: _dueTime, scheduler: _scheduler, cancel: cancel) let subscription = sink.run(source: _source) return (sink: sink, subscription: subscription) } }
mit
3b7e758fc2caf5125bfd7bfa2149d413
33.850829
181
0.572448
5.359388
false
false
false
false
szyulian/AnimationLoginSwift
AnimationLoginSwiftView/ViewController.swift
1
4685
// // ViewController.swift // AnimationLoginSwiftView // // Created by YuLian on 11/4/15. // Copyright © 2015 LianYU. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { enum LogingAnimationType{ case LogingAnimationType_NONE case LogingAnimationType_USER case LogingAnimationType_PWD }; var imgLeftHand: UIImageView?; var imgRightHand: UIImageView?; var imgLeftHandGone: UIImageView?; var imgRightHandGone: UIImageView?; var AnimationType: LogingAnimationType?; override func viewDidLoad() { self.UISetting() PasswordTextField.delegate = self UserNameTextField.delegate = self super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var right_hidden: UIImageView! @IBOutlet weak var left_hidden: UIImageView! @IBOutlet weak var loginView: UIView! @IBOutlet weak var PasswordTextField: UITextField! @IBOutlet weak var UserNameTextField: UITextField! @IBOutlet weak var left_look: UIImageView! @IBOutlet weak var right_look: UIImageView! func UISetting(){ AnimationType = LogingAnimationType.LogingAnimationType_NONE; let boColor: UIColor = UIColor.init(red: 221.0/255.0, green: 221.0/255.0, blue: 221.0/225.0, alpha: 100) UserNameTextField.layer.borderColor = boColor.CGColor; UserNameTextField.leftView = UIView.init(frame: CGRectMake(0, 0, 44, 44)) UserNameTextField.leftViewMode = UITextFieldViewMode.Always let imgUser: UIImageView = UIImageView.init(frame: CGRectMake(11, 11, 22, 22)) imgUser.image = UIImage(named: "iconfont-user") UserNameTextField.leftView!.addSubview(imgUser) PasswordTextField.layer.borderColor = boColor.CGColor; PasswordTextField.leftView = UIView.init(frame: CGRectMake(0, 0, 44, 44)) PasswordTextField.leftViewMode = UITextFieldViewMode.Always let imgPwd: UIImageView = UIImageView.init(frame: CGRectMake(11, 11, 22, 22)) imgPwd.image = UIImage(named:"iconfont-password") PasswordTextField.leftView!.addSubview(imgPwd); loginView.layer.borderColor = boColor.CGColor; } func textFieldDidBeginEditing(textField: UITextField) { if textField.isEqual(PasswordTextField) { AnimationType = LogingAnimationType.LogingAnimationType_PWD; self.AnimationUserToPassword() }else{ if AnimationType == LogingAnimationType.LogingAnimationType_NONE { AnimationType = LogingAnimationType.LogingAnimationType_USER; return; } AnimationType = LogingAnimationType.LogingAnimationType_USER; self.AnimationPasswordToUser(); } } func AnimationUserToPassword(){ UIView.animateWithDuration(0.5, animations: { self.left_look.frame = CGRectMake(self.left_look.frame.origin.x + 80, self.left_look.frame.origin.y, 0, 0); self.right_look.frame = CGRectMake(self.right_look.frame.origin.x - 40, self.right_look.frame.origin.y, 0, 0); self.right_hidden.frame = CGRectMake(self.right_hidden.frame.origin.x-55, self.right_hidden.frame.origin.y-40, 40, 66); self.left_hidden.frame = CGRectMake(self.left_hidden.frame.origin.x+60, self.left_hidden.frame.origin.y-40, 40, 66); }) } func AnimationPasswordToUser(){ UIView.animateWithDuration(0.5, animations: { self.left_look.frame = CGRectMake(self.left_look.frame.origin.x - 80, self.left_look.frame.origin.y, 40, 40); self.right_look.frame = CGRectMake(self.right_look.frame.origin.x + 40, self.right_look.frame.origin.y, 40, 40); self.right_hidden.frame = CGRectMake(self.right_hidden.frame.origin.x+55, self.right_hidden.frame.origin.y+40, 40, 66); self.left_hidden.frame = CGRectMake(self.left_hidden.frame.origin.x-60, self.left_hidden.frame.origin.y+40, 40, 66); }); } @IBAction func EndEditTap(sender: UITapGestureRecognizer) { if (AnimationType == LogingAnimationType.LogingAnimationType_PWD) { self.AnimationPasswordToUser(); } AnimationType = LogingAnimationType.LogingAnimationType_NONE; self.view.endEditing(true); } }
mit
b722cef72d1540e2e6f8d78d1c2bbd73
38.694915
131
0.662041
4.53876
false
false
false
false
davidjhodge/main-repository
What's Poppin?/What's Poppin?/ViewController.swift
1
3689
// // ViewController.swift // What's Poppin? // // Created by David Hodge on 1/24/15. // Copyright (c) 2015 Genesis Apps, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { let capacity = 200 var headCount = 0 var percentageIncrementFactor: CGFloat { return CGFloat(1.0/Double(capacity)) } var progressCircleLayer = CAShapeLayer() @IBOutlet weak var progressCircle: UIView! @IBOutlet weak var incrementButton: UIButton! @IBOutlet weak var decrementButton: UIButton! @IBOutlet weak var headCountLabel: UILabel! @IBOutlet weak var headCountView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Configure Navigation Bar var navFont: UIFont = UIFont(name: "HelveticaNeue-Light", size: 25)! self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: navFont] self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationItem.title = "Bar Counter" self.headCountLabel.text = String(headCount) createProgressCircle() //Configure ++ -- Buttons self.incrementButton.layer.cornerRadius = 0.5 * self.incrementButton.bounds.size.width self.decrementButton.layer.cornerRadius = 0.5 * self.decrementButton.bounds.size.width self.headCountView.layer.cornerRadius = 0.5 * self.headCountView.bounds.size.width } func createProgressCircle() { let centerPoint = CGPoint (x: self.progressCircle.bounds.width / 2, y: self.progressCircle.bounds.width / 2); let circleRadius : CGFloat = self.progressCircle.bounds.width / 2 * 1.1; var circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(-0.5 * M_PI), endAngle: CGFloat(1.5 * M_PI), clockwise: true); progressCircleLayer = CAShapeLayer (); progressCircleLayer.path = circlePath.CGPath; progressCircleLayer.strokeColor = UIColor.whiteColor().CGColor; progressCircleLayer.fillColor = UIColor.clearColor().CGColor; progressCircleLayer.lineWidth = 4; progressCircleLayer.strokeStart = 0; progressCircleLayer.strokeEnd = 0; self.progressCircle.layer.addSublayer(progressCircleLayer); } @IBAction func increment(sender: AnyObject) { updateProgressCircle(0) //0 stands for increment } @IBAction func decrement(sender: AnyObject) { updateProgressCircle(1) //1 stands for decrement } func updateProgressCircle(change: Int) { switch change { case 0: //Increment if (headCount < capacity) { println("Increment") self.headCount++ self.headCountLabel.text = String(headCount) progressCircleLayer.strokeEnd += percentageIncrementFactor println("Stroke End: \(progressCircleLayer.strokeEnd), Head Count: \(headCount)") } case 1: //Decrement if (headCount > 0) { println("Decrement") self.headCount-- self.headCountLabel.text = String(headCount) progressCircleLayer.strokeEnd -= percentageIncrementFactor println("Stroke End: \(progressCircleLayer.strokeEnd), Head Count: \(headCount)") } default: println("Head count did not change.") } } }
apache-2.0
42e9857b143d35ff0c3a4d4e3d2f9ee0
37.831579
166
0.645161
5.102351
false
false
false
false
yvzzztrk/SwiftTemplateProject
Project/template/Utilities/Dictionary+TryCasting.swift
1
4321
// // Dictionary+TryCasting.swift // template // // Created by YAVUZ ÖZTÜRK on 10/02/2017. // Copyright © 2017 Templete Project INC. All rights reserved. // import Foundation public enum CastingError: Error, DisplayableErrorType, CastingErrorKey { case Failure(key: String) var key: String? { switch self { case .Failure(let key): return key } } var errorMessage: String? { switch self { case .Failure(let key): return "Casting Error: \(key)" } } } protocol CastingErrorKey { var key: String? { get } } // Helper functions for Dictionary to get values with certain type or throw extension Dictionary { func get<T>(_ key: String) throws -> T { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], let objAs = obj as? T else { throw CastingError.Failure(key: key) } return objAs } func get<T: RawRepresentable>(_ key: String) throws -> T { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], let objAs = obj as? T.RawValue else { throw CastingError.Failure(key: key) } guard let value = T(rawValue: objAs) else { throw CastingError.Failure(key: key) } return value } func get<T: JsonInitializable>(_ key: String) throws -> T { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], let objAs = obj as? [String: AnyObject] else { throw CastingError.Failure(key: key) } return try T(json: objAs) } func get<T: JsonInitializable>(_ key: String) throws -> [T] { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], let objAs = obj as? [[String: AnyObject]] else { throw CastingError.Failure(key: key) } return try objAs.map { try T(json: $0) } } func convert<T: JsonInitializable>() throws -> [Key: T] { var result: [Key: T] = [:] for (key, innerObj) in self { guard let obj = innerObj as? [String: AnyObject] else { throw CastingError.Failure(key: "Convert") } result[key] = try T(json: obj) } return result } func getOptional<T>(_ key: String) throws -> T? { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], !(obj is NSNull) else { return nil } guard let objAs = obj as? T else { throw CastingError.Failure(key: key) } return objAs } func getOptional<T: RawRepresentable>(_ key: String) throws -> T? { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], !(obj is NSNull) else { return nil } guard let objAs = obj as? T.RawValue else { throw CastingError.Failure(key: key) } guard let value = T(rawValue: objAs) else { throw CastingError.Failure(key: key) } return value } func getOptional<T: JsonInitializable>(_ key: String) throws -> T? { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], !(obj is NSNull) else { return nil } guard let objAs = obj as? [String: AnyObject] else { throw CastingError.Failure(key: key) } return try T(json: objAs) } func getOptional<T: JsonInitializable>(_ key: String) throws -> [T]? { guard let keyAs = key as? Key else { throw CastingError.Failure(key: "-") } guard let obj = self[keyAs], !(obj is NSNull) else { return nil } guard let objAs = obj as? [[String: AnyObject]] else { throw CastingError.Failure(key: key) } return try objAs.map { try T(json: $0) } } }
apache-2.0
ed277f4e738a0a22694d6f72539374ff
28.986111
85
0.544233
4.24165
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TalkPageFindInPageSearchController.swift
1
5037
import Foundation /// Locates occurrences of search term in a `[TalkPageCellViewModel]` hierarchy final class TalkPageFindInPageSearchController { // MARK: - Nested Types struct SearchResult { enum Location { // Term was located within the topic's title for topic at associated index case topicTitle(topicIndex: Int, topicIdentifier: ObjectIdentifier) // Term was located within the topic's lead comment text for topic at associated index case topicLeadComment(topicIndex: Int, replyIdentifier: ObjectIdentifier) // Term was located within topic's other content text for topic at associated index case topicOtherContent(topicIndex: Int) // The term was located within a topic's reply text, for topic and reply at associated indices case reply(topicIndex: Int, topicIdentifier: ObjectIdentifier, replyIndex: Int, replyIdentifier: ObjectIdentifier) } // Term user searched for let term: String // Location of result in topic/reply hierarchy var location: Location // Case insensitive range of term in raw HTML-removed text at result location var range: NSRange? } // MARK: - Public /// Search for occurrences of a text term in `[TalkPageCellViewModel]` hierarchy /// - Parameters: /// - searchTerm: the term to locate, case insensitive /// - topics: an ordered array of topics /// - Returns: An ordered array of SearchResult's indicating occurrences where the term was located func search(term searchTerm: String, in topics: [TalkPageCellViewModel], traitCollection: UITraitCollection, theme: Theme) -> [SearchResult] { var results: [SearchResult] = [] for (topicIndex, topic) in topics.enumerated() { let topicTitleAttributedString = topic.topicTitleAttributedString(traitCollection: traitCollection, theme: theme) let textToSearch = topicTitleAttributedString.string if textToSearch.localizedCaseInsensitiveContains(searchTerm) { let bridgedText = NSString(string: textToSearch) let rangesOfTerm = bridgedText.ranges(of: searchTerm) for range in rangesOfTerm { let result = SearchResult(term: searchTerm, location: .topicTitle(topicIndex: topicIndex, topicIdentifier: topic.id), range: range) results.append(result) } } if let leadComment = topic.leadComment, let leadCommentAttributedString = topic.leadCommentAttributedString(traitCollection: traitCollection, theme: theme) { let textToSearch = leadCommentAttributedString.string if textToSearch.localizedCaseInsensitiveContains(searchTerm) { let bridgedText = NSString(string: textToSearch) let rangesOfTerm = bridgedText.ranges(of: searchTerm) for range in rangesOfTerm { let result = SearchResult(term: searchTerm, location: .topicLeadComment(topicIndex: topicIndex, replyIdentifier: leadComment.id), range: range) results.append(result) } } } else if topic.otherContentHtml != nil, let otherContentAttributedString = topic.otherContentAttributedString(traitCollection: traitCollection, theme: theme) { let textToSearch = otherContentAttributedString.string if textToSearch.localizedCaseInsensitiveContains(searchTerm) { let bridgedText = NSString(string: textToSearch) let rangesOfTerm = bridgedText.ranges(of: searchTerm) for range in rangesOfTerm { let result = SearchResult(term: searchTerm, location: .topicOtherContent(topicIndex: topicIndex), range: range) results.append(result) } } } for (replyIndex, reply) in topic.replies.enumerated() { let replyAttributedString = reply.commentAttributedString(traitCollection: traitCollection, theme: theme) let textToSearch = replyAttributedString.string if textToSearch.localizedCaseInsensitiveContains(searchTerm) { let bridgedText = NSString(string: textToSearch) let rangesOfTerm = bridgedText.ranges(of: searchTerm) for range in rangesOfTerm { let result = SearchResult(term: searchTerm, location: .reply(topicIndex: topicIndex, topicIdentifier: topic.id, replyIndex: replyIndex, replyIdentifier: reply.id), range: range) results.append(result) } } } } return results } }
mit
670e1c14234c1df7bd7d2b44f3e8e113
47.432692
201
0.622394
6.135201
false
false
false
false
omaralbeik/SwifterSwift
Sources/Extensions/SwiftStdlib/StringExtensions.swift
1
42045
// // StringExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // #if canImport(Foundation) import Foundation #endif #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif #if canImport(CoreGraphics) import CoreGraphics #endif // MARK: - Properties public extension String { #if canImport(Foundation) /// SwifterSwift: String decoded from base64 (if applicable). /// /// "SGVsbG8gV29ybGQh".base64Decoded = Optional("Hello World!") /// public var base64Decoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift guard let decodedData = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } #endif #if canImport(Foundation) /// SwifterSwift: String encoded in base64 (if applicable). /// /// "Hello World!".base64Encoded -> Optional("SGVsbG8gV29ybGQh") /// public var base64Encoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift let plainData = data(using: .utf8) return plainData?.base64EncodedString() } #endif /// SwifterSwift: Array of characters of a string. public var charactersArray: [Character] { return Array(self) } #if canImport(Foundation) /// SwifterSwift: CamelCase of string. /// /// "sOme vAriable naMe".camelCased -> "someVariableName" /// public var camelCased: String { let source = lowercased() let first = source[..<source.index(after: source.startIndex)] if source.contains(" ") { let connected = source.capitalized.replacingOccurrences(of: " ", with: "") let camel = connected.replacingOccurrences(of: "\n", with: "") let rest = String(camel.dropFirst()) return first + rest } let rest = String(source.dropFirst()) return first + rest } #endif /// SwifterSwift: Check if string contains one or more emojis. /// /// "Hello 😀".containEmoji -> true /// public var containEmoji: Bool { // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji for scalar in unicodeScalars { switch scalar.value { case 0x3030, 0x00AE, 0x00A9, // Special Characters 0x1D000...0x1F77F, // Emoticons 0x2100...0x27BF, // Misc symbols and Dingbats 0xFE00...0xFE0F, // Variation Selectors 0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs return true default: continue } } return false } /// SwifterSwift: First character of string (if applicable). /// /// "Hello".firstCharacterAsString -> Optional("H") /// "".firstCharacterAsString -> nil /// public var firstCharacterAsString: String? { guard let first = first else { return nil } return String(first) } #if canImport(Foundation) /// SwifterSwift: Check if string contains one or more letters. /// /// "123abc".hasLetters -> true /// "123".hasLetters -> false /// public var hasLetters: Bool { return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil } #endif #if canImport(Foundation) /// SwifterSwift: Check if string contains one or more numbers. /// /// "abcd".hasNumbers -> false /// "123abc".hasNumbers -> true /// public var hasNumbers: Bool { return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil } #endif #if canImport(Foundation) /// SwifterSwift: Check if string contains only letters. /// /// "abc".isAlphabetic -> true /// "123abc".isAlphabetic -> false /// public var isAlphabetic: Bool { let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil return hasLetters && !hasNumbers } #endif #if canImport(Foundation) /// SwifterSwift: Check if string contains at least one letter and one number. /// /// // useful for passwords /// "123abc".isAlphaNumeric -> true /// "abc".isAlphaNumeric -> false /// public var isAlphaNumeric: Bool { let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil let comps = components(separatedBy: .alphanumerics) return comps.joined(separator: "").count == 0 && hasLetters && hasNumbers } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is valid email format. /// /// - Note: Note that this property does not validate the email address against an email server. It merely attempts to determine whether its format is suitable for an email address. /// /// "[email protected]".isValidEmail -> true /// public var isValidEmail: Bool { // http://emailregex.com/ let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$" return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid URL. /// /// "https://google.com".isValidUrl -> true /// public var isValidUrl: Bool { return URL(string: self) != nil } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid schemed URL. /// /// "https://google.com".isValidSchemedUrl -> true /// "google.com".isValidSchemedUrl -> false /// public var isValidSchemedUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme != nil } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid https URL. /// /// "https://google.com".isValidHttpsUrl -> true /// public var isValidHttpsUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "https" } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid http URL. /// /// "http://google.com".isValidHttpUrl -> true /// public var isValidHttpUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "http" } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid file URL. /// /// "file://Documents/file.txt".isValidFileUrl -> true /// public var isValidFileUrl: Bool { return URL(string: self)?.isFileURL ?? false } #endif #if canImport(Foundation) /// SwifterSwift: Check if string is a valid Swift number. /// /// Note: /// In North America, "." is the decimal separator, /// while in many parts of Europe "," is used, /// /// "123".isNumeric -> true /// "1.3".isNumeric -> true (en_US) /// "1,3".isNumeric -> true (fr_FR) /// "abc".isNumeric -> false /// public var isNumeric: Bool { let scanner = Scanner(string: self) scanner.locale = NSLocale.current return scanner.scanDecimal(nil) && scanner.isAtEnd } #endif #if canImport(Foundation) /// SwifterSwift: Check if string only contains digits. /// /// "123".isDigits -> true /// "1.3".isDigits -> false /// "abc".isDigits -> false /// public var isDigits: Bool { return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: self)) } #endif /// SwifterSwift: Last character of string (if applicable). /// /// "Hello".lastCharacterAsString -> Optional("o") /// "".lastCharacterAsString -> nil /// public var lastCharacterAsString: String? { guard let last = last else { return nil } return String(last) } #if canImport(Foundation) /// SwifterSwift: Latinized string. /// /// "Hèllö Wórld!".latinized -> "Hello World!" /// public var latinized: String { return folding(options: .diacriticInsensitive, locale: Locale.current) } #endif #if canImport(Foundation) /// SwifterSwift: Bool value from string (if applicable). /// /// "1".bool -> true /// "False".bool -> false /// "Hello".bool = nil /// public var bool: Bool? { let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased() switch selfLowercased { case "true", "1": return true case "false", "0": return false default: return nil } } #endif #if canImport(Foundation) /// SwifterSwift: Date object from "yyyy-MM-dd" formatted string. /// /// "2007-06-29".date -> Optional(Date) /// public var date: Date? { let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd" return formatter.date(from: selfLowercased) } #endif #if canImport(Foundation) /// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string. /// /// "2007-06-29 14:23:09".dateTime -> Optional(Date) /// public var dateTime: Date? { let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.date(from: selfLowercased) } #endif /// SwifterSwift: Integer value from string (if applicable). /// /// "101".int -> 101 /// public var int: Int? { return Int(self) } /// SwifterSwift: Lorem ipsum string of given length. /// /// - Parameter length: number of characters to limit lorem ipsum to (default is 445 - full lorem ipsum). /// - Returns: Lorem ipsum dolor sit amet... string. public static func loremIpsum(ofLength length: Int = 445) -> String { guard length > 0 else { return "" } // https://www.lipsum.com/ let loremIpsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ if loremIpsum.count > length { return String(loremIpsum[loremIpsum.startIndex..<loremIpsum.index(loremIpsum.startIndex, offsetBy: length)]) } return loremIpsum } #if canImport(Foundation) /// SwifterSwift: URL from string (if applicable). /// /// "https://google.com".url -> URL(string: "https://google.com") /// "not url".url -> nil /// public var url: URL? { return URL(string: self) } #endif #if canImport(Foundation) /// SwifterSwift: String with no spaces or new lines in beginning and end. /// /// " hello \n".trimmed -> "hello" /// public var trimmed: String { return trimmingCharacters(in: .whitespacesAndNewlines) } #endif #if canImport(Foundation) /// SwifterSwift: Readable string from a URL string. /// /// "it's%20easy%20to%20decode%20strings".urlDecoded -> "it's easy to decode strings" /// public var urlDecoded: String { return removingPercentEncoding ?? self } #endif #if canImport(Foundation) /// SwifterSwift: URL escaped string. /// /// "it's easy to encode strings".urlEncoded -> "it's%20easy%20to%20encode%20strings" /// public var urlEncoded: String { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } #endif #if canImport(Foundation) /// SwifterSwift: String without spaces and new lines. /// /// " \n Swifter \n Swift ".withoutSpacesAndNewLines -> "SwifterSwift" /// public var withoutSpacesAndNewLines: String { return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "") } #endif #if canImport(Foundation) /// SwifterSwift: Check if the given string contains only white spaces public var isWhitespace: Bool { return trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } #endif #if os(iOS) || os(tvOS) /// SwifterSwift: Check if the given string spelled correctly public var isSpelledCorrectly: Bool { let checker = UITextChecker() let range = NSRange(location: 0, length: utf16.count) let misspelledRange = checker.rangeOfMisspelledWord(in: self, range: range, startingAt: 0, wrap: false, language: Locale.preferredLanguages.first ?? "en") return misspelledRange.location == NSNotFound } #endif } // MARK: - Methods public extension String { #if canImport(Foundation) /// Float value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional Float value from given string. public func float(locale: Locale = .current) -> Float? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self)?.floatValue } #endif #if canImport(Foundation) /// Double value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional Double value from given string. public func double(locale: Locale = .current) -> Double? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self)?.doubleValue } #endif #if canImport(CoreGraphics) && canImport(Foundation) /// CGFloat value from string (if applicable). /// /// - Parameter locale: Locale (default is Locale.current) /// - Returns: Optional CGFloat value from given string. public func cgFloat(locale: Locale = .current) -> CGFloat? { let formatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? CGFloat } #endif #if canImport(Foundation) /// SwifterSwift: Array of strings separated by new lines. /// /// "Hello\ntest".lines() -> ["Hello", "test"] /// /// - Returns: Strings separated by new lines. public func lines() -> [String] { var result = [String]() enumerateLines { line, _ in result.append(line) } return result } #endif #if canImport(Foundation) /// SwifterSwift: Returns a localized string, with an optional comment for translators. /// /// "Hello world".localized -> Hallo Welt /// public func localized(comment: String = "") -> String { return NSLocalizedString(self, comment: comment) } #endif /// SwifterSwift: The most common character in string. /// /// "This is a test, since e is appearing everywhere e should be the common character".mostCommonCharacter() -> "e" /// /// - Returns: The most common character. public func mostCommonCharacter() -> Character? { let mostCommon = withoutSpacesAndNewLines.reduce(into: [Character: Int]()) { let count = $0[$1] ?? 0 $0[$1] = count + 1 }.max { $0.1 < $1.1 }?.0 return mostCommon } /// SwifterSwift: Array with unicodes for all characters in a string. /// /// "SwifterSwift".unicodeArray() -> [83, 119, 105, 102, 116, 101, 114, 83, 119, 105, 102, 116] /// /// - Returns: The unicodes for all characters in a string. public func unicodeArray() -> [Int] { return unicodeScalars.map { Int($0.value) } } #if canImport(Foundation) /// SwifterSwift: an array of all words in a string /// /// "Swift is amazing".words() -> ["Swift", "is", "amazing"] /// /// - Returns: The words contained in a string. public func words() -> [String] { // https://stackoverflow.com/questions/42822838 let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let comps = components(separatedBy: chararacterSet) return comps.filter { !$0.isEmpty } } #endif #if canImport(Foundation) /// SwifterSwift: Count of words in a string. /// /// "Swift is amazing".wordsCount() -> 3 /// /// - Returns: The count of words contained in a string. public func wordCount() -> Int { // https://stackoverflow.com/questions/42822838 let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let comps = components(separatedBy: chararacterSet) let words = comps.filter { !$0.isEmpty } return words.count } #endif #if canImport(Foundation) /// SwifterSwift: Transforms the string into a slug string. /// /// "Swift is amazing".toSlug() -> "swift-is-amazing" /// /// - Returns: The string in slug format. public func toSlug() -> String { let lowercased = self.lowercased() let latinized = lowercased.latinized let withDashes = latinized.replacingOccurrences(of: " ", with: "-") let alphanumerics = NSCharacterSet.alphanumerics var filtered = withDashes.filter { guard String($0) != "-" else { return true } guard String($0) != "&" else { return true } return String($0).rangeOfCharacter(from: alphanumerics) != nil } while filtered.lastCharacterAsString == "-" { filtered = String(filtered.dropLast()) } while filtered.firstCharacterAsString == "-" { filtered = String(filtered.dropFirst()) } return filtered.replacingOccurrences(of: "--", with: "-") } #endif // swiftlint:disable next identifier_name /// SwifterSwift: Safely subscript string with index. /// /// "Hello World!"[safe: 3] -> "l" /// "Hello World!"[safe: 20] -> nil /// /// - Parameter i: index. public subscript(safe i: Int) -> Character? { guard i >= 0 && i < count else { return nil } return self[index(startIndex, offsetBy: i)] } /// SwifterSwift: Safely subscript string within a half-open range. /// /// "Hello World!"[safe: 6..<11] -> "World" /// "Hello World!"[safe: 21..<110] -> nil /// /// - Parameter range: Half-open range. public subscript(safe range: CountableRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil } return String(self[lowerIndex..<upperIndex]) } /// SwifterSwift: Safely subscript string within a closed range. /// /// "Hello World!"[safe: 6...11] -> "World!" /// "Hello World!"[safe: 21...110] -> nil /// /// - Parameter range: Closed range. public subscript(safe range: ClosedRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0, range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil } return String(self[lowerIndex..<upperIndex]) } #if os(iOS) || os(macOS) /// SwifterSwift: Copy string to global pasteboard. /// /// "SomeText".copyToPasteboard() // copies "SomeText" to pasteboard /// public func copyToPasteboard() { #if os(iOS) UIPasteboard.general.string = self #elseif os(macOS) NSPasteboard.general.clearContents() NSPasteboard.general.setString(self, forType: .string) #endif } #endif /// SwifterSwift: Converts string format to CamelCase. /// /// var str = "sOme vaRiabLe Name" /// str.camelize() /// print(str) // prints "someVariableName" /// public mutating func camelize() { let source = lowercased() let first = source[..<source.index(after: source.startIndex)] if source.contains(" ") { let connected = source.capitalized.replacingOccurrences(of: " ", with: "") let camel = connected.replacingOccurrences(of: "\n", with: "") let rest = String(camel.dropFirst()) self = first + rest return } let rest = String(source.dropFirst()) self = first + rest } /// SwifterSwift: First character of string uppercased(if applicable) while keeping the original string. /// /// "hello world".firstCharacterUppercased() -> "Hello world" /// "".firstCharacterUppercased() -> "" /// public mutating func firstCharacterUppercased() { guard let first = first else { return } self = String(first).uppercased() + dropFirst() } /// SwifterSwift: Check if string contains only unique characters. /// public func hasUniqueCharacters() -> Bool { guard count > 0 else { return false } var uniqueChars = Set<String>() for char in self { if uniqueChars.contains(String(char)) { return false } uniqueChars.insert(String(char)) } return true } #if canImport(Foundation) /// SwifterSwift: Check if string contains one or more instance of substring. /// /// "Hello World!".contain("O") -> false /// "Hello World!".contain("o", caseSensitive: false) -> true /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string contains one or more instance of substring. public func contains(_ string: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return range(of: string, options: .caseInsensitive) != nil } return range(of: string) != nil } #endif #if canImport(Foundation) /// SwifterSwift: Count of substring in string. /// /// "Hello World!".count(of: "o") -> 2 /// "Hello World!".count(of: "L", caseSensitive: false) -> 3 /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: count of appearance of substring in string. public func count(of string: String, caseSensitive: Bool = true) -> Int { if !caseSensitive { return lowercased().components(separatedBy: string.lowercased()).count - 1 } return components(separatedBy: string).count - 1 } #endif /// SwifterSwift: Check if string ends with substring. /// /// "Hello World!".ends(with: "!") -> true /// "Hello World!".ends(with: "WoRld!", caseSensitive: false) -> true /// /// - Parameters: /// - suffix: substring to search if string ends with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string ends with substring. public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasSuffix(suffix.lowercased()) } return hasSuffix(suffix) } #if canImport(Foundation) /// SwifterSwift: Latinize string. /// /// var str = "Hèllö Wórld!" /// str.latinize() /// print(str) // prints "Hello World!" /// public mutating func latinize() { self = folding(options: .diacriticInsensitive, locale: Locale.current) } #endif /// SwifterSwift: Random string of given length. /// /// String.random(ofLength: 18) -> "u7MMZYvGo9obcOcPj8" /// /// - Parameter length: number of characters in string. /// - Returns: random string of given length. public static func random(ofLength length: Int) -> String { guard length > 0 else { return "" } let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var randomString = "" for _ in 1...length { randomString.append(base.randomElement()!) } return randomString } /// SwifterSwift: Reverse string. public mutating func reverse() { let chars: [Character] = reversed() self = String(chars) } // swiftlint:disable next identifier_name /// SwifterSwift: Sliced string from a start index with length. /// /// "Hello World".slicing(from: 6, length: 5) -> "World" /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. /// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World") public func slicing(from i: Int, length: Int) -> String? { guard length >= 0, i >= 0, i < count else { return nil } guard i.advanced(by: length) <= count else { return self[safe: i..<count] } guard length > 0 else { return "" } return self[safe: i..<i.advanced(by: length)] } // swiftlint:disable next identifier_name /// SwifterSwift: Slice given string from a start index with length (if applicable). /// /// var str = "Hello World" /// str.slice(from: 6, length: 5) /// print(str) // prints "World" /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. public mutating func slice(from i: Int, length: Int) { if let str = slicing(from: i, length: length) { self = String(str) } } /// SwifterSwift: Slice given string from a start index to an end index (if applicable). /// /// var str = "Hello World" /// str.slice(from: 6, to: 11) /// print(str) // prints "World" /// /// - Parameters: /// - start: string index the slicing should start from. /// - end: string index the slicing should end at. public mutating func slice(from start: Int, to end: Int) { guard end >= start else { return } if let str = self[safe: start..<end] { self = str } } // swiftlint:disable next identifier_name /// SwifterSwift: Slice given string from a start index (if applicable). /// /// var str = "Hello World" /// str.slice(at: 6) /// print(str) // prints "World" /// /// - Parameter i: string index the slicing should start from. public mutating func slice(at i: Int) { guard i < count else { return } if let str = self[safe: i..<count] { self = str } } /// SwifterSwift: Check if string starts with substring. /// /// "hello World".starts(with: "h") -> true /// "hello World".starts(with: "H", caseSensitive: false) -> true /// /// - Parameters: /// - suffix: substring to search if string starts with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string starts with substring. public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasPrefix(prefix.lowercased()) } return hasPrefix(prefix) } #if canImport(Foundation) /// SwifterSwift: Date object from string of date format. /// /// "2017-01-15".date(withFormat: "yyyy-MM-dd") -> Date set to Jan 15, 2017 /// "not date string".date(withFormat: "yyyy-MM-dd") -> nil /// /// - Parameter format: date format. /// - Returns: Date object from string (if applicable). public func date(withFormat format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) } #endif #if canImport(Foundation) /// SwifterSwift: Removes spaces and new lines in beginning and end of string. /// /// var str = " \n Hello World \n\n\n" /// str.trim() /// print(str) // prints "Hello World" /// public mutating func trim() { self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } #endif /// SwifterSwift: Truncate string (cut it to a given number of characters). /// /// var str = "This is a very long sentence" /// str.truncate(toLength: 14) /// print(str) // prints "This is a very..." /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string (default is "..."). public mutating func truncate(toLength length: Int, trailing: String? = "...") { guard length > 0 else { return } if count > length { self = self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "") } } /// SwifterSwift: Truncated string (limited to a given number of characters). /// /// "This is a very long sentence".truncated(toLength: 14) -> "This is a very..." /// "Short sentence".truncated(toLength: 14) -> "Short sentence" /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string. /// - Returns: truncated string (this is an extr...). public func truncated(toLength length: Int, trailing: String? = "...") -> String { guard 1..<count ~= length else { return self } return self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "") } #if canImport(Foundation) /// SwifterSwift: Convert URL string to readable string. /// /// var str = "it's%20easy%20to%20decode%20strings" /// str.urlDecode() /// print(str) // prints "it's easy to decode strings" /// public mutating func urlDecode() { if let decoded = removingPercentEncoding { self = decoded } } #endif #if canImport(Foundation) /// SwifterSwift: Escape string. /// /// var str = "it's easy to encode strings" /// str.urlEncode() /// print(str) // prints "it's%20easy%20to%20encode%20strings" /// public mutating func urlEncode() { if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { self = encoded } } #endif #if canImport(Foundation) /// SwifterSwift: Verify if string matches the regex pattern. /// /// - Parameter pattern: Pattern to verify. /// - Returns: true if string matches the pattern. public func matches(pattern: String) -> Bool { return range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil } #endif /// SwifterSwift: Pad string to fit the length parameter size with another string in the start. /// /// "hue".padStart(10) -> " hue" /// "hue".padStart(10, with: "br") -> "brbrbrbhue" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". public mutating func padStart(_ length: Int, with string: String = " ") { self = paddingStart(length, with: string) } /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the start. /// /// "hue".paddingStart(10) -> " hue" /// "hue".paddingStart(10, with: "br") -> "brbrbrbhue" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". /// - Returns: The string with the padding on the start. public func paddingStart(_ length: Int, with string: String = " ") -> String { guard count < length else { return self } let padLength = length - count if padLength < string.count { return string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)] + self } else { var padding = string while padding.count < padLength { padding.append(string) } return padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] + self } } /// SwifterSwift: Pad string to fit the length parameter size with another string in the start. /// /// "hue".padEnd(10) -> "hue " /// "hue".padEnd(10, with: "br") -> "huebrbrbrb" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". public mutating func padEnd(_ length: Int, with string: String = " ") { self = paddingEnd(length, with: string) } /// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the end. /// /// "hue".paddingEnd(10) -> "hue " /// "hue".paddingEnd(10, with: "br") -> "huebrbrbrb" /// /// - Parameter length: The target length to pad. /// - Parameter string: Pad string. Default is " ". /// - Returns: The string with the padding on the end. public func paddingEnd(_ length: Int, with string: String = " ") -> String { guard count < length else { return self } let padLength = length - count if padLength < string.count { return self + string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)] } else { var padding = string while padding.count < padLength { padding.append(string) } return self + padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] } } /// SwifterSwift: Removes given prefix from the string. /// /// "Hello, World!".removingPrefix("Hello, ") -> "World!" /// /// - Parameter prefix: Prefix to remove from the string. /// - Returns: The string after prefix removing. public func removingPrefix(_ prefix: String) -> String { guard hasPrefix(prefix) else { return self } return String(dropFirst(prefix.count)) } /// SwifterSwift: Removes given suffix from the string. /// /// "Hello, World!".removingSuffix(", World!") -> "Hello" /// /// - Parameter suffix: Suffix to remove from the string. /// - Returns: The string after suffix removing. public func removingSuffix(_ suffix: String) -> String { guard hasSuffix(suffix) else { return self } return String(dropLast(suffix.count)) } } // MARK: - Initializers public extension String { #if canImport(Foundation) /// SwifterSwift: Create a new string from a base64 string (if applicable). /// /// String(base64: "SGVsbG8gV29ybGQh") = "Hello World!" /// String(base64: "hello") = nil /// /// - Parameter base64: base64 string. public init?(base64: String) { guard let decodedData = Data(base64Encoded: base64) else { return nil } guard let str = String(data: decodedData, encoding: .utf8) else { return nil } self.init(str) } #endif /// SwifterSwift: Create a new random string of given length. /// /// String(randomOfLength: 10) -> "gY8r3MHvlQ" /// /// - Parameter length: number of characters in string. public init(randomOfLength length: Int) { guard length > 0 else { self.init() return } let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var randomString = "" for _ in 1...length { randomString.append(base.randomElement()!) } self = randomString } } // MARK: - NSAttributedString public extension String { #if canImport(UIKit) private typealias Font = UIFont #endif #if canImport(Cocoa) private typealias Font = NSFont #endif #if os(iOS) || os(macOS) /// SwifterSwift: Bold string. public var bold: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.font: Font.boldSystemFont(ofSize: Font.systemFontSize)]) } #endif #if canImport(Foundation) /// SwifterSwift: Underlined string public var underline: NSAttributedString { return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue]) } #endif #if canImport(Foundation) /// SwifterSwift: Strikethrough string. public var strikethrough: NSAttributedString { return NSAttributedString(string: self, attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)]) } #endif #if os(iOS) /// SwifterSwift: Italic string. public var italic: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) } #endif #if canImport(UIKit) /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: UIColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color]) } #endif #if canImport(Cocoa) /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: NSColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color]) } #endif } // MARK: - Operators public extension String { /// SwifterSwift: Repeat string multiple times. /// /// 'bar' * 3 -> "barbarbar" /// /// - Parameters: /// - lhs: string to repeat. /// - rhs: number of times to repeat character. /// - Returns: new string with given string repeated n times. public static func * (lhs: String, rhs: Int) -> String { guard rhs > 0 else { return "" } return String(repeating: lhs, count: rhs) } /// SwifterSwift: Repeat string multiple times. /// /// 3 * 'bar' -> "barbarbar" /// /// - Parameters: /// - lhs: number of times to repeat character. /// - rhs: string to repeat. /// - Returns: new string with given string repeated n times. public static func * (lhs: Int, rhs: String) -> String { guard lhs > 0 else { return "" } return String(repeating: rhs, count: lhs) } } #if canImport(Foundation) // MARK: - NSString extensions public extension String { /// SwifterSwift: NSString from a string. public var nsString: NSString { return NSString(string: self) } /// SwifterSwift: NSString lastPathComponent. public var lastPathComponent: String { return (self as NSString).lastPathComponent } /// SwifterSwift: NSString pathExtension. public var pathExtension: String { return (self as NSString).pathExtension } /// SwifterSwift: NSString deletingLastPathComponent. public var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } /// SwifterSwift: NSString deletingPathExtension. public var deletingPathExtension: String { return (self as NSString).deletingPathExtension } /// SwifterSwift: NSString pathComponents. public var pathComponents: [String] { return (self as NSString).pathComponents } /// SwifterSwift: NSString appendingPathComponent(str: String) /// /// - Parameter str: the path component to append to the receiver. /// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator. public func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } /// SwifterSwift: NSString appendingPathExtension(str: String) /// /// - Parameter str: The extension to append to the receiver. /// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable). public func appendingPathExtension(_ str: String) -> String? { return (self as NSString).appendingPathExtension(str) } } #endif
mit
02f5757d1ffd0c37680f1850c2ab1663
34.087646
529
0.608874
4.31084
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/CommonUI/Views/RadioButton.swift
1
2959
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import UIKit protocol RadioButtonDelegate: AnyObject { func radioButtonTapped(radioButton: RadioButton) } class RadioButton: View { enum State { case selected case unselected } var state: State = .unselected { didSet { update() }} var title: String? { didSet { button.title = title }} weak var delegate: RadioButtonDelegate? private let button = Button(style: .plain) private let circleView = View() override func commonInit() { super.commonInit() circleView.layer.borderColor = Style.Colors.FoundationGreen.cgColor circleView.layer.borderWidth = 2 circleView.layer.cornerRadius = 8 button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) let tapGesture = UITapGestureRecognizer() circleView.addGestureRecognizer(tapGesture) addSubview(button) { $0.top.bottom.trailing.equalToSuperview() } addSubview(circleView) { $0.leading.equalToSuperview() $0.trailing.equalTo(button.snp.leading).offset(Style.Padding.p8) $0.centerY.equalToSuperview() $0.height.width.equalTo(16) } } private func update() { switch state { case .selected: circleView.backgroundColor = Style.Colors.FoundationGreen case .unselected: circleView.backgroundColor = nil } } @objc func buttonTapped() { delegate?.radioButtonTapped(radioButton: self) } @objc func radioTapped() { delegate?.radioButtonTapped(radioButton: self) } }
bsd-3-clause
b38b2394b402213ed52531f0bcaa0060
32.235955
80
0.731575
4.522936
false
false
false
false
Ossey/WeiBo
XYWeiBo/XYWeiBo/Classes/Tools/XYNetworkTools.swift
1
6957
// // XYNetworkingTools.swift // AFNetworking封装工具类 // // Created by mofeini on 16/9/29. // Copyright © 2016年 sey. All rights reserved. // import AFNetworking // MARK:- 定义枚举 enum XYRequestType : String { case GET = "GET" case POST = "POST" } class XYNetworkTools: AFHTTPSessionManager { // MARK:- 单例 // 使用闭包的方式初始化单例(方便初始化的时候给单例对象赋值) static let shareInstace : XYNetworkTools = { let tool = XYNetworkTools() tool.responseSerializer.acceptableContentTypes?.insert("text/html") tool.responseSerializer.acceptableContentTypes?.insert("text/plain") return tool }() } // MARK:- 封装网络请求方法 extension XYNetworkTools { /// 发送GET和POST请求 func request(requestType: XYRequestType, urlSring: String, parameters: [String: Any], finishedCallBack:@escaping (_ result: Any?, _ error: Error?) -> ()) { // 1.定义成功回调的闭包 let successCallBack = { (task: URLSessionDataTask, result: Any?) in finishedCallBack(result, nil) } // 2.定义失败回调的闭包 let failureCallBack = { (task: URLSessionDataTask?, error: Error) in finishedCallBack(nil, error) } // 3.发布网络请求 if requestType == .GET { // GET请求 get(urlSring, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } else if requestType == .POST { // POST请求 post(urlSring, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } } } // MARK:- 获取AccessToken extension XYNetworkTools { // 获取AccessToken func loadAccessToken(code: (String), finisedCallBack: @escaping (_ result: [String: Any]?, _ error : Error?) -> ()) { // 1. 获取请求路径 let urlString = "https://api.weibo.com/oauth2/access_token" // 2.拼接参数 let parameters = ["client_id": app_key, "client_secret": app_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri] // 3.发送POST请求 request(requestType: .POST, urlSring: urlString, parameters: parameters) { (result, error) in // 请求完成后将服务器返回的结果回调给闭 finisedCallBack(result as? [String: Any], error) } } } // MARK:- 获取用户的信息 extension XYNetworkTools { func loadUserInfo(access_token : String, uid : String, finisedCallBack: @escaping (_ result: [String: Any]?, _ error: Error?) -> ()) { // 1.获取请求路径 let urlString = "https://api.weibo.com/2/users/show.json" // 2.拼接参数 let parameters = ["access_token": access_token, "uid": uid] // 3.发送GET请求 request(requestType: .GET, urlSring: urlString, parameters: parameters) { (result, error) in // 请求完成后回调闭包 finisedCallBack(result as? [String : Any], error) } } } // MARK:- 请求微博数据:获取当前登录用户及其所关注(授权)用户的最新微博 接口statuses/home_timeline extension XYNetworkTools { func loadStatuses(since_id: Int, max_id: Int, finisedCallBack: @escaping (_ result : [[String : Any]]?, _ error : Error?) -> ()) { // 1.获取请求路径 let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" // 2.拼接请求参数 let parameters = ["access_token": (XYUserAccountViewModel.shareInstance.userAccount?.access_token)!, "since_id": "\(since_id)", "max_id": "\(max_id)"] // 3.发送GET请求 request(requestType: .GET, urlSring: urlString, parameters: parameters) { (result, error) in // 服务器返回的json数据,本身是一个字典,我们需要字典中的statuses这个数组(里面都是微博) guard let resultDict = result as? [String : Any] else { print(error) finisedCallBack(nil, error) return } let statusesArray = resultDict["statuses"] as? [[String: Any]] // 将数组数据回调 finisedCallBack(statusesArray , error) } } } // MARK:- 发布一条文字微博,接口statuses/update extension XYNetworkTools { func senderStatus(statusText: String, isSuccesCallBck: @escaping (_ isSucces: Bool) -> ()) { // 1.获取请求路径 let urlString = "https://api.weibo.com/2/statuses/update.json" let access_token = XYUserAccountViewModel.shareInstance.userAccount?.access_token // 2.拼接POST参数 let parameters = ["access_token": access_token!, "status": statusText] // 3.发送POST请求 request(requestType: .POST, urlSring: urlString, parameters: parameters) { (result, error) in if result != nil { // 发布成功 isSuccesCallBck(true) } else { print(error) isSuccesCallBck(false) } } } } // MARK:- 上传图片并发布一条微博 extension XYNetworkTools { func senderStatus(statusText: String, image: UIImage, isSuccesCallBack: @escaping (_ isSucces: Bool) -> ()) { // 1.获取请求路径 let urlString = "https://api.weibo.com/2/statuses/upload.json" // 2.拼接POST参数 let access_token = XYUserAccountViewModel.shareInstance.userAccount?.access_token let parameters = ["access_token": access_token!, "status": statusText] // 3.发送POST请求 post(urlString, parameters: parameters, constructingBodyWith: { (formData) in // 上传图片的参数:pic 必须要有 (要上传的图片,仅支持JPEG、GIF、PNG格式,图片大小小于5M) // 3.1将图片转换为二进制数据 if let imageData = UIImageJPEGRepresentation(image, 1.0) { // 可选对象校验 // 3.2将图片的二进制数据拼接到闭包参数中进行回调 formData.appendPart(withFileData: imageData, name: "pic", fileName: "sey.png", mimeType: "image/png") } }, progress: nil, success: { (_, _) in // 请求成功 isSuccesCallBack(true ) }) { (_, error) in // 请求失败 isSuccesCallBack(false) } } }
apache-2.0
e798dcd853d2e5366ef2d05bdeb06eeb
30.543147
159
0.559865
4.385321
false
false
false
false
na4lapy/Na4LapyAPI
Sources/Na4LapyCore/ShelterBackend.swift
1
1688
// // ShelterBackend.swift // Na4lapyAPI // // Created by Wojciech Bilicki on 22/02/2017. // // import Foundation public class ShelterBackend { let db: DBLayer public init(db: DBLayer) { self.db = db } public func get(byId id: Int) throws -> JSONDictionary { let dbresult = try db.fetch(byId: id, table: Config.shelterTable, idname: ShelterDBKey.id) if dbresult.count == 0 { throw ResultCode.ShelterBackendNoData } if dbresult.count > 1 { throw ResultCode.ShelterBackendTooManyEntries } guard let shelter = Shelter(dictionary: dbresult.first!) else { throw ResultCode.ShelterBackendBadParameters } return shelter.dictionaryRepresentation() } func getShelter(byId id: Int) throws -> Shelter? { let dbEntry = try get(byId: id) return Shelter(withJSON: dbEntry) } public func edit(withDictionary dictionary: JSONDictionary) throws -> Int { guard let shelter = Shelter(withJSON: dictionary) else { throw ResultCode.ShelterBackendBadParameters } let id = try db.editShelter(values: shelter.dbRepresentation()) return id } public func get() throws -> [JSONDictionary] { let dbresult = try db.fetch(fromTable: Config.shelterTable) if dbresult.isEmpty { throw ResultCode.ShelterBackendNoData } let shelters = dbresult.flatMap({ Shelter.init(dictionary: $0) }) if shelters.isEmpty { throw ResultCode.ShelterBackendNoData } return shelters.map { $0.dictionaryRepresentation() } } }
apache-2.0
47d1c0b907059907528808a2c179a2ac
24.575758
98
0.62737
4.489362
false
false
false
false
Eiryyy/NowPlaying
NowPlaying/TrackViewController.swift
1
1530
import Cocoa class TrackViewController: NSViewController, TrackInfoDelegate { var trackInfoController = TrackInfoController() @IBOutlet weak var artistLabel: NSTextField! @IBOutlet weak var nameLabel: NSTextField! @IBOutlet weak var albumLabel: NSTextField! @IBOutlet weak var tweetButon: NSButton! @IBOutlet weak var albumImage: NSImageView! @IBAction func buttonClicked (sender: AnyObject) { let sharingService = NSSharingService(named: NSSharingServiceNamePostOnTwitter) let trackInfo = trackInfoController.getInfo() let trackImage = trackInfoController.getImage() let text = trackInfo["name"]! + " / " + trackInfo["artist"]! + " #nowplaying" var items: [AnyObject] = [text] if trackImage != nil { items.append(trackImage!) } sharingService?.performWithItems(items) } override func viewDidLoad() { super.viewDidLoad() trackInfoController.delegate = self NSDistributedNotificationCenter.defaultCenter().addObserver(trackInfoController, selector: "onPlay:", name: "com.apple.iTunes.playerInfo", object: nil) updateTrackInfo(trackInfoController.getInfo(), image: trackInfoController.getImage()) } func updateTrackInfo(info: Dictionary<String, String>, image: NSImage?) { artistLabel.stringValue = info["artist"]! nameLabel.stringValue = info["name"]! albumLabel.stringValue = info["album"]! albumImage.image = image } }
mit
df0e41e3d2bd65b4a76c7c623d5ecd36
39.263158
159
0.684314
5.117057
false
false
false
false
zhaobin19918183/zhaobinCode
miniship/minishop/HomeViewController/HomeViewController.swift
1
6187
// // HomeViewController.swift // minishop // // Created by Zhao.bin on 16/3/9. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit class HomeViewController: UIViewController,UIScrollViewDelegate { @IBOutlet weak var _titileLable: UILabel! @IBOutlet weak var _imageScrolleView: UIScrollView! @IBOutlet weak var _PageControl: UIPageControl! @IBOutlet weak var _goodsView: goodsView! @IBOutlet weak var _salesPromotionView: SalesPromotionView! @IBOutlet weak var _recommendedView: RecommendedView! @IBOutlet weak var _scrollView: UIScrollView! var imageArray : NSArray! var timer: Timer? var lableTitle : NSMutableArray! var viewWidth: CGFloat{ return self.view.bounds.width } var index:CGFloat = 0 override func viewDidLoad() { super.viewDidLoad() imageArray = ["1-1.jpg","1-2.jpg","1-3.jpg","1-4.jpg"] let nextItem=UIBarButtonItem(title:"",style:.plain,target:self,action:nil); // 添加到到导航栏上 self.navigationItem.leftBarButtonItem = nextItem; } override func viewDidLayoutSubviews() { resetUILayout() } func resetUILayout() { let height = _goodsView.frame.size.height + _goodsView.frame.origin.y _scrollView.contentSize = CGSize(width: _scrollView.frame.size.width, height: height) imageScrollViewAction() } //TODO:imageScrollViewAction() func imageScrollViewAction() { _imageScrolleView.contentSize = CGSize(width: CGFloat(imageArray.count+2) * self.view.frame.width, height: _imageScrolleView.bounds.size.height) _imageScrolleView.showsHorizontalScrollIndicator = false _imageScrolleView.delegate = self _imageScrolleView.isPagingEnabled = true for i in 1...imageArray.count { let imgView: UIImageView = UIImageView(frame: CGRect(x: CGFloat(i) * self.view.frame.width, y: 0, width: self.view.frame.width, height: _imageScrolleView.bounds.size.height)) imgView.image = UIImage(named: imageArray[i-1] as!String) _imageScrolleView.addSubview(imgView) imgView.isUserInteractionEnabled = true let singleTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomeViewController.imageViewTouch)) imgView.addGestureRecognizer(singleTap) } let imgView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: _imageScrolleView.bounds.size.height)) imgView.image = UIImage(named: imageArray.lastObject as!String) imgView.isUserInteractionEnabled = true _imageScrolleView.addSubview(imgView) let imgView2: UIImageView = UIImageView(frame: CGRect(x: self.view.frame.width * 5, y: 0, width: self.view.frame.width, height: _imageScrolleView.bounds.size.height)) imgView2.image = UIImage(named: imageArray.firstObject as!String) imgView2.isUserInteractionEnabled = true _imageScrolleView.addSubview(imgView2) _imageScrolleView.setContentOffset(CGPoint(x: self.view.frame.width, y: 0), animated: false) } func imageViewTouch() { let page = Int(_PageControl.currentPage) switch page { case 0: print(page) let storyboard = UIStoryboard(name: "Main", bundle: nil) let target = storyboard.instantiateViewController(withIdentifier: "imageViewController") self.navigationController?.pushViewController(target, animated:true) case 1: print(page) case 2: print(page) case 3: print(page) default: "default" } } //TODO:UIScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollviewW = _imageScrolleView.frame.size.width let page = Int((_imageScrolleView.contentOffset.x + CGFloat( scrollviewW / 2)) / scrollviewW) _PageControl.currentPage = page - 1 } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { } //MARK:addTimer() func addTimer(){ timer = Timer.scheduledTimer(timeInterval: 1.5, target:self,selector:#selector(HomeViewController.nextPage), userInfo:nil,repeats:true) } func nextPage(){ index = index+1 if CGFloat(index) < CGFloat(imageArray.count+1) { animation() } else { index = 1 animation() } } func animation() { var page = Int(_PageControl.currentPage) if (page == imageArray.count-1) { page = 0 } else { page = page+1 } UIView.animate(withDuration: 0.5, animations: { [unowned self] () -> Void in self._imageScrolleView.setContentOffset(CGPoint(x: self.viewWidth*self.index , y: 0), animated: false) }) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let w = scrollView.frame.width let page : Int = Int(_imageScrolleView.contentOffset.x/w) if page == 0 { _imageScrolleView.setContentOffset(CGPoint(x: CGFloat(imageArray.count) * w, y: 0), animated: false) } else if page == imageArray.count+1 { _imageScrolleView.setContentOffset(CGPoint(x: w, y: 0), animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
c96c592b947d398fd2cab3973dc0a3dd
28.653846
186
0.578956
5.080725
false
false
false
false
Gypsyan/APNS-Sender_APNS-Client
APNS-Server/APNSPusher/APNSPusher/Response.swift
1
4893
// // Response.swift // APNSPusher // // Created by Anantha Krishnan K G on 20/02/17. // Copyright © 2017 Ananth. All rights reserved. // import UIKit import Security public enum APNServiceErrorReason:String { case PayloadEmpty = "PayloadEmpty" case PayloadTooLarge = "PayloadTooLarge" case BadTopic = "BadTopic" case TopicDisallowed = "TopicDisallowed" case BadMessageId = "BadMessageId" case BadExpirationDate = "BadExpirationDate" case BadPriority = "BadPriority" case MissingDeviceToken = "MissingDeviceToken" case BadDeviceToken = "BadDeviceToken" case DeviceTokenNotForTopic = "DeviceTokenNotForTopic" case Unregistered = "Unregistered" case DuplicateHeaders = "DuplicateHeaders" case BadCertificateEnvironment = "BadCertificateEnvironment" case BadCertificate = "BadCertificate" case Forbidden = "Forbidden" case BadPath = "BadPath" case MethodNotAllowed = "MethodNotAllowed" case TooManyRequests = "TooManyRequests" case IdleTimeout = "IdleTimeout" case Shutdown = "Shutdown" case InternalServerError = "InternalServerError" case ServiceUnavailable = "ServiceUnavailable" case MissingTopic = "MissingTopic" public func getReasonDescription() -> String { switch self { case .PayloadEmpty: return "The message payload was empty." case .PayloadTooLarge: return "The message payload was too large. The maximum payload size is 4096 bytes." case .BadTopic: return "The apns-topic was invalid." case .TopicDisallowed: return "Pushing to this topic is not allowed." case .BadMessageId: return "The apns-id value is bad." case .BadExpirationDate: return "The apns-expiration value is bad." case .BadPriority: return "The apns-priority value is bad." case .MissingDeviceToken: return "The device token is not specified in the request :path. Verify that the :path header contains the device token." case .BadDeviceToken: return "The specified device token was bad. Verify that the request contains a valid token and that the token matches the environment." case .DeviceTokenNotForTopic: return "The device token does not match the specified topic." case .Unregistered: return "The device token is inactive for the specified topic." case .DuplicateHeaders: return "One or more headers were repeated." case .BadCertificateEnvironment: return "The client certificate was for the wrong environment." case .BadCertificate: return "The certificate was bad." case .Forbidden: return "The specified action is not allowed." case .BadPath: return "The request contained a bad :path value." case .MethodNotAllowed: return "The specified :method was not POST." case .TooManyRequests: return "Too many requests were made consecutively to the same device token." case .IdleTimeout: return "Idle time out." case .Shutdown: return "The server is shutting down." case .InternalServerError: return "An internal server error occurred." case .ServiceUnavailable: return "The service is unavailable." case .MissingTopic: return "The apns-topic header of the request was not specified and was required. The apns-topic header is mandatory when the client is connected using a certificate that supports multiple topics." } } } public enum APNServiceStatus: Error { case success case badRequest case badCertitficate case badMethod case deviceTokenIsNoLongerActive case badNotificationPayload case serverReceivedTooManyRequests case internalServerError case serverShutingDownOrUnavailable public static func statusCodeFrom(response:HTTPURLResponse) -> (Int, APNServiceStatus) { switch response.statusCode { case 400: return (response.statusCode,APNServiceStatus.badRequest) case 403: return (response.statusCode,APNServiceStatus.badCertitficate) case 405: return (response.statusCode,APNServiceStatus.badMethod) case 410: return (response.statusCode,APNServiceStatus.deviceTokenIsNoLongerActive) case 413: return (response.statusCode,APNServiceStatus.badNotificationPayload) case 429: return (response.statusCode,APNServiceStatus.serverReceivedTooManyRequests) case 500: return (response.statusCode,APNServiceStatus.internalServerError) case 503: return (response.statusCode,APNServiceStatus.serverShutingDownOrUnavailable) default: return (response.statusCode,APNServiceStatus.success) } } } public struct APNServiceResponse { public var serviceStatus:(Int, APNServiceStatus) public var serviceErrorReason:APNServiceErrorReason? public var apnsId:String? }
apache-2.0
3ea9c52ac31db454660aca562b4035fb
45.590476
224
0.721791
4.946411
false
false
false
false
jonbalbarin/LibGroupMe
LibGroupMeTests/PowerupTest.swift
1
2662
import LibGroupMe import Quick import Nimble class PowerupTestHelper: NSObject { func powerupIndex() -> NSDictionary { let path = NSBundle(forClass: NSClassFromString(self.className)!).pathForResource("powerups", ofType: "json") let data = NSData(contentsOfFile: path!) let dataDict = try! NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions()) as! NSDictionary return dataDict } func powerupFixtures() -> Array<Powerup> { let dataDict = PowerupTestHelper().powerupIndex() expect(dataDict).toNot(beNil()) expect(dataDict.allKeys.count).to(beGreaterThan(0)) var powerups: Array = Array<Powerup>() if let powerupInfos = dataDict["powerups"] as? NSArray { expect(powerupInfos.count).to(equal(17)) for p in powerupInfos { powerups.append(Powerup(info: p as? NSDictionary)) } } else { fail() } expect(powerups.count).to(equal(17)) return powerups } } class PowerupTest: QuickSpec { override func spec() { describe("a list of powerup objects", { it("should generate a good list") { let powerups = PowerupTestHelper().powerupFixtures() expect(powerups.count).to(equal(17)) for powerup in powerups { expect(powerup.identifier).toNot(beNil()) expect(powerup.createdAt).toNot(beNil()) expect(powerup.updatedAt).toNot(beNil()) expect(powerup.storeName).toNot(beNil()) expect(powerup.storeDescription).toNot(beNil()) expect(powerup.meta).toNot(beNil()) expect(powerup.stickerFolderURL).toNot(beNil()) expect(powerup.packID).to(beGreaterThan(0)) expect(powerup.transliterations).toNot(beNil()) expect(powerup.numberOfCharsInPack).toNot(beNil()) if let translits = powerup.transliterations as Array<String>!, stickerFolder = powerup.stickerFolderURL { for (index, translit) in translits.enumerate() { let s = stickerFolder.URLByAppendingPathComponent("\(index).png", isDirectory: false) print("\(powerup.packID!) \(index) - \(translit) - \(s)\n") } } } } }) } }
mit
7163f6d1a76ccbd97cc71db6812383f8
38.731343
122
0.53719
5.271287
false
true
false
false
zhihuitang/Apollo
Pods/SwiftMagic/SwiftMagic/Classes/Extensions/Extension+UI.swift
1
6665
// // UI+extentions.swift // Pods // // Created by Zhihui Tang on 2017-10-30. // import Foundation public extension UIViewController { func showAlert(withTitle title: String?, message: String?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } var contentViewController: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController ?? self } else { return self } } } // Shake oritention public enum ShakeDirection: Int { case horizontal case vertical } public extension UIView { public func shake(direction: ShakeDirection = .horizontal, times: Int = 5, interval: TimeInterval = 0.1, delta: CGFloat = 2, completion: (() -> Void)? = nil) { UIView.animate(withDuration: interval, animations: { () -> Void in switch direction { case .horizontal: self.layer.setAffineTransform( CGAffineTransform(translationX: delta, y: 0)) break case .vertical: self.layer.setAffineTransform( CGAffineTransform(translationX: 0, y: delta)) break } }) { (complete) -> Void in if (times == 0) { // last shaking finish, reset location, callback UIView.animate(withDuration: interval, animations: { () -> Void in self.layer.setAffineTransform(CGAffineTransform.identity) }, completion: { (complete) -> Void in completion?() }) } else { // not last shaking, continue self.shake(direction: direction, times: times - 1, interval: interval, delta: delta * -1, completion:completion) } } } } extension UIView { var x: CGFloat { set { var frame = self.frame frame.origin.x = newValue self.frame = frame } get { return self.frame.origin.x } } var y: CGFloat { set { var frame = self.frame frame.origin.y = newValue self.frame = frame } get { return self.frame.origin.y } } var centerX: CGFloat { set { var center = self.center center.x = newValue self.center = center } get { return self.center.x } } var centerY: CGFloat { set { var center = self.center center.y = newValue self.center = center } get { return self.center.y } } var width: CGFloat { set { var frame = self.frame frame.size.width = newValue self.frame = frame } get { return self.frame.size.width } } var height: CGFloat { set { var frame = self.frame frame.size.height = newValue self.frame = frame } get { return self.frame.size.height } } var size: CGSize { set { var frame = self.frame frame.size = newValue self.frame = frame } get { return self.frame.size } } var origin: CGPoint { set { var frame = self.frame frame.origin = newValue self.frame = frame } get { return self.frame.origin } } var bottomY: CGFloat { set { var frame = self.frame frame.origin.y = newValue - frame.size.height self.frame = frame } get { return self.height + self.y } } var rightX: CGFloat { set { var frame = self.frame frame.origin.x = newValue - frame.size.width self.frame = frame } get { return self.width + self.x } } // MARK: - UIView round corner /// /// - Parameter cornerRadius: radius func roundedCorners(cornerRadius: CGFloat) { roundedCorners(cornerRadius: cornerRadius, borderWidth: 0, borderColor: nil) } /// /// - Parameters: /// - cornerRadius: /// - borderWidth: /// - borderColor: func roundedCorners(cornerRadius: CGFloat?, borderWidth: CGFloat?, borderColor: UIColor?) { self.layer.cornerRadius = cornerRadius! self.layer.borderWidth = borderWidth! self.layer.borderColor = borderColor?.cgColor self.layer.masksToBounds = true } /// /// - Parameters: /// - cornerRadius: /// - rectCorner: func roundedCorners(cornerRadius: CGFloat?, rectCorner: UIRectCorner?) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: rectCorner!, cornerRadii: CGSize(width: cornerRadius!, height: cornerRadius!)) let layer = CAShapeLayer() layer.frame = self.bounds layer.path = path.cgPath self.layer.mask = layer } /// /// - Parameters: /// - colors: /// - locations: /// - startPoint: [0...1] /// - endPoint: [0...1] func gradientColor(colors: [CGColor], locations: [NSNumber], startPoint: CGPoint, endPoint: CGPoint) { let gradientLayer = CAGradientLayer() gradientLayer.colors = colors gradientLayer.locations = locations /* // vertical gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 0, y: 1) */ gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.frame = self.frame self.layer.insertSublayer(gradientLayer, at: 0) } // MARK: - UIView blur /// /// - Parameter style: UIBlurEffectStyle func addBlurEffect(style: UIBlurEffectStyle) { let effect = UIBlurEffect(style: UIBlurEffectStyle.light) let effectView = UIVisualEffectView(effect: effect) effectView.frame = self.bounds self.backgroundColor = .clear self.addSubview(effectView) self.sendSubview(toBack: effectView) } }
apache-2.0
48f4be539b4131de5e4fc4bbb5158714
26.655602
155
0.528582
4.900735
false
false
false
false
tdscientist/ShelfView-iOS
Example/ShelfView/PlainShelfController.swift
1
3709
// // PlainShelfController.swift // ShelfView // // Created by tdscientist on 09/23/2017. // Copyright (c) 2017 tdscientist. All rights reserved. // import ShelfView class PlainShelfController: UIViewController, PlainShelfViewDelegate { let statusBarHeight = UIApplication.shared.statusBarFrame.height var bookModel = [BookModel]() var shelfView: PlainShelfView! @IBOutlet var motherView: UIView! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) shelfView.translatesAutoresizingMaskIntoConstraints = false shelfView.leftAnchor.constraint(equalTo: motherView.leftAnchor, constant: 0).isActive = true shelfView.rightAnchor.constraint(equalTo: motherView.rightAnchor, constant: 0).isActive = true shelfView.topAnchor.constraint(equalTo: motherView.topAnchor, constant: 0).isActive = true shelfView.bottomAnchor.constraint(equalTo: motherView.bottomAnchor, constant: 0).isActive = true } override func viewDidLoad() { super.viewDidLoad() bookModel.append(BookModel(bookCoverSource: "http://www.aidanf.net/images/learn-swift/cover-web.png", bookId: "0", bookTitle: "Learn Swift")) bookModel.append(BookModel(bookCoverSource: "https://images-na.ssl-images-amazon.com/images/I/41bUdNhz6pL._SX346_BO1,204,203,200_.jpg", bookId: "1", bookTitle: "Beginning iOS")) bookModel.append(BookModel(bookCoverSource: "https://www.packtpub.com/sites/default/files/1414OS_5764_Mastering%20Swift%203%20-%20Linux.jpg", bookId: "2", bookTitle: "Mastering Swift 3 - Linux")) bookModel.append(BookModel(bookCoverSource: "https://files.kerching.raywenderlich.com/uploads/c7f72825-5849-4d76-ba21-8d9486296119.png", bookId: "3", bookTitle: "iOS Apprentice")) shelfView = PlainShelfView(frame: CGRect(x: 0, y: statusBarHeight, width: 350, height: 500), bookModel: bookModel, bookSource: PlainShelfView.BOOK_SOURCE_URL) delay(3) { let books = [ BookModel(bookCoverSource: "https://www.packtpub.com/sites/default/files/5723cov_.png", bookId: "4", bookTitle: "Learning Xcode 8"), BookModel(bookCoverSource: "https://files.kerching.raywenderlich.com/uploads/bc41c949-c745-455e-8922-1b196fcf5e80.png", bookId: "5", bookTitle: "iOS Animations"), BookModel(bookCoverSource: "http://www.appsmith.dk/wp-content/uploads/2014/12/cover-small.jpg", bookId: "6", bookTitle: "Beginning iOS Development") ] self.shelfView.addBooks(bookModel: books) } delay(5) { let books = [ BookModel(bookCoverSource: "https://codewithchris.com/img/SwiftCourseThumbnail_v2.jpg", bookId: "7", bookTitle: "How To Make iPhone Apps"), BookModel(bookCoverSource: "http://whatpixel.com/images/2016/08/learning-swift-book-cover.jpg", bookId: "8", bookTitle: "Learning Swift"), BookModel(bookCoverSource: "https://www.packtpub.com/sites/default/files/9781785288197.png", bookId: "9", bookTitle: "Learning iOS UI Development") ] self.shelfView.addBooks(bookModel: books) } shelfView.delegate = self motherView.addSubview(shelfView) } func onBookClicked(_ shelfView: PlainShelfView, index: Int, bookId: String, bookTitle: String) { print("I just clicked \"\(bookTitle)\" with bookId \(bookId), at index \(index)") } func delay(_ delay: Double, closure: @escaping () -> ()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure ) } }
mit
46f9999953a5934379b5b427b39d7ee1
53.544118
203
0.686438
3.983888
false
false
false
false
gperdomor/dendrite
vendor/src/github.com/apache/thrift/lib/cocoa/src/TMap.swift
36
4336
/* * 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. */ import Foundation public struct TMap<Key : TSerializable, Value : TSerializable> : CollectionType, DictionaryLiteralConvertible, TSerializable { public static var thriftType : TType { return .MAP } typealias Storage = Dictionary<Key, Value> public typealias Index = Storage.Index public typealias Element = Storage.Element private var storage : Storage public var startIndex : Index { return storage.startIndex } public var endIndex: Index { return storage.endIndex } public var keys: LazyMapCollection<[Key : Value], Key> { return storage.keys } public var values: LazyMapCollection<[Key : Value], Value> { return storage.values } public init() { storage = Storage() } public init(dictionaryLiteral elements: (Key, Value)...) { storage = Storage() for (key, value) in elements { storage[key] = value } } public init(minimumCapacity: Int) { storage = Storage(minimumCapacity: minimumCapacity) } public subscript (position: Index) -> Element { get { return storage[position] } } public func indexForKey(key: Key) -> Index? { return storage.indexForKey(key) } public subscript (key: Key) -> Value? { get { return storage[key] } set { storage[key] = newValue } } public mutating func updateValue(value: Value, forKey key: Key) -> Value? { return updateValue(value, forKey: key) } public mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) -> (Key, Value) { return removeAtIndex(index) } public mutating func removeValueForKey(key: Key) -> Value? { return storage.removeValueForKey(key) } public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { storage.removeAll(keepCapacity: keepCapacity) } public var hashValue : Int { let prime = 31 var result = 1 for (key, value) in storage { result = prime * result + key.hashValue result = prime * result + value.hashValue } return result } public static func readValueFromProtocol(proto: TProtocol) throws -> TMap { let (keyType, valueType, size) = try proto.readMapBegin() if keyType != Key.thriftType || valueType != Value.thriftType { throw NSError( domain: TProtocolErrorDomain, code: Int(TProtocolError.InvalidData.rawValue), userInfo: [TProtocolErrorExtendedErrorKey: NSNumber(int: TProtocolExtendedError.UnexpectedType.rawValue)]) } var map = TMap() for _ in 0..<size { let key = try Key.readValueFromProtocol(proto) let value = try Value.readValueFromProtocol(proto) map.storage[key] = value } try proto.readMapEnd() return map } public static func writeValue(value: TMap, toProtocol proto: TProtocol) throws { try proto.writeMapBeginWithKeyType(Key.thriftType, valueType: Value.thriftType, size: value.count) for (key, value) in value.storage { try Key.writeValue(key, toProtocol: proto) try Value.writeValue(value, toProtocol: proto) } try proto.writeMapEnd() } } extension TMap : CustomStringConvertible, CustomDebugStringConvertible { public var description : String { return storage.description } public var debugDescription : String { return storage.debugDescription } } public func ==<Key, Value>(lhs: TMap<Key,Value>, rhs: TMap<Key, Value>) -> Bool { if lhs.count != rhs.count { return false } return lhs.storage == rhs.storage }
apache-2.0
ccbeeff226e6f47cb55ab2a450ebc721
26.443038
126
0.687039
4.438076
false
false
false
false
dhirajjadhao/Casper
Casper/Casper.swift
1
28066
// // Casper.swift // Eureka Sheet Demo // // Created by Dhiraj Jadhao on 05/12/16. // Copyright © 2016 Dhiraj Jadhao. All rights reserved. // import UIKit import Eureka /// Casper Controller Styles public enum UICasperControllerStyle : Int { case actionSheet case alert } /// Casper Controller Action Styles public enum UICasperActionStyle : Int { case switchToggle case label case segment case check case slider case stepper case textView case textField case urlField case intField case phoneField case passwordField case emailField case zipcodeField case date case time case dateTime case button //case ratings // Future Development case activity case qrCode case image //case webView // Future Development case gifActivity } enum DeviceType: String{ case iPhone = "iPhone" case iPad = "iPad" } /// Casper is a lightweight and highly customisable framework which extends the usability of UIAlertController to provide you with much more customisable and frequently required UI elements. public class UICasperController: NSObject { //MARK: Private Properties private var isAlertAddedInWindow:Bool? private let app = UIApplication.shared.delegate private var window = UIWindow() private var preferredStyle:UICasperControllerStyle! private var presentingViewController:UIViewController! private var casperViewHeightString = String() private var isCasperEditing = Bool() private var formView = FormViewController() private var form = Form() private var section = Section() private var alertController:UIAlertController! //MARK: Properties /// Casper Controller Title public var title:String? /// Casper Controller Message public var message:String? /// Casper Controller Tint Color public var tintColor:UIColor? /// Dismiss button title of Casper Controller public var dismissButtonTitle:String? /// Whether to hide or unhide dismiss button in Casper Cotroller public var dismissButtonHidden:Bool? /// Initializers public override init(){ super.init() form = formView.form form +++ section } public convenience init(title: String?, message: String?, preferredStyle: UICasperControllerStyle) { self.init() self.title = title self.message = message self.preferredStyle = preferredStyle if self.preferredStyle == UICasperControllerStyle.actionSheet { casperViewHeightString = "\n\n" } } //MARK: Add Actions /// Add actions to UICasperController /// /// - parameter title: Title of UICasperController /// - parameter style: Style of UICasperController action /// - parameter options: Which takes [Any]? of supported attributes for certain action style if supported. /// - parameter value: Which take Any? as value for specific action style if supported. public func addAction(title: String?, style: UICasperActionStyle, options: [Any]?, value: Any?, handler: ((Any) -> Swift.Void)?) { switch style { case .switchToggle: section <<< SwitchRow(){ row in row.title = title row.cell.switchControl?.onTintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Bool{ row.value = value as? Bool } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .label: section <<< LabelRow(){ row in row.title = title casperViewHeightString = casperViewHeightString + "\n\n" }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .segment: section <<< SegmentedRow<String>(){ row in row.title = title row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if (options != nil){ row.options = options as! [String] } if (value != nil){ row.value = value as! String? } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .check: section <<< CheckRow(){ row in row.title = title row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Bool{ row.value = value as? Bool } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .slider: section <<< SliderRow(){ row in row.title = title row.cell.height = {78} row.cell.slider.minimumTrackTintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n\n\n" if options != nil{ if (options?.count)! >= 2{ row.cell.slider.minimumValue = Float(options?[0] as! Int) row.cell.slider.maximumValue = Float(options?[1] as! Int) } } if value is Float { row.value = value as? Float }else if value is Int{ row.value = Float(value as! Int) } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .stepper: section <<< StepperRow(){ row in row.title = title row.cell.stepper.tintColor = tintColor row.cell.valueLabel.textColor = tintColor if options != nil{ if (options?.count)! >= 3{ row.cell.stepper.minimumValue = Double(options?[0] as! Int) row.cell.stepper.maximumValue = Double(options?[1] as! Int) if options?[2] is Int{ row.cell.stepper.stepValue = Double(options?[2] as! Int) }else if options?[2] is Double{ row.cell.stepper.stepValue = options?[2] as! Double } } } casperViewHeightString = casperViewHeightString + "\n\n" if value is Double{ row.value = value as? Double }else if value is Int{ row.value = Double(value as! Int) } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .textView: section <<< TextAreaRow("textView"){ row in row.placeholder = title row.cell.textView.tintColor = tintColor if preferredStyle == .alert{ casperViewHeightString = casperViewHeightString + "\n\n\n\n\n" }else{ casperViewHeightString = casperViewHeightString + "\n\n\n\n\n\n\n" } if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .textField: section <<< TextRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .urlField: section <<< URLRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is URL{ row.value = value as? URL } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .intField: section <<< IntRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Int{ row.value = value as? Int } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .phoneField: section <<< PhoneRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .passwordField: section <<< PasswordRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .emailField: section <<< EmailRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .zipcodeField: section <<< ZipCodeRow(){ row in row.title = title row.cell.textField.tintColor = tintColor row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is String{ row.value = value as? String } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .date: section <<< DateRow(){ row in row.title = title row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Date{ row.value = value as? Date } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .time: section <<< TimeRow(){ row in row.title = title row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Date{ row.value = value as? Date } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .dateTime: section <<< DateTimeRow(){ row in row.title = title row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" if value is Date{ row.value = value as? Date } }.onChange({ (row) in if handler != nil{ handler!(row.value!) } }) case .button: section <<< ButtonRow(){ row in row.title = title row.cell.backgroundColor = UIColor.clear row.cell.tintColor = tintColor casperViewHeightString = casperViewHeightString + "\n\n" }.onCellSelection({ (cell, row) in handler!(true) }) case .activity: section <<< ActivityRow(){ row in row.cell.tintColor = tintColor row.cell.backgroundColor = UIColor.clear row.cell.selectionStyle = UITableViewCellSelectionStyle.none formView.tableView?.separatorStyle = UITableViewCellSeparatorStyle.none casperViewHeightString = casperViewHeightString + "\n\n" if options != nil{ for object in options!{ if object is UIActivityIndicatorViewStyle{ row.cell.activityView.activityIndicatorViewStyle = object as! UIActivityIndicatorViewStyle } } } row.cell.activityView.color = tintColor } case .gifActivity: section <<< GIFActivityRow(){ row in if value is String{ row.value = value as! String? } row.cell.backgroundColor = UIColor.clear if options != nil{ for object in options!{ if object is UIViewContentMode{ row.cell.activityView.imageView.contentMode = object as! UIViewContentMode row.cell.localActivityView.contentMode = object as! UIViewContentMode }else if object is CGSize{ row.cell.activityView.bounds.size = object as! CGSize row.cell.height = {(object as! CGSize).height} row.cell.layoutIfNeeded() }else if object is UIColor{ row.cell.backgroundColor = object as? UIColor } } } row.cell.tintColor = tintColor row.cell.selectionStyle = UITableViewCellSelectionStyle.none let height = row.cell.height!() let numbeOflines = round(height/23) if numbeOflines > 0 { for _ in 0..<Int(numbeOflines){ casperViewHeightString = casperViewHeightString + "\n" } } } case .qrCode: section <<< QRCodeRow(){ row in if value is String{ row.value = value as! String? } row.cell.backgroundColor = UIColor.clear row.cell.tintColor = tintColor row.cell.selectionStyle = UITableViewCellSelectionStyle.none if preferredStyle == UICasperControllerStyle.actionSheet{ casperViewHeightString = casperViewHeightString + "\n\n\n\n\n\n\n\n\n" }else{ casperViewHeightString = casperViewHeightString + "\n\n\n\n\n\n\n\n" } row.cell.height = {180} } case .image: section <<< ImageRow(){ row in if value is UIImage{ row.value = value as! UIImage? } row.cell.tintColor = tintColor row.cell.backgroundColor = UIColor.clear row.cell.selectionStyle = UITableViewCellSelectionStyle.none row.cell.height = {150} if options != nil{ for object in options!{ if object is UIViewContentMode{ row.cell.imageCellView.contentMode = object as! UIViewContentMode } if object is CGSize{ row.cell.imageCellView.bounds.size = object as! CGSize row.cell.height = {(object as! CGSize).height} } } } if row.cell.height != nil { let height = row.cell.height!() let numbeOflines = round(height/23) if numbeOflines > 0 { for _ in 0..<Int(numbeOflines){ casperViewHeightString = casperViewHeightString + "\n" } } } } // case .webView: // section <<< WebViewRow(){ row in // // if value is String{ // row.value = (value as? String)! // } // // row.cell.tintColor = tintColor // row.cell.backgroundColor = UIColor.clear // row.cell.selectionStyle = UITableViewCellSelectionStyle.none // if preferredStyle == UICasperControllerStyle.actionSheet{ // casperViewHeightString = casperViewHeightString + "\n\n\n\n\n" // }else{ // casperViewHeightString = casperViewHeightString + "\n\n\n\n\n\n" // } // // row.cell.height = {130} // // } } } //MARK: Present UICasperController /// It presents the UICasperController in given view /// /// - parameter inViewController: ViewController in which UICasperController is to be presented. /// - parameter animated: Whether UICasperController should be presented with animation. public func present(inViewController:UIViewController, sourceView:UIView?, animated: Bool, completion: (() -> Swift.Void)? = nil) -> Void{ presentingViewController = inViewController let alertControllerText = NSMutableAttributedString() if self.title != nil { let attributes = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: 15)] let attributedTitle = NSMutableAttributedString(string: self.title!, attributes: attributes) alertControllerText.append(NSAttributedString(string: "\n")) alertControllerText.append(attributedTitle) } if self.message != nil { let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 13)] let attributedMessage = NSMutableAttributedString(string: "\n"+self.message!, attributes: attributes) alertControllerText.append(attributedMessage) alertControllerText.append(NSAttributedString(string: "\n")) } if preferredStyle == UICasperControllerStyle.alert { alertController = UIAlertController(title: nil, message:casperViewHeightString, preferredStyle: UIAlertControllerStyle.alert) var heightToBeReduced = CGFloat() if dismissButtonHidden != true { heightToBeReduced = 40 }else{ heightToBeReduced = 0 } var yPos = Int() if alertControllerText.length == 0 { yPos = -17 }else{ yPos = 0 } formView.view.frame = CGRect(x: 0, y: yPos, width: Int(alertController.view.bounds.width), height: (Int(alertController.view.bounds.height - heightToBeReduced))) formView.view.center.x = alertController.view.bounds.width/2.0 formView.tableView?.backgroundColor = UIColor.clear formView.tableView?.isScrollEnabled = false let header = UILabel(frame: CGRect(x: 0, y: 0, width: Int(alertController.view.bounds.width)-30, height: 40)) header.font = UIFont.boldSystemFont(ofSize: 14) header.numberOfLines = 0 header.textAlignment = NSTextAlignment.center header.attributedText = alertControllerText header.textColor = UIColor.darkGray header.sizeToFit() formView.tableView?.tableHeaderView = header let numbeOflines = round(header.frame.height/17) if numbeOflines > 0 { for _ in 0..<Int(numbeOflines)-2{ casperViewHeightString = casperViewHeightString + "\n" } } alertController.message = casperViewHeightString alertController.view.addSubview(formView.view) alertController.present(formView, animated: true, completion: nil) }else{ alertController = UIAlertController(title: nil, message:casperViewHeightString, preferredStyle: UIAlertControllerStyle.actionSheet) var heightToBeReduced = CGFloat() if dismissButtonHidden != true { heightToBeReduced = 70 }else{ heightToBeReduced = 0 } var yPos = Int() if alertControllerText.length == 0 { yPos = -15 }else{ yPos = 0 } if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad && sourceView != nil { alertController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.any alertController.popoverPresentationController?.sourceView = sourceView! alertController.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: (sourceView?.frame.width)!, height: (sourceView?.frame.height)!) heightToBeReduced = 0 }else if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad && sourceView == nil{ print("You should pass source view to present actionsheet on iPad device.") } formView.view.frame = CGRect(x: 0, y: yPos, width: Int(alertController.view.bounds.width), height: (Int(alertController.view.bounds.height - heightToBeReduced))) formView.view.center.x = alertController.view.bounds.width/2.0 formView.tableView?.backgroundColor = UIColor.clear formView.tableView?.isScrollEnabled = false let header = UILabel(frame: CGRect(x: 0, y: 0, width: Int(alertController.view.bounds.width)-40, height: 38)) header.font = UIFont.boldSystemFont(ofSize: 14) header.numberOfLines = 0 header.textAlignment = NSTextAlignment.center header.attributedText = alertControllerText header.textColor = UIColor.darkGray header.sizeToFit() formView.tableView?.tableHeaderView = header let numbeOflines = round(header.frame.height/17) if numbeOflines > 0 { for _ in 0..<Int(numbeOflines)-1{ casperViewHeightString = casperViewHeightString + "\n" } } alertController.message = casperViewHeightString alertController.view.addSubview(formView.view) alertController.present(formView, animated: true, completion: nil) } if dismissButtonTitle == nil { dismissButtonTitle = "Cancel" } if dismissButtonHidden != true { let cancelAction = UIAlertAction(title: dismissButtonTitle, style: .cancel, handler: {(alert: UIAlertAction!) in print("cancel")}) alertController.addAction(cancelAction) } if self.tintColor != nil { alertController.view.tintColor = self.tintColor! } presentingViewController.present(alertController, animated: animated) { } } //MARK: Dismiss UICasperController /// - parameter animated: Whether UICasperController should be dismissed with animation. public func dismiss(animated: Bool, completion: (() -> Void)?){ alertController.dismiss(animated: animated, completion: completion) } }
mit
3a34e82df0c8346ebfc12fcd1a515aaf
33.605425
190
0.462106
6.438403
false
false
false
false
fireflyexperience/BSImagePicker
Pod/Classes/View/SelectionView.swift
1
3268
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @IBDesignable final class SelectionView: UIView { var selectionString: String = "" { didSet { if selectionString != oldValue { setNeedsDisplay() } } } var settings: BSImagePickerSettings = Settings() override func draw(_ rect: CGRect) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Color Declarations //// Shadow Declarations let shadow2Offset = CGSize(width: 0.1, height: -0.1); let shadow2BlurRadius: CGFloat = 2.5; //// Frames let checkmarkFrame = bounds; //// Subframes let group = CGRect(x: checkmarkFrame.minX + 3, y: checkmarkFrame.minY + 3, width: checkmarkFrame.width - 6, height: checkmarkFrame.height - 6) //// CheckedOval Drawing let checkedOvalPath = UIBezierPath(ovalIn: CGRect(x: group.minX + floor(group.width * 0.0 + 0.5), y: group.minY + floor(group.height * 0.0 + 0.5), width: floor(group.width * 1.0 + 0.5) - floor(group.width * 0.0 + 0.5), height: floor(group.height * 1.0 + 0.5) - floor(group.height * 0.0 + 0.5))) context!.saveGState() context!.setShadow(offset: shadow2Offset, blur: shadow2BlurRadius, color: settings.selectionShadowColor.cgColor) settings.selectionFillColor.setFill() checkedOvalPath.fill() context!.restoreGState() settings.selectionStrokeColor.setStroke() checkedOvalPath.lineWidth = 1 checkedOvalPath.stroke() //// Bezier Drawing (Picture Number) context!.setFillColor(UIColor.white.cgColor) let size = selectionString.size(attributes: settings.selectionTextAttributes) selectionString.draw(in: CGRect(x: checkmarkFrame.midX - size.width / 2.0, y: checkmarkFrame.midY - size.height / 2.0, width: size.width, height: size.height), withAttributes: settings.selectionTextAttributes) } }
mit
dd94b71b5956e369325018048f3466a7
42.753425
302
0.651974
4.569231
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Skip.swift
11
3435
// // Skip.swift // RxSwift // // Created by Krunoslav Zaher on 6/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // count version class SkipCountSink<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.E typealias Parent = SkipCount<Element> let parent: Parent var remaining: Int init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent self.remaining = parent.count super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if remaining <= 0 { forwardOn(.next(value)) } else { remaining -= 1 } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } } class SkipCount<Element>: Producer<Element> { let source: Observable<Element> let count: Int init(source: Observable<Element>, count: Int) { self.source = source self.count = count } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) let subscription = source.subscribe(sink) return (sink: sink, subscription: subscription) } } // time version class SkipTimeSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipTime<ElementType> typealias Element = ElementType let parent: Parent // state var open = false init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if open { forwardOn(.next(value)) } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } func tick() { open = true } func run() -> Disposable { let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { self.tick() return Disposables.create() } let disposeSubscription = parent.source.subscribe(self) return Disposables.create(disposeTimer, disposeSubscription) } } class SkipTime<Element>: Producer<Element> { let source: Observable<Element> let duration: RxTimeInterval let scheduler: SchedulerType init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) { self.source = source self.scheduler = scheduler self.duration = duration } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
apache-2.0
bdebc56009ad0755ad42d8517f2f0e6c
25.828125
145
0.58707
4.64682
false
false
false
false
BenEmdon/swift-algorithm-club
Shunting Yard/ShuntingYard.swift
1
4904
// // ShuntingYardAlgorithm.swift // // // Created by Ali Hafizji on 2016-02-25. // // internal enum OperatorAssociativity { case LeftAssociative case RightAssociative } public enum OperatorType: CustomStringConvertible { case Add case Subtract case Divide case Multiply case Percent case Exponent public var description: String { switch self { case Add: return "+" case Subtract: return "-" case Divide: return "/" case Multiply: return "*" case Percent: return "%" case Exponent: return "^" } } } public enum TokenType: CustomStringConvertible { case OpenBracket case CloseBracket case Operator(OperatorToken) case Operand(Double) public var description: String { switch self { case OpenBracket: return "(" case CloseBracket: return ")" case Operator(let operatorToken): return operatorToken.description case Operand(let value): return "\(value)" } } } public struct OperatorToken: CustomStringConvertible { let operatorType: OperatorType init(operatorType: OperatorType) { self.operatorType = operatorType } var precedence: Int { switch operatorType { case .Add, .Subtract: return 0 case .Divide, .Multiply, .Percent: return 5 case .Exponent: return 10 } } var associativity: OperatorAssociativity { switch operatorType { case .Add, .Subtract, .Divide, .Multiply, .Percent: return .LeftAssociative case .Exponent: return .RightAssociative } } public var description: String { return operatorType.description } } func <= (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence <= right.precedence } func < (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence < right.precedence } public struct Token: CustomStringConvertible { let tokenType: TokenType init(tokenType: TokenType) { self.tokenType = tokenType } init(operand: Double) { tokenType = .Operand(operand) } init(operatorType: OperatorType) { tokenType = .Operator(OperatorToken(operatorType: operatorType)) } var isOpenBracket: Bool { switch tokenType { case .OpenBracket: return true default: return false } } var isOperator: Bool { switch tokenType { case .Operator(_): return true default: return false } } var operatorToken: OperatorToken? { switch tokenType { case .Operator(let operatorToken): return operatorToken default: return nil } } public var description: String { return tokenType.description } } public class InfixExpressionBuilder { private var expression = [Token]() public func addOperator(operatorType: OperatorType) -> InfixExpressionBuilder { expression.append(Token(operatorType: operatorType)) return self } public func addOperand(operand: Double) -> InfixExpressionBuilder { expression.append(Token(operand: operand)) return self } public func addOpenBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .OpenBracket)) return self } public func addCloseBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .CloseBracket)) return self } public func build() -> [Token] { // Maybe do some validation here return expression } } // This returns the result of the shunting yard algorithm public func reversePolishNotation(expression: [Token]) -> String { var tokenStack = Stack<Token>() var reversePolishNotation = [Token]() for token in expression { switch token.tokenType { case .Operand(_): reversePolishNotation.append(token) case .OpenBracket: tokenStack.push(token) case .CloseBracket: while tokenStack.count > 0, let tempToken = tokenStack.pop() where !tempToken.isOpenBracket { reversePolishNotation.append(tempToken) } case .Operator(let operatorToken): for tempToken in tokenStack.generate() { if !tempToken.isOperator { break } if let tempOperatorToken = tempToken.operatorToken { if operatorToken.associativity == .LeftAssociative && operatorToken <= tempOperatorToken || operatorToken.associativity == .RightAssociative && operatorToken < tempOperatorToken { reversePolishNotation.append(tokenStack.pop()!) } else { break } } } tokenStack.push(token) } } while tokenStack.count > 0 { reversePolishNotation.append(tokenStack.pop()!) } return reversePolishNotation.map({token in token.description}).joinWithSeparator(" ") }
mit
19bb8ee27180abf0f999d5e80d824ee2
21.392694
106
0.650285
4.879602
false
false
false
false
HeMet/AppCoordinatorExample
CoordinatorExample/StackCoordinator.swift
1
2203
// // StackCoordinator.swift // CoordinatorExample // // Created by Evgeniy Gubin on 22.04.17. // Copyright © 2017 Eugene Gubin. All rights reserved. // import UIKit class StackCoordinator: CoordinatorProps, PresentingCoordinator { var sceneViewController: UIViewController { return stackViewController } let stackViewController = StackViewController() func start(completion: Callback?) { addElement() completion?(self) } func stop(completion: Callback?) { completion?(self) } func addElement() { let child = makeChildCoordinator() presentChild(child) } func makeChildCoordinator() -> ChildCoordinator { let child = ChildCoordinator(colorSeed: children.count) child.output = self return child } func removeChild(coordinator: Coordinator) { dismissChild(identifier: coordinator.identifier) } func present(childCoordinator coordinator: Coordinator) { let childScene = coordinator.sceneViewController stackViewController.addChildViewController(childScene) stackViewController.stackView.addArrangedSubview(childScene.view) childScene.didMove(toParentViewController: stackViewController) } func dismiss(childCoordinator coordinator: Coordinator) { coordinator.sceneViewController.willMove(toParentViewController: nil) stackViewController.stackView.removeArrangedSubview(coordinator.sceneViewController.view) coordinator.sceneViewController.removeFromParentViewController() } } extension StackCoordinator: ChildCoordinatorOutput { func childCoordinatorAdd(_ sender: ChildCoordinator) { addElement() } func childCoordinatorRemove(_ sender: ChildCoordinator) { removeChild(coordinator: sender) } } class StackViewController: UIViewController { var coordinator: StackCoordinator! var stackView: UIStackView { return view as! UIStackView } override func loadView() { let _view = UIStackView() _view.axis = .vertical _view.distribution = .fillEqually view = _view } }
mit
280b86e1fe710ff577ab0e34d66a0029
26.873418
97
0.691644
5.491272
false
false
false
false
rnystrom/GitHawk
Local Pods/SwipeCellKit/Example/MailExample/MailViewController.swift
2
8785
// // MailViewController.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit import SwipeCellKit class MailViewController: UITableViewController { var emails: [Email] = [] var defaultOptions = SwipeTableOptions() var isSwipeRightEnabled = true var buttonDisplayMode: ButtonDisplayMode = .titleAndImage var buttonStyle: ButtonStyle = .backgroundColor // MARK: - Lifecycle override func viewDidLoad() { tableView.allowsSelection = true tableView.allowsMultipleSelectionDuringEditing = true tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 navigationItem.rightBarButtonItem = editButtonItem view.layoutMargins.left = 32 resetData() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return emails.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MailCell") as! MailTableCell cell.delegate = self cell.selectedBackgroundView = createSelectedBackgroundView() let email = emails[indexPath.row] cell.fromLabel.text = email.from cell.dateLabel.text = email.relativeDateString cell.subjectLabel.text = email.subject cell.bodyLabel.text = email.body cell.unread = email.unread return cell } // MARK: - Actions @IBAction func moreTapped(_ sender: Any) { let controller = UIAlertController(title: "Swipe Transition Style", message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: "Border", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .border })) controller.addAction(UIAlertAction(title: "Drag", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .drag })) controller.addAction(UIAlertAction(title: "Reveal", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .reveal })) controller.addAction(UIAlertAction(title: "\(isSwipeRightEnabled ? "Disable" : "Enable") Swipe Right", style: .default, handler: { _ in self.isSwipeRightEnabled = !self.isSwipeRightEnabled })) controller.addAction(UIAlertAction(title: "Button Display Mode", style: .default, handler: { _ in self.buttonDisplayModeTapped() })) controller.addAction(UIAlertAction(title: "Button Style", style: .default, handler: { _ in self.buttonStyleTapped() })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) controller.addAction(UIAlertAction(title: "Reset", style: .destructive, handler: { _ in self.resetData() })) present(controller, animated: true, completion: nil) } func buttonDisplayModeTapped() { let controller = UIAlertController(title: "Button Display Mode", message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: "Image + Title", style: .default, handler: { _ in self.buttonDisplayMode = .titleAndImage })) controller.addAction(UIAlertAction(title: "Image Only", style: .default, handler: { _ in self.buttonDisplayMode = .imageOnly })) controller.addAction(UIAlertAction(title: "Title Only", style: .default, handler: { _ in self.buttonDisplayMode = .titleOnly })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(controller, animated: true, completion: nil) } func buttonStyleTapped() { let controller = UIAlertController(title: "Button Style", message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: "Background Color", style: .default, handler: { _ in self.buttonStyle = .backgroundColor self.defaultOptions.transitionStyle = .border })) controller.addAction(UIAlertAction(title: "Circular", style: .default, handler: { _ in self.buttonStyle = .circular self.defaultOptions.transitionStyle = .reveal })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(controller, animated: true, completion: nil) } // MARK: - Helpers func createSelectedBackgroundView() -> UIView { let view = UIView() view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2) return view } func resetData() { emails = mockEmails emails.forEach { $0.unread = false } tableView.reloadData() } } extension MailViewController: SwipeTableViewCellDelegate { func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { let email = emails[indexPath.row] if orientation == .left { guard isSwipeRightEnabled else { return nil } let read = SwipeAction(style: .default, title: nil) { action, indexPath in let updatedStatus = !email.unread email.unread = updatedStatus let cell = tableView.cellForRow(at: indexPath) as! MailTableCell cell.setUnread(updatedStatus, animated: true) } read.hidesWhenSelected = true read.accessibilityLabel = email.unread ? "Mark as Read" : "Mark as Unread" let descriptor: ActionDescriptor = email.unread ? .read : .unread configure(action: read, with: descriptor) return [read] } else { let flag = SwipeAction(style: .default, title: nil, handler: nil) flag.hidesWhenSelected = true configure(action: flag, with: .flag) let delete = SwipeAction(style: .destructive, title: nil) { action, indexPath in self.emails.remove(at: indexPath.row) } configure(action: delete, with: .trash) let cell = tableView.cellForRow(at: indexPath) as! MailTableCell let closure: (UIAlertAction) -> Void = { _ in cell.hideSwipe(animated: true) } let more = SwipeAction(style: .default, title: nil) { action, indexPath in let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: "Reply", style: .default, handler: closure)) controller.addAction(UIAlertAction(title: "Forward", style: .default, handler: closure)) controller.addAction(UIAlertAction(title: "Mark...", style: .default, handler: closure)) controller.addAction(UIAlertAction(title: "Notify Me...", style: .default, handler: closure)) controller.addAction(UIAlertAction(title: "Move Message...", style: .default, handler: closure)) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: closure)) self.present(controller, animated: true, completion: nil) } configure(action: more, with: .more) return [delete, flag, more] } } func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeTableOptions { var options = SwipeTableOptions() options.expansionStyle = orientation == .left ? .selection : .destructive options.transitionStyle = defaultOptions.transitionStyle switch buttonStyle { case .backgroundColor: options.buttonSpacing = 11 case .circular: options.buttonSpacing = 4 options.backgroundColor = #colorLiteral(red: 0.9467939734, green: 0.9468161464, blue: 0.9468042254, alpha: 1) } return options } func configure(action: SwipeAction, with descriptor: ActionDescriptor) { action.title = descriptor.title(forDisplayMode: buttonDisplayMode) action.image = descriptor.image(forStyle: buttonStyle, displayMode: buttonDisplayMode) switch buttonStyle { case .backgroundColor: action.backgroundColor = descriptor.color case .circular: action.backgroundColor = .clear action.textColor = descriptor.color action.font = .systemFont(ofSize: 13) action.transitionDelegate = ScaleTransition.default } } }
mit
e5c4854e33916d1f6c310d56cab7f20d
45.231579
200
0.650501
5.054085
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/ArticleURLListViewController.swift
3
5346
import UIKit class ArticleURLListViewController: ArticleCollectionViewController, DetailPresentingFromContentGroup { let articleURLs: [URL] private let articleKeys: Set<String> let contentGroupIDURIString: String? required init(articleURLs: [URL], dataStore: MWKDataStore, contentGroup: WMFContentGroup? = nil, theme: Theme) { self.articleURLs = articleURLs self.articleKeys = Set<String>(articleURLs.compactMap { $0.wmf_databaseKey } ) self.contentGroupIDURIString = contentGroup?.objectID.uriRepresentation().absoluteString super.init() feedFunnelContext = FeedFunnelContext(contentGroup) self.theme = theme self.dataStore = dataStore } deinit { NotificationCenter.default.removeObserver(self) } @objc func articleDidChange(_ note: Notification) { guard let article = note.object as? WMFArticle, article.hasChangedValuesForCurrentEventThatAffectPreviews, let articleKey = article.key, articleKeys.contains(articleKey) else { return } collectionView.reloadData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported") } override func articleURL(at indexPath: IndexPath) -> URL? { guard indexPath.item < articleURLs.count else { return nil } return articleURLs[indexPath.item] } override func article(at indexPath: IndexPath) -> WMFArticle? { guard let articleURL = articleURL(at: indexPath) else { return nil } return dataStore.fetchOrCreateArticle(with: articleURL) } override func viewDidLoad() { super.viewDidLoad() collectionView.reloadData() NotificationCenter.default.addObserver(self, selector: #selector(articleDidChange(_:)), name: NSNotification.Name.WMFArticleUpdated, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if isMovingFromParent { FeedFunnel.shared.logFeedCardClosed(for: feedFunnelContext, maxViewed: maxViewed) } } override var eventLoggingCategory: EventLoggingCategory { return .feed } override var eventLoggingLabel: EventLoggingLabel? { return feedFunnelContext?.label } override func collectionViewFooterButtonWasPressed(_ collectionViewFooter: CollectionViewFooter) { navigationController?.popViewController(animated: true) } } // MARK: - UICollectionViewDataSource extension ArticleURLListViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return articleURLs.count } } // MARK: - UICollectionViewDelegate extension ArticleURLListViewController { override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { super.collectionView(collectionView, didSelectItemAt: indexPath) FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: feedFunnelContext, index: indexPath.item, maxViewed: maxViewed) } } // MARK: - UIViewControllerPreviewingDelegate extension ArticleURLListViewController { override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let vc = super.previewingContext(previewingContext, viewControllerForLocation: location) FeedFunnel.shared.logArticleInFeedDetailPreviewed(for: feedFunnelContext, index: previewedIndexPath?.item) return vc } override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { super.previewingContext(previewingContext, commit: viewControllerToCommit) FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: feedFunnelContext, index: previewedIndexPath?.item, maxViewed: maxViewed) } } // MARK: - WMFArticlePreviewingActionsDelegate extension ArticleURLListViewController { override func shareArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, shareActivityController: UIActivityViewController) { FeedFunnel.shared.logFeedDetailShareTapped(for: feedFunnelContext, index: previewedIndexPath?.item) super.shareArticlePreviewActionSelected(withArticleController: articleController, shareActivityController: shareActivityController) } override func readMoreArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) { articleController.wmf_removePeekableChildViewControllers() wmf_push(articleController, context: feedFunnelContext, index: previewedIndexPath?.item, animated: true) } } extension ArticleURLListViewController { override func didPerformAction(_ action: Action) -> Bool { if action.type == .share { FeedFunnel.shared.logFeedDetailShareTapped(for: feedFunnelContext, index: action.indexPath.item) } return super.didPerformAction(action) } }
mit
d4c8acdd414d1fc7eb723b1d7ab8782c
39.80916
171
0.730079
5.993274
false
false
false
false
zhubinchen/MarkLite
MarkLite/ViewController/TextViewController.swift
2
9995
// // TextViewController.swift // Markdown // // Created by zhubch on 2017/6/28. // Copyright © 2017年 zhubch. All rights reserved. // import UIKit import RxSwift import RxCocoa import EZSwiftExtensions class TextViewController: UIViewController { @IBOutlet weak var editView: TextView! var contentHeight: CGFloat { // if _textWidth != editView.w { // _textWidth = editView.w // let w = _textWidth - editView.contentInset.left * 2 // _textHeight = editView.sizeThatFits(editView.contentSize).height + editView.contentInset.bottom // } return editView.contentSize.height } var _textHeight: CGFloat = 0 var _textWidth: CGFloat = 0 var offset: CGFloat = 0.0 { didSet { var y = offset * (contentHeight - editView.h) if y > contentHeight - editView.h { y = contentHeight - editView.h } if y < 0 { y = 0 } editView.contentOffset = CGPoint(x: editView.contentOffset.x,y: y) } } var lastOffsetY: CGFloat = 0.0 var textChangedHandler: ((String)->Void)? var didScrollHandler: ((CGFloat)->Void)? let bag = DisposeBag() let assistBar = KeyboardBar() var timer: Timer? var text: String = "" var visibleRange: NSRange? { let topLeft = CGPoint(x: editView.bounds.minX, y: editView.bounds.minY) let bottomRight = CGPoint(x: editView.bounds.maxX, y: editView.bounds.maxY) guard let topLeftTextPosition = editView.closestPosition(to: topLeft), let bottomRightTextPosition = editView.closestPosition(to: bottomRight) else { return nil } let location = editView.offset(from: editView.beginningOfDocument, to: topLeftTextPosition) let length = editView.offset(from: topLeftTextPosition, to: bottomRightTextPosition) return NSRange(location: location, length: length) } var highlightmanager = MarkdownHighlightManager() override func viewDidLoad() { super.viewDidLoad() setupRx() editView.viewController = self editView.textContainer.lineBreakMode = .byCharWrapping view.setBackgroundColor(.background) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if _textWidth != editView.w { updateInset() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in guard let this = self else { return } let offset = this.editView.contentOffset.y if this.contentHeight - this.editView.h > 0 { this.didScrollHandler?(offset / (this.contentHeight - this.editView.h)) } } } func setupRx() { Configure.shared.isAssistBarEnabled.asObservable().subscribe(onNext: { [unowned self](enable) in if enable { self.assistBar.textView = self.editView self.editView.inputAccessoryView = self.assistBar } else { self.editView.inputAccessoryView = nil } }).disposed(by: bag) Configure.shared.theme.asObservable().subscribe(onNext: { [unowned self] _ in self.highlightmanager = MarkdownHighlightManager() self.textViewDidChange(self.editView) }).disposed(by: bag) Configure.shared.fontSize.asObservable().subscribe(onNext: { [unowned self] (size) in HighlightStyle.boldFont = UIFont.monospacedDigitSystemFont(ofSize: CGFloat(size), weight: UIFont.Weight.medium) HighlightStyle.normalFont = UIFont.monospacedDigitSystemFont(ofSize: CGFloat(size), weight: UIFont.Weight.regular) self.highlightmanager = MarkdownHighlightManager() self.textViewDidChange(self.editView) }).disposed(by: bag) } func showTOC(_ toc: TOCItem) { let expStr = "#+ +\(toc.title)\\s*\n" guard let range = editView.text.firstMatchRange(expStr) else { return } if let position = editView.position(from: editView.beginningOfDocument, offset: range.location) { let rect = editView.caretRect(for: position) let y = max(min(rect.y,editView.contentSize.height - editView.h),0) editView.setContentOffset(CGPoint(x: editView.contentOffset.x, y: y), animated: true) } } func updateInset() { let inset = max((self.view.w - 500) * 0.3,0) + 8 self.editView.contentInset = UIEdgeInsetsMake(0, inset + 8, 20, inset) _textWidth = 0 } func loadText(_ text: String) { self.text = text if text.count == 0 { editView.becomeFirstResponder() return } if text.length > 800 { editView.text = text[0..<800] ActivityIndicator.show(on: self.editView) DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in guard let this = self else { return } this.editView.text = text this.textViewDidChange(this.editView) ActivityIndicator.dismissOnView(this.editView) } } else { editView.text = text textViewDidChange(editView) } } func appendText(_ text: String) { } @objc func highlight() { if editView.text.count < 5000 { highlightmanager.highlight(editView.textStorage,visibleRange: nil) } else if let range = self.visibleRange { highlightmanager.highlight(editView.textStorage,visibleRange: range) } } func newLine(_ last: String) -> String { if last.hasPrefix("- [x] ") { return last + "\n- [x] " } if last.hasPrefix("- [ ] ") { return last + "\n- [ ] " } if let str = last.firstMatch("^[\\s]*(-|\\*|\\+|([0-9]+\\.)) ") { if last.firstMatch("^[\\s]*(-|\\*|\\+|([0-9]+\\.)) +[\\S]+") == nil { return "\n" } guard let range = str.firstMatchRange("[0-9]+") else { return last + "\n" + str } let num = str.substring(with: range).toInt() ?? 0 return last + "\n" + str.replacingCharacters(in: range, with: "\(num+1)") } if let str = last.firstMatch("^( {4}|\\t)+") { return last + "\n" + str } return last + "\n" } deinit { timer?.invalidate() removeNotificationObserver() print("deinit text_vc") } } extension TextViewController: UITextViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.isDragging { let offset = scrollView.contentOffset.y if contentHeight - scrollView.h > 0 { didScrollHandler?(offset / (contentHeight - scrollView.h)) } } if Configure.shared.autoHideNavigationBar.value == false { return } let pan = scrollView.panGestureRecognizer let velocity = pan.velocity(in: scrollView).y if velocity < -600 { self.navigationController?.setNavigationBarHidden(true, animated: true) } else if velocity > 600 { self.navigationController?.setNavigationBarHidden(false, animated: true) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if editView.text.count < 5000 { return } if fabs(scrollView.contentOffset.y - lastOffsetY) < 500 { return } timer?.invalidate() let contentOffset = editView.contentOffset highlight() editView.contentOffset = contentOffset lastOffsetY = scrollView.contentOffset.y } func textViewDidBeginEditing(_ textView: UITextView) { UIApplication.shared.isIdleTimerDisabled = true if Configure.shared.autoHideNavigationBar.value { navigationController?.setNavigationBarHidden(true, animated: true) } } func textViewDidEndEditing(_ textView: UITextView) { UIApplication.shared.isIdleTimerDisabled = false navigationController?.setNavigationBarHidden(false, animated: true) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { let begin = max(range.location - 100, 0) let len = range.location - begin let nsString = textView.text! as NSString let nearText = nsString.substring(with: NSRange(location:begin, length: len)) let texts = nearText.components(separatedBy: "\n") if texts.count < 2 { return true } let lastLineCount = texts.last!.count let beginning = textView.beginningOfDocument guard let from = textView.position(from: beginning, offset: range.location - lastLineCount), let to = textView.position(from: beginning, offset: range.location), let textRange = textView.textRange(from: from, to: to) else { return true } textView.replace(textRange, withText: newLine(texts.last!)) return false } return true } func textViewDidChange(_ textView: UITextView) { self.text = textView.text if editView.markedTextRange != nil { return } textChangedHandler?(text) timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(highlight), userInfo: nil, repeats: false) _textWidth = 0 } }
gpl-3.0
5769a38c54d13c2ff6396d5051032add
34.685714
235
0.586469
4.848132
false
false
false
false
ArsalanWahid/yemekye
yemekye/Network Layer/constants.swift
1
694
// // constants.swift // yemekye // // Created by Arsalan Wahid Asghar on 12/31/17. // Copyright © 2017 Arsalan Wahid Asghar. All rights reserved. // struct Constants{ // This will be use to contruct the calls to the zomaoAPI struct Zomato{ static let APIBaseURL = "https://developers.zomato.com/api/v2.1/" } struct Method{ static let cities = "cities" static let locations = "locations" static let location_details = "location_details" } struct ParametersKeys{ static let q = "q" static let query = "query" static let lat = "lat" static let lon = "lon" } }
apache-2.0
266d3cb5c9e1ee4a3df7215bc23f5050
19.382353
73
0.58153
3.725806
false
false
false
false
jlyu/swift-demo
CtrlEffect/CtrlEffect/TransformControlsViewController.swift
1
4087
// // TransformControlsViewController.swift // CtrlEffect // // Created by chain on 14-8-14. // Copyright (c) 2014 Chain. All rights reserved. // import UIKit protocol TransformControlsDelegate { func transformDidChange(transform: CGAffineTransform, sender: AnyObject) } struct Vect2D { var x: Float var y: Float var xCG: CGFloat { return CGFloat(x) } var yCG: CGFloat { return CGFloat(y) } } class TransformControlsViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var rotationSlider: UISlider! var transformDelegate: TransformControlsDelegate? var currentTransform: CGAffineTransform? var backgroundView: UIVisualEffectView? override func viewDidLoad() { if currentTransform != nil { applyTransformToSliders(currentTransform!) } backgroundView = prepareVisualEffectView() view.addSubview(backgroundView!) applyEqualSizeConstraints(view, v2: backgroundView!, includeTop: false) view.backgroundColor = UIColor.clearColor() } func applyTransformToSliders(transform: CGAffineTransform) { let decomposition = decomposeAffineTransform(transform) rotationSlider.value = decomposition.rotation } func prepareVisualEffectView() -> UIVisualEffectView { // Create the blur effect let blurEffect = UIBlurEffect(style: .Light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.contentView.backgroundColor = UIColor.clearColor() // Create the vibrancy effect - to be added to the blur let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect) let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect) // Add the content to the views appropriately vibrancyEffectView.contentView.addSubview(containerView) blurEffectView.contentView.addSubview(vibrancyEffectView) // Prepare autolayout containerView.setTranslatesAutoresizingMaskIntoConstraints(false) blurEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) vibrancyEffectView.setTranslatesAutoresizingMaskIntoConstraints(false) applyEqualSizeConstraints(vibrancyEffectView.contentView, v2: containerView, includeTop: true) applyEqualSizeConstraints(blurEffectView.contentView, v2: vibrancyEffectView, includeTop: true) return blurEffectView } func applyEqualSizeConstraints(v1: UIView, v2: UIView, includeTop: Bool) { v1.addConstraint(NSLayoutConstraint(item: v1, attribute: .Left, relatedBy: .Equal, toItem: v2, attribute: .Left, multiplier: 1, constant: 0)) v1.addConstraint(NSLayoutConstraint(item: v1, attribute: .Right, relatedBy: .Equal, toItem: v2, attribute: .Right, multiplier: 1, constant: 0)) v1.addConstraint(NSLayoutConstraint(item: v1, attribute: .Bottom, relatedBy: .Equal, toItem: v2, attribute: .Bottom, multiplier: 1, constant: 0)) if(includeTop) { v1.addConstraint(NSLayoutConstraint(item: v1, attribute: .Top, relatedBy: .Equal, toItem: v2, attribute: .Top, multiplier: 1, constant: 0)) } } func decomposeAffineTransform(transform: CGAffineTransform) -> (rotation: Float, scale: Vect2D, translation: Vect2D) { // This requires a specific ordering (and no skewing). It matches the constructTransform method // Translation first let translation = Vect2D(x: Float(transform.tx), y: Float(transform.ty)) // Then scale let scaleX = sqrt(Double(transform.a * transform.a + transform.c * transform.c)) let scaleY = sqrt(Double(transform.b * transform.b + transform.d * transform.d)) let scale = Vect2D(x: Float(scaleX), y: Float(scaleY)) // And rotation let rotation = Float(atan2(Double(transform.b), Double(transform.a))) return (rotation, scale, translation) } }
mit
03dfc1f6a223c23b5d82f9f5eb8862b8
37.933333
153
0.690727
4.990232
false
false
false
false
KoCMoHaBTa/MHAppKit
MHAppKit/Extensions/UIKit/UISegmentedControl.swift
1
1685
// // UISegmentedControl.swift // MHAppKit // // Created by Milen Halachev on 14.03.18. // Copyright © 2018 Milen Halachev. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import Foundation import UIKit extension UISegmentedControl { public func framesForAllSegments() -> [CGRect] { let height = self.frame.size.height let y: CGFloat = 0 var x: CGFloat = 0 var result: [CGRect] = [] for index in 0..<self.numberOfSegments { var width = self.widthForSegment(at: index) //if segments are autosized if width == 0 { if self.apportionsSegmentWidthsByContent { //segments have different size based on contet //look trough their subviews let title = self.titleForSegment(at: index) width = self.subview(matching: { ($0 as? UILabel)?.text == title })?.superview(matching: { $0.frame.size.height == height })?.frame.size.width ?? 0 } else { //segments have the same size based on contet width = self.frame.size.width / CGFloat(self.numberOfSegments) } } let frame = CGRect(x: x, y: y, width: width, height: height) result.append(frame) x += width } return result } public func frameForSegment(at index: Int) -> CGRect { return self.framesForAllSegments()[index] } } #endif
mit
4a3b6dbe1eebb894a0c17f4c2634d5b1
28.54386
167
0.508907
4.909621
false
false
false
false
DmitryBespalov/Dynamics
Dynamics/DynamicLayout.swift
1
4994
// // DynamicLayout.swift // Dynamics // // Created by Dmitry Bespalov on 08/03/17. // Copyright © 2017 Dmitry Bespalov. All rights reserved. // import UIKit class DynamicLayout: UICollectionViewFlowLayout { private var animator: UIDynamicAnimator! private var translation: CGFloat = 0 /// Coefficient that reduces springy motion. The bigger it is, less motion is produced. private let springStiffness: CGFloat = 2000 /// How fast spring will be moving; Units/second private let springSpeed: CGFloat = 2 /// How much energy will be lost between spring movements private let springDamping: CGFloat = 0.9 private let springLength: CGFloat = 0 override init() { super.init() configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } private func configure() { animator = UIDynamicAnimator(collectionViewLayout: self) } override func prepare() { super.prepare() guard let visibleAttributes = super.layoutAttributesForElements(in: visibleRect) else { return } removeDisappearedBehaviors(with: visibleAttributes) addAppearedBehaviors(with: visibleAttributes) } private var visibleRect: CGRect { guard let collectionView = collectionView else { return CGRect.zero } return CGRect(origin: collectionView.bounds.origin, size: collectionView.frame.size) } private func removeDisappearedBehaviors(with visibleAttributes: [UICollectionViewLayoutAttributes]) { let visiblePaths = Set<IndexPath>(visibleAttributes.map { $0.indexPath }) let disappearedBehaviors = behaviors.filter { !visiblePaths.contains( item(of: $0).indexPath ) } disappearedBehaviors.forEach { animator.removeBehavior($0) } } private func addAppearedBehaviors(with visibleAttributes: [UICollectionViewLayoutAttributes]) { let existingPaths = Set<IndexPath>(animatedAttributes.map { $0.indexPath }) let appearedAttributes = visibleAttributes.filter { !existingPaths.contains($0.indexPath) } appearedAttributes.forEach { attribute in let attachment = behavior(for: attribute) updateAttribute(in: attachment) animator.addBehavior(attachment) } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return animator.items(in: rect) as? [UICollectionViewLayoutAttributes] } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return animator.layoutAttributesForCell(at: indexPath) ?? super.layoutAttributesForItem(at: indexPath) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard let collectionView = collectionView else { return false } translation = newBounds.minY - collectionView.bounds.minY behaviors.forEach { updateAttribute(in: $0) } return false } private var animatedAttributes: [UICollectionViewLayoutAttributes] { return animator.behaviors.flatMap { ($0 as? UIAttachmentBehavior)?.items.first as? UICollectionViewLayoutAttributes } } private var behaviors: [UIAttachmentBehavior] { return animator.behaviors.flatMap { $0 as? UIAttachmentBehavior } } private func item(of behavior: UIAttachmentBehavior) -> UICollectionViewLayoutAttributes { return behavior.items.first as! UICollectionViewLayoutAttributes } private func behavior(for attribute: UICollectionViewLayoutAttributes) -> UIAttachmentBehavior { // each attribute has its own behavior that attaches an item to its center. let behavior = UIAttachmentBehavior(item: attribute, attachedToAnchor: attribute.center) behavior.damping = springDamping behavior.length = springLength behavior.frequency = springSpeed return behavior } private func updateAttribute(in behavior: UIAttachmentBehavior) { let attribute = item(of: behavior) var screenAnchor: CGFloat = 0 if let collectionView = collectionView { let touch = collectionView.panGestureRecognizer.location(in: collectionView) let isTouching = collectionView.panGestureRecognizer.state == UIGestureRecognizerState.changed // when collection view scrolled programmatically, we want to use its bounds instead of touch point screenAnchor = isTouching ? touch.y : collectionView.bounds.midY } // the factor is dependent on distance of the item from a screen anchor let factor = (screenAnchor - behavior.anchorPoint.y) / springStiffness let clampFunc: (CGFloat, CGFloat) -> CGFloat = translation < 0 ? max : min attribute.center.y += clampFunc(translation * factor, translation) animator.updateItem(usingCurrentState: attribute) } }
mit
7b6ec0fbf0597435917d31dcad8ee22a
40.957983
111
0.70699
5.427174
false
false
false
false
srn214/Floral
Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/controller/CLImagePickersViewController.swift
1
10579
// // ImagePickersViewController.swift // ImageDeal // // Created by darren on 2017/7/27. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit import Photos import PhotosUI typealias CLChooseImageCompleteClouse = (Array<PHAsset>,UIImage?)->() //MARK: - 导航控制器 class CLImagePickersViewController: UINavigationController { @objc static let share = CLImagePickersViewController() @objc var imageCompleteClouse: CLChooseImageCompleteClouse? @objc let albumVC = CLImageAlbumPickerController() func initWith( MaxImagesCount:Int, isHiddenVideo:Bool, cameraOut:Bool, singleType:CLImagePickerToolType?, singlePictureCropScale:CGFloat?, onlyChooseImageOrVideo:Bool, singleModelImageCanEditor: Bool, showCamaroInPicture: Bool, isHiddenImage:Bool, navColor:UIColor? = nil, navTitleColor:UIColor? = nil, statusBarType:CLImagePickerToolStatusBarType, didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) -> CLImagePickersViewController { // 存储用户设置的最多图片数量 UserDefaults.standard.set(MaxImagesCount, forKey: CLImagePickerMaxImagesCount) UserDefaults.standard.synchronize() CLNotificationCenter.addObserver(self, selector: #selector(CLPhotoListRefreshNoticMethod(notic:)), name: NSNotification.Name(rawValue:CLPhotoListRefreshNotic), object: nil) // 清除保存的数据 CLPickersTools.instence.clearPicture() // 如果用户之前设置的是onlyChooseImageOrVideo类型,记得将这个类型刚开始就置空 UserDefaults.standard.set(0, forKey: UserChooserType) UserDefaults.standard.synchronize() // CLPickersTools是一个单利,在这个单利中记录导航栏的信息,可以对导航栏进行设置 CLPickersTools.instence.isHiddenVideo = isHiddenVideo // 是否隐藏视频文件赋值 CLPickersTools.instence.isHiddenImage = isHiddenImage CLPickersTools.instence.navColor = navColor CLPickersTools.instence.navTitleColor = navTitleColor CLPickersTools.instence.statusBarType = statusBarType let dataArr = CLPickersTools.instence.loadData() albumVC.dataArr = dataArr albumVC.cameraOut = cameraOut albumVC.imageCompleteClouse = didChooseImageSuccess albumVC.singleType = singleType albumVC.singlePictureCropScale = singlePictureCropScale albumVC.onlyChooseImageOrVideo = onlyChooseImageOrVideo albumVC.singleModelImageCanEditor = singleModelImageCanEditor let vc = CLImagePickersViewController.init(rootViewController: albumVC) vc.setupOnce(array: dataArr, cameraOut:cameraOut, singleType:singleType, singlePictureCropScale:singlePictureCropScale, onlyChooseImageOrVideo:onlyChooseImageOrVideo, singleModelImageCanEditor:singleModelImageCanEditor, showCamaroInPicture: showCamaroInPicture, didChooseImageSuccess:didChooseImageSuccess) return vc } func setupOnce(array:[[String:[CLImagePickerPhotoModel]]], cameraOut:Bool, singleType:CLImagePickerToolType?, singlePictureCropScale:CGFloat?, onlyChooseImageOrVideo:Bool, singleModelImageCanEditor:Bool, showCamaroInPicture: Bool, didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) { self.imageCompleteClouse = didChooseImageSuccess let rowData = array.first let singleVC = CLImagePickerSingleViewController.init(nibName: "CLImagePickerSingleViewController", bundle: BundleUtil.getCurrentBundle()) singleVC.navTitle = rowData?.keys.first ?? "" singleVC.photoArr = rowData?.values.first singleVC.showCamaroInPicture = showCamaroInPicture if singleVC.navTitle == allPhoto || singleVC.navTitle == allPhoto2 || singleVC.navTitle == allPhoto3 || singleVC.navTitle == allPhoto4 { if cameraOut == false { // 相机不是放在外面 singleVC.isAllPhoto = true } } singleVC.onlyChooseImageOrVideo = onlyChooseImageOrVideo singleVC.singlePictureCropScale = singlePictureCropScale singleVC.singleType = singleType singleVC.singleModelImageCanEditor = singleModelImageCanEditor singleVC.singleChooseImageCompleteClouse = {[weak self] (assetArr:Array<PHAsset>,image) in self?.imageCompleteClouse!(assetArr,image) } self.pushViewController(singleVC, animated: true) } deinit { print("CLImagePickersViewController释放") CLNotificationCenter.removeObserver(self) } @objc func CLPhotoListRefreshNoticMethod(notic:Notification) { albumVC.dataArr = notic.object as? [[String : [CLImagePickerPhotoModel]]] } } //MARK: - 相册列表控制器 class CLImageAlbumPickerController: CLBaseImagePickerViewController { @objc var imageCompleteClouse: CLChooseImageCompleteClouse? // 相机是否放在内部 @objc var cameraOut: Bool = false // 单选状态的类型 var singleType: CLImagePickerToolType? // 图片裁剪比例 var singlePictureCropScale: CGFloat? // 视频和照片只能选择一种,不能同时选择,默认可以同时选择 @objc var onlyChooseImageOrVideo: Bool = false // 单选模式下图片可以编辑 @objc var singleModelImageCanEditor: Bool = false var showCamaroInPicture: Bool = true @objc lazy var tableView: UITableView = { let tableView = UITableView.init(frame: CGRect(x:0,y:KNavgationBarHeight,width:KScreenWidth,height:KScreenHeight-KNavgationBarHeight), style: .plain) tableView.tableFooterView = UIView() tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 60 return tableView }() fileprivate var dataArr: [[String:[CLImagePickerPhotoModel]]]? { didSet{ self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.initView() // 判断用户是否开启访问相册功能 CLPickersTools.instence.authorize(authorizeClouse: { (state) in if state == .authorized { self.tableView.reloadData() } else { return } }) initConstraints() } func initConstraints() { self.tableView.translatesAutoresizingMaskIntoConstraints = false let margin: CGFloat = UIDevice.current.isX() == true ? 34:0 self.view.addConstraints([ NSLayoutConstraint.init(item: self.tableView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: KNavgationBarHeight), NSLayoutConstraint.init(item: self.tableView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0), NSLayoutConstraint.init(item: self.tableView, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0), NSLayoutConstraint.init(item: self.tableView, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: -margin) ]) } override func rightBtnClick() { self.dismiss(animated: true, completion: nil) } @objc func initView() { self.navTitle = photoStr self.backBtn.isHidden = true self.rightBtn.setTitle(cancelStr, for: .normal) self.view.addSubview(tableView) if #available(iOS 9.0, *) { self.tableView.cellLayoutMarginsFollowReadableWidth = false } else { } } deinit { print("CLImageAlbumPickerController释放") } } //MARK: - UITableViewDelegate,UITableViewDataSource extension CLImageAlbumPickerController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.dataArr == nil { return 0 } else { return self.dataArr!.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = CLImagePickerListCell.cellWithTableView(tableView: tableView) cell.rowData = self.dataArr?[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let rowData = self.dataArr?[indexPath.row] let singleVC = CLImagePickerSingleViewController.init(nibName: "CLImagePickerSingleViewController", bundle: BundleUtil.getCurrentBundle()) singleVC.navTitle = rowData?.keys.first ?? "" singleVC.photoArr = rowData?.values.first singleVC.showCamaroInPicture = showCamaroInPicture if singleVC.navTitle == allPhoto || singleVC.navTitle == allPhoto2 || singleVC.navTitle == allPhoto3 || singleVC.navTitle == allPhoto4 { if cameraOut == false { // 相机不是放在外面 singleVC.isAllPhoto = true } } singleVC.onlyChooseImageOrVideo = onlyChooseImageOrVideo singleVC.singleType = singleType singleVC.singleModelImageCanEditor = singleModelImageCanEditor singleVC.singlePictureCropScale = singlePictureCropScale singleVC.singleChooseImageCompleteClouse = {[weak self] (assetArr:Array<PHAsset>,image) in self?.imageCompleteClouse!(assetArr,image) } self.navigationController?.pushViewController(singleVC, animated: true) } }
mit
c57e04f6e1188613c1f7f22659365857
40.745902
259
0.679462
5.609031
false
false
false
false
glock45/swiftX
Source/http/json.swift
1
4233
// // json.swift // swiftx // // Copyright © 2016 kolakowski. All rights reserved. // import Foundation public class JsonResponse: Response { private func commonInit() { self.headers.append(("Content-Type", "application/json")) } public init(_ status: Int = Status.ok.rawValue, _ dictionary: Dictionary<String, Any>) { super.init(status) self.commonInit() self.body = dictionary.toJson() } public init(_ status: Int = Status.ok.rawValue, _ array: Array<Any>) { super.init(status) self.commonInit() self.body = array.toJson() } } extension Dictionary { public func toJson() -> [UInt8] { var result = [UInt8]() result.append(0x7B) for (key, value) in self { if let stringKey = key as? String { result.append(contentsOf: escapeJSONString(stringKey)) result.append(0x3A) result.append(contentsOf: asJsonValue(value)) } result.append(0x2C) } if !self.isEmpty { result.removeLast() } result.append(0x7D) return result } } extension Array { public func toJson() -> [UInt8] { var result = [UInt8]() result.append(0x5B) for item in self { result.append(contentsOf: asJsonValue(item)) result.append(0x2C) } if !self.isEmpty { result.removeLast() } result.append(0x5D) return result } } private func escapeJSONString(_ string: String) -> [UInt8] { var result = [UInt8]() result.append(0x22) for scalar in string.unicodeScalars { switch scalar.value { case 0 : result.append(contentsOf: [UInt8]("\\0".utf8)) case 7 : result.append(contentsOf: [UInt8]("\\a".utf8)) case 8 : result.append(contentsOf: [UInt8]("\\b".utf8)) case 9 : result.append(contentsOf: [UInt8]("\\t".utf8)) case 10: result.append(contentsOf: [UInt8]("\\n".utf8)) case 11: result.append(contentsOf: [UInt8]("\\v".utf8)) case 12: result.append(contentsOf: [UInt8]("\\f".utf8)) case 13: result.append(contentsOf: [UInt8]("\\r".utf8)) case 34: result.append(contentsOf: [UInt8]("\\\"".utf8)) case 39: result.append(contentsOf: [UInt8]("\\'".utf8)) case 47: result.append(contentsOf: [UInt8]("\\/".utf8)) case 92: result.append(contentsOf: [UInt8]("\\\\".utf8)) case let n where n > 127: result.append(contentsOf: [UInt8]("\\u".utf8)) result.append(contentsOf: [UInt8](String(format:"%04X", n).utf8)) default: result.append(UInt8(scalar.value)) } } result.append(0x22) return result } private func asJsonValue(_ value: Any?) -> [UInt8] { if let value = value { switch value { case let int as Int8: return [UInt8](String(int).utf8) case let int as UInt8: return [UInt8](String(int).utf8) case let int as Int16: return [UInt8](String(int).utf8) case let int as UInt16: return [UInt8](String(int).utf8) case let int as Int32: return [UInt8](String(int).utf8) case let int as UInt32: return [UInt8](String(int).utf8) case let int as Int64: return [UInt8](String(int).utf8) case let int as UInt64: return [UInt8](String(int).utf8) case let int as Int: return [UInt8](String(int).utf8) case let int as UInt: return [UInt8](String(int).utf8) case let int as Float: return [UInt8](String(int).utf8) case let int as Double: return [UInt8](String(int).utf8) case let bool as Bool: return bool ? [0x74, 0x72, 0x75, 0x65] : [0x66, 0x61, 0x6C, 0x73, 0x65] case let dict as Dictionary<String, Any>: return dict.toJson() case let dict as Dictionary<String, Any?>: return dict.toJson() case let array as Array<Any>: return array.toJson() case let array as Array<Any?>: return array.toJson() case let string as String: return escapeJSONString(string) default: return [0x6E, 0x75, 0x6C, 0x6C] } } return [0x6E, 0x75, 0x6C, 0x6C] }
bsd-3-clause
11a2a7f957dbd449c558b2b9861d1bb5
33.975207
102
0.584121
3.565291
false
false
false
false
slepcat/mint
MINT/MintLeafOperators.swift
1
16302
// // MintLeafOperators.swift // MINT // // Created by NemuNeko on 2015/04/26. // Copyright (c) 2015年 Taizo A. All rights reserved. // import Foundation /* class SetColor : Leaf { override init(newID: Int) { super.init(newID: newID) args = [Color(r: 0.5, g: 0.5, b: 0.5, a: 1.0)] args.append(nil) argLabels += ["color", "mesh"] argTypes += ["Color", "Mesh"] returnType = "Mesh" let count = BirthCount.get.count("SetColor") name = "SetColor\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "color": let color = Color(r: 0.5, g: 0.5, b: 0.5, a: 1.0) setArg("color", value: color) case "mesh": setArg("mesh", value: nil) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if let color = eval("color") as? Color, let mesh = eval("mesh") as? Mesh { for var i = 0; mesh.mesh.count > i; i++ { for var j = 0; mesh.mesh[i].vertices.count > j; j++ { mesh.mesh[i].vertices[j].color = [color.r, color.g, color.b] } } return mesh } return nil } } // Transform operation of Mesh // Boolean operation of Mesh class Union : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, nil] argLabels += ["target1", "target2"] argTypes += ["Mesh", "Mesh"] returnType = "Mesh" let count = BirthCount.get.count("Union") name = "Union\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "target1": setArg("target1", value: nil) case "target2": setArg("target2", value: nil) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { // Like union, but when we know that the two solids are not intersecting // Do not use if you are not completely sure that the solids do not intersect! func unionForNonIntersecting(target1: Mesh, target2: Mesh) -> Mesh { return Mesh(m: target1.mesh + target2.mesh) } if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let targetMesh = eval("target1") as? Mesh, let targetMesh2 = eval("target2") as? Mesh { if !targetMesh.mayOverlap(targetMesh2) { mesh = unionForNonIntersecting(targetMesh, targetMesh2) } else { var a = MeshTree(polygons: targetMesh.mesh) var b = MeshTree(polygons: targetMesh2.mesh) a.clipTo(b, alsoRemovecoplanarFront: false) b.clipTo(a, alsoRemovecoplanarFront: false) b.invert() b.clipTo(a, alsoRemovecoplanarFront: false) b.invert() var newpolygons = a.allPolygons() + b.allPolygons() //if(retesselate) result = result.reTesselated(); //if(canonicalize) result = result.canonicalized(); mesh = Mesh(m: newpolygons) } needUpdate = false return mesh } return nil } } class Subtract : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, nil] argLabels += ["target", "subtract"] argTypes += ["Mesh", "Mesh"] returnType = "Mesh" let count = BirthCount.get.count("Subtract") name = "Subtract\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "target": setArg("target", value: nil) case "subtract": setArg("subtract", value: nil) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let targetMesh = eval("target") as? Mesh, let subtractMesh = eval("subtract") as? Mesh { var a = MeshTree(polygons: targetMesh.mesh) var b = MeshTree(polygons: subtractMesh.mesh) a.invert() a.clipTo(b, alsoRemovecoplanarFront: false) b.clipTo(a, alsoRemovecoplanarFront: true) a.addPolygons(b.allPolygons()) a.invert() var result = a.allPolygons() //if(retesselate) result = result.reTesselated(); //if(canonicalize) result = result.canonicalized(); mesh = Mesh(m: result) needUpdate = false return mesh } return nil } } // Boolean operation of Mesh class Intersect : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, nil] argLabels += ["target1", "target2"] argTypes += ["Mesh", "Mesh"] returnType = "Mesh" let count = BirthCount.get.count("Intersect") name = "Intersect\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "target1": setArg("target1", value: nil) case "target2": setArg("target2", value: nil) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let targetMesh = eval("target1") as? Mesh, let targetMesh2 = eval("target2") as? Mesh { var a = MeshTree(polygons: targetMesh.mesh) var b = MeshTree(polygons: targetMesh2.mesh) a.invert() b.clipTo(a, alsoRemovecoplanarFront: false) b.invert() a.clipTo(b, alsoRemovecoplanarFront: false) b.clipTo(a, alsoRemovecoplanarFront: false) a.addPolygons(b.allPolygons()) a.invert() var newpolygons = a.allPolygons() //if(retesselate) result = result.reTesselated(); //if(canonicalize) result = result.canonicalized(); mesh = Mesh(m: newpolygons) needUpdate = false return mesh } return nil } } // # Rotate leaf class Rotate : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, 0.0, 0.0, 0.0] argLabels += ["mesh", "x_angle", "y_angle", "z_angle"] argTypes += ["Mesh", "Double", "Double", "Double"] returnType = "Mesh" let count = BirthCount.get.count("Rotate") name = "Rotate\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "mesh": setArg("mesh", value: nil) case "x_angle": setArg("x_angle", value: 0.0) case "y_angle": setArg("y_angle", value: 0.0) case "z_angle": setArg("z_angle", value: 0.0) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let original = eval("mesh") as? Mesh, let xangle = eval("x_angle") as? Double, let yangle = eval("y_angle") as? Double, let zangle = eval("z_angle") as? Double { let rotatematrix = Matrix4x4.rotationZ(zangle) * Matrix4x4.rotationX(xangle) * Matrix4x4.rotationY(yangle) var newpolygons : [Polygon] = [] for var i = 0; original.mesh.count > i; i++ { var newpolyvex : [Vertex] = [] for var j = 0; original.mesh[i].vertices.count > j; j++ { newpolyvex += [original.mesh[i].vertices[j].transform(rotatematrix)] } var newpoly = Polygon(vertices: newpolyvex) newpoly.generateNormal() newpolygons.append(newpoly) } mesh = Mesh(m: newpolygons) needUpdate = false return mesh } return nil } } class RotateAxis : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, Vector(x: 0, y: 0, z: 1), 0.0, Vector(x: 0, y: 0, z: 0)] argLabels += ["mesh", "axis", "angle", "center"] argTypes += ["Mesh", "Vector", "Double", "Vector"] returnType = "Mesh" let count = BirthCount.get.count("RotateAxis") name = "RotateAxis\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "mesh": setArg("mesh", value: nil) case "axis": setArg("axis", value: Vector(x: 0, y: 0, z: 1)) case "angle": setArg("angle", value: 0.0) case "center": setArg("center", value: Vector(x: 0, y: 0, z: 0)) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let original = eval("mesh") as? Mesh, let axis = eval("axis") as? Vector, let angle = eval("angle") as? Double, let center = eval("center") as? Vector { let rotatematrix = Matrix4x4.rotation(center, rotationAxis: axis, degrees: angle) var newpolygons : [Polygon] = [] for var i = 0; original.mesh.count > i; i++ { var newpolyvex : [Vertex] = [] for var j = 0; original.mesh[i].vertices.count > j; j++ { newpolyvex += [original.mesh[i].vertices[j].transform(rotatematrix)] } var newpoly = Polygon(vertices: newpolyvex) newpoly.generateNormal() newpolygons.append(newpoly) } mesh = Mesh(m: newpolygons) needUpdate = false return mesh } return nil } } class Translate : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, Vector(x: 0, y: 0, z: 0)] argLabels += ["mesh", "center"] argTypes += ["Mesh", "Vector"] returnType = "Mesh" let count = BirthCount.get.count("Translate") name = "Translate\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "mesh": setArg("mesh", value: nil) case "center": setArg("center", value: Vector(x: 0, y: 0, z: 0)) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let original = eval("mesh") as? Mesh, let center = eval("center") as? Vector { let matrix = Matrix4x4.translation(center) var newpolygons : [Polygon] = [] for var i = 0; original.mesh.count > i; i++ { var newpolyvex : [Vertex] = [] for var j = 0; original.mesh[i].vertices.count > j; j++ { newpolyvex += [original.mesh[i].vertices[j].transform(matrix)] } var newpoly = Polygon(vertices: newpolyvex) newpoly.generateNormal() newpolygons.append(newpoly) } mesh = Mesh(m: newpolygons) needUpdate = false return mesh } return nil } } class Scale : Leaf { var mesh : Mesh? = nil override init(newID: Int) { super.init(newID: newID) args = [nil, Vector(x: 1.0, y: 1.0, z: 1.0)] argLabels += ["mesh", "scale"] argTypes += ["Mesh", "Vector"] returnType = "Mesh" let count = BirthCount.get.count("Scale") name = "Scale\(count)" } override func initArg(label: String) { super.initArg(label) switch label { case "mesh": setArg("mesh", value: nil) case "scale": setArg("scale", value: Vector(x: 1.0, y: 1.0, z: 1.0)) default: MintErr.exc.raise(MintEXC.ArgNotExist(leafName: name, leafID: leafID, reguired: label)) } } override func solve() -> Any? { if mesh != nil && needUpdate == false { return mesh } if let err = MintErr.exc.catch { MintErr.exc.raise(err) return nil } if let original = eval("mesh") as? Mesh, let scale = eval("scale") as? Vector { if scale.x > 0 && scale.y > 0 && scale.z > 0 { let matrix = Matrix4x4.scaling(scale) var newpolygons : [Polygon] = [] for var i = 0; original.mesh.count > i; i++ { var newpolyvex : [Vertex] = [] for var j = 0; original.mesh[i].vertices.count > j; j++ { newpolyvex += [original.mesh[i].vertices[j].transform(matrix)] } var newpoly = Polygon(vertices: newpolyvex) newpoly.generateNormal() newpolygons.append(newpoly) } mesh = Mesh(m: newpolygons) needUpdate = false return mesh } } return nil } } */
gpl-3.0
ccf4df2375ef69c289d2ff427679048e
26.863248
173
0.466994
4.596729
false
false
false
false
LoveAlwaysYoung/EnjoyUniversity
EnjoyUniversity/EnjoyUniversity/Classes/View/Profile/Search/EUUserInfoCell.swift
1
2856
// // EUUserInfoCell.swift // EnjoyUniversity // // Created by lip on 17/4/24. // Copyright © 2017年 lip. All rights reserved. // import UIKit class EUUserInfoCell: UITableViewCell { /// 头像 let logoImageView = UIImageView() /// 姓名 let nameLabel = UILabel() /// 班级 let classLabel = UILabel() /// 性别 let sexImageView = UIImageView() var viewmodel:UserinfoViewModel?{ didSet{ nameLabel.text = viewmodel?.model?.name classLabel.text = viewmodel?.model?.professionclass nameLabel.sizeToFit() sexImageView.frame.origin = CGPoint(x: nameLabel.frame.maxX + 7, y: 24) switch viewmodel?.model?.gender ?? 3{ case 0: sexImageView.image = UIImage(named: "user_man") break case 1: sexImageView.image = UIImage(named: "user_woman") break case 3: sexImageView.image = UIImage(named: "user_secret") break default: break } logoImageView.kf.setImage(with: URL(string: viewmodel?.headsculptureurl ?? ""), placeholder: UIImage(named: "profile_templogo"), options: [.transition(.fade(1))], progressBlock: nil) { (image, _, _, _) in self.logoImageView.image = avatarImage(image: image, size: CGSize(width: 50, height: 50), opaque: true, backColor: UIColor.white) } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ logoImageView.frame = CGRect(x: 12, y: 15, width: 50, height: 50) addSubview(logoImageView) nameLabel.frame = CGRect(x: 75, y: 22.5, width: 50, height: 18) nameLabel.font = UIFont.boldSystemFont(ofSize: 15) nameLabel.sizeToFit() nameLabel.textColor = TEXTVIEWCOLOR addSubview(nameLabel) sexImageView.frame = CGRect(x: 172, y: 24, width: 15, height: 15) sexImageView.center.y = nameLabel.center.y addSubview(sexImageView) classLabel.frame = CGRect(x: 75, y: 46, width: UIScreen.main.bounds.width - 100, height: 12) classLabel.font = UIFont.boldSystemFont(ofSize: 12) classLabel.textColor = UIColor.init(red: 158/255, green: 158/255, blue: 158/255, alpha: 1) addSubview(classLabel) } }
mit
d28b1b141002a587d057ec3439d68c11
31.238636
169
0.548467
4.69702
false
false
false
false
iThinkersTeam/Blog
SnapKitLoginScreen/Pods/SnapKit/Source/ConstraintViewDSL.swift
1
4425
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public struct ConstraintViewDSL: ConstraintAttributesDSL { @discardableResult public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] { return ConstraintMaker.prepareConstraints(view: self.view, closure: closure) } public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.makeConstraints(view: self.view, closure: closure) } public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.remakeConstraints(view: self.view, closure: closure) } public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) { ConstraintMaker.updateConstraints(view: self.view, closure: closure) } public func removeConstraints() { ConstraintMaker.removeConstraints(view: self.view) } public var contentHuggingHorizontalPriority: Float { get { return self.view.contentHuggingPriority(for: .horizontal) } set { self.view.setContentHuggingPriority(newValue, for: .horizontal) } } public var contentHuggingVerticalPriority: Float { get { return self.view.contentHuggingPriority(for: .vertical) } set { self.view.setContentHuggingPriority(newValue, for: .vertical) } } public var contentCompressionResistanceHorizontalPriority: Float { get { return self.view.contentCompressionResistancePriority(for: .horizontal) } set { self.view.setContentHuggingPriority(newValue, for: .horizontal) } } public var contentCompressionResistanceVerticalPriority: Float { get { return self.view.contentCompressionResistancePriority(for: .vertical) } set { self.view.setContentCompressionResistancePriority(newValue, for: .vertical) } } public var target: AnyObject? { return self.view } internal let view: ConstraintView internal init(view: ConstraintView) { self.view = view } internal var constraints: [Constraint] { return self.constraintsHashTable.allObjects } internal func add(constraints: [Constraint]) { let hashTable = self.constraintsHashTable for constraint in constraints { hashTable.add(constraint) } } internal func remove(constraints: [Constraint]) { let hashTable = self.constraintsHashTable for constraint in constraints { hashTable.remove(constraint) } } private var constraintsHashTable: NSHashTable<Constraint> { let constraints: NSHashTable<Constraint> if let existing = objc_getAssociatedObject(self.view, &constraintsKey) as? NSHashTable<Constraint> { constraints = existing } else { constraints = NSHashTable<Constraint>() objc_setAssociatedObject(self.view, &constraintsKey, constraints, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraints } } private var constraintsKey: UInt8 = 0
mit
df9691a1dcc320c53455aafa98fb3aca
33.038462
113
0.679096
4.960762
false
false
false
false
wojteklu/logo
Logo/IDE/LogoSyntaxTextView.swift
1
1307
import Cocoa class LogoSyntaxTextView: NSTextView { override func awakeFromNib() { font = NSFont(name: "Menlo", size: 15) } override func didChangeText() { guard let textStorage = textStorage else { return } textStorage.beginEditing() setTextColor(.white, range:NSRange(location: 0, length: string.count)) colorText(regexString: "\\d", color: NSColor(hexString: "d19a66")) colorText(regexString: "([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\\()", color: NSColor(hexString: "61aeee")) colorText(regexString: "\\b(if|else|end|to|repeat)\\b", color: NSColor(hexString: "c678dd")) colorText(regexString: "[:]\\w+", color: NSColor(hexString: "e6c07b")) textStorage.endEditing() } private func colorText(regexString: String, color: NSColor) { guard let regex = try? NSRegularExpression(pattern: regexString, options: []) else { return } let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.count)) for match in matches { setTextColor(color, range: match.range) } } }
mit
f146e2a84f2f8087f8cfe9f1286a5827
29.395349
92
0.55088
4.476027
false
false
false
false
silan-liu/SwiftDanmuView
SwiftDanmuView/DanmuView/SLDanmuBgItemView.swift
1
953
// // SLDanmuBgItemView.swift // SwiftDanmuView // // Created by liusilan on 2017/4/19. // Copyright © 2017年 silan. All rights reserved. // import Foundation import UIKit class SLDanmuBgItemView: SLDanmuItemView { typealias T = SLBgDanmuInfo lazy var bgView: UIView = { var bgView = UIView() bgView.backgroundColor = UIColor.lightGray bgView.layer.cornerRadius = 4 bgView.clipsToBounds = true return bgView }() override func commonInit() { super.commonInit() self.insertSubview(bgView, belowSubview: label) } override func sizeToFit() { super.sizeToFit() bgView.frame = self.bounds } override func updateDanmuInfo(info: SLDanmuInfo) { super.updateDanmuInfo(info: info) if let info = info as? SLBgDanmuInfo { bgView.backgroundColor = info.bgColor } } }
mit
eabc35cc23ee36356591f9673cc6b419
20.590909
55
0.608421
4.398148
false
false
false
false
saagarjha/iina
iina/SleepPreventer.swift
1
3130
// // SleepPreventer.swift // iina // // Created by lhc on 6/1/2017. // Copyright © 2017 lhc. All rights reserved. // import IOKit.pwr_mgt class SleepPreventer: NSObject { static private let reason = "IINA is playing video" as CFString static private var assertionID = IOPMAssertionID() static private var haveShownAlert = false static private var preventedSleep = false /// Ask macOS to not dim or sleep the display. /// /// This method uses the macOS function [IOPMAssertionCreateWithName](https://developer.apple.com/documentation/iokit/1557134-iopmassertioncreatewithname) /// to create a [kIOPMAssertionTypeNoDisplaySleep](https://developer.apple.com/documentation/iokit/kiopmassertiontypenodisplaysleep) /// assertion with the macOS power management system. /// - Attention: This portion of macOS has proven to be **unreliable**. /// /// It is important to inform the user that macOS power management is malfunctioning as this can explain /// why there is trouble with audio/video playback. For this reason IINA posts an alert if `IOPMAssertionCreateWithName` fails. /// /// As this alert can be irritating to users the alert is only displayed once per IINA invocation. In addition /// the alert supports a [suppression button](https://developer.apple.com/documentation/appkit/nsalert/1535196-showssuppressionbutton) /// to allow the user to permanently suppress this alert. /// /// See issues [#3842](https://github.com/iina/iina/issues/3842) and [#3478](https://github.com/iina/iina/issues/3478) for details on the macOS failure. static func preventSleep() { if preventedSleep { return } let success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep as NSString, IOPMAssertionLevel(kIOPMAssertionLevelOn), reason, &assertionID) guard success != kIOReturnSuccess else { preventedSleep = true return } // Something has gone wrong with power management on this Mac. Logger.log(String(format: "IOPMAssertionCreateWithName returned 0x%0X8, \(String(cString: mach_error_string(success)))", success), level: .error) Logger.log( "Cannot prevent display sleep because macOS power management is broken on this machine", level: .error) // To avoid irritating users only display this alert once per IINA invocation and support a // button to allow the alert to be permanently suppressed. guard !haveShownAlert else { return } haveShownAlert = true DispatchQueue.main.async { Utility.showAlert("sleep", arguments: [success], suppressionKey: .suppressCannotPreventDisplaySleep) } } static func allowSleep() { if !preventedSleep { return } else { let success = IOPMAssertionRelease(assertionID) if success == kIOReturnSuccess { preventedSleep = false } else { Logger.log("Cannot allow display sleep", level: .warning) } } } }
gpl-3.0
867bc4892420d089ac866213f5dd0b9d
38.607595
156
0.681048
4.476395
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallRotateChase.swift
4
2280
// // Created by Tom Baranes on 23/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallRotateChase: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1.5 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize = size.width / 5 for i in 0 ..< 5 { let factor = Float(i) * 1.0 / 5 let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color) let animation = rotateAnimation(rate: factor, x: layer.bounds.size.width / 2, y: layer.bounds.size.height / 2, size: CGSize(width: size.width - circleSize, height: size.height - circleSize)) circle.frame = CGRect(x: 0, y: 0, width: circleSize, height: circleSize) circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } // MARK: - Setup // swiftlint:disable variable_name_min_length private extension ActivityIndicatorAnimationBallRotateChase { func rotateAnimation(rate: Float, x: CGFloat, y: CGFloat, size: CGSize) -> CAAnimationGroup { let fromScale = 1 - rate let toScale = 0.2 + rate let timeFunc = CAMediaTimingFunction(controlPoints: 0.5, 0.15 + rate, 0.25, 1.0) let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.repeatCount = .infinity scaleAnimation.fromValue = fromScale scaleAnimation.toValue = toScale let positionAnimation = CAKeyframeAnimation(keyPath: "position") positionAnimation.duration = duration positionAnimation.repeatCount = .infinity positionAnimation.path = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: size.width / 2, startAngle: 3 * CGFloat.pi / 2, endAngle: 3 * CGFloat.pi / 2 + 2 * CGFloat.pi, clockwise: true).cgPath let animation = CAAnimationGroup() animation.animations = [scaleAnimation, positionAnimation] animation.timingFunction = timeFunc animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } } // swiftlint:enable variable_name_min_length
gpl-3.0
ab79804353bdfe201c5a2a959a449770
37.627119
200
0.724002
4.433852
false
false
false
false
iMetalk/TCZKit
TCZKitDemo/TCZKit/ViewControllers/TCZBaseViewController.swift
1
5955
// // TCZBaseViewController.swift // Dormouse // // Created by tczy on 2017/8/14. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit import AVFoundation import PKHUD class TCZBaseViewController: UIViewController { var isCloseShake: Bool = false //MARK: - Life Cycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) print("Init: ", self) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { print("Dealloc: ", self) } override func viewDidLoad() { super.viewDidLoad() if self.navigationController != nil { if (self.navigationController?.viewControllers.count)! > 1 { self.setLeftBackImage() } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } //MARK: - Methond /// 设置导航左边按钮为 × func setLeftCloseImage() { self.setLeftButtonItemWithImage(image: UIImage(named: "navi_close")!) } /// 设置导航左边按钮为 → func setLeftBackImage() { self.setLeftButtonItemWithImage(image: UIImage(named: "navi_back")!) } /// 导航左按钮点击事件(子类需要就重写) func didClickNavigationBarBackButton() { popOrDismissCurrentViewControllerAnimate(isAnimate: true) } /// 导航右按钮点击事件(子类需要就重写) func didClickNavigationBarRightButton() { } /// 设置导航左按钮的标题 /// /// - Parameter title: 标题 public func setLeftButtonItemWithTitle(title: NSString) { self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: title as String, style: .plain, target: self, action: #selector(didClickNavigationBarBackButton)) } /// 设置导航左按钮的图片 /// /// - Parameter image: 图片 public func setLeftButtonItemWithImage(image: UIImage) { self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: image, style: .plain, target: self, action: #selector(didClickNavigationBarBackButton)) } /// 设置导航右按钮的标题 /// /// - Parameter title: 标题 public func setRightButtonItemWithTitle(title: NSString) { self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: title as String, style: .plain, target: self, action: #selector(didClickNavigationBarRightButton)) } /// 设置导航右按钮的图片 /// /// - Parameter image: 图片 public func setRightButtonItemWithImage(image: UIImage) { self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: image, style: .plain, target: self, action: #selector(didClickNavigationBarRightButton)) } /// pop 或者 dismiss出当前的controller /// /// - Parameter isAnimate: 是否动画 func popOrDismissCurrentViewControllerAnimate(isAnimate: Bool) { if let navVC = self.navigationController { let vcs = navVC.viewControllers if vcs.count > 1 { if vcs[vcs.count-1] == self { navVC.popViewController(animated: isAnimate) } else { navVC.dismiss(animated: isAnimate, completion: nil) } } } } } //MARK: - 发生错误时,从顶部弹出错误提示,3秒之后消失 extension TCZBaseViewController { // MARK: - motion override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) let path:String? = Bundle.main.path(forResource: "shake", ofType: "mp3") if path != nil { var soundID:SystemSoundID? AudioServicesCreateSystemSoundID(URL.init(fileURLWithPath: path!) as CFURL,&soundID!) //播放声音 AudioServicesPlaySystemSound(soundID!) } print("开始抖动") } override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) { print("取消抖动") HUD.flash(.label("不给力啊"), delay: 2.0) { _ in } } override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) { if isCloseShake { return } if motion == UIEventSubtype.motionShake { print("结束抖动") // let popVC = TCZLogPopViewController() // // popVC.afterDismissAction = { [weak self] in // // self?.view.window?.makeKeyAndVisible() // } // // popWindow.rootViewController = popVC // popWindow.windowLevel = UIWindowLevelAlert - 1 // popWindow.makeKeyAndVisible() } } func showErrorFromTop(errorDes: String) -> Void { let tipLable = UILabel.tczLabel(text: errorDes, font: nil, color: nil) tipLable.frame = CGRect(x: 0, y: -40, width: WINDOW_WIDTH, height: 40) self.view.addSubview(tipLable) tipLable.backgroundColor = .red tipLable.textColor = .white tipLable.textAlignment = .center UIView.animate(withDuration: 0.25, animations: { tipLable.TCZ_y = 0; }) { (isFinish) in if isFinish { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: { UIView.animate(withDuration: 0.25, animations: { tipLable.TCZ_y = -40 }, completion: { (isFinish) in if isFinish { tipLable.removeFromSuperview() } }) }) } } } }
mit
c28c3792995d1ba05e13253140b0c0d1
29.857923
175
0.587037
4.777496
false
false
false
false
akosma/Swift-Presentation
PresentationKit/BaseDemo.swift
1
3172
import AppKit public class BaseDemo : NSObject, Demo { private var source : NSAttributedString? public override required init() { } public var tweet : NSURL { return NSURL(string: "http://akos.ma/swift") } public var URL : NSURL { return NSURL(string: "http://akos.ma/swift") } override public var description : String { return "" } final public var sourceCode : NSAttributedString { if source == nil { let url = findURL() var options : NSDictionary = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType ] // Load the NSMutableAttributedString corresponding to the // contents of the HTML file var error : NSError? = nil; let string = NSMutableAttributedString(URL:url, options:options, documentAttributes:nil, error:&error) let range = NSMakeRange(0, string.length - 1) let newFont = NSFont(name: "Menlo", size: 18.0) string.addAttribute(NSFontAttributeName, value: newFont, range: range) source = string } return source! } final public func explain() { explain("Alex") } private func findURL() -> NSURL { // Let's find out the path of the HTML file to show var filename = "html/\(self.className).swift" // Swift frameworks are namespaced by default; in this case, // the product name is used, and the classes have that prefix. // We strip the prefix to match the name of the HTML file. filename = filename.stringByReplacingOccurrencesOfString("PresentationKit.", withString: "") // Get the path in the bundle of the framework let bundle = NSBundle(forClass: Presentation.self) let path : NSString = bundle.pathForResource(filename, ofType:"html")! let url = NSURL.fileURLWithPath(path)! return url } final public func copyCode() { // Copy the contents of the file to the pasteboard let url = findURL() var rawString = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: nil) var pasteboard = NSPasteboard.generalPasteboard() pasteboard.declareTypes([NSHTMLPboardType], owner:nil) pasteboard.setString(rawString, forType:NSHTMLPboardType) } final public func explain(voice: String) { println("\(voice) says: \(self.description)") println() // Unfortunately NSSpeechSynthesizer does not currently // work in the playground... // So we use an NSTask to pipe the text to the OS instead! // var speech = NSSpeechSynthesizer() // speech.startSpeakingString("Boom") let task = NSTask() task.launchPath = "/usr/bin/say" task.arguments = [ "--voice=\(voice)", self.description ] task.launch() } public func show() { // To be overridden by subclasses } }
bsd-2-clause
feb7542a36c0edcf61e6c47fe271e1aa
32.744681
84
0.587011
5.191489
false
false
false
false
natestedman/LayoutModules
LayoutModules/LayoutModule+Table.swift
1
2844
// LayoutModules // Written in 2015 by Nate Stedman <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import UIKit extension LayoutModule { // MARK: - Table Modules /** Arranges cells in rows along the major dimension, determining the major dimension of each dynamically. - parameter padding: The padding between each cell in the major dimension. This padding is not applied before the first cell, or after the last cell. For applying padding to those areas, the `inset` function can be used. - parameter calculateMajorDimension: A function to calculate the major dimension of each cell, which will receive the parameters `index`, the current index within the section, and `otherDimension`, the minor dimension of the layout module. */ public static func dynamicTable(padding padding: CGFloat = 0, calculateMajorDimension: CalculateDimension) -> LayoutModule { return LayoutModule { count, origin, axis, minorDimension in var offset = origin.major let attributes = (0..<count).map({ index -> LayoutAttributes in let majorDimension = calculateMajorDimension(index: index, axis: axis, otherDimension: minorDimension) let frame = Rect( origin: Point(major: offset, minor: origin.minor), size: Size(major: majorDimension, minor: minorDimension) ) offset += majorDimension + padding return LayoutAttributes(frame: frame) }) return LayoutResult(layoutAttributes: attributes, finalOffset: offset - padding) } } /** Arranges cells in vertical rows. - parameter majorDimension: The height of each row. - parameter padding: The padding between each cell in the major dimension. This padding is not applied before the first cell, or after the last cell. For applying padding to those areas, the `inset` function can be used. */ public static func table(majorDimension majorDimension: CGFloat, padding: CGFloat = 0) -> LayoutModule { return dynamicTable(padding: padding, calculateMajorDimension: { _ in majorDimension }) } }
cc0-1.0
1c852ea5314444695d36ecbc42143414
44.870968
120
0.626582
5.54386
false
false
false
false
GoGoCarl/appygram_ios
Pod/Classes/AppygramMessage.swift
1
3737
import Foundation import ObjectMapper /** * <p>Represents an Appygram message. The message parameter is required, * the rest are optional. If you need more fields, you can supply them * via the app_json HashMap.</p> * * <p>All data is serialized to JSON when sending to Appygram.</p> * * <p>This class can be extended for ease of development.</p> * * @author Carl Scott, <a href="http://solertium.com">Solertium Corporation</a> * */ public class AppygramMessage : NSObject, Mappable { public var name, email, phone, topic, message, platform, software, summary, api_key: String? public var app_json : String? public required init?(_ map : Map) { super.init() mapping(map) } public override init() { super.init() } public func mapping(map: Map) { name <- map["name"] email <- map["email"] phone <- map["phone"] topic <- map["topic"] message <- map["message"] platform <- map["platform"] software <- map["software"] summary <- map["summary"] api_key <- map["api_key"] app_json <- map["app_json"] } public func getName() -> String? { return name } public func getEmail() -> String? { return email } public func getPhone() -> String? { return phone } public func getTopic() -> String? { return topic } public func getMessage() -> String? { return message } public func getPlatform() -> String? { return platform } public func getSoftware() -> String? { return software } public func getSummary() -> String? { return summary } public func getAppJSON() -> Dictionary<String, AnyObject>? { if let uJSON = app_json { return JSONParseDictionary(uJSON) } else { return Dictionary<String, AnyObject>() } } public func setAppJSON(appJson : Dictionary<String, AnyObject>) { self.app_json = JSONStringify(appJson) } public func isValid() -> Bool { return message != nil && !(message!).isEmpty } public func toJSON(token : String, _ topic : String?) -> String { self.api_key = token if let uTopic = topic { if self.topic == nil || self.topic!.isEmpty { self.topic = uTopic } } return Mapper().toJSONString(self, prettyPrint: true)! } public override var description : String { return toJSON("[unset]", self.topic) } func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } } return "" } func JSONParseDictionary(jsonString: String) -> [String: AnyObject] { if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) { if let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) as? [String: AnyObject] { return dictionary } } return [String: AnyObject]() } /** * Simple convenience method for printing exceptions. * @param e the exception * @param lineBreakRule use \n for plain text, <br/> for html * @return */ /*static func toString(e:NSException, lineBreakRule:String) -> String { TODO, if exceptions become a standard thing }*/ }
mit
7743bac5482f307a5cc3e2ed384dc2c8
26.284672
149
0.602087
4.175419
false
false
false
false
BryanHoke/swift-corelibs-foundation
TestFoundation/TestNSHTTPCookie.swift
2
5008
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSHTTPCookie: XCTestCase { var allTests : [(String, () -> ())] { return [ ("test_BasicConstruction", test_BasicConstruction), ("test_RequestHeaderFields", test_RequestHeaderFields) ] } func test_BasicConstruction() { let invalidVersionZeroCookie = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/" ]) XCTAssertNil(invalidVersionZeroCookie) let minimalVersionZeroCookie = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com" ]) XCTAssertNotNil(minimalVersionZeroCookie) XCTAssert(minimalVersionZeroCookie?.name == "TestCookie") XCTAssert(minimalVersionZeroCookie?.value == "Test value @#$%^$&*") XCTAssert(minimalVersionZeroCookie?.path == "/") XCTAssert(minimalVersionZeroCookie?.domain == "apple.com") let versionZeroCookieWithOriginURL = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithOriginURL?.domain == "apple.com") // Domain takes precedence over originURL inference let versionZeroCookieWithDomainAndOriginURL = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ]) XCTAssert(versionZeroCookieWithDomainAndOriginURL?.domain == "apple.com") // This is implicitly a v0 cookie. Properties that aren't valid for v0 should fail. let versionZeroCookieWithInvalidVersionOneProps = NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie", NSHTTPCookieValue: "Test value @#$%^$&*", NSHTTPCookiePath: "/", NSHTTPCookieDomain: "apple.com", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")!, NSHTTPCookieComment: "This comment should be nil since this is a v0 cookie.", NSHTTPCookieCommentURL: NSURL(string: "https://apple.com")!, NSHTTPCookieDiscard: "TRUE", NSHTTPCookieExpires: NSDate(timeIntervalSince1970: 1000), NSHTTPCookieMaximumAge: "2000", NSHTTPCookiePort: "443,8443", NSHTTPCookieSecure: "YES" ]) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.comment) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.commentURL) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.sessionOnly == true) // v0 should never use NSHTTPCookieMaximumAge XCTAssert( versionZeroCookieWithInvalidVersionOneProps?.expiresDate?.timeIntervalSince1970 == NSDate(timeIntervalSince1970: 1000).timeIntervalSince1970 ) XCTAssertNil(versionZeroCookieWithInvalidVersionOneProps?.portList) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.secure == true) XCTAssert(versionZeroCookieWithInvalidVersionOneProps?.version == 0) } func test_RequestHeaderFields() { let noCookies: [NSHTTPCookie] = [] XCTAssertEqual(NSHTTPCookie.requestHeaderFieldsWithCookies(noCookies)["Cookie"], "") let basicCookies: [NSHTTPCookie] = [ NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie1", NSHTTPCookieValue: "testValue1", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ])!, NSHTTPCookie(properties: [ NSHTTPCookieName: "TestCookie2", NSHTTPCookieValue: "testValue2", NSHTTPCookiePath: "/", NSHTTPCookieOriginURL: NSURL(string: "https://apple.com")! ])!, ] let basicCookieString = NSHTTPCookie.requestHeaderFieldsWithCookies(basicCookies)["Cookie"] XCTAssertEqual(basicCookieString, "TestCookie1=testValue1; TestCookie2=testValue2") } }
apache-2.0
2845b5fc579145c93762ad7bbb70a5fd
41.811966
99
0.644569
6.182716
false
true
false
false
vespax/GoMap-keyboard
Keyboard/Custom Views/Buttons/KeyButton.swift
1
2105
// // KeyButton.swift // ELDeveloperKeyboard // // Created by Eric Lin on 2014-07-02. // Copyright (c) 2014 Eric Lin. All rights reserved. // import Foundation import UIKit import QuartzCore /** KeyButton is a UIButton subclass with keyboard button styling. */ class KeyButton: UIButton { // MARK: Constructors override init(frame: CGRect) { super.init(frame: frame) titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20.0) titleLabel?.textAlignment = .center setTitleColor(UIColor(white: 1.0/255, alpha: 1.0), for: UIControlState()) titleLabel?.sizeToFit() let gradient = CAGradientLayer() gradient.frame = bounds let gradientColors: [AnyObject] = [UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0).cgColor, UIColor(red: 254.0/255, green: 254.0/255, blue: 254.0/255, alpha: 1.0).cgColor] gradient.colors = gradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error. //setBackgroundImage(gradient.UIImageFromCALayer(), forState: .Normal) setBackgroundImage(UIImage.fromColor(UIColor.white), for:UIControlState() ) let selectedGradient = CAGradientLayer() selectedGradient.frame = bounds let selectedGradientColors: [AnyObject] = [UIColor(red: 1.0, green: 1.0/255, blue: 1.0/255, alpha: 1.0).cgColor, UIColor(red: 200.0/255, green: 210.0/255, blue: 214.0/255, alpha: 1.0).cgColor] selectedGradient.colors = selectedGradientColors // Declaration broken into two lines to prevent 'unable to bridge to Objective C' error. setBackgroundImage(selectedGradient.UIImageFromCALayer(), for: .selected) layer.masksToBounds = true layer.cornerRadius = 3.0 contentVerticalAlignment = .center contentHorizontalAlignment = .center contentEdgeInsets = UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f9d5553b6d9f201faeb755c50d82a112
39.480769
200
0.663658
4.201597
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/Quests/PartyQuestView.swift
1
6380
// // PartyQuestView.swift // Habitica // // Created by Phillip Thelen on 07.05.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class PartyQuestView: UIView { let questImageView: NetworkImageView = { let imageView = NetworkImageView() imageView.contentMode = .center return imageView }() let backgroundView: UIView = { let view = UIImageView() view.isHidden = true let theme = ThemeService.shared.theme view.image = HabiticaIcons.imageOfQuestBackground(bossColorDark: theme.windowBackgroundColor, bossColorMedium: theme.dimmedTextColor, bossColorLight: theme.dimmedColor) .resizableImage(withCapInsets: UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10), resizingMode: UIImage.ResizingMode.stretch) return view }() var progressBarViews = [QuestProgressBarView]() var isBossQuest = true init() { super.init(frame: CGRect.zero) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { addSubview(questImageView) addSubview(backgroundView) } func configure(state: QuestStateProtocol, quest: QuestProtocol) { ImageManager.getImage(name: "quest_\(quest.key ?? "")") {[weak self] (image, _) in self?.questImageView.image = image self?.setNeedsLayout() self?.invalidateIntrinsicContentSize() } if let boss = quest.boss { isBossQuest = true let bossView = progressBarViews.first ?? QuestProgressBarView() var newProgressBars = [bossView] if progressBarViews.isEmpty { addSubview(bossView) progressBarViews.append(bossView) } bossView.titleTextColor = ThemeService.shared.theme.primaryTextColor bossView.valueTextColor = ThemeService.shared.theme.secondaryTextColor bossView.barBackgroundColor = ThemeService.shared.theme.dimmedColor bossView.title = boss.name bossView.maxValue = Float(boss.health) bossView.barColor = UIColor.red100 bossView.currentValue = state.progress?.health ?? 0 bossView.bigIcon = nil if let rage = boss.rage, rage.value > 0 { let rageView = progressBarViews.count >= 2 ? progressBarViews[1] : QuestProgressBarView() newProgressBars.append(rageView) if progressBarViews.count < 2 { addSubview(rageView) progressBarViews.append(rageView) } rageView.titleTextColor = ThemeService.shared.theme.primaryTextColor rageView.valueTextColor = ThemeService.shared.theme.ternaryTextColor rageView.barBackgroundColor = ThemeService.shared.theme.dimmedColor rageView.title = rage.title rageView.maxValue = Float(rage.value) rageView.barColor = UIColor.orange100 rageView.currentValue = state.progress?.rage ?? 0 rageView.bigIcon = nil } if progressBarViews.count > newProgressBars.count { progressBarViews.forEach { (view) in if view != bossView { view.removeFromSuperview() } } progressBarViews = newProgressBars } } else { progressBarViews.forEach { (view) in view.removeFromSuperview() } progressBarViews.removeAll() isBossQuest = false quest.collect?.forEach { (questCollect) in let collectView = QuestProgressBarView() collectView.titleTextColor = ThemeService.shared.theme.primaryTextColor collectView.valueTextColor = ThemeService.shared.theme.ternaryTextColor collectView.barBackgroundColor = ThemeService.shared.theme.dimmedColor collectView.title = questCollect.text collectView.maxValue = Float(questCollect.count) let value = state.progress?.collect.first(where: { (collect) -> Bool in return collect.key == questCollect.key })?.count collectView.currentValue = Float(value ?? 0) collectView.barColor = UIColor.green100 ImageManager.getImage(name: "quest_\(quest.key ?? "")_\(questCollect.key ?? "")", completion: { (image, _) in collectView.bigIcon = image }) addSubview(collectView) progressBarViews.append(collectView) } } backgroundView.isHidden = false setNeedsLayout() invalidateIntrinsicContentSize() } func setPendingDamage(_ pending: Float) { if isBossQuest { progressBarViews.first?.pendingBarColor = UIColor.yellow50 progressBarViews.first?.pendingTitle = L10n.pendingDamage progressBarViews.first?.pendingValue = pending } } override func layoutSubviews() { super.layoutSubviews() layout() } func layout() { questImageView.pin.top(12).hCenter().height(questImageView.image?.size.height ?? 0) backgroundView.pin.top(to: questImageView.edge.bottom).marginTop(12) var edge = backgroundView.edge.top for progressView in progressBarViews { progressView.pin.top(to: edge).marginTop(10).start(16).end(16).height(progressView.intrinsicContentSize.height) edge = progressView.edge.bottom } backgroundView.pin.top(to: questImageView.edge.bottom).marginTop(12).bottom(to: edge).marginBottom(-10).start().end() } override var intrinsicContentSize: CGSize { layout() return CGSize(width: bounds.size.width, height: backgroundView.frame.origin.y + backgroundView.frame.size.height + 12) } }
gpl-3.0
29176c35d0671b25a578e00024188539
39.891026
126
0.590688
5.508636
false
false
false
false
rb-de0/tech.reb-dev.com
Sources/App/Middleware/CSRFMiddleware.swift
2
1312
import Foundation final class CSRFMiddleware: Middleware { private let hash: HashProtocol init(hash: HashProtocol) { self.hash = hash } func respond(to request: Request, chainingTo next: Responder) throws -> Response { guard let session = request.session else { throw Abort.badRequest } if request.method == .post { guard let sessionToken = session.data["csrf_token"]?.string, let requestToken = request.data["csrf_token"]?.string else { throw Abort.badRequest } guard requestToken == sessionToken else { throw Abort.badRequest } } let token: String if let existToken = session.data["csrf_token"]?.string { token = existToken } else { let uuid = UUID().uuidString let newToken = try hash.make(uuid + session.identifier).makeString() session.data["csrf_token"] = .string(newToken) token = newToken } request.storage["csrf_token"] = token let response = try next.respond(to: request) return response } }
mit
3da24cd41e2c02bf020e72ca475977f1
26.914894
86
0.51753
5.443983
false
false
false
false
nathawes/swift
validation-test/compiler_crashers_2_fixed/sr12723.swift
13
2703
// RUN: %target-swift-emit-silgen %s -verify func SR12723_thin(_: (@convention(thin) () -> Void) -> Void) {} func SR12723_block(_: (@convention(block) () -> Void) -> Void) {} func SR12723_c(_: (@convention(c) () -> Void) -> Void) {} func SR12723_function(_: () -> Void) {} func context() { SR12723_c(SR12723_function) SR12723_block(SR12723_function) SR12723_thin(SR12723_function) } struct SR12723_C { let function: (@convention(c) () -> Void) -> Void } struct SR12723_Thin { let function: (@convention(thin) () -> Void) -> Void } struct SR12723_Block { let function: (@convention(block) () -> Void) -> Void } func proxy(_ f: (() -> Void) -> Void) { let a = 1 f { print(a) } } func cContext() { let c = SR12723_C { app in app() } proxy(c.function) // expected-error@-1 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = c.function // expected-error@-1 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = c.function // OK let _ : (@convention(thin) () -> Void) -> Void = c.function // OK let _ : (() -> Void) -> Void = c.function // expected-error@-1 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func thinContext() { let thin = SR12723_Thin { app in app() } proxy(thin.function) // expected-error@-1 {{cannot convert value of type '(@convention(thin) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = thin.function // expected-error@-1 {{cannot convert value of type '(@convention(thin) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = thin.function // OK let _ : (@convention(thin) () -> Void) -> Void = thin.function // OK let _ : (() -> Void) -> Void = thin.function // expected-error@-1 {{cannot convert value of type '(@convention(thin) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func blockContext() { let block = SR12723_Block { app in app() } proxy(block.function) let _ : (@convention(block) () -> Void) -> Void = block.function // OK let _ : (@convention(c) () -> Void) -> Void = block.function // OK let _ : (@convention(thin) () -> Void) -> Void = block.function // OK let _ : (() -> Void) -> Void = block.function // OK }
apache-2.0
54e77d0b242c75cd96993e4a42c1d1b1
32.37037
158
0.564928
3.412879
false
false
false
false