repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
YQqiang/Nunchakus | refs/heads/master | Pods/BMPlayer/BMPlayer/Classes/BMPlayerControlView.swift | mit | 1 | //
// BMPlayerControlView.swift
// Pods
//
// Created by BrikerMan on 16/4/29.
//
//
import UIKit
import NVActivityIndicatorView
@objc public protocol BMPlayerControlViewDelegate: class {
/**
call when control view choose a definition
- parameter controlView: control view
- parameter index: index of definition
*/
func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int)
/**
call when control view pressed an button
- parameter controlView: control view
- parameter button: button type
*/
func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton)
/**
call when slider action trigged
- parameter controlView: control view
- parameter slider: progress slider
- parameter event: action
*/
func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents)
/**
call when needs to change playback rate
- parameter controlView: control view
- parameter rate: playback rate
*/
@objc optional func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float)
}
open class BMPlayerControlView: UIView {
open weak var delegate: BMPlayerControlViewDelegate?
// MARK: Variables
open var resource: BMPlayerResource?
open var selectedIndex = 0
open var isFullscreen = false
open var isMaskShowing = true
open var totalDuration:TimeInterval = 0
open var delayItem: DispatchWorkItem?
var playerLastState: BMPlayerState = .notSetURL
fileprivate var isSelectecDefitionViewOpened = false
// MARK: UI Components
/// main views which contains the topMaskView and bottom mask view
open var mainMaskView = UIView()
open var topMaskView = UIView()
open var bottomMaskView = UIView()
/// Image view to show video cover
open var maskImageView = UIImageView()
/// top views
open var backButton = UIButton(type : UIButtonType.custom)
open var titleLabel = UILabel()
open var chooseDefitionView = UIView()
/// bottom view
open var currentTimeLabel = UILabel()
open var totalTimeLabel = UILabel()
/// Progress slider
open var timeSlider = BMTimeSlider()
/// load progress view
open var progressView = UIProgressView()
/* play button
playButton.isSelected = player.isPlaying
*/
open var playButton = UIButton(type: UIButtonType.custom)
/* fullScreen button
fullScreenButton.isSelected = player.isFullscreen
*/
open var fullscreenButton = UIButton(type: UIButtonType.custom)
open var subtitleLabel = UILabel()
open var subtitleBackView = UIView()
open var subtileAttrabute: [String : Any]?
/// Activty Indector for loading
open var loadingIndector = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
open var seekToView = UIView()
open var seekToViewImage = UIImageView()
open var seekToLabel = UILabel()
open var replayButton = UIButton(type: UIButtonType.custom)
/// Gesture used to show / hide control view
open var tapGesture: UITapGestureRecognizer!
// MARK: - handle player state change
/**
call on when play time changed, update duration here
- parameter currentTime: current play time
- parameter totalTime: total duration
*/
open func playTimeDidChange(currentTime: TimeInterval, totalTime: TimeInterval) {
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
totalTimeLabel.text = BMPlayer.formatSecondsToString(totalTime)
timeSlider.value = Float(currentTime) / Float(totalTime)
if let subtitle = resource?.subtitle {
showSubtile(from: subtitle, at: currentTime)
}
}
/**
call on load duration changed, update load progressView here
- parameter loadedDuration: loaded duration
- parameter totalDuration: total duration
*/
open func loadedTimeDidChange(loadedDuration: TimeInterval , totalDuration: TimeInterval) {
progressView.setProgress(Float(loadedDuration)/Float(totalDuration), animated: true)
}
open func playerStateDidChange(state: BMPlayerState) {
switch state {
case .readyToPlay:
hideLoader()
case .buffering:
showLoader()
case .bufferFinished:
hideLoader()
case .playedToTheEnd:
playButton.isSelected = false
showPlayToTheEndView()
controlViewAnimation(isShow: true)
cancelAutoFadeOutAnimation()
default:
break
}
playerLastState = state
}
/**
Call when User use the slide to seek function
- parameter toSecound: target time
- parameter totalDuration: total duration of the video
- parameter isAdd: isAdd
*/
open func showSeekToView(to toSecound: TimeInterval, total totalDuration:TimeInterval, isAdd: Bool) {
seekToView.isHidden = false
seekToLabel.text = BMPlayer.formatSecondsToString(toSecound)
let rotate = isAdd ? 0 : CGFloat(Double.pi)
seekToViewImage.transform = CGAffineTransform(rotationAngle: rotate)
let targetTime = BMPlayer.formatSecondsToString(toSecound)
timeSlider.value = Float(toSecound / totalDuration)
currentTimeLabel.text = targetTime
}
// MARK: - UI update related function
/**
Update UI details when player set with the resource
- parameter resource: video resouce
- parameter index: defualt definition's index
*/
open func prepareUI(for resource: BMPlayerResource, selectedIndex index: Int) {
self.resource = resource
self.selectedIndex = index
titleLabel.text = resource.name
prepareChooseDefinitionView()
autoFadeOutControlViewWithAnimation()
}
open func playStateDidChange(isPlaying: Bool) {
autoFadeOutControlViewWithAnimation()
playButton.isSelected = isPlaying
}
/**
auto fade out controll view with animtion
*/
open func autoFadeOutControlViewWithAnimation() {
cancelAutoFadeOutAnimation()
delayItem = DispatchWorkItem {
self.controlViewAnimation(isShow: false)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + BMPlayerConf.animateDelayTimeInterval,
execute: delayItem!)
}
/**
cancel auto fade out controll view with animtion
*/
open func cancelAutoFadeOutAnimation() {
delayItem?.cancel()
}
/**
Implement of the control view animation, override if need's custom animation
- parameter isShow: is to show the controlview
*/
open func controlViewAnimation(isShow: Bool) {
let alpha: CGFloat = isShow ? 1.0 : 0.0
self.isMaskShowing = isShow
UIApplication.shared.setStatusBarHidden(!isShow, with: .fade)
UIView.animate(withDuration: 0.3, animations: {
self.topMaskView.alpha = alpha
self.bottomMaskView.alpha = alpha
self.mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: isShow ? 0.4 : 0.0)
if isShow {
if self.isFullscreen { self.chooseDefitionView.alpha = 1.0 }
} else {
self.replayButton.isHidden = true
self.chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(35)
}
self.chooseDefitionView.alpha = 0.0
}
self.layoutIfNeeded()
}) { (_) in
if isShow {
self.autoFadeOutControlViewWithAnimation()
}
}
}
/**
Implement of the UI update when screen orient changed
- parameter isForFullScreen: is for full screen
*/
open func updateUI(_ isForFullScreen: Bool) {
isFullscreen = isForFullScreen
fullscreenButton.isSelected = isForFullScreen
chooseDefitionView.isHidden = !isForFullScreen
if isForFullScreen {
if BMPlayerConf.topBarShowInCase.rawValue == 2 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
} else {
if BMPlayerConf.topBarShowInCase.rawValue >= 1 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
}
}
/**
Call when video play's to the end, override if you need custom UI or animation when played to the end
*/
open func showPlayToTheEndView() {
replayButton.isHidden = false
}
open func hidePlayToTheEndView() {
replayButton.isHidden = true
}
open func showLoader() {
loadingIndector.isHidden = false
loadingIndector.startAnimating()
}
open func hideLoader() {
loadingIndector.isHidden = true
}
open func hideSeekToView() {
seekToView.isHidden = true
}
open func showCoverWithLink(_ cover:String) {
self.showCover(url: URL(string: cover))
}
open func showCover(url: URL?) {
if let url = url {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async(execute: {
if let data = data {
self.maskImageView.image = UIImage(data: data)
} else {
self.maskImageView.image = nil
}
self.hideLoader()
});
}
}
}
open func hideCoverImageView() {
self.maskImageView.isHidden = true
}
open func prepareChooseDefinitionView() {
guard let resource = resource else {
return
}
for item in chooseDefitionView.subviews {
item.removeFromSuperview()
}
for i in 0..<resource.definitions.count {
let button = BMPlayerClearityChooseButton()
if i == 0 {
button.tag = selectedIndex
} else if i <= selectedIndex {
button.tag = i - 1
} else {
button.tag = i
}
button.setTitle("\(resource.definitions[button.tag].definition)", for: UIControlState())
chooseDefitionView.addSubview(button)
button.addTarget(self, action: #selector(self.onDefinitionSelected(_:)), for: UIControlEvents.touchUpInside)
button.snp.makeConstraints({ (make) in
make.top.equalTo(chooseDefitionView.snp.top).offset(35 * i)
make.width.equalTo(50)
make.height.equalTo(25)
make.centerX.equalTo(chooseDefitionView)
})
if resource.definitions.count == 1 {
button.isEnabled = false
}
}
}
// MARK: - Action Response
/**
Call when some action button Pressed
- parameter button: action Button
*/
open func onButtonPressed(_ button: UIButton) {
autoFadeOutControlViewWithAnimation()
if let type = ButtonType(rawValue: button.tag) {
switch type {
case .play, .replay:
if playerLastState == .playedToTheEnd {
hidePlayToTheEndView()
}
default:
break
}
}
delegate?.controlView(controlView: self, didPressButton: button)
}
/**
Call when the tap gesture tapped
- parameter gesture: tap gesture
*/
open func onTapGestureTapped(_ gesture: UITapGestureRecognizer) {
if playerLastState == .playedToTheEnd {
return
}
controlViewAnimation(isShow: !isMaskShowing)
}
// MARK: - handle UI slider actions
@objc func progressSliderTouchBegan(_ sender: UISlider) {
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchDown)
}
@objc func progressSliderValueChanged(_ sender: UISlider) {
hidePlayToTheEndView()
cancelAutoFadeOutAnimation()
let currentTime = Double(sender.value) * totalDuration
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .valueChanged)
}
@objc func progressSliderTouchEnded(_ sender: UISlider) {
autoFadeOutControlViewWithAnimation()
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchUpInside)
}
// MARK: - private functions
fileprivate func showSubtile(from subtitle: BMSubtitles, at time: TimeInterval) {
if let group = subtitle.search(for: time) {
subtitleBackView.isHidden = false
subtitleLabel.attributedText = NSAttributedString(string: group.text,
attributes: subtileAttrabute)
} else {
subtitleBackView.isHidden = true
}
}
@objc fileprivate func onDefinitionSelected(_ button:UIButton) {
let height = isSelectecDefitionViewOpened ? 35 : resource!.definitions.count * 40
chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
})
isSelectecDefitionViewOpened = !isSelectecDefitionViewOpened
if selectedIndex != button.tag {
selectedIndex = button.tag
delegate?.controlView(controlView: self, didChooseDefition: button.tag)
}
prepareChooseDefinitionView()
}
@objc fileprivate func onReplyButtonPressed() {
replayButton.isHidden = true
}
// MARK: - Init
override public init(frame: CGRect) {
super.init(frame: frame)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
/// Add Customize functions here
open func customizeUIComponents() {
}
func setupUIComponents() {
// Subtile view
subtitleLabel.numberOfLines = 0
subtitleLabel.textAlignment = .center
subtitleLabel.textColor = UIColor.white
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.minimumScaleFactor = 0.5
subtitleLabel.font = UIFont.systemFont(ofSize: 13)
subtitleBackView.layer.cornerRadius = 2
subtitleBackView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
subtitleBackView.addSubview(subtitleLabel)
subtitleBackView.isHidden = true
addSubview(subtitleBackView)
// Main mask view
addSubview(mainMaskView)
mainMaskView.addSubview(topMaskView)
mainMaskView.addSubview(bottomMaskView)
mainMaskView.insertSubview(maskImageView, at: 0)
mainMaskView.clipsToBounds = true
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 )
// Top views
topMaskView.addSubview(backButton)
topMaskView.addSubview(titleLabel)
addSubview(chooseDefitionView)
backButton.tag = BMPlayerControlView.ButtonType.back.rawValue
backButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_back"), for: .normal)
backButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
titleLabel.textColor = UIColor.white
titleLabel.text = ""
titleLabel.font = UIFont.systemFont(ofSize: 16)
chooseDefitionView.clipsToBounds = true
// Bottom views
bottomMaskView.addSubview(playButton)
bottomMaskView.addSubview(currentTimeLabel)
bottomMaskView.addSubview(totalTimeLabel)
bottomMaskView.addSubview(progressView)
bottomMaskView.addSubview(timeSlider)
bottomMaskView.addSubview(fullscreenButton)
playButton.tag = BMPlayerControlView.ButtonType.play.rawValue
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_play"), for: .normal)
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_pause"), for: .selected)
playButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
currentTimeLabel.textColor = UIColor.white
currentTimeLabel.font = UIFont.systemFont(ofSize: 12)
currentTimeLabel.text = "00:00"
currentTimeLabel.textAlignment = NSTextAlignment.center
totalTimeLabel.textColor = UIColor.white
totalTimeLabel.font = UIFont.systemFont(ofSize: 12)
totalTimeLabel.text = "00:00"
totalTimeLabel.textAlignment = NSTextAlignment.center
timeSlider.maximumValue = 1.0
timeSlider.minimumValue = 0.0
timeSlider.value = 0.0
timeSlider.setThumbImage(BMImageResourcePath("Pod_Asset_BMPlayer_slider_thumb"), for: .normal)
timeSlider.maximumTrackTintColor = UIColor.clear
timeSlider.minimumTrackTintColor = BMPlayerConf.tintColor
timeSlider.addTarget(self, action: #selector(progressSliderTouchBegan(_:)),
for: UIControlEvents.touchDown)
timeSlider.addTarget(self, action: #selector(progressSliderValueChanged(_:)),
for: UIControlEvents.valueChanged)
timeSlider.addTarget(self, action: #selector(progressSliderTouchEnded(_:)),
for: [UIControlEvents.touchUpInside,UIControlEvents.touchCancel, UIControlEvents.touchUpOutside])
progressView.tintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 )
progressView.trackTintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3 )
fullscreenButton.tag = BMPlayerControlView.ButtonType.fullscreen.rawValue
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_fullscreen"), for: .normal)
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_portialscreen"), for: .selected)
fullscreenButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
mainMaskView.addSubview(loadingIndector)
loadingIndector.type = BMPlayerConf.loaderType
loadingIndector.color = BMPlayerConf.tintColor
// View to show when slide to seek
addSubview(seekToView)
seekToView.addSubview(seekToViewImage)
seekToView.addSubview(seekToLabel)
seekToLabel.font = UIFont.systemFont(ofSize: 13)
seekToLabel.textColor = UIColor ( red: 0.9098, green: 0.9098, blue: 0.9098, alpha: 1.0 )
seekToView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 )
seekToView.layer.cornerRadius = 4
seekToView.layer.masksToBounds = true
seekToView.isHidden = true
seekToViewImage.image = BMImageResourcePath("Pod_Asset_BMPlayer_seek_to_image")
addSubview(replayButton)
replayButton.isHidden = true
replayButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_replay"), for: .normal)
replayButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
replayButton.tag = ButtonType.replay.rawValue
tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureTapped(_:)))
addGestureRecognizer(tapGesture)
}
func addSnapKitConstraint() {
// Main mask view
mainMaskView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
maskImageView.snp.makeConstraints { (make) in
make.edges.equalTo(mainMaskView)
}
topMaskView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(mainMaskView)
make.height.equalTo(65)
}
bottomMaskView.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(mainMaskView)
make.height.equalTo(50)
}
// Top views
backButton.snp.makeConstraints { (make) in
make.width.height.equalTo(50)
make.left.bottom.equalTo(topMaskView)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(backButton.snp.right)
make.centerY.equalTo(backButton)
}
chooseDefitionView.snp.makeConstraints { (make) in
make.right.equalTo(topMaskView.snp.right).offset(-20)
make.top.equalTo(titleLabel.snp.top).offset(-4)
make.width.equalTo(60)
make.height.equalTo(30)
}
// Bottom views
playButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.left.bottom.equalTo(bottomMaskView)
}
currentTimeLabel.snp.makeConstraints { (make) in
make.left.equalTo(playButton.snp.right)
make.centerY.equalTo(playButton)
make.width.equalTo(40)
}
timeSlider.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(currentTimeLabel.snp.right).offset(10).priority(750)
make.height.equalTo(30)
}
progressView.snp.makeConstraints { (make) in
make.centerY.left.right.equalTo(timeSlider)
make.height.equalTo(2)
}
totalTimeLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(timeSlider.snp.right).offset(5)
make.width.equalTo(40)
}
fullscreenButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(totalTimeLabel.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
loadingIndector.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX).offset(0)
make.centerY.equalTo(mainMaskView.snp.centerY).offset(0)
}
// View to show when slide to seek
seekToView.snp.makeConstraints { (make) in
make.center.equalTo(self.snp.center)
make.width.equalTo(100)
make.height.equalTo(40)
}
seekToViewImage.snp.makeConstraints { (make) in
make.left.equalTo(seekToView.snp.left).offset(15)
make.centerY.equalTo(seekToView.snp.centerY)
make.height.equalTo(15)
make.width.equalTo(25)
}
seekToLabel.snp.makeConstraints { (make) in
make.left.equalTo(seekToViewImage.snp.right).offset(10)
make.centerY.equalTo(seekToView.snp.centerY)
}
replayButton.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX)
make.centerY.equalTo(mainMaskView.snp.centerY)
make.width.height.equalTo(50)
}
subtitleBackView.snp.makeConstraints {
$0.bottom.equalTo(snp.bottom).offset(-5)
$0.centerX.equalTo(snp.centerX)
$0.width.lessThanOrEqualTo(snp.width).offset(-10).priority(750)
}
subtitleLabel.snp.makeConstraints {
$0.left.equalTo(subtitleBackView.snp.left).offset(10)
$0.right.equalTo(subtitleBackView.snp.right).offset(-10)
$0.top.equalTo(subtitleBackView.snp.top).offset(2)
$0.bottom.equalTo(subtitleBackView.snp.bottom).offset(-2)
}
}
fileprivate func BMImageResourcePath(_ fileName: String) -> UIImage? {
let bundle = Bundle(for: BMPlayer.self)
let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
return image
}
}
| c2ee5e00c9b458dab912bea4c918099b | 34.436185 | 126 | 0.610465 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB简单封装版/MGDYZB/Class/Live/ViewModel/AllListViewModel.swift | mit | 1 | //
// AllListViewModel.swift
// MGDYZB
//
// Created by ming on 16/10/30.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
import UIKit
class AllListViewModel: NSObject {
// 用于上下拉刷新
var currentPage = 0
var rooms: [RoomModel] = []
fileprivate let tagID: String = "0"
}
extension AllListViewModel {
func loadAllListData(_ finishedCallback: @escaping () -> ()) {
let parameters:[String : Any] = ["offset": 20*currentPage, "limit": 20, "time": String(format: "%.0f", Date().timeIntervalSince1970)]
let url = "http://capi.douyucdn.cn/api/v1/live/" + "\(tagID)?"
NetWorkTools.requestData(type: .get, urlString: url,parameters: parameters, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
NetWorkTools.requestData(type: .get, urlString: "http://www.douyu.com/api/v1/live/directory",parameters: nil, succeed: { (result, err) in
// 1.获取到数据
guard let resultDict = result as? [String: Any] else { return }
guard let dataArray = resultDict["data"] as? [[String: Any]] else { return }
// debugPrint(dataArray)
// 2.字典转模型
for dict in dataArray {
self.rooms.append(RoomModel(dict: dict))
}
// 3.完成回调
finishedCallback()
}) { (err) in
finishedCallback()
}
}
}
| 189ca15da02c2fc7f6f094903211ff5a | 32.775862 | 145 | 0.552833 | false | false | false | false |
jkereako/MassStateKeno | refs/heads/master | Sources/Views/DrawingTableViewCell.swift | mit | 1 | //
// DrawingTableViewCell.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/19/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import UIKit
final class DrawingTableViewCell: UITableViewCell {
var viewModel: DrawingViewModel? {
didSet {
gameIdentifier.text = viewModel?.gameIdentifier
bonusMultiplier.text = viewModel?.bonus
}
}
@IBOutlet private weak var innerContent: UIView!
@IBOutlet private weak var gameIdentifier: UILabel!
@IBOutlet private weak var bonusMultiplier: UILabel!
@IBInspectable private var innerContentBorderColor: UIColor = UIColor.white
@IBInspectable private var innerContentBorderWidth: CGFloat = 3.0
@IBInspectable private var innerContentCornerRadius: CGFloat = 15.0
private let selectedBackgroundColor = UIColor(named: "DarkBlue")
private let unselectedBackgroundColor = UIColor(named: "MediumBlue")
override func awakeFromNib() {
super.awakeFromNib()
gameIdentifier.text = nil
bonusMultiplier.text = nil
innerContent.layer.borderColor = innerContentBorderColor.cgColor
innerContent.layer.borderWidth = innerContentBorderWidth
innerContent.layer.cornerRadius = innerContentCornerRadius
selectionStyle = .none
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
if (highlighted) {
innerContent.backgroundColor = selectedBackgroundColor
return
}
innerContent.backgroundColor = unselectedBackgroundColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
if (selected) {
innerContent.backgroundColor = selectedBackgroundColor
return
}
innerContent.backgroundColor = unselectedBackgroundColor
}
override func layoutSubviews() {
super.layoutSubviews()
#if TARGET_INTERFACE_BUILDER
innerContent.layer.borderColor = innerContentBorderColor.cgColor
innerContent.layer.borderWidth = innerContentBorderWidth
innerContent.layer.cornerRadius = innerContentCornerRadius
#endif
}
}
| f7c8bd57c39e0711fbdf62d77579a449 | 29.985915 | 79 | 0.695909 | false | false | false | false |
psobot/hangover | refs/heads/master | Hangover/ConversationEvent.swift | mit | 1 | //
// ConversationEvent.swift
// Hangover
//
// Created by Peter Sobot on 6/8/15.
// Copyright © 2015 Peter Sobot. All rights reserved.
//
import Foundation
struct UserID : Hashable {
let chat_id: String
let gaia_id: String
var hashValue: Int {
get {
return chat_id.hashValue &+ gaia_id.hashValue
}
}
}
func ==(lhs: UserID, rhs: UserID) -> Bool {
return lhs.hashValue == rhs.hashValue
}
class ConversationEvent : Equatable {
// An event which becomes part of the permanent record of a conversation.
// This corresponds to ClientEvent in the API.
// This is the base class for such events.
let event: CLIENT_EVENT
init(client_event: CLIENT_EVENT) {
event = client_event
}
lazy var timestamp: NSDate = {
// A timestamp of when the event occurred.
return self.event.timestamp
}()
lazy var user_id: UserID = {
// A UserID indicating who created the event.
return UserID(
chat_id: self.event.sender_id!.chat_id as String,
gaia_id: self.event.sender_id!.gaia_id as String
)
}()
lazy var conversation_id: NSString = {
// The ID of the conversation the event belongs to.
return self.event.conversation_id.id
}()
lazy var id: Conversation.EventID = {
// The ID of the ConversationEvent.
return self.event.event_id! as Conversation.EventID
}()
}
func ==(lhs: ConversationEvent, rhs: ConversationEvent) -> Bool {
return lhs.event == rhs.event
}
class ChatMessageSegment {
let type: SegmentType
let text: String
let is_bold: Bool
let is_italic: Bool
let is_strikethrough: Bool
let is_underline: Bool
let link_target: String?
// A segment of a chat message.
init(text: String,
segment_type: SegmentType?=nil,
is_bold: Bool=false,
is_italic: Bool=false,
is_strikethrough: Bool=false,
is_underline: Bool=false,
link_target: String?=nil
) {
// Create a new chat message segment.
if let type = segment_type {
self.type = type
} else if link_target != nil {
self.type = SegmentType.LINK
} else {
self.type = SegmentType.TEXT
}
self.text = text
self.is_bold = is_bold
self.is_italic = is_italic
self.is_strikethrough = is_strikethrough
self.is_underline = is_underline
self.link_target = link_target
}
// static func from_str(string: text) -> [ChatMessageSegment] {
// // Generate ChatMessageSegment list parsed from a string.
// // This method handles automatically finding line breaks, URLs and
// // parsing simple formatting markup (simplified Markdown and HTML).
// segment_list = chat_message_parser.parse(text)
// return [ChatMessageSegment(segment.text, **segment.params) for segment in segment_list]
// }
init(segment: MESSAGE_SEGMENT) {
// Create a chat message segment from a parsed MESSAGE_SEGMENT.
text = segment.text! as String
type = segment.type_
// The formatting options are optional.
is_bold = segment.formatting?.bold?.boolValue ?? false
is_italic = segment.formatting?.italic?.boolValue ?? false
is_strikethrough = segment.formatting?.strikethrough?.boolValue ?? false
is_underline = segment.formatting?.underline?.boolValue ?? false
link_target = (segment.link_data?.link_target as String?) ?? nil
}
func serialize() -> NSArray {
// Serialize the segment to pblite.
return [self.type.representation, self.text, [
self.is_bold ? 1 : 0,
self.is_italic ? 1 : 0,
self.is_strikethrough ? 1 : 0,
self.is_underline ? 1 : 0,
], [self.link_target ?? NSNull()]]
}
}
class ChatMessageEvent : ConversationEvent {
// An event containing a chat message.
// Corresponds to ClientChatMessage in the API.
lazy var text: String = {
// A textual representation of the message.
var lines = [""]
for segment in self.segments {
switch (segment.type) {
case SegmentType.TEXT, SegmentType.LINK:
let replacement = lines.last! + segment.text
lines.removeLast()
lines.append(replacement)
case SegmentType.LINE_BREAK:
lines.append("")
default:
print("Ignoring unknown chat message segment type: \(segment.type.representation)")
}
}
lines += self.attachments
return "\n".join(lines)
}()
lazy var segments: [ChatMessageSegment] = {
// List of ChatMessageSegments in the message.
if let list = self.event.chat_message?.message_content.segment {
return list.map { ChatMessageSegment(segment: $0) }
} else {
return []
}
}()
var attachments: [String] {
get {
// Attachments in the message.
let raw_attachments = self.event.chat_message?.message_content.attachment ?? [MESSAGE_ATTACHMENT]()
var attachments = [String]()
for attachment in raw_attachments {
if attachment.embed_item.type_ == [249] { // PLUS_PHOTO
// Try to parse an image message. Image messages contain no
// message segments, and thus have no automatic textual
// fallback.
if let data = attachment.embed_item.data["27639957"] as? NSArray,
zeroth = data[0] as? NSArray,
third = zeroth[3] as? String {
attachments.append(third)
}
} else if attachment.embed_item.type_ == [340, 335, 0] {
// Google Maps URL that's already in the text.
} else {
print("Ignoring unknown chat message attachment: \(attachment)")
}
}
return attachments
}
}
}
class RenameEvent : ConversationEvent {
// An event that renames a conversation.
// Corresponds to ClientConversationRename in the API.
var new_name: String {
get {
// The conversation's new name.
// An empty string if the conversation's name was cleared.
return self.event.conversation_rename!.new_name as String
}
}
var old_name: String {
get {
// The conversation's old name.
// An empty string if the conversation had no previous name.
return self.event.conversation_rename!.old_name as String
}
}
}
class MembershipChangeEvent : ConversationEvent {
// An event that adds or removes a conversation participant.
// Corresponds to ClientMembershipChange in the API.
var type: MembershipChangeType {
get {
// The membership change type (MembershipChangeType).
return self.event.membership_change!.type_
}
}
var participant_ids: [UserID] {
get {
// Return the UserIDs involved in the membership change.
// Multiple users may be added to a conversation at the same time.
return self.event.membership_change!.participant_ids.map {
UserID(chat_id: $0.chat_id as String, gaia_id: $0.gaia_id as String)
}
}
}
} | 4ed9af8062051c3022e731c6ca4f3bdc | 31.616379 | 111 | 0.583928 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | IAWExtensionTool/IAWExtensionTool/Classes/Common/IAW_EditTextViewController.swift | mit | 1 | //
// EditViewController.swift
// WingBid
//
// Created by winston on 16/10/6.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
//import OMExtension
import Easy
public protocol EditTextViewDelegate: NSObjectProtocol {
func editClick(editKey: String,editValue:String)
}
// key value的形式 key实际就是title value
open class IAW_EditTextViewController: IAW_BaseViewController {
var editKey:String = ""
var editValue: String = ""
weak var delegate: EditTextViewDelegate?
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initUI()
}
override open func viewWillAppear(_ animated: Bool) {
editTextfield.text = editValue
}
func initUI(){
setRightBarBtn()
view.addSubview(editTextfield)
editTextfield.snp.makeConstraints{
(make) in
make.top.equalTo(10)
make.width.equalTo(view)
make.height.equalTo(40)
}
}
func setRightBarBtn(){
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(rightBarBtnClick))
}
private lazy var editTextfield:UITextField = {
let editTextfield = UITextField()
editTextfield.clearButtonMode = .always
editTextfield.leftView = UIView(frame: CGRect(x:0,y:0,width:8,height:0))
editTextfield.leftViewMode = .always
editTextfield.backgroundColor = UIColor.white
editTextfield.textColor = UIColor.iaw_Color(0, g: 0, b: 0, a: 0.6)
editTextfield.font = UIFont.systemFont(ofSize: 16)
editTextfield.setLimit(20)
return editTextfield
}()
@objc func rightBarBtnClick(){
if (editTextfield.text?.isEmpty)! {
IAW_ProgressHUDTool.showErrorInfo(msg: "\(navigationItem.title!)不能为空!")
return
}
if(editValue == editTextfield.text!){//没有改变直接关闭
_ = self.navigationController?.popViewController(animated: true)
return
}
delegate?.editClick(editKey: editKey,editValue:editTextfield.text!)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 6f064644cbe4af8ba79fddedff73e8e2 | 30.933333 | 138 | 0.640501 | false | false | false | false |
stv-ekushida/STV-Extensions | refs/heads/master | STV-Extensions/Classes/Foundation/Date+Helper.swift | mit | 1 | //
// Date+Helper.swift
// ios-extension-demo
//
// Created by Eiji Kushida on 2017/03/13.
// Copyright © 2017年 Eiji Kushida. All rights reserved.
//
import Foundation
public extension Date {
/// Date型をString型に変更する
func toStr(dateFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP") as Locale!
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .short
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: self)
}
/// Unixタイムスタンプを取得する
static var unixTimestamp: String {
get {
return Date().timeIntervalSince1970.description
}
}
}
| b77e7d2716ea12dc17c8302cd743ea7d | 23.0625 | 77 | 0.623377 | false | false | false | false |
tonyarnold/Differ | refs/heads/main | Sources/Differ/NestedExtendedDiff.swift | mit | 1 | public struct NestedExtendedDiff: DiffProtocol {
public typealias Index = Int
public enum Element {
case deleteSection(Int)
case insertSection(Int)
case moveSection(from: Int, to: Int)
case deleteElement(Int, section: Int)
case insertElement(Int, section: Int)
case moveElement(from: (item: Int, section: Int), to: (item: Int, section: Int))
}
/// Returns the position immediately after the given index.
///
/// - Parameters:
/// - i: A valid index of the collection. `i` must be less than `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
/// An array of particular diff operations
public var elements: [Element]
/// Initializes a new ``NestedExtendedDiff`` from a given array of diff operations.
///
/// - Parameters:
/// - elements: an array of particular diff operations
public init(elements: [Element]) {
self.elements = elements
}
}
public typealias NestedElementEqualityChecker<T: Collection> = (T.Element.Element, T.Element.Element) -> Bool where T.Element: Collection
public extension Collection
where Element: Collection {
/// Creates a diff between the callee and `other` collection. It diffs elements two levels deep (therefore "nested")
///
/// - Parameters:
/// - other: a collection to compare the calee to
/// - Returns: a ``NestedDiff`` between the calee and `other` collection
func nestedExtendedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedExtendedDiff {
// FIXME: This implementation is a copy paste of NestedDiff with some adjustments.
let diffTraces = outputDiffPathTraces(to: to, isEqual: isEqualSection)
let sectionDiff =
extendedDiff(
from: Diff(traces: diffTraces),
other: to,
isEqual: isEqualSection
).map { element -> NestedExtendedDiff.Element in
switch element {
case let .delete(at):
return .deleteSection(at)
case let .insert(at):
return .insertSection(at)
case let .move(from, to):
return .moveSection(from: from, to: to)
}
}
// Diff matching sections (moves, deletions, insertions)
let filterMatchPoints = { (trace: Trace) -> Bool in
if case .matchPoint = trace.type() {
return true
}
return false
}
let sectionMoves =
sectionDiff.compactMap { diffElement -> (Int, Int)? in
if case let .moveSection(from, to) = diffElement {
return (from, to)
}
return nil
}.flatMap { move -> [NestedExtendedDiff.Element] in
return itemOnStartIndex(advancedBy: move.0).extendedDiff(to.itemOnStartIndex(advancedBy: move.1), isEqual: isEqualElement)
.map { diffElement -> NestedExtendedDiff.Element in
switch diffElement {
case let .insert(at):
return .insertElement(at, section: move.1)
case let .delete(at):
return .deleteElement(at, section: move.0)
case let .move(from, to):
return .moveElement(from: (from, move.0), to: (to, move.1))
}
}
}
// offset & section
let matchingSectionTraces = diffTraces
.filter(filterMatchPoints)
let fromSections = matchingSectionTraces.map {
itemOnStartIndex(advancedBy: $0.from.x)
}
let toSections = matchingSectionTraces.map {
to.itemOnStartIndex(advancedBy: $0.from.y)
}
let elementDiff = zip(zip(fromSections, toSections), matchingSectionTraces)
.flatMap { (args) -> [NestedExtendedDiff.Element] in
let (sections, trace) = args
return sections.0.extendedDiff(sections.1, isEqual: isEqualElement).map { diffElement -> NestedExtendedDiff.Element in
switch diffElement {
case let .delete(at):
return .deleteElement(at, section: trace.from.x)
case let .insert(at):
return .insertElement(at, section: trace.from.y)
case let .move(from, to):
return .moveElement(from: (from, trace.from.x), to: (to, trace.from.y))
}
}
}
return NestedExtendedDiff(elements: sectionDiff + sectionMoves + elementDiff)
}
}
public extension Collection
where Element: Collection,
Element.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(
to: Self,
isEqualSection: EqualityChecker<Self>
) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: isEqualSection,
isEqualElement: { $0 == $1 }
)
}
}
public extension Collection
where Element: Collection, Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(
to: Self,
isEqualElement: NestedElementEqualityChecker<Self>
) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: isEqualElement
)
}
}
public extension Collection
where Element: Collection, Element: Equatable,
Element.Element: Equatable {
/// - SeeAlso: `nestedDiff(to:isEqualSection:isEqualElement:)`
func nestedExtendedDiff(to: Self) -> NestedExtendedDiff {
return nestedExtendedDiff(
to: to,
isEqualSection: { $0 == $1 },
isEqualElement: { $0 == $1 }
)
}
}
extension NestedExtendedDiff.Element: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .deleteElement(row, section):
return "DE(\(row),\(section))"
case let .deleteSection(section):
return "DS(\(section))"
case let .insertElement(row, section):
return "IE(\(row),\(section))"
case let .insertSection(section):
return "IS(\(section))"
case let .moveElement(from, to):
return "ME((\(from.item),\(from.section)),(\(to.item),\(to.section)))"
case let .moveSection(from, to):
return "MS(\(from),\(to))"
}
}
}
extension NestedExtendedDiff: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: NestedExtendedDiff.Element...) {
self.elements = elements
}
}
| 677aa840003ca7bf4be535f234fd3fb8 | 34.173267 | 138 | 0.572695 | false | false | false | false |
bmichotte/HSTracker | refs/heads/master | HSTracker/Logging/Parsers/TagChangeActions.swift | mit | 1 | //
// TagChanceActions.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
struct TagChangeActions {
func callAction(eventHandler: PowerEventHandler, tag: GameTag, id: Int, value: Int, prevValue: Int) {
switch tag {
case .zone: self.zoneChange(eventHandler: eventHandler, id: id, value: value, prevValue: prevValue)
case .playstate: self.playstateChange(eventHandler: eventHandler, id: id, value: value)
case .cardtype: self.cardTypeChange(eventHandler: eventHandler, id: id, value: value)
case .last_card_played: self.lastCardPlayedChange(eventHandler: eventHandler, value: value)
case .defending: self.defendingChange(eventHandler: eventHandler, id: id, value: value)
case .attacking: self.attackingChange(eventHandler: eventHandler, id: id, value: value)
case .proposed_defender: self.proposedDefenderChange(eventHandler: eventHandler, value: value)
case .proposed_attacker: self.proposedAttackerChange(eventHandler: eventHandler, value: value)
case .num_minions_played_this_turn:
self.numMinionsPlayedThisTurnChange(eventHandler: eventHandler, value: value)
case .predamage: self.predamageChange(eventHandler: eventHandler, id: id, value: value)
case .num_turns_in_play: self.numTurnsInPlayChange(eventHandler: eventHandler, id: id, value: value)
case .num_attacks_this_turn: self.numAttacksThisTurnChange(eventHandler: eventHandler, id: id, value: value)
case .zone_position: self.zonePositionChange(eventHandler: eventHandler, id: id)
case .card_target: self.cardTargetChange(eventHandler: eventHandler, id: id, value: value)
case .equipped_weapon: self.equippedWeaponChange(eventHandler: eventHandler, id: id, value: value)
case .exhausted: self.exhaustedChange(eventHandler: eventHandler, id: id, value: value)
case .controller:
self.controllerChange(eventHandler: eventHandler, id: id, prevValue: prevValue, value: value)
case .fatigue: self.fatigueChange(eventHandler: eventHandler, value: value, id: id)
case .step: self.stepChange(eventHandler: eventHandler)
case .turn: self.turnChange(eventHandler: eventHandler)
case .state: self.stateChange(eventHandler: eventHandler, value: value)
case .transformed_from_card: self.transformedFromCardChange(eventHandler: eventHandler,
id: id,
value: value)
default: break
}
}
private func transformedFromCardChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == 0 { return }
guard let entity = eventHandler.entities[id] else { return }
entity.info.set(originalCardId: value)
}
private func lastCardPlayedChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.lastCardPlayed = value
}
private func defendingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.defending(entity: value == 1 ? entity : nil)
}
private func attackingChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
eventHandler.attacking(entity: value == 1 ? entity : nil)
}
private func proposedDefenderChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.opponentSecrets?.proposedDefenderEntityId = value
}
private func proposedAttackerChange(eventHandler: PowerEventHandler, value: Int) {
eventHandler.opponentSecrets?.proposedAttackerEntityId = value
}
private func numMinionsPlayedThisTurnChange(eventHandler: PowerEventHandler, value: Int) {
guard value > 0 else { return }
guard let playerEntity = eventHandler.playerEntity else { return }
if playerEntity.isCurrentPlayer {
eventHandler.playerMinionPlayed()
}
}
private func predamageChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let playerEntity = eventHandler.playerEntity, let entity = eventHandler.entities[id] else { return }
if playerEntity.isCurrentPlayer {
eventHandler.opponentDamage(entity: entity)
}
}
private func numTurnsInPlayChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
eventHandler.turnsInPlayChange(entity: entity, turn: eventHandler.turnNumber())
}
private func fatigueChange(eventHandler: PowerEventHandler, value: Int, id: Int) {
guard let entity = eventHandler.entities[id] else { return }
let controller = entity[.controller]
if controller == eventHandler.player.id {
eventHandler.playerFatigue(value: value)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentFatigue(value: value)
}
}
private func controllerChange(eventHandler: PowerEventHandler, id: Int, prevValue: Int, value: Int) {
guard let entity = eventHandler.entities[id] else { return }
if prevValue <= 0 {
entity.info.originalController = value
return
}
guard !entity.has(tag: .player_id) else { return }
if value == eventHandler.player.id {
if entity.isInZone(zone: .secret) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.opponentStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
} else if value == eventHandler.opponent.id && prevValue != value {
if entity.isInZone(zone: .secret) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
} else if entity.isInZone(zone: .play) {
eventHandler.playerStolen(entity: entity, cardId: entity.cardId, turn: eventHandler.turnNumber())
}
}
}
private func exhaustedChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
guard value > 0 else { return }
guard let entity = eventHandler.entities[id] else { return }
guard entity[.cardtype] == CardType.hero_power.rawValue else { return }
}
private func equippedWeaponChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func cardTargetChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func zonePositionChange(eventHandler: PowerEventHandler, id: Int) {
}
private func numAttacksThisTurnChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
}
private func stateChange(eventHandler: PowerEventHandler, value: Int) {
if value != State.complete.rawValue {
return
}
eventHandler.gameEnd()
eventHandler.gameEnded = true
}
private func turnChange(eventHandler: PowerEventHandler) {
guard eventHandler.setupDone && eventHandler.playerEntity != nil else { return }
guard let playerEntity = eventHandler.playerEntity else { return }
let activePlayer: PlayerType = playerEntity.has(tag: .current_player) ? .player : .opponent
if activePlayer == .player {
eventHandler.playerUsedHeroPower = false
} else {
eventHandler.opponentUsedHeroPower = false
}
}
private func stepChange(eventHandler: PowerEventHandler) {
guard !eventHandler.setupDone && eventHandler.entities.first?.1.name == "GameEntity" else { return }
Log.info?.message("Game was already in progress.")
eventHandler.wasInProgress = true
}
private func cardTypeChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == CardType.hero.rawValue {
setHeroAsync(eventHandler: eventHandler, id: id)
}
}
private func playstateChange(eventHandler: PowerEventHandler, id: Int, value: Int) {
if value == PlayState.conceded.rawValue {
eventHandler.concede()
}
guard !eventHandler.gameEnded else { return }
if let entity = eventHandler.entities[id], !entity.isPlayer(eventHandler: eventHandler) {
return
}
if let value = PlayState(rawValue: value) {
switch value {
case .won:
eventHandler.win()
case .lost:
eventHandler.loss()
case .tied:
eventHandler.tied()
default: break
}
}
}
private func zoneChange(eventHandler: PowerEventHandler, id: Int, value: Int, prevValue: Int) {
guard id > 3 else { return }
guard let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == nil {
if prevValue != Zone.invalid.rawValue && prevValue != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: prevValue)
} else if value != Zone.invalid.rawValue && value != Zone.setaside.rawValue {
entity.info.originalZone = Zone(rawValue: value)
}
}
let controller = entity[.controller]
guard let zoneValue = Zone(rawValue: prevValue) else { return }
switch zoneValue {
case .deck:
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue,
controller: controller,
cardId: entity.cardId)
case .hand:
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .play:
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .secret:
zoneChangeFromSecret(eventHandler: eventHandler, id: id, value: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
case .invalid:
let maxId = getMaxHeroPowerId(eventHandler: eventHandler)
if !eventHandler.setupDone
&& (id <= maxId || eventHandler.gameEntity?[.step] == Step.invalid.rawValue
&& entity[.zone_position] < 5) {
entity.info.originalZone = .deck
simulateZoneChangesFromDeck(eventHandler: eventHandler, id: id, value: value,
cardId: entity.cardId, maxId: maxId)
} else {
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value,
prevValue: prevValue, controller: controller,
cardId: entity.cardId)
}
case .graveyard, .setaside, .removedfromgame:
zoneChangeFromOther(eventHandler: eventHandler, id: id, rawValue: value, prevValue: prevValue,
controller: controller, cardId: entity.cardId)
}
}
// The last heropower is created after the last hero, therefore +1
private func getMaxHeroPowerId(eventHandler: PowerEventHandler) -> Int {
return max(eventHandler.playerEntity?[.hero_entity] ?? 66,
eventHandler.opponentEntity?[.hero_entity] ?? 66) + 1
}
private func simulateZoneChangesFromDeck(eventHandler: PowerEventHandler, id: Int,
value: Int, cardId: String?, maxId: Int) {
if value == Zone.deck.rawValue {
return
}
guard let entity = eventHandler.entities[id] else { return }
if value == Zone.setaside.rawValue {
entity.info.created = true
return
}
if entity.isHero || entity.isHeroPower || entity.has(tag: .player_id)
|| entity[.cardtype] == CardType.game.rawValue || entity.has(tag: .creator) {
return
}
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: Zone.hand.rawValue,
prevValue: Zone.deck.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.hand.rawValue {
return
}
zoneChangeFromHand(eventHandler: eventHandler, id: id, value: Zone.play.rawValue,
prevValue: Zone.hand.rawValue,
controller: entity[.controller], cardId: cardId)
if value == Zone.play.rawValue {
return
}
zoneChangeFromPlay(eventHandler: eventHandler, id: id, value: value, prevValue: Zone.play.rawValue,
controller: entity[.controller], cardId: cardId)
}
private func zoneChangeFromOther(eventHandler: PowerEventHandler, id: Int, rawValue: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let value = Zone(rawValue: rawValue), let entity = eventHandler.entities[id] else { return }
if entity.info.originalZone == .deck && rawValue != Zone.deck.rawValue {
// This entity was moved from DECK to SETASIDE to HAND, e.g. by Tracking
entity.info.discarded = false
zoneChangeFromDeck(eventHandler: eventHandler, id: id, value: rawValue, prevValue: prevValue,
controller: controller, cardId: cardId)
return
}
entity.info.created = true
switch value {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .deck:
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.playerGetToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
break
}
eventHandler.opponentGetToDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerGet(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentGet(entity: entity, turn: eventHandler.turnNumber(), id: id)
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId, from: -1,
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .setaside:
if controller == eventHandler.player.id {
eventHandler.playerCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentCreateInSetAside(entity: entity, turn: eventHandler.turnNumber())
}
default:
break
}
}
private func zoneChangeFromSecret(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .secret, .graveyard:
if controller == eventHandler.opponent.id {
eventHandler.opponentSecretTrigger(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), otherId: id)
}
default:
break
}
}
private func zoneChangeFromPlay(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerBackToHand(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToHand(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), id: id)
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlayToDeck(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerPlayToGraveyard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if let playerEntity = eventHandler.playerEntity {
eventHandler.opponentPlayToGraveyard(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(),
playersTurn: playerEntity.isCurrentPlayer)
}
}
case .removedfromgame, .setaside:
if controller == eventHandler.player.id {
eventHandler.playerRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentRemoveFromPlay(entity: entity, turn: eventHandler.turnNumber())
}
case .play:
break
default:
break
}
}
private func zoneChangeFromHand(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .play:
if controller == eventHandler.player.id {
eventHandler.playerPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentPlay(entity: entity, cardId: cardId, from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .removedfromgame, .setaside, .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerHandDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentHandDiscard(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: entity[.zone_position],
turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
case .deck:
if controller == eventHandler.player.id {
eventHandler.playerMulligan(entity: entity, cardId: cardId)
} else if controller == eventHandler.opponent.id {
eventHandler.opponentMulligan(entity: entity, from: entity[.zone_position])
}
default:
break
}
}
private func zoneChangeFromDeck(eventHandler: PowerEventHandler, id: Int, value: Int,
prevValue: Int, controller: Int, cardId: String?) {
guard let zoneValue = Zone(rawValue: value), let entity = eventHandler.entities[id] else { return }
switch zoneValue {
case .hand:
if controller == eventHandler.player.id {
eventHandler.playerDraw(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDraw(entity: entity, turn: eventHandler.turnNumber())
}
case .setaside, .removedfromgame:
if !eventHandler.setupDone {
entity.info.created = true
return
}
if controller == eventHandler.player.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.playerRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
if eventHandler.joustReveals > 0 {
eventHandler.joustReveals -= 1
break
}
eventHandler.opponentRemoveFromDeck(entity: entity, turn: eventHandler.turnNumber())
}
case .graveyard:
if controller == eventHandler.player.id {
eventHandler.playerDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckDiscard(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .play:
if controller == eventHandler.player.id {
eventHandler.playerDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
} else if controller == eventHandler.opponent.id {
eventHandler.opponentDeckToPlay(entity: entity, cardId: cardId, turn: eventHandler.turnNumber())
}
case .secret:
if controller == eventHandler.player.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.playerSecretPlayed(entity: entity, cardId: cardId,
turn: eventHandler.turnNumber(), fromZone: prevZone)
}
} else if controller == eventHandler.opponent.id {
if let prevZone = Zone(rawValue: prevValue) {
eventHandler.opponentSecretPlayed(entity: entity, cardId: cardId,
from: -1, turn: eventHandler.turnNumber(),
fromZone: prevZone, otherId: id)
}
}
default:
break
}
}
private func setHeroAsync(eventHandler: PowerEventHandler, id: Int) {
Log.info?.message("Found hero with id \(id) ")
DispatchQueue.global().async {
if eventHandler.playerEntity == nil {
Log.info?.message("Waiting for playerEntity")
while eventHandler.playerEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let playerEntity = eventHandler.playerEntity,
let entity = eventHandler.entities[id] {
Log.info?.message("playerEntity found playerClass : "
+ "\(String(describing: eventHandler.player.playerClass)), "
+ "\(id) -> \(playerEntity[.hero_entity]) -> \(entity) ")
if id == playerEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(playerHero: cardId)
}
return
}
}
if eventHandler.opponentEntity == nil {
Log.info?.message("Waiting for opponentEntity")
while eventHandler.opponentEntity == nil {
Thread.sleep(forTimeInterval: 0.1)
}
}
if let opponentEntity = eventHandler.opponentEntity,
let entity = eventHandler.entities[id] {
Log.info?.message("opponentEntity found playerClass : "
+ "\(String(describing: eventHandler.opponent.playerClass)),"
+ " \(id) -> \(opponentEntity[.hero_entity]) -> \(entity) ")
if id == opponentEntity[.hero_entity] {
let cardId = entity.cardId
DispatchQueue.main.async {
eventHandler.set(opponentHero: cardId)
}
return
}
}
}
}
}
| d3ab00cd8583721d0e56a250484c6b54 | 44.787022 | 116 | 0.574715 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Utility/Views/SearchController.swift | lgpl-2.1 | 2 | //
// SearchController.swift
// Neocom
//
// Created by Artem Shimanski on 5/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Combine
struct SearchController<Results, Content: View, P: Publisher>: UIViewControllerRepresentable where P.Failure == Never, P.Output == Results {
var search: (String) -> P
var content: (Results?) -> Content
init(search: @escaping (String) -> P, @ViewBuilder content: @escaping (Results?) -> Content) {
self.search = search
self.content = content
}
func makeUIViewController(context: Context) -> SearchControllerWrapper<Results, Content, P> {
SearchControllerWrapper(search: search, content: content)
}
func updateUIViewController(_ uiViewController: SearchControllerWrapper<Results, Content, P>, context: Context) {
}
}
struct SearchControllerTest: View {
@State private var text: String = "123"
@State private var isEditing: Bool = false
@State private var text2: String = "321"
let subject = CurrentValueSubject<String, Never>("123")
var binding: Binding<String> {
Binding(get: {
self.text
}) {
self.text = $0
self.subject.send($0)
}
}
var body: some View {
VStack{
// SearchBar()
SearchField(text: binding, isEditing: $isEditing)
List {
Text(text2)
}.onReceive(subject.debounce(for: .seconds(0.25), scheduler: RunLoop.main)) {
self.text2 = $0
}
}
}
}
struct SearchController_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
SearchControllerTest()
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
| 75ce5e9288a0df80011dd4c3e0acb4c7 | 27.184615 | 140 | 0.6119 | false | false | false | false |
apple/swift | refs/heads/main | test/Interop/Cxx/stdlib/overlay/custom-collection-module-interface.swift | apache-2.0 | 1 | // RUN: %target-swift-ide-test -print-module -module-to-print=CustomSequence -source-filename=x -I %S/Inputs -enable-experimental-cxx-interop -module-cache-path %t | %FileCheck %s
// CHECK: struct SimpleArrayWrapper : CxxRandomAccessCollection {
// CHECK: typealias Element = UnsafePointer<Int32>.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleArrayWrapper>
// CHECK: typealias RawIterator = UnsafePointer<Int32>
// CHECK: }
// CHECK: struct SimpleCollectionNoSubscript : CxxRandomAccessCollection {
// CHECK: typealias Element = ConstRACIterator.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleCollectionNoSubscript>
// CHECK: typealias RawIterator = SimpleCollectionNoSubscript.iterator
// CHECK: }
// CHECK: struct SimpleCollectionReadOnly : CxxRandomAccessCollection {
// CHECK: typealias Element = ConstRACIteratorRefPlusEq.Pointee
// CHECK: typealias Iterator = CxxIterator<SimpleCollectionReadOnly>
// CHECK: typealias RawIterator = SimpleCollectionReadOnly.iterator
// CHECK: }
| f51629d51112f8a6a1d7ba86cc43ed1c | 53 | 179 | 0.778752 | false | true | false | false |
ios-ximen/DYZB | refs/heads/master | 斗鱼直播/斗鱼直播/Classes/Home/Views/KGameView.swift | mit | 1 | //
// KGameView.swift
// 斗鱼直播
//
// Created by niujinfeng on 2017/7/6.
// Copyright © 2017年 niujinfeng. All rights reserved.
//
import UIKit
fileprivate let KGameID = "KGameID"
fileprivate let KEdgeMargin : CGFloat = 10
class KGameView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
//定义模型属性
var gameGroup : [BaseGameModel]?{
didSet{
//刷新数据
collectionView.reloadData()
}
}
//系统回调方法
override func awakeFromNib() {
super.awakeFromNib()
//子控件不随父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
//注册cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: KGameID)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(0, KEdgeMargin, 0, KEdgeMargin)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: 80, height: 90)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.showsHorizontalScrollIndicator = false
}
}
//快速创建类方法
extension KGameView {
class func kGameView() -> KGameView {
return Bundle.main.loadNibNamed("KGameView", owner: nil, options: nil)?.first as! KGameView
}
}
extension KGameView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameGroup?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KGameID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameGroup?[indexPath.item]
//cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.green
return cell
}
}
| cd777174a470320da0225be99d1fb793 | 30.235294 | 122 | 0.670433 | false | false | false | false |
PurpleSweetPotatoes/customControl | refs/heads/master | SwiftKit/UI/BQSheetView.swift | apache-2.0 | 1 | //
// BQSheetView.swift
// swift-Test
//
// Created by MrBai on 2017/6/13.
// Copyright © 2017年 MrBai. All rights reserved.
//
import UIKit
enum SheetType {
case table
case collection
}
class BQSheetView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
//MARK: - ***** Ivars *****
private var title: String?
private var type: SheetType!
private var tableDatas: [String] = []
private var shareDatas: [Dictionary<String,String>] = []
private var backView: UIView!
private var bottomView: UIView!
private var callBlock: ((Int) -> ())!
//MARK: - ***** Class Method *****
class func showSheetView(tableDatas:[String] ,title:String? = nil, handle:@escaping (Int)->()) {
let sheetView = BQSheetView(tableDatas: tableDatas, title: title)
sheetView.callBlock = handle
UIApplication.shared.keyWindow?.addSubview(sheetView)
sheetView.startAnimation()
}
/// 弹出脚部分享视图
///
/// - Parameters:
/// - shareDatas: ["image":"图片名"]
/// - title: 抬头名称
/// - handle: 回调方法
class func showShareView(shareDatas:[Dictionary<String,String>] ,title:String, handle:@escaping (Int)->()) {
let sheetView = BQSheetView(shareDatas: shareDatas, title: title)
sheetView.callBlock = handle
UIApplication.shared.keyWindow?.addSubview(sheetView)
sheetView.startAnimation()
}
//MARK: - ***** initialize Method *****
private init(tableDatas:[String] ,title:String? = nil) {
self.title = title
self.type = .table
self.tableDatas = tableDatas
super.init(frame: UIScreen.main.bounds)
self.initData()
self.initUI()
}
private init(shareDatas:[Dictionary<String,String>] ,title:String? = nil) {
self.title = title
self.type = .collection
self.shareDatas = shareDatas
super.init(frame: UIScreen.main.bounds)
self.initData()
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ***** public Method *****
//MARK: - ***** private Method *****
private func initData() {
}
private func initUI() {
self.backView = UIView(frame: self.bounds)
self.backView.backgroundColor = UIColor(white: 0.3, alpha: 0.6)
self.backView.alpha = 0
self.backView.addTapGes {[weak self] (view) in
self?.removeAnimation()
}
self.addSubview(self.backView)
self.bottomView = UIView(frame: CGRect(x: 0, y: self.height, width: self.width, height: 0))
self.addSubview(self.bottomView)
var top: CGFloat = 0
if self.type == .table {
top = self.createTableUI(y: top)
}else {
top = self.createShareUI(y: top)
}
self.bottomView.height = top + 8
}
private func startAnimation() {
UIView.animate(withDuration: 0.25) {
self.bottomView.top = self.height - self.bottomView.height
self.backView.alpha = 1
}
}
private func removeAnimation() {
UIView.animate(withDuration: 0.25, animations: {
self.bottomView.top = self.height
self.backView.alpha = 0
}) { (flag) in
self.removeFromSuperview()
}
}
//MARK: - ***** LoadData Method *****
//MARK: - ***** respond event Method *****
@objc private func tableBtnAction(btn:UIButton) {
self.callBlock(btn.tag)
self.removeAnimation()
}
//MARK: - ***** Protocol *****
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.shareDatas.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BQShareItemCell", for: indexPath) as! BQShareItemCell
cell.loadInfo(dic: self.shareDatas[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
self.callBlock(indexPath.row)
self.removeAnimation()
}
//MARK: - ***** create Method *****
private func createTableUI(y:CGFloat) -> CGFloat {
var top = y
let spacing: CGFloat = 20
let height: CGFloat = 44
let labWidth: CGFloat = self.width - spacing * 2
if let titl = self.title {
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = titl
lab.textAlignment = .center
lab.numberOfLines = 0
lab.font = UIFont.systemFont(ofSize: 14)
lab.textColor = UIColor.gray
let labHeight = titl.boundingRect(with: CGSize(width: labWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:lab.font], context: nil).size.height + 20
lab.height = labHeight
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
top = labHeight
}
top += 1
var count = 0
for str in self.tableDatas {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: spacing, y: top, width: labWidth, height: height)
btn.setTitle(str, for: .normal)
btn.tag = count
btn.titleLabel?.textAlignment = .center
btn.setTitleColor(UIColor.black, for: .normal)
btn.addTarget(self, action: #selector(tableBtnAction(btn:)), for: .touchUpInside)
self.bottomView.addSubview(btn)
if count == self.tableDatas.count - 1 {
btn.setCornerColor(color: UIColor.white, readius: 8, corners: [.bottomLeft,.bottomRight])
}else {
if count == 0 && self.title == nil {
btn.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
}else {
btn.backgroundColor = UIColor.white
}
}
count += 1
top = btn.bottom + 1
}
top += 7
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = "返回"
lab.layer.cornerRadius = 8
lab.layer.masksToBounds = true
lab.textAlignment = .center
lab.backgroundColor = UIColor.white
lab.addTapGes(action: {[weak self] (view) in
self?.removeAnimation()
})
self.bottomView.addSubview(lab)
return lab.bottom
}
private func createShareUI(y:CGFloat) -> CGFloat {
var top = y
let spacing: CGFloat = 10
let labWidth: CGFloat = self.width - spacing * 2
let itemWidth = labWidth / 4.0
if let titl = self.title {
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: height))
lab.text = titl
lab.textAlignment = .center
lab.numberOfLines = 0
lab.font = UIFont.systemFont(ofSize: 14)
lab.textColor = UIColor.gray
let labHeight = titl.boundingRect(with: CGSize(width: labWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName:lab.font], context: nil).size.height + 20
lab.height = labHeight
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.topLeft,.topRight])
top = labHeight
}
top += 1
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.scrollDirection = .vertical
var num = self.shareDatas.count / 4
if self.shareDatas.count % 4 > 0 {
num += 1
}
let collectionView = UICollectionView(frame: CGRect(x: spacing, y: top, width: labWidth, height: CGFloat(num) * itemWidth), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.register(BQShareItemCell.classForCoder(), forCellWithReuseIdentifier: "BQShareItemCell")
collectionView.dataSource = self
collectionView.delegate = self
self.bottomView.addSubview(collectionView)
top = collectionView.bottom + 1
let lab = UILabel(frame: CGRect(x: spacing, y: top, width: labWidth, height: 44))
lab.text = "返回"
lab.textAlignment = .center
lab.addTapGes(action: {[weak self] (view) in
self?.removeAnimation()
})
self.bottomView.addSubview(lab)
lab.setCornerColor(color: UIColor.white, readius: 8, corners: [.bottomLeft,.bottomRight])
return lab.bottom
}
}
class BQShareItemCell: UICollectionViewCell {
private var imgView: UIImageView!
private var titleLab: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func initUI() {
let imgWidth = self.width / 2.0
let spacing = (self.width - imgWidth) * 0.5
let imageView = UIImageView(frame: CGRect(x: spacing, y: spacing * 0.7, width: imgWidth, height: imgWidth))
self.contentView.addSubview(imageView)
self.imgView = imageView
let lab = UILabel(frame: CGRect(x: 0, y: imageView.bottom, width: self.width, height: spacing))
lab.textAlignment = .center
lab.font = UIFont.systemFont(ofSize: 13)
lab.textColor = UIColor.gray
self.contentView.addSubview(lab)
self.titleLab = lab
}
public func loadInfo(dic:Dictionary<String,String>) {
self.imgView.image = UIImage(named:dic["image"] ?? "")
self.titleLab.text = dic["image"]
}
}
| 3aefb19d28c1be2761e067259ff67bb9 | 37.935849 | 226 | 0.604381 | false | false | false | false |
freshOS/Komponents | refs/heads/master | Source/PageControl.swift | mit | 1 | //
// PageControl.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 12/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
public struct PageControl: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public var children = [IsNode]()
let props: PageControlProps
public var layout: Layout
public let ref: UnsafeMutablePointer<UIPageControl>?
public init(props:((inout PageControlProps) -> Void)? = nil,
_ layout: Layout? = nil,
ref: UnsafeMutablePointer<UIPageControl>? = nil) {
let defaultProps = PageControlProps()
if let p = props {
var prop = defaultProps
p(&prop)
self.props = prop
} else {
self.props = defaultProps
}
self.layout = layout ?? Layout()
self.ref = ref
}
}
public func == (lhs: PageControl, rhs: PageControl) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public struct PageControlProps: HasViewProps, Equatable, Hashable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public var numberOfPages = 0
public var currentPage = 0
public var pageIndicatorTintColor: UIColor?
public var currentPageIndicatorTintColor: UIColor?
public var hashValue: Int {
return viewPropsHash
^ numberOfPages.hashValue
^ currentPage.hashValue
^ hashFor(pageIndicatorTintColor)
^ hashFor(currentPageIndicatorTintColor)
}
}
public func == (lhs: PageControlProps, rhs: PageControlProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| c94a12bd630e223bdd951c27bdc88e3f | 28.753623 | 71 | 0.645397 | false | false | false | false |
minikin/Algorithmics | refs/heads/master | Pods/PSOperations/PSOperations/ReachabilityCondition.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
#if !os(watchOS)
import Foundation
import SystemConfiguration
/**
This is a condition that performs a very high-level reachability check.
It does *not* perform a long-running reachability check, nor does it respond to changes in reachability.
Reachability is evaluated once when the operation to which this is attached is asked about its readiness.
*/
public struct ReachabilityCondition: OperationCondition {
public static let hostKey = "Host"
public static let name = "Reachability"
public static let isMutuallyExclusive = false
let host: NSURL
public init(host: NSURL) {
self.host = host
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return nil
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
ReachabilityController.requestReachability(host) { reachable in
if reachable {
completion(.Satisfied)
}
else {
let error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.hostKey: self.host
])
completion(.Failed(error))
}
}
}
}
/// A private singleton that maintains a basic cache of `SCNetworkReachability` objects.
private class ReachabilityController {
static var reachabilityRefs = [String: SCNetworkReachability]()
static let reachabilityQueue = dispatch_queue_create("Operations.Reachability", DISPATCH_QUEUE_SERIAL)
static func requestReachability(url: NSURL, completionHandler: (Bool) -> Void) {
if let host = url.host {
dispatch_async(reachabilityQueue) {
var ref = self.reachabilityRefs[host]
if ref == nil {
let hostString = host as NSString
ref = SCNetworkReachabilityCreateWithName(nil, hostString.UTF8String)
}
if let ref = ref {
self.reachabilityRefs[host] = ref
var reachable = false
var flags: SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(ref, &flags) {
/*
Note that this is a very basic "is reachable" check.
Your app may choose to allow for other considerations,
such as whether or not the connection would require
VPN, a cellular connection, etc.
*/
reachable = flags.contains(.Reachable)
}
completionHandler(reachable)
}
else {
completionHandler(false)
}
}
}
else {
completionHandler(false)
}
}
}
#endif
| 1995a86ff8c309982bd978a9e99c5ee3 | 33.177083 | 109 | 0.57391 | false | false | false | false |
grandiere/box | refs/heads/master | box/Model/Stats/MStatsItemBugs.swift | mit | 1 | import UIKit
class MStatsItemBugs:MStatsItem
{
init()
{
let image:UIImage = #imageLiteral(resourceName: "assetTextureBugDetail")
let title:String = NSLocalizedString("MStatsItemBugs_title", comment:"")
let count:Int
if let bugs:Int16 = MSession.sharedInstance.settings?.stats?.bugs
{
count = Int(bugs)
}
else
{
count = 0
}
super.init(
image:image,
title:title,
count:count)
}
}
| 1b8c03b870bd1232e0cc03732f6d495a | 20.96 | 80 | 0.520947 | false | false | false | false |
sman591/csh-drink-ios | refs/heads/master | CSH Drink/TimeAgo.swift | mit | 1 | //
// TimeAgo.swift
// CSH Drink
//
// Created by Henry Saniuk on 10/14/16.
// Copyright © 2016 Stuart Olivera. All rights reserved.
//
// Based on https://github.com/zemirco/swift-timeago
//
import Foundation
public func timeAgoSince(_ date: Date, timestamp: String) -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let month = components.month, month >= 2 {
return timestamp
}
if let month = components.month, month >= 1 {
return "Last month"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) weeks ago"
}
if let week = components.weekOfYear, week >= 1 {
return "Last week"
}
if let day = components.day, day >= 2 {
return "\(day) days ago"
}
if let day = components.day, day >= 1 {
return "Yesterday"
}
if let hour = components.hour, hour >= 2 {
return "\(hour) hours ago"
}
if let hour = components.hour, hour >= 1 {
return "An hour ago"
}
if let minute = components.minute, minute >= 2 {
return "\(minute) minutes ago"
}
if let minute = components.minute, minute >= 1 {
return "A minute ago"
}
if let second = components.second, second >= 3 {
return "\(second) seconds ago"
}
return "Just now"
}
| 2d6c85396774335a87c415c482647e70 | 22.910448 | 101 | 0.566167 | false | false | false | false |
PjGeeroms/IOSRecipeDB | refs/heads/master | YummlyProject/Controllers/RecipeOverviewController.swift | mit | 1 | //
// RecipeOverviewController.swift
// YummlyProject
//
// Created by Pieter-Jan Geeroms on 25/12/2016.
// Copyright © 2016 Pieter-Jan Geeroms. All rights reserved.
//
import UIKit
import Alamofire
class RecipeOverviewController: UIViewController {
var recipe: Recipe!
@IBOutlet weak var recipeTitle: UILabel!
@IBOutlet weak var recipeDescription: UILabel!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var deleteButton: UIButton!
@IBAction func makeRecipe() {}
@IBAction func delete() {
let confirm = UIAlertController(title: "Delete recipe", message: "Are you sure you want to delete the recipe?", preferredStyle: .alert)
confirm.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action: UIAlertAction!) in
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type" : "application/json",
"Authorization" : "Token \(Service.shared.user.token!)"
]
Alamofire.request("\(Service.shared.baseApi)/recipes/\(self.recipe.slug)", method: .delete, headers: headers).responseJSON(completionHandler: {
response in
if response.result.isSuccess {
self.image.isHidden = true
self.performSegue(withIdentifier: "unwindFromAdd", sender: self)
}
})
}))
confirm.addAction(UIAlertAction(title: "Hell no", style: .cancel, handler: { (action: UIAlertAction!) in
// Do nothing
}))
present(confirm, animated: true, completion: nil)
}
@IBAction func back() {
image.isHidden = true
performSegue(withIdentifier: "unwindToRecipes", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier! {
case "recipeGuide":
let recipeGuideController = segue.destination as! RecipeGuideController
recipeGuideController.recipe = self.recipe
default: break
}
}
override func viewDidLoad() {
navigationController?.isNavigationBarHidden = true
recipeTitle.text = recipe.name
recipeDescription.text = recipe.body
image.image = recipe.image
recipeTitle.adjustsFontSizeToFitWidth = true
if recipe.author.username != Service.shared.user.username {
deleteButton.isHidden = true
}
}
}
| 05690c425ee79081f22271fca6cad596 | 33.648649 | 155 | 0.610374 | false | false | false | false |
kingslay/KSSwiftExtension | refs/heads/master | Core/Source/KSDebugStatusBar.swift | mit | 1 | //
// KSDebugStatusBar.swift
// KSSwiftExtension
//
// Created by king on 16/3/29.
// Copyright © 2016年 king. All rights reserved.
//
import UIKit
public class KSDebugStatusBar: UIWindow {
static let shareInstance = KSDebugStatusBar()
public static func post(message: String) {
shareInstance.post(message)
}
var messageQueue = [String]()
var messageLabel: UILabel
private init() {
let statusBarFrame = CGRect(x: 0,y: 0,width: KS.SCREEN_WIDTH,height: 20)
self.messageLabel = UILabel(frame: statusBarFrame)
super.init(frame: statusBarFrame)
self.windowLevel = UIWindowLevelStatusBar + 1
self.backgroundColor = UIColor.clearColor();
self.userInteractionEnabled = false
self.messageLabel.font = UIFont.systemFontOfSize(13)
self.messageLabel.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.messageLabel.alpha = 0
self.messageLabel.textAlignment = .Center;
self.messageLabel.textColor = UIColor.whiteColor()
self.addSubview(self.messageLabel)
var keyWindow = UIApplication.sharedApplication().keyWindow
if keyWindow == nil, let delegate = UIApplication.sharedApplication().delegate {
keyWindow = delegate.window!
}
self.makeKeyAndVisible()
keyWindow?.makeKeyAndVisible()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func post(message: String) {
self.messageQueue.append(message)
if self.messageQueue.count == 1 {
self.showNextMessage()
}
}
private func showNextMessage() {
self.messageLabel.text = self.messageQueue.first
self.messageLabel.alpha = 1
self.hidden = false
let transition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.messageLabel.layer.addAnimation(transition, forKey: nil)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
self.messageQueue.removeFirst()
if self.messageQueue.count == 0 {
self.messageLabel.alpha = 0
self.hidden = true
}else{
self.showNextMessage()
}
}
}
}
| f540c9a3fea35a950d9b7493841b503e | 33.955882 | 110 | 0.637779 | false | false | false | false |
WeltN24/Carlos | refs/heads/master | Tests/CarlosTests/StringConvertibleTests.swift | mit | 1 | import Foundation
import Nimble
import Quick
import Carlos
final class StringConvertibleTests: QuickSpec {
override func spec() {
describe("String values") {
let value = "this is the value"
it("should return self") {
expect(value.toString()) == value
}
}
describe("NSString values") {
let value = "this is the value"
it("should return self") {
expect(value.toString()) == value
}
}
}
}
| 726c0e41979de0235201f75d45b6e099 | 16.846154 | 47 | 0.599138 | false | false | false | false |
cenfoiOS/ImpesaiOSCourse | refs/heads/master | Translate/Translate/Constants.swift | mit | 1 | //
// Constants.swift
// Translate
//
// Created by Cesar Brenes on 6/1/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import Foundation
struct Constants{
static let API_KEY = "NXrPcrRP7ImshGC3WtYKTWhgLT6Hp1ITgE0jsncYik9Kxxjjhm"
static let API_URL = "https://gybra-trans-lator.p.mashape.com/"
static let DIRS_KEY = "dirs"
static let LANGUAGE_KEY = "langs"
static let LANGUAGES_ARRAY_KEY = "LANGUAGES_ARRAY_KEY"
static let GET_LANGUAGES_NOTIFICATION = "GET_LANGUAGES_NOTIFICATION"
static let ERROR_FOUND_NOTIFICATION = "ERROR_FOUND_NOTIFICATION"
static let GET_TRANSLATE_NOTIFICATION = "GET_TRANSLATE_NOTIFICATION"
static let TRANSLATE_RESULT_KEY = "TRANSLATE_RESULT_KEY"
static let TEXT_TRANSLATED_KEY = "text"
static let API_HEADER_KEY = "X-Mashape-Key"
enum LanguageType: Int {
case origin = 0, destination
}
}
| 74bf9dc21489ac927721d2e3756cc09b | 29.3 | 77 | 0.705171 | false | false | false | false |
brandhill/WeatherMap | refs/heads/master | WeatherAroundUs/WeatherAroundUs/DigestWeatherView.swift | apache-2.0 | 3 | //
// DigestWeatherView.swift
// WeatherAroundUs
//
// Created by Wang Yu on 4/24/15.
// Copyright (c) 2015 Kedan Li. All rights reserved.
//
import UIKit
import Spring
import Shimmer
class DigestWeatherView: DesignableView {
@IBOutlet var line: UIImageView!
var parentController: CityDetailViewController!
var tempRange: SpringLabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup(forecastInfos: [[String: AnyObject]]) {
let todayTemp = forecastInfos[0]["temp"] as! [String: AnyObject]
let todayWeather = ((WeatherInfo.citiesAroundDict[WeatherInfo.currentCityID] as! [String : AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject]
let beginY = line.frame.origin.y + line.frame.height
let beginX = line.frame.origin.x
//digest icon
let weatherIcon = SpringImageView(frame: CGRectMake(beginX + line.frame.width / 12, beginY + 8, self.frame.height * 2 / 3, self.frame.height * 2 / 3))
weatherIcon.image = UIImage(named: todayWeather["icon"] as! String)
self.addSubview(weatherIcon)
weatherIcon.animation = "zoomIn"
weatherIcon.animate()
//digest current weather condition
let labelView = UIView(frame: CGRectMake(beginX + line.frame.width / 2, beginY, self.frame.width / 2, self.frame.height))
self.addSubview(labelView)
let shimmerWeatherDescription = FBShimmeringView(frame: CGRectMake(0, 26, line.frame.width / 2, 30))
labelView.addSubview(shimmerWeatherDescription)
let cityDisplay = SpringLabel(frame: CGRectMake(0, 0, line.frame.width / 2, 30))
cityDisplay.text = (WeatherInfo.citiesAroundDict[parentController.cityID] as! [String: AnyObject])["name"]! as? String
cityDisplay.textAlignment = .Left
cityDisplay.font = UIFont(name: "AvenirNext-Medium", size: 18)
cityDisplay.adjustsFontSizeToFitWidth = true
cityDisplay.textColor = UIColor.whiteColor()
shimmerWeatherDescription.addSubview(cityDisplay)
cityDisplay.animation = "fadeIn"
cityDisplay.delay = 0.1
cityDisplay.animate()
shimmerWeatherDescription.contentView = cityDisplay
shimmerWeatherDescription.shimmering = true
//digest tempature range for the day
let shimmerTempRange = FBShimmeringView(frame: CGRectMake(0, self.frame.height / 5 - 5, line.frame.width / 2, self.frame.height / 2))
labelView.addSubview(shimmerTempRange)
tempRange = SpringLabel(frame: CGRectMake(0, 0, line.frame.width / 2, self.frame.height / 2))
let minTemp = todayTemp["min"]!.doubleValue
let maxTemp = todayTemp["max"]!.doubleValue
tempRange.font = UIFont(name: "AvenirNext-Regular", size: 24)
tempRange.adjustsFontSizeToFitWidth = true
tempRange.textAlignment = .Left
tempRange.textColor = UIColor.whiteColor()
let unit = parentController.unit.stringValue
tempRange.text = "\(WeatherMapCalculations.kelvinConvert(minTemp, unit: parentController.unit))° ~ \(WeatherMapCalculations.kelvinConvert(maxTemp, unit: parentController.unit))°\(unit)"
shimmerTempRange.addSubview(tempRange)
tempRange.animation = "fadeIn"
tempRange.delay = 0.2
tempRange.animate()
shimmerTempRange.contentView = tempRange
shimmerTempRange.shimmering = true
//digest the main weather of the day
let mainWeather = SpringLabel(frame: CGRectMake(0, beginY + self.frame.height / 5 + 18 - beginY, line.frame.width / 2 + 10, self.frame.height / 2))
mainWeather.font = UIFont(name: "AvenirNext-Regular", size: 14)
mainWeather.textAlignment = .Left
mainWeather.textColor = UIColor.whiteColor()
mainWeather.text = (todayWeather["description"] as? String)?.capitalizedString
labelView.addSubview(mainWeather)
mainWeather.animation = "fadeIn"
mainWeather.delay = 0.3
mainWeather.animate()
}
func reloadTemperature(forecastInfos: [[String: AnyObject]]) {
let todayTemp = forecastInfos[0]["temp"] as! [String: AnyObject]
let minTemp = todayTemp["min"]!.doubleValue
let maxTemp = todayTemp["max"]!.doubleValue
var unit = parentController.unit.stringValue
tempRange.text = "\(WeatherMapCalculations.kelvinConvert(minTemp, unit: parentController.unit))° ~ \(WeatherMapCalculations.kelvinConvert(maxTemp, unit: parentController.unit))°\(unit)"
setNeedsDisplay()
}
}
| 77f31eef96fb663d6c572d56eb5d78aa | 47.421053 | 193 | 0.681304 | false | false | false | false |
zxpLearnios/MyProject | refs/heads/master | test_projectDemo1/HUD/MyProgressHUD.swift | mit | 1 | //
// MyProgressHUD.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/7/14.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 1. 此弹出框, 可以在任何地方初始化,可以在任何地方使用,包括didFinishLaunching里。但在didFinishLaunching使用第一方式且调用的是showProgressImage方法,则当lanunchImage加载完毕后,虽然进度图片消失了但主窗口仍不能与用户交互,故须在合适的时候主动调用dismiss方法, 调用的是其他展示方法时,没有任何问题,因为它们都会自动消失,但是总共需要2s,之后窗口才可与用户交互。外部无须在主动调用dismiss了;故第一种方式不如第二种好。
// 2. isShow, 控制消失动画完成后才可再次显示,避免不停地显示
// 3. 并行队列同步操作:和主线程同步执行且不会阻塞主线程
// 4. 默认的是第一种方式
// 5. swift已经不远onceToken来创建单例了,直接使用全局let量即可
// 6. 只有展示进度图片即showProgressImage时不会自动消失,其余展示情况全都自动消失. 即showProgressImage后,需要用户自行调用dismiss,并看好使用的是第一还是第二种方式. 外部若无使用show....,则不要调用dismiss,不会出错但是会展示缩放过程了,不好。
// 7. 在展示过程中,window皆不可与用户交互,展示结束后,window才可以与用户交互
import UIKit
class MyProgressHUD: NSObject {
private let view = UIView(), titleLab = UILabel(), imgV = UIImageView(), alertWindow = UIWindow.init(frame: kbounds)
private let width:CGFloat = 100, fontSize:CGFloat = 15, animateTime = 0.25, aniKey = "aniKey_rotation_forImageView"
private var imgWH:CGFloat = 0, ani:CAKeyframeAnimation!
private var isFirstMethod = false // 是否是第一种方式
private var isShow = false // 在 doShowAnimate 和 doDismissAnimate里使用
private var isImgVHidden = false // 用此量来使展示成功的图片文字、失败时的图片文字也自动消失, 在doDismissAnimate里使用
// 当其指向类对象时,并不会添加类对象的引用计数;
// 当其指向的类对象不存在时,ARC会自动把weak reference设置为nil;
// unowned 不会引起对象引用计数的变化, 不会将之置为nil
weak var superView:UIView!
/** 第一种方式. 外部传入view非window,只在当前view中显示谈出框 */
// 重写父类方法
private override init (){
super.init()
}
/** -1. 外部的初始化方法,用于第一种方式 */
convenience init(superView:UIView) {
self.init()
self.superView = superView
doInit()
}
// 用于第一种方式的。
private func doInit(){
// 0.
isFirstMethod = true
// 1.
superView.addSubview(view)
// 这段没用
// let frontToBackWindows = UIApplication.sharedApplication().windows.reverse()
//
// for window in frontToBackWindows {
// if window.windowLevel == UIWindowLevelNormal {
// window.addSubview(view)
// }
// }
view.frame = CGRect(x: UIScreen.main.bounds.width/2 - width/2, y: UIScreen.main.bounds.height/2 - width/2, width: width, height: width)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 10
// 2.
view.addSubview(imgV)
imgWH = width * 4 / 5
imgV.center = CGPoint(x: width/2, y: 10 + imgWH/2)
imgV.bounds = CGRect(x: 0, y: 0, width: imgWH, height: imgWH)
imgV.image = UIImage(named: "progress_circular") // progress_circular 实际上是一个PDF,PDF竟然也可以这样用
// 3.
view.addSubview(titleLab)
titleLab.textAlignment = .center
titleLab.textColor = UIColor.red
titleLab.font = UIFont.systemFont(ofSize: fontSize)
titleLab.numberOfLines = 0
// titleLab.text = "最终加载最终加载最终加载"
// let bestSize = titleLab.sizeThatFits(CGSizeMake(width, width))
// titleLab.frame = CGRectMake(0, imgV.frame.maxY + 10, width, bestSize.height)
//
// // 4.
// var gap:CGFloat = 0
// // 此时需增加view的高度
// if titleLab.frame.maxY > width {
// gap = titleLab.frame.maxY - width
//
// }
// view.height += gap
// 5.
// doShowAnimate(true, isKeyWindowEnable: false)
}
/** 0. 第二种方式. 外部无须传参,此弹出框加在alertWindow上,此弹出框在当前window的所有页面都展示直至弹出框自己消失 */
private static var obj = MyProgressHUD()
class var sharedInstance: MyProgressHUD {
return MyProgressHUD.obj
}
// 用于第二种方式的,外部必须调用此法,然后才可以使用此弹出框
func hudInit() {
// 0.
isFirstMethod = false
// 此时 此window在kwyWindow上,若要kwyWindow不能交互则必须设置kwyWindow不能交互
alertWindow.backgroundColor = UIColor.clear
alertWindow.windowLevel = UIWindowLevelAlert // 最高级别
alertWindow.addSubview(view)
alertWindow.makeKeyAndVisible()
view.frame = CGRect(x: UIScreen.main.bounds.width/2 - width/2, y: UIScreen.main.bounds.height/2 - width/2, width: width, height: width)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 10
// 2.
view.addSubview(imgV)
imgWH = width * 4 / 5
imgV.center = CGPoint(x: width/2, y: imgWH/2)
imgV.bounds = CGRect(x:0, y:0, width:imgWH, height:imgWH)
imgV.image = UIImage(named: "progress_circular")
// 3.
view.addSubview(titleLab)
titleLab.textAlignment = .center
titleLab.textColor = UIColor.red
titleLab.font = UIFont.systemFont(ofSize: fontSize)
titleLab.numberOfLines = 0
}
// ------------------------ 外部调用 ------------------------ //
/**
1. 只展示提示信息, 此时字体变大了、字居view的中间显示、隐藏了图片。展示完后自动消失
*/
func showPromptText(_ text:String) {
// 全局并行队列(同步、异步都在主线程中,前者不会死锁)
let que = DispatchQueue.global()
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = true
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.titleLab.font = UIFont.systemFont(ofSize: self.fontSize + 10)
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: kwidth - 20, height: CGFloat(MAXFLOAT)))
self.view.height = bestSize.height + 20
self.view.width = bestSize.width + 20
self.titleLab.center = CGPoint(x: self.view.width / 2, y: self.view.height / 2)
self.titleLab.bounds = CGRect(x: 0, y: 0, width: bestSize.width, height: bestSize.height)
// self.imgV.setNeedsLayout()
// self.view.setNeedsLayout()
// self.titleLab.setNeedsLayout()
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: true)
}
}
/**
2. 只展示图片, 图片居中、隐藏了titleLab,展示完后不会自动消失
*/
func showProgressImage(_ image:UIImage) {
// 和主线程同步执行且不会阻塞主线程
let que = DispatchQueue(label: "myque1", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.titleLab.isHidden = true
self.imgV.isHidden = false
// 以使其在 外部调用dismiss时, 执行缩小动画doDismissAnimate后, 自动消失
isImgVHidden = true
self.imgV.image = image
self.view.width = self.imgWH + 20
self.view.height = self.imgWH + 20
self.imgV.center = CGPoint(x: self.view.width/2, y: self.view.height/2)
})
if !isShow {
doShowAnimate(true, isKeyWindowEnable: false)
}
}
/**
3。成功时的图片和文字 ,展示完后自动消失
*/
func showSuccessText(_ text:String, successImage image:UIImage) {
// 和主线程同步执行且不会阻塞主线程
let que = DispatchQueue(label: "myque2", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = false
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.imgV.image = image
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: self.width, height: self.width))
self.titleLab.frame = CGRect(x: 0, y: self.imgV.frame.maxY + 10, width: self.width, height: bestSize.height)
var gap:CGFloat = 20 // 确保顶部、底部都有间距 10
// 此时需增加view的高度
if self.titleLab.frame.maxY > self.width {
gap = self.titleLab.frame.maxY - self.width + 10
}
self.view.height += gap
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: false)
}
}
/**
4. 失败时的图片和文字 ,展示完后自动消失
*/
func showFailedText(_ text:String, failedImage image:UIImage) {
let que = DispatchQueue(label: "myque3", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = false
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.imgV.image = image
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: self.width, height: self.width))
self.titleLab.frame = CGRect(x: 0, y: self.imgV.frame.maxY + 10, width: self.width, height: bestSize.height)
var gap:CGFloat = 20 // 确保顶部、底部都有间距 10
// 此时需增加view的高度
if self.titleLab.frame.maxY > self.width {
gap = self.titleLab.frame.maxY - self.width + 10
}
self.view.height += gap
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: false)
}
}
/**
5. 消失 ; isForFirstMethod:用于哪种方式的消失.
* 只有展示进度图片时,外部需要调此法,其余展示情况内部已经处理让其自动消失了
*/
func dismiss(_ isForFirstMethod:Bool = true) {
self.isFirstMethod = isForFirstMethod
self.doDismissAnimate(isKeyWindowEnable: true)
}
// ------------------------ private ------------------------ //
/** 显示动画
- parameter isForTitleLab: 为图片 还是 文字执行动画
- parameter enable: 主窗口是否可与用户交互
*/
private func doShowAnimate(_ isForImageView:Bool, isKeyWindowEnable enable:Bool){
isShow = true
if isFirstMethod {
// 重新添加view
superView.addSubview(view)
// 主窗口不可交互
kwindow?.isUserInteractionEnabled = enable
}else{
// 设置它无用, 也不用设置
// alertWindow.userInteractionEnabled = enable
// 重新显示 alertWindow
self.alertWindow.isHidden = false
// 主窗口不可交互
beforWindow.isUserInteractionEnabled = enable
}
view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
UIView.animate(withDuration: animateTime, animations: {
self.view.transform = CGAffineTransform.identity
}, completion: { (bl) in
if isForImageView { // 只有图片时的情况
// 给图片加旋转动画
if self.ani == nil {
self.ani = CAKeyframeAnimation.init(keyPath: "transform.rotation")
self.ani.duration = 1
// self.ani.rotationMode = kCAAnimationDiscrete // 此属性貌似无用
// self.ani.timingFunctions = [CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)] // 这个有用
// self.ani.calculationMode = kCAAnimationDiscrete
self.ani.values = [0, M_PI * 2]
self.ani.repeatCount = MAXFLOAT
}
self.imgV.layer.add(self.ani, forKey: self.aniKey)
}else{
// 2s后消失(提示label、 成功图片加label、失败图片加label)
let time = DispatchTime.now() + Double(Int64(2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.doDismissAnimate(isKeyWindowEnable: true)
}
}
})
}
/** 消失动画
- parameter isForTitleLab: 为图片 还是 文字执行动画
- parameter enable: 主窗口是否可与用户交互
*/
private func doDismissAnimate(isKeyWindowEnable enable:Bool){
UIView.animate(withDuration: animateTime, animations: {
self.view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
}, completion: { (bl) in
// 移除图片的旋转动画
self.imgV.layer.removeAnimation(forKey: self.aniKey)
if self.isFirstMethod {
// 主窗口可交互
kwindow?.isUserInteractionEnabled = enable
// 移除、主窗口恢复
self.view.removeFromSuperview()
}else{
beforWindow.isUserInteractionEnabled = enable
// 上面此时只显示了提醒文字,故需要2s后自动消失;其他情况,都不消失的
if self.isImgVHidden {
self.alertWindow.isHidden = true
}
}
// 消失动画完成后才可再次显示,避免不停地显示
self.isShow = false
})
}
deinit{
}
}
| e703b87b87ebfa7bcc8ca8086052829c | 32.790816 | 254 | 0.542881 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/TXTReader/Reader/Service/ZSReaderManager.swift | mit | 1 | //
// ZSReaderManager.swift
// zhuishushenqi
//
// Created by yung on 2018/7/9.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
final class ZSReaderManager {
var cachedChapter:[String:QSChapter] = [:]
// 获取下一个页面
func getNextPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
//2.获取当前阅读的章节与页码,这里由于是网络小说,有几种情况
//(1).当前章节信息为空,那么这一章只有一页,翻页直接进入了下一页,章节加一
//(2).当前章节信息不为空,说明已经请求成功了,那么计算当前页码是否为该章节的最后一页
//这是2(2)
if let chapterModel = record.chapterModel {
let page = record.page
if page < chapterModel.pages.count - 1 {
let pageIndex = page + 1
let pageModel = chapterModel.pages[pageIndex]
callback?(pageModel)
} else { // 新的章节
getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
} else {
getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
}
func getLastPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
if let chapterModel = record.chapterModel {
let page = record.page
if page > 0 {
// 当前页存在
let pageIndex = page - 1
let pageModel = chapterModel.pages[pageIndex]
callback?(pageModel)
} else {// 当前章节信息不存在,必然是新的章节
getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
} else {
getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
}
func getNewChapter(chapterOffset:Int,record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
let chapter = record.chapter + chapterOffset
if chapter > 0 && chapter < (chaptersInfo?.count ?? 0) {
if let chapterInfo = chaptersInfo?[chapter] {
let link = chapterInfo.link
// 内存缓存
if let model = cachedChapter[link] {
callback?(model.pages.first)
} else {
callback?(nil)
// viewModel.fetchChapter(key: link, { (body) in
// if let bodyInfo = body {
// if let network = self.cacheChapter(body: bodyInfo, index: chapter) {
// callback?(network.pages.first)
// }
// }
// })
}
}
}
}
}
| c0d9b42f5a8060f73a38c3da4c473e2f | 36.712329 | 129 | 0.550672 | false | false | false | false |
mleiv/MEGameTracker | refs/heads/master | MEGameTracker/Views/Common/Markupable/MarkupLabel.swift | mit | 1 | //
// MarkupLabel.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/17/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
// right now labels won't have clickable links, so stick to text views unless you don't want clicks
final public class MarkupLabel: IBStyledLabel, Markupable {
public override var text: String? {
didSet {
guard !isInsideSetter else { return }
unmarkedText = text
applyMarkup()
}
}
public var useAttributedText: NSAttributedString? {
get { return attributedText }
set {
isInsideSetter = true
attributedText = newValue
// does not apply styles unless explicitly run in main queue,
// which dies because already in main queue.
isInsideSetter = false
}
}
public var unmarkedText: String?
public var isInsideSetter = false
/// I expect this to only be called on main/UI dispatch queue, otherwise bad things will happen.
/// I can't dispatch to main async or layout does not render properly.
public func applyMarkup() {
guard !UIWindow.isInterfaceBuilder else { return }
markup()
}
}
| 5731d94b3571e201c5e71ab1e9dfa6e2 | 24.928571 | 99 | 0.717172 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Rules/Idiomatic/DiscouragedOptionalBooleanRuleExamples.swift | mit | 1 | internal struct DiscouragedOptionalBooleanRuleExamples {
static let nonTriggeringExamples = [
// Global variable
Example("var foo: Bool"),
Example("var foo: [String: Bool]"),
Example("var foo: [Bool]"),
Example("let foo: Bool = true"),
Example("let foo: Bool = false"),
Example("let foo: [String: Bool] = [:]"),
Example("let foo: [Bool] = []"),
// Computed get variable
Example("var foo: Bool { return true }"),
Example("let foo: Bool { return false }()"),
// Free function return
Example("func foo() -> Bool {}"),
Example("func foo() -> [String: Bool] {}"),
Example("func foo() -> ([Bool]) -> String {}"),
// Free function parameter
Example("func foo(input: Bool = true) {}"),
Example("func foo(input: [String: Bool] = [:]) {}"),
Example("func foo(input: [Bool] = []) {}"),
// Method return
wrapExample("class", "func foo() -> Bool {}"),
wrapExample("class", "func foo() -> [String: Bool] {}"),
wrapExample("class", "func foo() -> ([Bool]) -> String {}"),
wrapExample("struct", "func foo() -> Bool {}"),
wrapExample("struct", "func foo() -> [String: Bool] {}"),
wrapExample("struct", "func foo() -> ([Bool]) -> String {}"),
wrapExample("enum", "func foo() -> Bool {}"),
wrapExample("enum", "func foo() -> [String: Bool] {}"),
wrapExample("enum", "func foo() -> ([Bool]) -> String {}"),
// Method parameter
wrapExample("class", "func foo(input: Bool = true) {}"),
wrapExample("class", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("class", "func foo(input: [Bool] = []) {}"),
wrapExample("struct", "func foo(input: Bool = true) {}"),
wrapExample("struct", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("struct", "func foo(input: [Bool] = []) {}"),
wrapExample("enum", "func foo(input: Bool = true) {}"),
wrapExample("enum", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("enum", "func foo(input: [Bool] = []) {}")
]
static let triggeringExamples = [
// Global variable
Example("var foo: ↓Bool?"),
Example("var foo: [String: ↓Bool?]"),
Example("var foo: [↓Bool?]"),
Example("let foo: ↓Bool? = nil"),
Example("let foo: [String: ↓Bool?] = [:]"),
Example("let foo: [↓Bool?] = []"),
Example("let foo = ↓Optional.some(false)"),
Example("let foo = ↓Optional.some(true)"),
// Computed Get Variable
Example("var foo: ↓Bool? { return nil }"),
Example("let foo: ↓Bool? { return nil }()"),
// Free function return
Example("func foo() -> ↓Bool? {}"),
Example("func foo() -> [String: ↓Bool?] {}"),
Example("func foo() -> [↓Bool?] {}"),
Example("static func foo() -> ↓Bool? {}"),
Example("static func foo() -> [String: ↓Bool?] {}"),
Example("static func foo() -> [↓Bool?] {}"),
Example("func foo() -> (↓Bool?) -> String {}"),
Example("func foo() -> ([Int]) -> ↓Bool? {}"),
// Free function parameter
Example("func foo(input: ↓Bool?) {}"),
Example("func foo(input: [String: ↓Bool?]) {}"),
Example("func foo(input: [↓Bool?]) {}"),
Example("static func foo(input: ↓Bool?) {}"),
Example("static func foo(input: [String: ↓Bool?]) {}"),
Example("static func foo(input: [↓Bool?]) {}"),
// Instance variable
wrapExample("class", "var foo: ↓Bool?"),
wrapExample("class", "var foo: [String: ↓Bool?]"),
wrapExample("class", "let foo: ↓Bool? = nil"),
wrapExample("class", "let foo: [String: ↓Bool?] = [:]"),
wrapExample("class", "let foo: [↓Bool?] = []"),
wrapExample("struct", "var foo: ↓Bool?"),
wrapExample("struct", "var foo: [String: ↓Bool?]"),
wrapExample("struct", "let foo: ↓Bool? = nil"),
wrapExample("struct", "let foo: [String: ↓Bool?] = [:]"),
wrapExample("struct", "let foo: [↓Bool?] = []"),
// Instance computed variable
wrapExample("class", "var foo: ↓Bool? { return nil }"),
wrapExample("class", "let foo: ↓Bool? { return nil }()"),
wrapExample("struct", "var foo: ↓Bool? { return nil }"),
wrapExample("struct", "let foo: ↓Bool? { return nil }()"),
wrapExample("enum", "var foo: ↓Bool? { return nil }"),
wrapExample("enum", "let foo: ↓Bool? { return nil }()"),
// Method return
wrapExample("class", "func foo() -> ↓Bool? {}"),
wrapExample("class", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("class", "func foo() -> [↓Bool?] {}"),
wrapExample("class", "static func foo() -> ↓Bool? {}"),
wrapExample("class", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("class", "static func foo() -> [↓Bool?] {}"),
wrapExample("class", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("class", "func foo() -> ([Int]) -> ↓Bool? {}"),
wrapExample("struct", "func foo() -> ↓Bool? {}"),
wrapExample("struct", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("struct", "func foo() -> [↓Bool?] {}"),
wrapExample("struct", "static func foo() -> ↓Bool? {}"),
wrapExample("struct", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("struct", "static func foo() -> [↓Bool?] {}"),
wrapExample("struct", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("struct", "func foo() -> ([Int]) -> ↓Bool? {}"),
wrapExample("enum", "func foo() -> ↓Bool? {}"),
wrapExample("enum", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("enum", "func foo() -> [↓Bool?] {}"),
wrapExample("enum", "static func foo() -> ↓Bool? {}"),
wrapExample("enum", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("enum", "static func foo() -> [↓Bool?] {}"),
wrapExample("enum", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("enum", "func foo() -> ([Int]) -> ↓Bool? {}"),
// Method parameter
wrapExample("class", "func foo(input: ↓Bool?) {}"),
wrapExample("class", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("class", "func foo(input: [↓Bool?]) {}"),
wrapExample("class", "static func foo(input: ↓Bool?) {}"),
wrapExample("class", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("class", "static func foo(input: [↓Bool?]) {}"),
wrapExample("struct", "func foo(input: ↓Bool?) {}"),
wrapExample("struct", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("struct", "func foo(input: [↓Bool?]) {}"),
wrapExample("struct", "static func foo(input: ↓Bool?) {}"),
wrapExample("struct", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("struct", "static func foo(input: [↓Bool?]) {}"),
wrapExample("enum", "func foo(input: ↓Bool?) {}"),
wrapExample("enum", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("enum", "func foo(input: [↓Bool?]) {}"),
wrapExample("enum", "static func foo(input: ↓Bool?) {}"),
wrapExample("enum", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("enum", "static func foo(input: [↓Bool?]) {}"),
// Optional chaining
Example("_ = ↓Bool?.values()")
]
}
// MARK: - Private
private func wrapExample(_ type: String, _ test: String, file: StaticString = #file, line: UInt = #line) -> Example {
return Example("\(type) Foo {\n\t\(test)\n}", file: file, line: line)
}
| da50623c97b4019a31d0e255b97dfc9f | 45.011905 | 117 | 0.513195 | false | false | false | false |
scottsievert/swix | refs/heads/master | swix/swix/swix/matrix/m-operators.swift | mit | 2 | //
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(_ lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
let lhsM = lhs.flat
let rhsM = rhs.flat
var resM:vector = zeros_like(lhsM) // flat vector
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
let lhsM = lhs.flat
var resM:vector = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
let rhsM = rhs.flat
var resM:vector = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOUBLE ASSIGNMENT
func <- (lhs:inout matrix, rhs:Double){
let assign = ones((lhs.shape)) * rhs
lhs = assign
}
// SOLVE
infix operator !/ : Multiplicative
func !/ (lhs: matrix, rhs: vector) -> vector{
return solve(lhs, b: rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == : ComparisonPrecedence
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== : ComparisonPrecedence
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + : Additive
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
// MINUS
infix operator - : Additive
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
// TIMES
infix operator * : Multiplicative
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
// DIVIDE
infix operator / : Multiplicative
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
// LESS THAN
infix operator < : ComparisonPrecedence
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
// GREATER THAN
infix operator > : ComparisonPrecedence
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
// GREATER THAN OR EQUAL
infix operator >= : ComparisonPrecedence
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
// LESS THAN OR EQUAL
infix operator <= : ComparisonPrecedence
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
| a6b3d9cbafefc0d9ef9acee5ab9fd990 | 37.263158 | 74 | 0.627235 | false | false | false | false |
benlangmuir/swift | refs/heads/master | test/SILGen/dynamic_callable_attribute.swift | apache-2.0 | 2 | // RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s
// Check that dynamic calls resolve to the right `dynamicallyCall` method in SIL.
@dynamicCallable
public struct Callable {
func dynamicallyCall(withArguments: [Int]) {}
func dynamicallyCall(withKeywordArguments: KeyValuePairs<String, Int>) {}
}
@_silgen_name("foo")
public func foo(a: Callable) {
// The first two calls should resolve to the `withArguments:` method.
a()
a(1, 2, 3)
// The last call should resolve to the `withKeywordArguments:` method.
a(1, 2, 3, label: 4)
}
// CHECK-LABEL: sil [ossa] @foo
// CHECK: bb0(%0 : $Callable):
// CHECK: [[DYN_CALL_1:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall13withArgumentsySaySiG_tF
// CHECK-NEXT: apply [[DYN_CALL_1]]
// CHECK: [[DYN_CALL_2:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall13withArgumentsySaySiG_tF
// CHECK-NEXT: apply [[DYN_CALL_2]]
// CHECK: [[DYN_CALL_3:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall20withKeywordArgumentsys13KeyValuePairsVySSSiG_tF
@dynamicCallable
public struct Callable2 {
func dynamicallyCall(withKeywordArguments: KeyValuePairs<String, Any>) {}
}
// CHECK-LABEL: sil [ossa] @keywordCoerceBug
// CHECK:[[DYN_CALL:%.*]] = function_ref @$s26dynamic_callable_attribute9Callable2V15dynamicallyCall20withKeywordArgumentsys13KeyValuePairsVySSypG_tF
@_silgen_name("keywordCoerceBug")
public func keywordCoerceBug(a: Callable2, s: Int) {
a(s)
}
@dynamicCallable
struct S {
func dynamicallyCall(withArguments x: [Int]) -> Int! { nil }
}
@dynamicCallable
protocol P1 {
func dynamicallyCall(withKeywordArguments: [String: Any])
}
@dynamicCallable
protocol P2 {
func dynamicallyCall(withArguments x: [Int]) -> Self
}
@dynamicCallable
class C {
func dynamicallyCall(withKeywordArguments x: [String: String]) -> Self { return self }
}
// CHECK-LABEL: sil hidden [ossa] @$s26dynamic_callable_attribute05test_A10_callablesyyAA1SV_AA2P1_pAA2P2_pxtAA1CCRbzlF : $@convention(thin) <T where T : C> (S, @in_guaranteed any P1, @in_guaranteed any P2, @guaranteed T) -> ()
func test_dynamic_callables<T : C>(_ s: S, _ p1: P1, _ p2: P2, _ t: T) {
// SR-12615: Compiler crash on @dynamicCallable IUO.
// CHECK: function_ref @$s26dynamic_callable_attribute1SV15dynamicallyCall13withArgumentsSiSgSaySiG_tF : $@convention(method) (@guaranteed Array<Int>, S) -> Optional<Int>
// CHECK: switch_enum %{{.+}} : $Optional<Int>
let _: Int = s(0)
// CHECK: witness_method $@opened({{.+}} any P1) Self, #P1.dynamicallyCall : <Self where Self : P1> (Self) -> ([String : Any]) -> ()
p1(x: 5)
// CHECK: witness_method $@opened({{.+}} any P2) Self, #P2.dynamicallyCall : <Self where Self : P2> (Self) -> ([Int]) -> Self
_ = p2()
// CHECK: class_method %{{.+}} : $C, #C.dynamicallyCall : (C) -> ([String : String]) -> @dynamic_self C, $@convention(method) (@guaranteed Dictionary<String, String>, @guaranteed C) -> @owned C
// CHECK: unchecked_ref_cast %{{.+}} : $C to $T
_ = t("")
}
| c102125917aec666a43aef3172357949 | 38.205128 | 227 | 0.700458 | false | false | false | false |
knehez/edx-app-ios | refs/heads/master | Source/CourseOutline.swift | apache-2.0 | 2 | //
// CourseOutline.swift
// edX
//
// Created by Akiva Leffert on 4/29/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public typealias CourseBlockID = String
public struct CourseOutline {
public let root : CourseBlockID
public let blocks : [CourseBlockID:CourseBlock]
private let parents : [CourseBlockID:CourseBlockID]
public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) {
self.root = root
self.blocks = blocks
var parents : [CourseBlockID:CourseBlockID] = [:]
for (blockID, block) in blocks {
for child in block.children {
parents[child] = blockID
}
}
self.parents = parents
}
public init?(json : JSON) {
if let root = json["root"].string, blocks = json["blocks+navigation"].dictionaryObject {
var validBlocks : [CourseBlockID:CourseBlock] = [:]
for (blockID, blockBody) in blocks {
let body = JSON(blockBody)
let webURL = NSURL(string: body["web_url"].stringValue)
let children = body["descendants"].arrayObject as? [String] ?? []
let name = body["display_name"].string ?? ""
let blockURL = body["block_url"].string.flatMap { NSURL(string:$0) }
let format = body["format"].string
let type : CourseBlockType
let typeName = body["type"].string ?? ""
let isResponsive = body["responsive_ui"].bool ?? true
let blockCounts : [String:Int] = (body["block_count"].object as? NSDictionary)?.mapValues {
$0 as? Int ?? 0
} ?? [:]
let graded = body["graded"].bool ?? false
if let category = CourseBlock.Category(rawValue: typeName) {
switch category {
case CourseBlock.Category.Course:
type = .Course
case CourseBlock.Category.Chapter:
type = .Chapter
case CourseBlock.Category.Section:
type = .Section
case CourseBlock.Category.Unit:
type = .Unit
case CourseBlock.Category.HTML:
type = .HTML
case CourseBlock.Category.Problem:
type = .Problem
case CourseBlock.Category.Video :
let bodyData = (body["block_json"].object as? NSDictionary).map { ["summary" : $0 ] }
let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, name : name)
type = .Video(summary)
}
}
else {
type = .Unknown(typeName)
}
validBlocks[blockID] = CourseBlock(
type: type,
children: children,
blockID: blockID,
name: name,
blockCounts : blockCounts,
blockURL : blockURL,
webURL: webURL,
format : format,
isResponsive : isResponsive,
graded : graded
)
}
self = CourseOutline(root: root, blocks: validBlocks)
}
else {
return nil
}
}
func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? {
return self.parents[blockID]
}
}
public enum CourseBlockType {
case Unknown(String)
case Course
case Chapter
case Section
case Unit
case Video(OEXVideoSummary)
case Problem
case HTML
public var asVideo : OEXVideoSummary? {
switch self {
case let .Video(summary):
return summary
default:
return nil
}
}
}
public class CourseBlock {
/// Simple list of known block categories strings
public enum Category : String {
case Chapter = "chapter"
case Course = "course"
case HTML = "html"
case Problem = "problem"
case Section = "sequential"
case Unit = "vertical"
case Video = "video"
}
public let type : CourseBlockType
public let blockID : CourseBlockID
/// Children in the navigation hierarchy.
/// Note that this may be different than the block's list of children, server side
/// Since we flatten out the hierarchy for display
public let children : [CourseBlockID]
/// User visible name of the block.
public let name : String
/// TODO: Match final API name
/// The type of graded component
public let format : String?
/// Mapping between block types and number of blocks of that type in this block's
/// descendants (recursively) for example ["video" : 3]
public let blockCounts : [String:Int]
/// Just the block content itself as a web page.
/// Suitable for embedding in a web view.
public let blockURL : NSURL?
/// If this is web content, can we actually display it.
public let isResponsive : Bool
/// A full web page for the block.
/// Suitable for opening in a web browser.
public let webURL : NSURL?
/// Whether or not the block is graded.
/// TODO: Match final API name
public let graded : Bool?
public init(type : CourseBlockType,
children : [CourseBlockID],
blockID : CourseBlockID,
name : String,
blockCounts : [String:Int] = [:],
blockURL : NSURL? = nil,
webURL : NSURL? = nil,
format : String? = nil,
isResponsive : Bool = true,
graded : Bool = false) {
self.type = type
self.children = children
self.name = name
self.blockCounts = blockCounts
self.blockID = blockID
self.blockURL = blockURL
self.webURL = webURL
self.graded = graded
self.format = format
self.isResponsive = isResponsive
}
}
| 72614c65482b30ea9c09f90d8f743eef | 32.408602 | 113 | 0.53653 | false | false | false | false |
ACChe/eidolon | refs/heads/master | Kiosk/App/Networking/RAC+JSONAble.swift | mit | 7 | import Foundation
import Moya
import ReactiveCocoa
extension RACSignal {
/// Get given JSONified data, pass back objects
func mapToObject(classType: JSONAble.Type) -> RACSignal {
func resultFromJSON(object:[String: AnyObject], classType: JSONAble.Type) -> AnyObject {
return classType.fromJSON(object)
}
return tryMap({ (object, error) -> AnyObject! in
if let dict = object as? [String:AnyObject] {
return resultFromJSON(dict, classType: classType)
}
if error != nil {
error.memory = NSError(domain: MoyaErrorDomain, code: MoyaErrorCode.Data.rawValue, userInfo: ["data": object])
}
return nil
})
}
/// Get given JSONified data, pass back objects as an array
func mapToObjectArray(classType: JSONAble.Type) -> RACSignal {
func resultFromJSON(object:[String: AnyObject], classType: JSONAble.Type) -> AnyObject {
return classType.fromJSON(object)
}
return tryMap({ (object, error) -> AnyObject! in
if let dicts = object as? Array<Dictionary<String, AnyObject>> {
let jsonables:[JSONAble] = dicts.map({ return classType.fromJSON($0) })
return jsonables
}
if error != nil {
error.memory = NSError(domain: MoyaErrorDomain, code: MoyaErrorCode.Data.rawValue, userInfo: ["data": object])
}
return nil
})
}
}
| ebade705c9dab5840043c08b27310ee4 | 31.425532 | 126 | 0.591864 | false | false | false | false |
netguru/inbbbox-ios | refs/heads/develop | Unit Tests/PageableProviderSpec.swift | gpl-3.0 | 1 | //
// PageableProviderSpec.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 05/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Nimble
import Quick
import PromiseKit
import Mockingjay
import SwiftyJSON
@testable import Inbbbox
class PageableProviderSpec: QuickSpec {
override func spec() {
var sut: PageableProvider!
beforeEach {
sut = PageableProvider()
}
afterEach {
sut = nil
}
describe("when init with custom initializer") {
beforeEach {
sut = PageableProvider(page: 2, pagination: 10)
}
it("should have properly set page") {
expect(sut.page).to(equal(2))
}
it("should have properly set pagination") {
expect(sut.pagination).to(equal(10))
}
}
describe("when init with default initializer") {
beforeEach {
sut = PageableProvider()
}
it("should have properly set page") {
expect(sut.page).to(equal(1))
}
it("should have properly set pagination") {
expect(sut.pagination).to(equal(30))
}
}
describe("when providing first page with success") {
var result: [ModelMock]?
beforeEach {
self.stub(everything, json([self.fixtureJSON]))
}
afterEach {
result = nil
self.removeAllStubs()
}
it("result should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _result in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
context("then next/previous page with unavailable pageable") {
var error: Error!
afterEach {
error = nil
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.nextPageFor(ModelMock.self)
}.then { _ -> Void in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.previousPageFor(ModelMock.self)
}.then { _ -> Void in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
}
context("then next/previous page with available pageable components") {
beforeEach {
self.removeAllStubs()
self.stub(everything, json([self.fixtureJSON], headers: self.fixtureHeader))
}
it("results from next page should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.nextPageFor(ModelMock.self)
}.then { _result -> Void in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
it("results from next page should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.previousPageFor(ModelMock.self)
}.then { _result -> Void in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
}
}
describe("when providing first page with network error") {
var error: Error!
beforeEach {
let error = NSError(domain: "", code: 0, userInfo: nil)
self.stub(everything, failure(error))
}
afterEach {
error = nil
self.removeAllStubs()
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error).toEventuallyNot(beNil())
}
}
describe("when providing next/previous page without using firstPage method first") {
var error: Error?
afterEach {
error = nil
}
it("error should appear") {
sut.nextPageFor(ModelMock.self).then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
it("error should appear") {
sut.previousPageFor(ModelMock.self).then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
}
}
}
private struct ModelMock: Mappable {
let identifier: String
let title: String?
static var map: (JSON) -> ModelMock {
return { json in
return ModelMock(
identifier: json["identifier"].stringValue,
title: json["title"].stringValue
)
}
}
}
private extension PageableProviderSpec {
var fixtureJSON: [String: AnyObject] {
return [
"identifier" : "fixture.identifier" as AnyObject,
"title" : "fixture.title" as AnyObject
]
}
var fixtureHeader: [String: String] {
return [
"Link" :
"<https://fixture.host/v1/fixture.path?page=1&per_page=100>; rel=\"prev\"," +
"<https://fixture.host/v1/fixture.path?page=3&per_page=100>; rel=\"next\""
]
}
}
private struct QueryMock: Query {
let path = "/fixture/path"
var parameters = Parameters(encoding: .json)
let method = Method.POST
}
| a2c3339ccf8b484392151b9b9f0672b1 | 30.850394 | 122 | 0.436959 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/longest-palindromic-substring.swift | mit | 2 | /**
* Problem Link: https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
class Solution {
func longestPalindrome(_ s: String) -> String {
let list = s.characters.map(){"\($0)"}
var ret = ""
for i in 0..<list.count {
let s1 = findPalindromString(at: i, and: i, for: list)
let s2 = findPalindromString(at: i, and: i+1, for: list)
if s1.characters.count > ret.characters.count {
ret = s1
}
if s2.characters.count > ret.characters.count {
ret = s2
}
}
return ret
}
private func findPalindromString(at left: Int, and right: Int, for s: [String]) -> String {
var l = left
var r = right
var ret = ""
while(l>=0 && r < s.count && s[l] == s[r]) {
if l != r {
ret = s[l] + ret + s[r]
} else {
ret += s[l]
}
l -= 1
r += 1
}
return ret
}
}
/**
* https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
// Date: Tue Jan 19 09:21:21 PST 2021
class Solution {
func longestPalindrome(_ s: String) -> String {
let n = s.count
let s = Array(s)
var dp = Array(repeating: Array(repeating: false, count: n), count: n)
var ret = (0, 0)
for len in 1 ... n {
for start in 0 ... (n - len) {
var end = start + len - 1
if len > 2 {
dp[start][end] = dp[start + 1][end - 1] && (s[start] == s[end])
} else {
dp[start][end] = (s[start] == s[end])
}
if dp[start][end], ret.1 - ret.0 + 1 < len {
ret = (start, end)
}
}
}
return String(s[ret.0 ... ret.1])
}
}/**
* https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
// Date: Tue Jan 19 09:47:54 PST 2021
class Solution {
func longestPalindrome(_ s: String) -> String {
let list = Array(s)
var ret = (0, 0)
for center in 0 ..< list.count {
var left = center
var right = center
while left >= 0, right < list.count, list[left] == list[right] {
left -= 1
right += 1
}
left += 1
right -= 1
if right - left > ret.1 - ret.0 {
ret = (left, right)
}
left = center
right = center + 1
while left >= 0, right < list.count, list[left] == list[right] {
left -= 1
right += 1
}
left += 1
right -= 1
if right - left > ret.1 - ret.0 {
ret = (left, right)
}
}
return String(list[ret.0 ... ret.1])
}
} | 0cb80aec7c84a266b5aa39c6bd910eac | 27.601942 | 95 | 0.424788 | false | false | false | false |
StephenVinouze/ios-charts | refs/heads/master | Advanced/Pods/Charts/Charts/Classes/Renderers/PieChartRenderer.swift | apache-2.0 | 5 | //
// PieChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class PieChartRenderer: ChartDataRendererBase
{
public weak var chart: PieChartView?
public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
public override func drawData(context context: CGContext)
{
guard let chart = chart else { return }
let pieData = chart.data
if (pieData != nil)
{
for set in pieData!.dataSets as! [IPieChartDataSet]
{
if set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
public func calculateMinimumRadiusForSpacedSlice(
center center: CGPoint,
radius: CGFloat,
angle: CGFloat,
arcStartPointX: CGFloat,
arcStartPointY: CGFloat,
startAngle: CGFloat,
sweepAngle: CGFloat) -> CGFloat
{
let angleMiddle = startAngle + sweepAngle / 2.0
// Other point of the arc
let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
// Middle point on the arc
let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
// This is the base of the contained triangle
let basePointsDistance = sqrt(
pow(arcEndPointX - arcStartPointX, 2) +
pow(arcEndPointY - arcStartPointY, 2))
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
let containedTriangleHeight = (basePointsDistance / 2.0 *
tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD))
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) +
pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2))
return spacedRadius
}
public func drawDataSet(context context: CGContext, dataSet: IPieChartDataSet)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else {return }
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var drawAngles = chart.drawAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace
CGContextSaveGState(context)
for j in 0 ..< entryCount
{
let sliceAngle = drawAngles[j]
var innerRadius = userInnerRadius
guard let e = dataSet.entryForIndex(j) else { continue }
// draw only if the value is greater than zero
if ((abs(e.value) > 0.000001))
{
if (!chart.needsHighlight(xIndex: e.xIndex,
dataSetIndex: data.indexOfDataSet(dataSet)))
{
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
arcStartPointX,
arcStartPointY)
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
radius,
startAngleOuter * ChartUtils.Math.FDEG2RAD,
sweepAngleOuter * ChartUtils.Math.FDEG2RAD)
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let sliceSpaceOffset =
calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
}
angle += sliceAngle * phaseX
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
let center = chart.centerCircleBox
// get whole the radius
var r = chart.radius
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var off = r / 10.0 * 3.0
if chart.drawHoleEnabled
{
off = (r - (r * chart.holeRadiusPercent)) / 2.0
}
r -= off; // offset to keep things inside the chart
var dataSets = data.dataSets
let yValueSum = (data as! PieChartData).yValueSum
let drawXVals = chart.isDrawSliceTextEnabled
let usePercentValuesEnabled = chart.usePercentValuesEnabled
var angle: CGFloat = 0.0
var xIndex = 0
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue }
let drawYVals = dataSet.isDrawValuesEnabled
if (!drawYVals && !drawXVals)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
for j in 0 ..< dataSet.entryCount
{
if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil))
{
continue
}
guard let e = dataSet.entryForIndex(j) else { continue }
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceAngle = drawAngles[xIndex]
let sliceSpace = dataSet.sliceSpace
let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * r)
// offset needed to center the drawn text in the slice
let offset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0
angle = angle + offset
// calculate the text position
let x = r
* cos((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD)
+ center.x
var y = r
* sin((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD)
+ center.y
let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value
let val = formatter.stringFromNumber(value)!
let lineHeight = valueFont.lineHeight
y -= lineHeight
// draw everything, depending on settings
if (drawXVals && drawYVals)
{
ChartUtils.drawText(
context: context,
text: val,
point: CGPoint(x: x, y: y),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if (j < data.xValCount && data.xVals[j] != nil)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if (drawXVals)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if (drawYVals)
{
ChartUtils.drawText(
context: context,
text: val,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
xIndex += 1
}
}
}
public override func drawExtras(context context: CGContext)
{
drawHole(context: context)
drawCenterText(context: context)
}
/// draws the hole in the center of the chart and the transparent circle / hole
private func drawHole(context context: CGContext)
{
guard let
chart = chart,
animator = animator
else { return }
if (chart.drawHoleEnabled)
{
CGContextSaveGState(context)
let radius = chart.radius
let holeRadius = radius * chart.holeRadiusPercent
let center = chart.centerCircleBox
if let holeColor = chart.holeColor
{
if holeColor != NSUIColor.clearColor()
{
// draw the hole-circle
CGContextSetFillColorWithColor(context, chart.holeColor!.CGColor)
CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0))
}
}
// only draw the circle if it can be seen (not covered by the hole)
if let transparentCircleColor = chart.transparentCircleColor
{
if transparentCircleColor != NSUIColor.clearColor() &&
chart.transparentCircleRadiusPercent > chart.holeRadiusPercent
{
let alpha = animator.phaseX * animator.phaseY
let secondHoleRadius = radius * chart.transparentCircleRadiusPercent
// make transparent
CGContextSetAlpha(context, alpha);
CGContextSetFillColorWithColor(context, transparentCircleColor.CGColor)
// draw the transparent-circle
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, CGRect(
x: center.x - secondHoleRadius,
y: center.y - secondHoleRadius,
width: secondHoleRadius * 2.0,
height: secondHoleRadius * 2.0))
CGContextAddEllipseInRect(context, CGRect(
x: center.x - holeRadius,
y: center.y - holeRadius,
width: holeRadius * 2.0,
height: holeRadius * 2.0))
CGContextEOFillPath(context)
}
}
CGContextRestoreGState(context)
}
}
/// draws the description text in the center of the pie chart makes most sense when center-hole is enabled
private func drawCenterText(context context: CGContext)
{
guard let
chart = chart,
centerAttributedText = chart.centerAttributedText
else { return }
if chart.drawCenterTextEnabled && centerAttributedText.length > 0
{
let center = chart.centerCircleBox
let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius
let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)
var boundingRect = holeRect
if (chart.centerTextRadiusPercent > 0.0)
{
boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0)
}
let textBounds = centerAttributedText.boundingRectWithSize(boundingRect.size, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
var drawingRect = boundingRect
drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0
drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0
drawingRect.size = textBounds.size
CGContextSaveGState(context)
let clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil)
CGContextBeginPath(context)
CGContextAddPath(context, clippingPath)
CGContextClip(context)
centerAttributedText.drawWithRect(drawingRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
CGContextRestoreGState(context)
}
}
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
CGContextSaveGState(context)
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
for i in 0 ..< indices.count
{
// get the index to highlight
let xIndex = indices[i].xIndex
if (xIndex >= drawAngles.count)
{
continue
}
guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
let entryCount = set.entryCount
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace
let sliceAngle = drawAngles[xIndex]
var innerRadius = userInnerRadius
let shift = set.selectionShift
let highlightedRadius = radius + shift
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let sliceSpaceAngleShifted = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY
var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY
if (sweepAngleShifted < 0.0)
{
sweepAngleShifted = 0.0
}
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD),
center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
highlightedRadius,
startAngleShifted * ChartUtils.Math.FDEG2RAD,
sweepAngleShifted * ChartUtils.Math.FDEG2RAD)
var sliceSpaceRadius: CGFloat = 0.0
if accountForSliceSpacing
{
sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD),
arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD),
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
}
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = sliceSpaceRadius
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
CGContextRestoreGState(context)
}
}
| 54d214ed71e192a0edd4dff08ac690f1 | 38.311707 | 220 | 0.484895 | false | false | false | false |
ip3r/Cart | refs/heads/master | Cart/Checkout/UI/AmountTitle.swift | mit | 1 | //
// AmountTitle.swift
// Cart
//
// Created by Jens Meder on 12.06.17.
// Copyright © 2017 Jens Meder. All rights reserved.
//
import UIKit
internal final class AmountTitle: ViewDelegate {
private let amount: Amount
private let currencies: Currencies
// MARK: Init
internal required init(amount: Amount, currencies: Currencies) {
self.amount = amount
self.currencies = currencies
}
// MARK: ViewDelegate
func viewWillAppear(viewController: UIViewController, animated: Bool) {
let total = amount.value * currencies.current.rate
let code = currencies.current.sign.stringValue
viewController.title = String(format: "%.2f %@", arguments: [total, code])
}
}
| ed1366389989f74645db9e579e80160d | 23.413793 | 76 | 0.699153 | false | false | false | false |
czechboy0/Redbird | refs/heads/main | Sources/Redis/RedisID.swift | mit | 1 | import Foundation
import Vapor
/// A type-safe representation of a String representing individual identifiers of separate Redis connections and configurations.
///
/// It is recommended to define static extensions for your definitions to make it easier at call sites to reference them.
///
/// For example:
/// ```swift
/// extension RedisID { static let oceanic = RedisID("oceanic") }
/// app.redis(.oceanic) // Application.Redis instance
/// ```
public struct RedisID: Hashable,
Codable,
RawRepresentable,
ExpressibleByStringLiteral,
ExpressibleByStringInterpolation,
CustomStringConvertible,
Comparable {
public let rawValue: String
public init(stringLiteral: String) {
self.rawValue = stringLiteral
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ string: String) {
self.rawValue = string
}
public var description: String { rawValue }
public static func < (lhs: RedisID, rhs: RedisID) -> Bool { lhs.rawValue < rhs.rawValue }
public static let `default`: RedisID = "default"
}
extension Application {
/// The default Redis connection.
///
/// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead.
public var redis: Redis {
redis(.default)
}
/// Returns the Redis connection for the given ID.
/// - Parameter id: The Redis ID that identifies the specific connection to be used.
/// - Returns: A Redis connection that is identified by the given `id`.
public func redis(_ id: RedisID) -> Redis {
.init(application: self, redisID: id)
}
}
extension Request {
/// The default Redis connection.
///
/// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead.
public var redis: Redis {
redis(.default)
}
/// Returns the Redis connection for the given ID.
/// - Parameter id: The Redis ID that identifies the specific connection to be used.
/// - Returns: A Redis connection that is identified by the given `id`.
public func redis(_ id: RedisID) -> Redis {
.init(request: self, id: id)
}
}
| 35fe53a3c7df3125b5e075f38d203939 | 31.873239 | 128 | 0.634533 | false | false | false | false |
Sharelink/Bahamut | refs/heads/master | Bahamut/BahamutCommon/AppRateHelper.swift | mit | 1 | //
// AppRateHelper.swift
// snakevsblock
//
// Created by Alex Chow on 2017/7/8.
// Copyright © 2017年 Bahamut. All rights reserved.
//
import Foundation
let AppRateNotification = Notification.Name("AppRateNotification")
let kAppRateNotificationEvent = "kAppRateNotificationEvent"
class AppRateHelper:NSObject {
static let shared:AppRateHelper = {
return AppRateHelper()
}()
private static var appId:String!
private static var nextRateAlertDays:Int = 1
private var lastShowDate:NSNumber{
get{
let date = UserDefaults.standard.double(forKey: "AppRateLastDate")
return NSNumber(value: date)
}
set{
UserDefaults.standard.set(newValue.doubleValue, forKey: "AppRateLastDate")
}
}
private(set) var isUserRated:Bool{
get{
return UserDefaults.standard.bool(forKey: "AppRateHelper_USER_RATED_US")
}
set{
UserDefaults.standard.set(newValue, forKey: "AppRateHelper_USER_RATED_US")
}
}
func configure(appId:String,nextRateAlertDays:Int){
if lastShowDate.doubleValue < 100 {
lastShowDate = NSNumber(value: Date().timeIntervalSince1970)
}
AppRateHelper.nextRateAlertDays = nextRateAlertDays
AppRateHelper.appId = appId
}
private(set) var rateusShown = false
class RateAlertModel {
var title:String!
var message:String!
var actionGoRateTitle:String!
var actionRejectTitle:String!
var actionCancelTitle:String!
var showConfrimRejectRateUs = false
var confirmRejectTitle:String!
var confirmRejectMessage:String!
var actionConfirmRejectGoRate:String!
var actionConfirmRejectNoRate:String!
}
func shouldShowRateAlert() -> Bool {
return !rateusShown && !isUserRated && lastShowDate.int64Value + 24 * 3600 * Int64(AppRateHelper.nextRateAlertDays) < Int64(Date().timeIntervalSince1970)
}
func clearRatedRecord() {
isUserRated = false
}
@discardableResult
func tryShowRateUsAlert(vc:UIViewController,alertModel:RateAlertModel) -> Bool {
if shouldShowRateAlert() {
let like = UIAlertAction(title: alertModel.actionGoRateTitle, style: .default, handler: { (ac) in
self.postEvent(event: "like_it")
self.rateus()
})
let hate = UIAlertAction(title: alertModel.actionRejectTitle, style: .default, handler: { (ac) in
self.postEvent(event: "hate_it")
if alertModel.showConfrimRejectRateUs{
let ok = UIAlertAction(title: alertModel.actionConfirmRejectGoRate, style: .default, handler: { (a) in
self.rateus()
})
let no = UIAlertAction(title: alertModel.actionConfirmRejectNoRate, style: .cancel, handler: { (a) in
})
vc.showAlert(alertModel.confirmRejectTitle, msg: alertModel.confirmRejectMessage, actions: [ok,no])
}
})
let nextTime = UIAlertAction(title: alertModel.actionCancelTitle, style: .cancel, handler: { (ac) in
self.postEvent(event: "next_time")
})
vc.showAlert(alertModel.title, msg: alertModel.message, actions: [like,hate,nextTime])
lastShowDate = NSNumber(value: Date().timeIntervalSince1970)
rateusShown = true
return true
}
return false
}
func rateus() {
let url = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=\(AppRateHelper.appId ?? "")"
let _ = UIApplication.shared.openURL(URL(string: url)!)
UserDefaults.standard.set(true, forKey: "AppRateHelper_USER_RATED_US")
postEvent(event: "go_rate")
}
private func postEvent(event:String) {
NotificationCenter.default.post(name: AppRateNotification, object: AppRateHelper.shared, userInfo: [kAppRateNotificationEvent:event])
}
}
private let eventFirebase = "eventFirebase"
extension AppRateHelper{
func addRateFirebaseEvent() {
NotificationCenter.default.addObserver(self, selector: #selector(AppRateHelper.onFirebaseEvent(a:)), name: AppRateNotification, object: eventFirebase)
}
func removeFirebaseEvent() {
NotificationCenter.default.removeObserver(self, name: AppRateNotification, object: eventFirebase)
}
@objc func onFirebaseEvent(a:Notification) {
if let event = a.userInfo?[kAppRateNotificationEvent] as? String{
AnManager.shared.firebaseEvent(event: event)
}
}
}
| efbc8d618447d70453450b7acdb5c679 | 34.449275 | 161 | 0.62592 | false | false | false | false |
klaus01/Centipede | refs/heads/master | Centipede/Foundation/CE_NSMetadataQuery.swift | mit | 1 | //
// CE_NSMetadataQuery.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import Foundation
extension NSMetadataQuery {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: NSMetadataQuery_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? NSMetadataQuery_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: NSMetadataQuery_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is NSMetadataQuery_Delegate {
return obj as! NSMetadataQuery_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal func getDelegateInstance() -> NSMetadataQuery_Delegate {
return NSMetadataQuery_Delegate()
}
@discardableResult
public func ce_metadataQuery_replacementObjectForResultObject(handle: @escaping (NSMetadataQuery, NSMetadataItem) -> Any) -> Self {
ce._metadataQuery_replacementObjectForResultObject = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_metadataQuery_replacementValueForAttribute(handle: @escaping (NSMetadataQuery, String, Any) -> Any) -> Self {
ce._metadataQuery_replacementValueForAttribute = handle
rebindingDelegate()
return self
}
}
internal class NSMetadataQuery_Delegate: NSObject, NSMetadataQueryDelegate {
var _metadataQuery_replacementObjectForResultObject: ((NSMetadataQuery, NSMetadataItem) -> Any)?
var _metadataQuery_replacementValueForAttribute: ((NSMetadataQuery, String, Any) -> Any)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(metadataQuery(_:replacementObjectForResultObject:)) : _metadataQuery_replacementObjectForResultObject,
#selector(metadataQuery(_:replacementValueForAttribute:value:)) : _metadataQuery_replacementValueForAttribute,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func metadataQuery(_ query: NSMetadataQuery, replacementObjectForResultObject result: NSMetadataItem) -> Any {
return _metadataQuery_replacementObjectForResultObject!(query, result)
}
@objc func metadataQuery(_ query: NSMetadataQuery, replacementValueForAttribute attrName: String, value attrValue: Any) -> Any {
return _metadataQuery_replacementValueForAttribute!(query, attrName, attrValue)
}
}
| d1f78006a709106d61f9596277612caa | 34.809524 | 135 | 0.672207 | false | false | false | false |
abunur/quran-ios | refs/heads/master | Pods/GenericDataSources/Sources/UICollectionView+CollectionView.swift | gpl-3.0 | 3 | //
// UICollectionView+CollectionView.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 4/11/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import Foundation
extension UICollectionView: GeneralCollectionView {
/**
Represents the underlying scroll view. Use this method if you want to get the
`UICollectionView`/`UITableView` itself not a wrapper.
So, if you have for example an instance like the following
```
let generalCollectionView: GeneralCollectionView = <...>
// Not Recommented, can result crashes if there is a CompositeDataSource.
let underlyingTableView = generalCollectionView as! UITableView
// Recommended, safer
let underlyingTableView = generalCollectionView.ds_scrollView as! UITableView
```
The later can result a crash if the scroll view is a UICollectionView not a UITableView.
*/
open var ds_scrollView: UIScrollView { return self }
/**
Just calls the corresponding method `registerNib(nib, forCellWithReuseIdentifier: identifier)`.
*/
open func ds_register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
register(nib, forCellWithReuseIdentifier: identifier)
}
/**
Just calls the corresponding method `registerClass(cellClass, forCellWithReuseIdentifier: identifier)`.
*/
open func ds_register(_ cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) {
register(cellClass, forCellWithReuseIdentifier: identifier)
}
/**
Just calls the corresponding method `reloadData()`.
*/
open func ds_reloadData() {
reloadData()
}
/**
Just calls the corresponding method `performBatchUpdates(updates, completion: completion)`.
*/
open func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) {
internal_performBatchUpdates(updates, completion: completion)
}
/**
Just calls the corresponding method `insertSections(sections)`.
*/
open func ds_insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
insertSections(sections)
}
/**
Just calls the corresponding method `deleteSections(sections)`.
*/
open func ds_deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
deleteSections(sections)
}
/**
Just calls the corresponding method `reloadSections(sections)`.
*/
open func ds_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
reloadSections(sections)
}
/**
Just calls the corresponding method `moveSection(section, toSection: newSection)`.
*/
open func ds_moveSection(_ section: Int, toSection newSection: Int) {
moveSection(section, toSection: newSection)
}
/**
Just calls the corresponding method `insertItemsAtIndexPaths(indexPaths)`.
*/
open func ds_insertItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
insertItems(at: indexPaths)
}
/**
Just calls the corresponding method `deleteItemsAtIndexPaths(indexPaths)`.
*/
open func ds_deleteItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
deleteItems(at: indexPaths)
}
/**
Just calls the corresponding method `reloadItemsAtIndexPaths(indexPaths)`.
*/
open func ds_reloadItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
reloadItems(at: indexPaths)
}
/**
Just calls the corresponding method `moveItemAt(indexPath, toIndexPath: newIndexPath)`.
*/
open func ds_moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) {
moveItem(at: indexPath, to: newIndexPath)
}
/**
Just calls the corresponding method `scrollToItemAt(indexPath, atScrollPosition: scrollPosition, animated: animated)`.
*/
open func ds_scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) {
scrollToItem(at: indexPath, at: scrollPosition, animated: animated)
}
/**
Just calls the corresponding method `selectItemAt(indexPath, animated: animated, scrollPosition: scrollPosition)`.
*/
open func ds_selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) {
selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
/**
Just calls the corresponding method `deselectItemAt(indexPath, animated: animated)`.
*/
open func ds_deselectItem(at indexPath: IndexPath, animated: Bool) {
deselectItem(at: indexPath, animated: animated)
}
/**
Just calls the corresponding method `return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)`.
*/
open func ds_dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableCell {
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
}
/**
Just calls the corresponding method `dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)`.
*/
open func ds_dequeueReusableSupplementaryView(ofKind kind: String, withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableSupplementaryView {
return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
}
/**
Just calls the corresponding method `return indexPathForCell(cell)`.
*/
open func ds_indexPath(for reusableCell: ReusableCell) -> IndexPath? {
let cell: UICollectionViewCell = cast(reusableCell, message: "Cell '\(reusableCell)' should be of type UICollectionViewCell.")
return indexPath(for: cell)
}
/**
Just calls the corresponding method `return indexPathForItemAtPoint(point)`.
*/
open func ds_indexPathForItem(at point: CGPoint) -> IndexPath? {
return indexPathForItem(at: point)
}
/**
Just calls the corresponding method `return numberOfSections()`.
*/
open func ds_numberOfSections() -> Int {
return numberOfSections
}
/**
Just calls the corresponding method `return numberOfItemsInSection(section)`.
*/
open func ds_numberOfItems(inSection section: Int) -> Int {
return numberOfItems(inSection: section)
}
/**
Just calls the corresponding method `return cellForItemAt(indexPath)`.
*/
open func ds_cellForItem(at indexPath: IndexPath) -> ReusableCell? {
return cellForItem(at: indexPath)
}
/**
Just calls the corresponding method `visibleCells()`.
*/
open func ds_visibleCells() -> [ReusableCell] {
let cells = visibleCells
var reusableCells = [ReusableCell]()
for cell in cells {
reusableCells.append(cell)
}
return reusableCells
}
/**
Just calls the corresponding method `return indexPathsForVisibleItems()`.
*/
open func ds_indexPathsForVisibleItems() -> [IndexPath] {
return indexPathsForVisibleItems
}
/**
Just calls the corresponding method `return indexPathsForSelectedItems() ?? []`.
*/
open func ds_indexPathsForSelectedItems() -> [IndexPath] {
return indexPathsForSelectedItems ?? []
}
/**
Always returns the same value passed.
*/
open func ds_localIndexPathForGlobalIndexPath(_ globalIndex: IndexPath) -> IndexPath {
return globalIndex
}
/**
Always returns the same value passed.
*/
open func ds_globalIndexPathForLocalIndexPath(_ localIndex: IndexPath) -> IndexPath {
return localIndex
}
/**
Always returns the same value passed.
*/
open func ds_globalSectionForLocalSection(_ localSection: Int) -> Int {
return localSection
}
}
| 07dc4ac2eb8d005a6578e4d74df4d6dc | 33.431034 | 162 | 0.686655 | false | false | false | false |
North-American-Signs/DKImagePickerController | refs/heads/develop | Sources/DKImagePickerController/View/Cell/DKAssetGroupDetailImageCell.swift | mit | 2 | //
// DKAssetGroupDetailImageCell.swift
// DKImagePickerController
//
// Created by ZhangAo on 07/12/2016.
// Copyright © 2016 ZhangAo. All rights reserved.
//
import UIKit
@objcMembers
public class DKAssetGroupDetailImageCell: DKAssetGroupDetailBaseCell {
public class override func cellReuseIdentifier() -> String {
return "DKImageAssetIdentifier"
}
override init(frame: CGRect) {
super.init(frame: frame)
self.thumbnailImageView.frame = self.bounds
self.thumbnailImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.contentView.addSubview(self.thumbnailImageView)
self.checkView.frame = self.bounds
self.checkView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.checkView.checkImageView.tintColor = nil
self.checkView.checkLabel.font = UIFont.boldSystemFont(ofSize: 14)
self.checkView.checkLabel.textColor = UIColor.white
self.contentView.addSubview(self.checkView)
self.contentView.accessibilityIdentifier = "DKImageAssetAccessibilityIdentifier"
self.contentView.isAccessibilityElement = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open class DKImageCheckView: UIView {
internal lazy var checkImageView: UIImageView = {
let imageView = UIImageView(image: DKImagePickerControllerResource.checkedImage())
return imageView
}()
internal lazy var checkLabel: UILabel = {
let label = UILabel()
label.textAlignment = .right
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.checkImageView)
self.addSubview(self.checkLabel)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func layoutSubviews() {
super.layoutSubviews()
self.checkImageView.frame = self.bounds
self.checkLabel.frame = CGRect(x: 0, y: 5, width: self.bounds.width - 5, height: 20)
}
} /* DKImageCheckView */
override public var thumbnailImage: UIImage? {
didSet {
self.thumbnailImageView.image = self.thumbnailImage
}
}
override public var selectedIndex: Int {
didSet {
self.checkView.checkLabel.text = "\(self.selectedIndex + 1)"
}
}
internal lazy var _thumbnailImageView: UIImageView = {
let thumbnailImageView = UIImageView()
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.clipsToBounds = true
return thumbnailImageView
}()
override public var thumbnailImageView: UIImageView {
get {
return _thumbnailImageView
}
}
public let checkView = DKImageCheckView()
override public var isSelected: Bool {
didSet {
self.checkView.isHidden = !super.isSelected
}
}
} /* DKAssetGroupDetailCell */
| 294b91ddb851bb77fea8c63efc3f8661 | 30.132075 | 96 | 0.619697 | false | false | false | false |
CGLueng/DYTV | refs/heads/master | DYZB/DYZB/Classes/Main/Controller/BasicAnchorViewController.swift | mit | 1 |
//
// BasicAnchorViewController.swift
// DYZB
//
// Created by CGLueng on 2016/12/24.
// Copyright © 2016年 com.ruixing. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) * 0.5
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kheaderH : CGFloat = 50
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class BasicAnchorViewController: UIViewController {
// MARK:- 定义属性
var basicVM : BasicViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
//创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kheaderH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//创建collectionview
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
//宽高随着父控件拉伸而拉伸
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
//注册 cell
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
//注册组头
// collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置 UI
extension BasicAnchorViewController {
func setupUI() {
view.addSubview(collectionView)
}
}
// MARK:- 请求数据
extension BasicAnchorViewController {
func loadData() {
}
}
// MARK:- 遵守 UIcollectionview 的数据源
extension BasicAnchorViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return basicVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return basicVM.anchorGroups[section].anchorArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
//设置数据
cell.anchor = basicVM.anchorGroups[indexPath.section].anchorArr[indexPath.item]
return cell;
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! HomeCollectionHeaderView
headView.group = basicVM.anchorGroups[indexPath.section]
return headView
}
}
// MARK:- 遵守 UIcollectionview 的代理
extension BasicAnchorViewController : UICollectionViewDelegate {
}
| 0bf47197de60719b9d2fc07d07191f48 | 36.953271 | 190 | 0.721005 | false | false | false | false |
xlexi/Textual-Inline-Media | refs/heads/master | Textual Inline Media/Inline Media Handlers/Wikipedia.swift | bsd-3-clause | 1 | /*
Copyright (c) 2015, Alex S. Glomsaas
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
class Wikipedia: NSObject, InlineMediaHandler {
static func name() -> String {
return "Wikipedia"
}
static func icon() -> NSImage? {
return NSImage.fromAssetCatalogue("Wikipedia")
}
required convenience init(url: NSURL, controller: TVCLogController, line: String) {
self.init()
if let query = url.pathComponents?[2] {
let requestString = "format=json&action=query&exsentences=4&prop=extracts|pageimages&titles=\(query)&pithumbsize=200"
.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let subdomain = url.host?.componentsSeparatedByString(".")[0]
guard subdomain != nil else {
return
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["User-Agent": "TextualInlineMedia/1.0 (https://github.com/xlexi/Textual-Inline-Media/; [email protected])"]
let session = NSURLSession(configuration: config)
if let requestUrl = NSURL(string: "https://\(subdomain!).wikipedia.org/w/api.php?\(requestString)") {
session.dataTaskWithURL(requestUrl, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard data != nil else {
return
}
do {
/* Attempt to serialise the JSON results into a dictionary. */
let root = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
guard let query = root["query"] as? Dictionary<String, AnyObject> else {
return
}
guard let pages = query["pages"] as? Dictionary<String, AnyObject> else {
WebRequest(url: response!.URL!, controller: controller, line: line).start()
return
}
let page = pages.first!
if page.0 != "-1" {
guard let article = page.1 as? Dictionary<String, AnyObject> else {
return
}
let title = article["title"] as? String
let description = article["extract"] as? String
var thumbnailUrl = ""
if let thumbnail = article["thumbnail"] as? Dictionary<String, AnyObject> {
guard let source = thumbnail["source"] as? String else {
return
}
thumbnailUrl = source
}
self.performBlockOnMainThread({
let document = controller.webView.mainFrameDocument
/* Create the container for the entire inline media element. */
let wikiContainer = document.createElement("a")
wikiContainer.setAttribute("href", value: url.absoluteString)
wikiContainer.className = "inline_media_wiki"
/* If we found a preview image element, we will add it. */
if thumbnailUrl.characters.count > 0 {
let previewImage = document.createElement("img")
previewImage.className = "inline_media_wiki_thumbnail"
previewImage.setAttribute("src", value: thumbnailUrl)
wikiContainer.appendChild(previewImage)
}
/* Create the container that holds the title and description. */
let infoContainer = document.createElement("div")
infoContainer.className = "inline_media_wiki_info"
wikiContainer.appendChild(infoContainer)
/* Create the title element */
let titleElement = document.createElement("div")
titleElement.className = "inline_media_wiki_title"
titleElement.appendChild(document.createTextNode(title))
infoContainer.appendChild(titleElement)
/* If we found a description, create the description element. */
if description!.characters.count > 0 {
let descriptionElement = document.createElement("div")
descriptionElement.className = "inline_media_wiki_desc"
descriptionElement.innerHTML = description
infoContainer.appendChild(descriptionElement)
}
controller.insertInlineMedia(line, node: wikiContainer, url: url.absoluteString)
})
}
} catch {
return
}
}).resume()
}
}
}
static func matchesServiceSchema(url: NSURL) -> Bool {
if url.host?.hasSuffix(".wikipedia.org") == true && url.pathComponents?.count === 3 {
return url.pathComponents![1] == "wiki"
}
return false
}
}
| 84106b3350e082434d899a1d2423a2f3 | 53.111888 | 151 | 0.519773 | false | false | false | false |
lennet/proNotes | refs/heads/master | app/proNotes/DocumentOverview/RenameDocumentManager.swift | mit | 1 | //
// RenameDocumentManager.swift
// proNotes
//
// Created by Leo Thomas on 19/09/2016.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import UIKit
struct RenameDocumentManager {
var oldURL: URL
var newName: String
weak var viewController: UIViewController?
var completion: ((Bool, URL?) -> ())
var documentManager: DocumentManager {
return DocumentManager.sharedInstance
}
func rename() {
if documentManager.fileNameExistsInObjects(newName) {
showFileExistsAlert(to: viewController)
} else {
moveDocument()
}
}
private func moveDocument() {
let newURL = DocumentManager.sharedInstance.getDocumentURL(newName, uniqueFileName: true)
documentManager.moveObject(fromURL: oldURL, to: newURL, completion: { (success, error) in
if success && error == nil {
self.callCompletion(success: true, url: newURL)
} else {
self.showUnknownErrorMessage()
}
})
}
private func override() {
let newURL = DocumentManager.sharedInstance.getDocumentURL(newName, uniqueFileName: false)
guard let object = documentManager.objectForURL(newURL) else {
showUnknownErrorMessage()
return
}
documentManager.deleteObject(object) { (success, error) in
DispatchQueue.main.async(execute: {
if success && error == nil {
self.moveDocument()
} else {
self.showUnknownErrorMessage()
}
})
}
}
func showFileExistsAlert(to viewController: UIViewController?) {
let alertView = UIAlertController(title: nil, message: NSLocalizedString("ErrorFileAlreadyExists", comment:"error message if a file with the given name already exists & ask for override"), preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: NSLocalizedString("Override", comment:""), style: .destructive, handler: {
(action) -> Void in
self.override()
}))
alertView.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:""), style: .cancel, handler: {
(action) -> Void in
self.callCompletion(success: false, url: nil)
}))
viewController?.present(alertView, animated: true, completion: nil)
}
func showUnknownErrorMessage() {
let alertView = UIAlertController(title: nil, message: NSLocalizedString("ErrorUnknown", comment:""), preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment:""), style: .default, handler: {
(action) -> Void in
self.callCompletion(success: false, url: nil)
}))
viewController?.present(alertView, animated: true, completion: nil)
}
func callCompletion(success: Bool, url: URL?) {
DispatchQueue.main.async(execute: {
self.completion(success, url)
})
}
}
| e961e382e476049b2ba2aa0538e98e77 | 35.127907 | 220 | 0.612488 | false | false | false | false |
stulevine/firefox-ios | refs/heads/master | Storage/SQL/SQLFavicons.swift | mpl-2.0 | 1 | /* 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 UIKit
/**
* The sqlite-backed implementation of the favicons protocol.
*/
public class SQLiteFavicons : Favicons {
let files: FileAccessor
let db: BrowserDB
let table = JoinedFaviconsHistoryTable<(Site, Favicon)>()
lazy public var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
required public init(files: FileAccessor) {
self.files = files
self.db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
public func clear(options: QueryOptions?, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
files.remove("favicons")
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
public func get(options: QueryOptions?, complete: (data: Cursor) -> Void) {
var err: NSError? = nil
let res = db.query(&err) { connection, err in
return self.table.query(connection, options: options)
}
dispatch_async(dispatch_get_main_queue()) {
complete(data: res)
}
}
public func add(icon: Favicon, site: Site, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.insert(&err) { (conn, inout err: NSError?) -> Int in
return self.table.insert(conn, item: (icon: icon, site: site), err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
private let debug_enabled = false
private func debug(msg: String) {
if debug_enabled {
println("FaviconsSqlite: " + msg)
}
}
}
| 9c78c466961c19a92f74c8ba6fee20a1 | 29.26087 | 86 | 0.588602 | false | false | false | false |
mbogh/ProfileKit | refs/heads/master | ProfileKit/Profile.swift | mit | 1 | //
// Profile.swift
// ProfileKit
//
// Created by Morten Bøgh on 25/01/15.
// Copyright (c) 2015 Morten Bøgh. All rights reserved.
//
import Foundation
public enum ProfileStatus {
case Expired
case OK
var description: String {
switch self {
case .Expired: return "Expired"
case .OK: return "OK"
}
}
}
public struct Profile {
public let filePath: String
public let name: String
public let creationDate: NSDate
public let expirationDate: NSDate
public let teamName: String?
public let teamID: String?
public var status: ProfileStatus {
return (expirationDate.compare(NSDate()) != .OrderedDescending) ? .Expired : .OK
}
/// Designated initializer
public init?(filePath path: String, data: NSDictionary) {
filePath = path
if data["Name"] == nil { return nil }
if data["CreationDate"] == nil { return nil }
if data["ExpirationDate"] == nil { return nil }
name = data["Name"] as String
creationDate = data["CreationDate"] as NSDate
expirationDate = data["ExpirationDate"] as NSDate
teamName = data["TeamName"] as? String
teamID = bind(data["TeamIdentifier"]) { teamIdentifiers in (teamIdentifiers as [String]).first }
}
} | 1b7e1baacb70514184046cfb8e148817 | 24.076923 | 104 | 0.629317 | false | false | false | false |
HongliYu/firefox-ios | refs/heads/master | Client/Frontend/Browser/TemporaryDocument.swift | mpl-2.0 | 3 | /* 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 Deferred
import Shared
private let temporaryDocumentOperationQueue = OperationQueue()
class TemporaryDocument: NSObject {
fileprivate let request: URLRequest
fileprivate let filename: String
fileprivate var session: URLSession?
fileprivate var downloadTask: URLSessionDownloadTask?
fileprivate var localFileURL: URL?
fileprivate var pendingResult: Deferred<URL>?
init(preflightResponse: URLResponse, request: URLRequest) {
self.request = request
self.filename = preflightResponse.suggestedFilename ?? "unknown"
super.init()
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: temporaryDocumentOperationQueue)
}
deinit {
// Delete the temp file.
if let url = localFileURL {
try? FileManager.default.removeItem(at: url)
}
}
func getURL() -> Deferred<URL> {
if let url = localFileURL {
let result = Deferred<URL>()
result.fill(url)
return result
}
if let result = pendingResult {
return result
}
let result = Deferred<URL>()
pendingResult = result
downloadTask = session?.downloadTask(with: request)
downloadTask?.resume()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
return result
}
}
extension TemporaryDocument: URLSessionTaskDelegate, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
ensureMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// If we encounter an error downloading the temp file, just return with the
// original remote URL so it can still be shared as a web URL.
if error != nil, let remoteURL = request.url {
pendingResult?.fill(remoteURL)
pendingResult = nil
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempDocs")
let url = tempDirectory.appendingPathComponent(filename)
try? FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)
try? FileManager.default.removeItem(at: url)
do {
try FileManager.default.moveItem(at: location, to: url)
localFileURL = url
pendingResult?.fill(url)
pendingResult = nil
} catch {
// If we encounter an error downloading the temp file, just return with the
// original remote URL so it can still be shared as a web URL.
if let remoteURL = request.url {
pendingResult?.fill(remoteURL)
pendingResult = nil
}
}
}
}
| 76fdaaa84680d720e3282e98bf2bf9c5 | 32.8 | 122 | 0.657428 | false | false | false | false |
Baza207/Alamofire | refs/heads/Doharmony | Alamofire/Tests/ServerTrustPolicyTests.swift | apache-2.0 | 15 | // MultipartFormDataTests.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
private struct TestCertificates {
// Root Certificates
static let RootCA = TestCertificates.certificateWithFileName("alamofire-root-ca")
// Intermediate Certificates
static let IntermediateCA1 = TestCertificates.certificateWithFileName("alamofire-signing-ca1")
static let IntermediateCA2 = TestCertificates.certificateWithFileName("alamofire-signing-ca2")
// Leaf Certificates - Signed by CA1
static let LeafWildcard = TestCertificates.certificateWithFileName("wildcard.alamofire.org")
static let LeafMultipleDNSNames = TestCertificates.certificateWithFileName("multiple-dns-names")
static let LeafSignedByCA1 = TestCertificates.certificateWithFileName("signed-by-ca1")
static let LeafDNSNameAndURI = TestCertificates.certificateWithFileName("test.alamofire.org")
// Leaf Certificates - Signed by CA2
static let LeafExpired = TestCertificates.certificateWithFileName("expired")
static let LeafMissingDNSNameAndURI = TestCertificates.certificateWithFileName("missing-dns-name-and-uri")
static let LeafSignedByCA2 = TestCertificates.certificateWithFileName("signed-by-ca2")
static let LeafValidDNSName = TestCertificates.certificateWithFileName("valid-dns-name")
static let LeafValidURI = TestCertificates.certificateWithFileName("valid-uri")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data)!
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
// Root Public Keys
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
// Intermediate Public Keys
static let IntermediateCA1 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA1)
static let IntermediateCA2 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA2)
// Leaf Public Keys - Signed by CA1
static let LeafWildcard = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafWildcard)
static let LeafMultipleDNSNames = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafMultipleDNSNames)
static let LeafSignedByCA1 = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafSignedByCA1)
static let LeafDNSNameAndURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafDNSNameAndURI)
// Leaf Public Keys - Signed by CA2
static let LeafExpired = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafExpired)
static let LeafMissingDNSNameAndURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafMissingDNSNameAndURI)
static let LeafSignedByCA2 = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafSignedByCA2)
static let LeafValidDNSName = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafValidDNSName)
static let LeafValidURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafValidURI)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
SecTrustCreateWithCertificates(certificate, policy, &trust)
let publicKey = SecTrustCopyPublicKey(trust!)!
return publicKey
}
}
// MARK: -
private enum TestTrusts {
// Leaf Trusts - Signed by CA1
case LeafWildcard
case LeafMultipleDNSNames
case LeafSignedByCA1
case LeafDNSNameAndURI
// Leaf Trusts - Signed by CA2
case LeafExpired
case LeafMissingDNSNameAndURI
case LeafSignedByCA2
case LeafValidDNSName
case LeafValidURI
// Invalid Trusts
case LeafValidDNSNameMissingIntermediate
case LeafValidDNSNameWithIncorrectIntermediate
var trust: SecTrust {
let trust: SecTrust
switch self {
case .LeafWildcard:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafWildcard,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafMultipleDNSNames:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafMultipleDNSNames,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafSignedByCA1:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafSignedByCA1,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafDNSNameAndURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafExpired:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafExpired,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafMissingDNSNameAndURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafMissingDNSNameAndURI,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafSignedByCA2:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafSignedByCA2,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafValidDNSName:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafValidURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidURI,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case LeafValidDNSNameMissingIntermediate:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.RootCA
])
case LeafValidDNSNameWithIncorrectIntermediate:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
}
return trust
}
static func trustWithCertificates(certificates: [SecCertificate]) -> SecTrust {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
SecTrustCreateWithCertificates(certificates, policy, &trust)
return trust!
}
}
// MARK: - Basic X509 and SSL Exploration Tests -
class ServerTrustPolicyTestCase: BaseTestCase {
func setRootCertificateAsLoneAnchorCertificateForTrust(trust: SecTrust) {
SecTrustSetAnchorCertificates(trust, [TestCertificates.RootCA])
SecTrustSetAnchorCertificatesOnly(trust, true)
}
func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
isValid = result == unspecified || result == proceed
}
return isValid
}
}
// MARK: -
class ServerTrustPolicyExplorationBasicX509PolicyValidationTestCase: ServerTrustPolicyTestCase {
func testThatAnchoredRootCertificatePassesBasicX509ValidationWithRootInTrust() {
// Given
let trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatAnchoredRootCertificatePassesBasicX509ValidationWithoutRootInTrust() {
// Given
let trust = TestTrusts.LeafDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatCertificateMissingDNSNamePassesBasicX509Validation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatExpiredCertificateFailsBasicX509Validation() {
// Given
let trust = TestTrusts.LeafExpired.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
}
// MARK: -
class ServerTrustPolicyExplorationSSLPolicyValidationTestCase: ServerTrustPolicyTestCase {
func testThatAnchoredRootCertificatePassesSSLValidationWithRootInTrust() {
// Given
let trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatAnchoredRootCertificatePassesSSLValidationWithoutRootInTrust() {
// Given
let trust = TestTrusts.LeafDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatCertificateMissingDNSNameFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
func testThatWildcardCertificatePassesSSLValidation() {
// Given
let trust = TestTrusts.LeafWildcard.trust // *.alamofire.org
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatDNSNameCertificatePassesSSLValidation() {
// Given
let trust = TestTrusts.LeafValidDNSName.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatURICertificateFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafValidURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
func testThatMultipleDNSNamesCertificatePassesSSLValidationForAllEntries() {
// Given
let trust = TestTrusts.LeafMultipleDNSNames.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [
SecPolicyCreateSSL(true, "test.alamofire.org"),
SecPolicyCreateSSL(true, "blog.alamofire.org"),
SecPolicyCreateSSL(true, "www.alamofire.org")
]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should not be valid")
}
func testThatPassingNilForHostParameterAllowsCertificateMissingDNSNameToPassSSLValidation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, nil)]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should not be valid")
}
func testThatExpiredCertificateFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafExpired.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
}
// MARK: - Server Trust Policy Tests -
class ServerTrustPolicyPerformDefaultEvaluationTestCase: ServerTrustPolicyTestCase {
// MARK: Do NOT Validate Host
func testThatValidCertificateChainPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatNonAnchoredRootCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2
])
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingDNSNameLeafCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafMissingDNSNameAndURI.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingIntermediateCertificateInChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Validate Host
func testThatValidCertificateChainPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatNonAnchoredRootCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2
])
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingDNSNameLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafMissingDNSNameAndURI.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatWildcardedLeafCertificateChainPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafWildcard.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingIntermediateCertificateInChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyPinCertificatesTestCase: ServerTrustPolicyTestCase {
// MARK: Validate Certificate Chain Without Validating Host
func testThatPinnedLeafCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Validate Certificate Chain and Host
func testThatPinnedLeafCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Do NOT Validate Certificate Chain or Host
func testThatPinnedLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningMultipleCertificatesWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [
TestCertificates.LeafMultipleDNSNames, // not in certificate chain
TestCertificates.LeafSignedByCA1, // not in certificate chain
TestCertificates.LeafExpired, // in certificate chain 👍🏼👍🏼
TestCertificates.LeafWildcard, // not in certificate chain
TestCertificates.LeafDNSNameAndURI, // not in certificate chain
]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyPinPublicKeysTestCase: ServerTrustPolicyTestCase {
// MARK: Validate Certificate Chain Without Validating Host
func testThatPinningLeafKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningKeyNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningBackupKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA1, TestPublicKeys.IntermediateCA1, TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
// MARK: Validate Certificate Chain and Host
func testThatPinningLeafKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningKeyNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningBackupKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA1, TestPublicKeys.IntermediateCA1, TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
// MARK: Do NOT Validate Certificate Chain or Host
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithMissingIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyWithoutCertificateChainValidationFailsEvaluationWithMissingIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithIncorrectIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameWithIncorrectIntermediate.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyDisableEvaluationTestCase: ServerTrustPolicyTestCase {
func testThatCertificateChainMissingIntermediateCertificatePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.DisableEvaluation
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredLeafCertificatePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.DisableEvaluation
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyCustomEvaluationTestCase: ServerTrustPolicyTestCase {
func testThatReturningTrueFromClosurePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.CustomEvaluation { _, _ in
return true
}
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatReturningFalseFromClosurePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.CustomEvaluation { _, _ in
return false
}
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyCertificatesInBundleTestCase: ServerTrustPolicyTestCase {
func testOnlyValidCertificatesAreDetected() {
// Given
// Files present in bundle in the form of type+encoding+extension [key|cert][DER|PEM].[cer|crt|der|key|pem]
// certDER.cer: DER-encoded well-formed certificate
// certDER.crt: DER-encoded well-formed certificate
// certDER.der: DER-encoded well-formed certificate
// certPEM.*: PEM-encoded well-formed certificates, expected to fail: Apple API only handles DER encoding
// devURandomGibberish.crt: Random data, should fail
// keyDER.der: DER-encoded key, not a certificate, should fail
// When
let certificates = ServerTrustPolicy.certificatesInBundle(
NSBundle(forClass: ServerTrustPolicyCertificatesInBundleTestCase.self)
)
// Then
// Expectation: 18 well-formed certificates in the test bundle plus 4 invalid certificates.
#if os(OSX)
// For some reason, OSX is allowing all certificates to be considered valid. Need to file a
// rdar demonstrating this behavior.
XCTAssertEqual(certificates.count, 22, "Expected 22 well-formed certificates")
#else
XCTAssertEqual(certificates.count, 18, "Expected 18 well-formed certificates")
#endif
}
}
| b9992b2415e2f7f7870410bed56f5c95 | 37.684767 | 126 | 0.702142 | false | true | false | false |
Killectro/RxGrailed | refs/heads/master | RxGrailed/RxGrailed/ViewModels/ListingViewModel.swift | mit | 1 | //
// ListingViewModel.swift
// RxGrailed
//
// Created by DJ Mitchell on 2/25/17.
// Copyright © 2017 Killectro. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Kingfisher
/// Defines the basic information necessary to display a listing
protocol ListingDisplayable {
var image: Driver<UIImage?> { get }
var price: String { get }
var designer: String { get }
var title: String { get }
var description: String { get }
var size: String { get }
var titleAndSize: String { get }
var sellerName: String { get }
}
final class ListingViewModel: ListingDisplayable {
// MARK: Public properties
let image: Driver<UIImage?>
let price: String
let designer: String
let title: String
let description: String
let size: String
let titleAndSize: String
let sellerName: String
// MARK: Private properties
private let listing: Listing
// MARK: Initialization
init(listing: Listing) {
self.listing = listing
image = KingfisherManager.shared.rx
.image(URL: listing.imageUrl, optionsInfo: [.backgroundDecode])
.retry(3)
.map(Optional.some)
// When an image fetch is cancelled it returns an error, but we don't want to
// bind that error to our UI so we catch it here and just return `nil`
.asDriver(onErrorJustReturn: nil)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 0
// Force unwrap here is safe because we have an integer, which
// can always be turned into a currency value
price = formatter.string(from: listing.price as NSNumber)!
designer = listing.designer.uppercased()
title = listing.title
description = listing.description
size = listing.size.uppercased()
titleAndSize = title + " size " + size
sellerName = listing.sellerName.uppercased()
}
}
| aa5d39b5e6bd49a9842a5f83dc7ec6d8 | 26.958333 | 89 | 0.653254 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Interpreter/imported_objc_generics.swift | apache-2.0 | 35 | // RUN: %empty-directory(%t)
//
// RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import StdlibUnittest
import ObjCClasses
var ImportedObjCGenerics = TestSuite("ImportedObjCGenerics")
ImportedObjCGenerics.test("Creation") {
let cs = Container<NSString>(object: "i-just-met-you")
expectEqual("i-just-met-you", cs.object)
expectTrue(type(of: cs) === Container<NSString>.self)
expectTrue(type(of: cs) === Container<AnyObject>.self)
}
ImportedObjCGenerics.test("Blocks") {
let cs = Container<NSString>(object: "and-this-is-crazy")
var fromBlock: NSString = ""
cs.processObject { fromBlock = $0 }
expectEqual("and-this-is-crazy", fromBlock)
cs.updateObject { "but-heres-my-number" }
expectEqual("but-heres-my-number", cs.object)
}
ImportedObjCGenerics.test("Categories") {
let cs = Container<NSString>(cat1: "so-call-me-maybe")
expectEqual("so-call-me-maybe", cs.getCat1())
cs.setCat1("its-hard-to-look-right")
expectEqual("its-hard-to-look-right", cs.cat1Property)
}
ImportedObjCGenerics.test("Subclasses") {
let subContainer = SubContainer<NSString>(object: "at-you-baby")
expectEqual("at-you-baby", subContainer.object)
let nestedContainer = NestedContainer<NSString>(object: Container(object: "but-heres-my-number"))
expectEqual("but-heres-my-number", nestedContainer.object.object)
let stringContainer = StringContainer(object: "so-call-me-maybe")
expectEqual("so-call-me-maybe", stringContainer.object)
}
ImportedObjCGenerics.test("SwiftGenerics") {
func openContainer<T: AnyObject>(_ x: Container<T>) -> T {
return x.object
}
func openStringContainer<T: Container<NSString>>(_ x: T) -> NSString {
return x.object
}
func openArbitraryContainer<S: AnyObject, T: Container<S>>(_ x: T) -> S {
return x.object
}
let scs = SubContainer<NSString>(object: "before-you-came-into-my-life")
expectEqual("before-you-came-into-my-life", openContainer(scs))
expectEqual("before-you-came-into-my-life", openStringContainer(scs))
expectEqual("before-you-came-into-my-life", openArbitraryContainer(scs))
let cs = Container<NSString>(object: "i-missed-you-so-bad")
expectEqual("i-missed-you-so-bad", openContainer(cs))
expectEqual("i-missed-you-so-bad", openStringContainer(cs))
expectEqual("i-missed-you-so-bad", openArbitraryContainer(cs))
let strContainer = SubContainer<NSString>(object: "i-missed-you-so-so-bad")
expectEqual("i-missed-you-so-so-bad", openContainer(strContainer))
expectEqual("i-missed-you-so-so-bad", openStringContainer(strContainer))
expectEqual("i-missed-you-so-so-bad", openArbitraryContainer(strContainer))
let numContainer = Container<NSNumber>(object: NSNumber(value: 21))
expectEqual(NSNumber(value: 21), openContainer(numContainer))
expectEqual(NSNumber(value: 21), openArbitraryContainer(numContainer))
let subNumContainer = SubContainer<NSNumber>(object: NSNumber(value: 22))
expectEqual(NSNumber(value: 22), openContainer(subNumContainer))
expectEqual(NSNumber(value: 22), openArbitraryContainer(subNumContainer))
}
ImportedObjCGenerics.test("SwiftGenerics/Creation") {
func makeContainer<T: AnyObject>(_ x: T) -> Container<T> {
return Container(object: x)
}
let c = makeContainer(NSNumber(value: 22))
expectEqual(NSNumber(value: 22), c.object)
}
ImportedObjCGenerics.test("ProtocolConstraints") {
func copyContainerContents<T: NSCopying>(_ x: CopyingContainer<T>) -> T {
return x.object.copy(with: nil) as! T
}
let cs = CopyingContainer<NSString>(object: "Happy 2012")
expectEqual("Happy 2012", copyContainerContents(cs))
}
ImportedObjCGenerics.test("ClassConstraints") {
func makeContainedAnimalMakeNoise<T>(x: AnimalContainer<T>) -> NSString {
return x.object.noise as NSString
}
let petCarrier = AnimalContainer(object: Dog())
expectEqual("woof", makeContainedAnimalMakeNoise(x: petCarrier))
}
@objc @objcMembers class ClassWithMethodsUsingObjCGenerics: NSObject {
func copyContainer(_ x: CopyingContainer<NSString>) -> CopyingContainer<NSString> {
return x
}
func maybeCopyContainer(_ x: CopyingContainer<NSString>) -> CopyingContainer<NSString>? {
return x
}
}
ImportedObjCGenerics.test("ClassWithMethodsUsingObjCGenerics") {
let x: AnyObject = ClassWithMethodsUsingObjCGenerics()
let y = CopyingContainer<NSString>(object: "")
let z = x.copyContainer(y)
expectTrue(y === z)
let w = x.perform(#selector(ClassWithMethodsUsingObjCGenerics.copyContainer), with: y).takeUnretainedValue()
expectTrue(y === w)
let zq = x.maybeCopyContainer(y)
expectTrue(y === zq!)
let wq = x.perform(#selector(ClassWithMethodsUsingObjCGenerics.maybeCopyContainer), with: y).takeUnretainedValue()
expectTrue(y === wq)
}
ImportedObjCGenerics.test("InheritanceFromNongeneric") {
// Test NSObject methods inherited into Container<>
let gc = Container<NSString>(object: "")
expectTrue(gc.description.range(of: "Container") != nil)
expectTrue(type(of: gc).superclass() == NSObject.self)
expectTrue(Container<NSString>.superclass() == NSObject.self)
expectTrue(Container<NSObject>.superclass() == NSObject.self)
expectTrue(Container<NSObject>.self == Container<NSString>.self)
}
public class InheritInSwift: Container<NSString> {
public override init(object: NSString) {
super.init(object: object.lowercased as NSString)
}
public override var object: NSString {
get {
return super.object.uppercased as NSString
}
set {
super.object = newValue.lowercased as NSString
}
}
public var superObject: NSString {
get {
return super.object as NSString
}
}
}
ImportedObjCGenerics.test("InheritInSwift") {
let s = InheritInSwift(object: "HEllo")
let sup: Container = s
expectEqual(s.superObject, "hello")
expectEqual(s.object, "HELLO")
expectEqual(sup.object, "HELLO")
s.object = "GOodbye"
expectEqual(s.superObject, "goodbye")
expectEqual(s.object, "GOODBYE")
expectEqual(sup.object, "GOODBYE")
s.processObject { o in
expectEqual(o, "GOODBYE")
}
s.updateObject { "Aloha" }
expectEqual(s.superObject, "aloha")
expectEqual(s.object, "ALOHA")
expectEqual(sup.object, "ALOHA")
}
ImportedObjCGenerics.test("BridgedInitializer") {
let strings: [NSString] = ["hello", "world"]
let s = BridgedInitializer(array: strings)
expectEqual(s.count, 2)
}
runAllTests()
| 62ed5387387f23aa7c0b87ce70fac061 | 32.614213 | 116 | 0.728179 | false | true | false | false |
Ezimetzhan/XMLParser | refs/heads/master | XMLParser/XMLParser.swift | mit | 4 | //
// XMLParser.swift
// XMLParser
//
// Created by Eugene Mozharovsky on 8/29/15.
// Copyright © 2015 DotMyWay LCC. All rights reserved.
//
import Foundation
/// A parser class supposed to provide features for (de)coding
/// data into XML and vice versa.
/// The class provides a singleton.
public class XMLParser: XMLCoder, XMLDecoder {
/// A singleton accessor.
public static let sharedParser = XMLParser()
// MARK: - XMLCoder & XMLDecoder
/// Encodes a dictionary into an XML string.
/// - parameter data: A generic dictionary. Generally, the **Key** should be hashable and
/// in most of cases it must be a **String**. The value
/// might vary.
/// - parameter header: A header for the XML string.
/// - returns: A converted XML string.
public func encode<Key : Hashable, Value>(data: Dictionary<Key, Value>, header: String = "") -> String {
guard let tries = data.generateTries() else {
return ""
}
return header + tries.map { $0.parsedRequestBody() }.reduce("", combine: +)
}
/// Decodes the given input into the specified output.
/// - parameter data: An input data, *String* type.
/// - returns: An array of string values.
public func decode(data: String) -> Dictionary<String, [String]> {
return findTags(data)
}
// MARK: - Initialization
/// A private initializer for singleton implementation.
private init() { }
// MARK: - Utils
/// Finds XML tags in a given string (supposed to be previously parsed into XML format).
/// - parameter body: A given XML parsed string.
/// - returns: A dictionary with arrays of values.
private func findTags(body: String) -> [String : [String]] {
var keys: [String] = []
var write = false
var char = ""
var value = ""
var values: [String : [String]] = [:]
for ch in body.characters {
if ch == "<" {
write = true
} else if ch == ">" {
write = false
}
if ch == "\n" {
continue
}
if write {
if let last = keys.last where value != "" {
if let _ = values[last.original()] {
values[last.original()]! += [value]
} else {
values[last.original()] = []
values[last.original()]! += [value]
}
value = ""
}
char += String(ch)
} else {
if char != "" {
char += String(ch)
keys += [char]
char = ""
} else if let last = keys.last where last == last.original().startHeader() {
if ch == " " && (value.characters.last == " " || value.characters.last == "\n" || value.characters.count == 0) {
continue
}
value += String(ch)
}
}
}
return values
}
}
| a096474ae5d806c09acc3e24d8e54f11 | 31.66 | 133 | 0.482854 | false | false | false | false |
Sorix/CloudCore | refs/heads/master | Source/Classes/Setup Operation/UploadAllLocalDataOperation.swift | mit | 1 | //
// UploadAllLocalDataOperation.swift
// CloudCore
//
// Created by Vasily Ulianov on 12/12/2017.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
import CoreData
class UploadAllLocalDataOperation: Operation {
let managedObjectModel: NSManagedObjectModel
let parentContext: NSManagedObjectContext
var errorBlock: ErrorBlock? {
didSet {
converter.errorBlock = errorBlock
cloudSaveOperationQueue.errorBlock = errorBlock
}
}
private let converter = ObjectToRecordConverter()
private let cloudSaveOperationQueue = CloudSaveOperationQueue()
init(parentContext: NSManagedObjectContext, managedObjectModel: NSManagedObjectModel) {
self.parentContext = parentContext
self.managedObjectModel = managedObjectModel
}
override func main() {
super.main()
CloudCore.delegate?.willSyncToCloud()
defer {
CloudCore.delegate?.didSyncToCloud()
}
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
var allManagedObjects = Set<NSManagedObject>()
for entity in managedObjectModel.cloudCoreEnabledEntities {
guard let entityName = entity.name else { continue }
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
guard let fetchedObjects = try childContext.fetch(fetchRequest) as? [NSManagedObject] else {
continue
}
allManagedObjects.formUnion(fetchedObjects)
} catch {
errorBlock?(error)
}
}
converter.setUnconfirmedOperations(inserted: allManagedObjects, updated: Set<NSManagedObject>(), deleted: Set<NSManagedObject>())
let recordsToSave = converter.confirmConvertOperationsAndWait(in: childContext).recordsToSave
cloudSaveOperationQueue.addOperations(recordsToSave: recordsToSave, recordIDsToDelete: [RecordIDWithDatabase]())
cloudSaveOperationQueue.waitUntilAllOperationsAreFinished()
do {
try childContext.save()
} catch {
errorBlock?(error)
}
}
override func cancel() {
cloudSaveOperationQueue.cancelAllOperations()
super.cancel()
}
}
| f22755fd16b8ae3f51afecdd56c9d48d | 26.415584 | 131 | 0.766461 | false | false | false | false |
tassiahmed/SplitScreen | refs/heads/master | OSX/SplitScreen/MouseDragEventHandling.swift | apache-2.0 | 1 | //
// MouseDragEventHandling.swift
// SplitScreen
//
// Created by Evan Thompson on 10/13/15.
// Copyright © 2015 SplitScreen. All rights reserved.
//
import Foundation
import AppKit
import Carbon
private var current_window_position: CGPoint?
private var new_window_position: CGPoint?
private var drawing: Bool = false
private var mouse_seen: Bool = false
private var mouse_up_pos: NSPoint?
private var callback_seen: Bool = false
private var callback_executed: Bool = false
/**
Returns the current top application by pid
- Returns: The pid that is the top application
*/
func get_focused_pid() -> pid_t {
let info = NSWorkspace.shared.frontmostApplication
// If the focused app is `SplitScreen` return a `pid` of 0
if(info == NSRunningApplication()) {
return pid_t(0)
}
return (info?.processIdentifier)!
}
/**
Compares the coordinates of `current_window_position` with the coordinates of `new_position`
- Parameter new_position: The `CGPoint` whose coordinates to compare w/ those of `current_window_position`
- Returns: `true` or `false` depending on whether `current_window_position` and `new_position` have the same coordinates
*/
func comparePosition() -> Bool {
return (current_window_position!.x == new_window_position!.x && current_window_position!.y == new_window_position!.y)
}
/**
Moves and Resizes the current window depending on the location of where the mouse up location was
*/
func move_and_resize() {
let loc: (CGFloat, CGFloat) = (mouse_up_pos!.x, mouse_up_pos!.y)
if layout.is_hardpoint(loc.0, y: loc.1) {
let resize = layout.get_snap_dimensions(loc.0, y: loc.1)
print(" ++ \(resize)")
if resize.0 == -1 || resize.1 == -1 || resize.2 == -1 || resize.3 == -1 {
return
}
// Gets the focused app
let focused_pid = get_focused_pid()
// Stops if there was no focused app to resize
if(focused_pid == pid_t(0)) {
return
}
// Moves and resizes the focused window
move_focused_window(CFloat(resize.0), CFloat(resize.1), focused_pid)
resize_focused_window(CFloat(resize.2), CFloat(resize.3), focused_pid)
}
}
/**
Starts the drawing process for the highlighting window
*/
func start_drawing() {
//begin drawing again
drawing = true
//adds the dimensions info so that a window can be created
snapHighlighter.update_window(layout.get_snap_dimensions(lastKnownMouseDrag!.x, y: lastKnownMouseDrag!.y))
snapHighlighter.draw_create()
}
/**
Handles the dragging of mouse
- Parameter event: the input event for mouse dragging
*/
func mouse_dragged_handler(_ event: NSEvent) {
//holds a reference to the last position of a drag
lastKnownMouseDrag = CGPoint(x: event.locationInWindow.x, y: event.locationInWindow.y)
if callback_seen {
if drawing {
//if still in a position that requires highlighting
if layout.is_hardpoint(event.locationInWindow.x, y: event.locationInWindow.y) {
snapHighlighter.update_window(layout.get_snap_dimensions(event.locationInWindow.x, y: event.locationInWindow.y))
print(layout.get_snap_dimensions(event.locationInWindow.x, y: event.locationInWindow.y))
} else {
snapHighlighter.draw_destroy()
drawing = false
}
} else if layout.is_hardpoint(event.locationInWindow.x, y: event.locationInWindow.y) {
drawing = true
//prevents annoying immediate display during quick motions
//also prevents lag on highligh window creation
snapHighlighter.delay_update(0.2)
}
}
}
/**
Handles the event of user releasing the mouse
- Parameter event: `NSEvent` that is received when user releases the mouse
*/
func mouse_up_handler(_ event: NSEvent) {
print("mouse up")
mouse_up_pos = event.locationInWindow
mouse_seen = true
if drawing {
//end the drawing
snapHighlighter.kill_delay_create()
snapHighlighter.draw_destroy()
drawing = false
}
// Check if the callback was executed too early
if callback_seen && callback_executed == false {
callback_seen = false
move_and_resize()
} else {
callback_executed = false
callback_seen = false
}
}
/**
Call back function for when a specific window moves
*/
func moved_callback(_ observer: AXObserver, element: AXUIElement, notificationName: CFString, contextData: UnsafeMutableRawPointer?) -> Void {
AXObserverRemoveNotification(observer, element, kAXMovedNotification as CFString);
if callback_seen == false {
callback_seen = true
} else {
return
}
callback_executed = false
// Check if the mouse up handler was executed
if mouse_seen == false {
//handle highlighting
if drawing == false && layout.is_hardpoint(lastKnownMouseDrag!.x, y: lastKnownMouseDrag!.y) {
snapHighlighter = SnapHighlighter()
start_drawing()
}
return
}
callback_executed = true
move_and_resize();
}
/**
Sets up the observer for the moved notification
*/
func setup_observer(_ pid: pid_t) {
var frontMostApp: AXUIElement
let frontMostWindow: UnsafeMutablePointer<AnyObject?> = UnsafeMutablePointer<AnyObject?>.allocate(capacity: 1)
frontMostApp = AXUIElementCreateApplication(pid)
AXUIElementCopyAttributeValue(frontMostApp, kAXFocusedWindowAttribute as CFString, frontMostWindow);
// Check if the frontMostWindow object is nil or not
if let placeHolder = frontMostWindow.pointee {
let frontMostWindow_true: AXUIElement = placeHolder as! AXUIElement
let observer: UnsafeMutablePointer<AXObserver?> = UnsafeMutablePointer<AXObserver?>.allocate(capacity: 1)
AXObserverCreate(pid, moved_callback as AXObserverCallback, observer)
let observer_true: AXObserver = observer.pointee!
let data_ptr: UnsafeMutablePointer<UInt16> = UnsafeMutablePointer<UInt16>.allocate(capacity: 1)
AXObserverAddNotification(observer_true, frontMostWindow_true, kAXMovedNotification as CFString, data_ptr);
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer_true), CFRunLoopMode.defaultMode);
}
}
/**
Handles the mouse down event
*/
func mouse_down_handler(_ event: NSEvent) {
// Reset all of the sync checks
mouse_seen = false
callback_seen = false
drawing = false
callback_executed = false
setup_observer(get_focused_pid())
}
| 8e0b861becbc1ca94fbcb4165df81f59 | 29.480583 | 142 | 0.714286 | false | false | false | false |
jfrowies/iEMI | refs/heads/master | iEMI/Parking.swift | apache-2.0 | 1 | //
// Parking.swift
// iEMI
//
// Created by Fer Rowies on 8/19/15.
// Copyright © 2015 Rowies. All rights reserved.
//
import UIKit
class Parking: NSObject {
var number: String = ""
var year: String = ""
var serie: String = ""
init(json:[String:AnyObject]) {
//The service returns "TarNro" or "Tarnro"
if let number = json["TarNro"] as? String {
self.number = number
}
if let number = json["Tarnro"] as? String {
self.number = number
}
//The service returns "TarAno" or "Tarano"
if let year = json["TarAno"] as? String {
self.year = year
}
if let year = json["TarAno"] as? Int {
self.year = String(year)
}
if let year = json["Tarano"] as? String {
self.year = year
}
if let year = json["Tarano"] as? Int {
self.year = String(year)
}
//The service returns "TarSerie" or "Tarserie"
if let serie = json["TarSerie"] as? String {
self.serie = serie
}
if let serie = json["Tarserie"] as? String {
self.serie = serie
}
}
init(number:String, year:String, serie:String) {
self.number = number
self.year = year
self.serie = serie
}
}
| 8499d242ad9e4da43adb0afd40e4f5c3 | 22.633333 | 54 | 0.485896 | false | false | false | false |
zSher/BulletThief | refs/heads/master | BulletThief/BulletThief/Enemy.swift | mit | 1 | //
// Enemy.swift
// BulletThief
//
// Created by Zachary on 5/6/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import Foundation
import SpriteKit
class Enemy: SKSpriteNode {
var gun:Gun!
var movementPath:UIBezierPath?
var weakened:Bool = false //flag to be stolen
//MARK: - Init -
convenience override init(){
var bulletEffects: [BulletEffectProtocol] = [TextureBulletEffect(textureName: "lineBullet"), FireDelayBulletEffect(delay: 3.5), SpeedBulletEffect(speed: 8), LinePathBulletEffect(direction: Directions.Down), StandardSpawnBulletEffect()]
self.init(textureName: "enemy", bulletEffects: bulletEffects, numBullets: 1, bulletCount: 20, speed: 5, name: "enemy")
}
//Init using set properties
init(textureName: String, bulletEffects: [BulletEffectProtocol], numBullets:UInt, bulletCount: UInt, speed:CGFloat, name:String) {
var texture = SKTexture(imageNamed: textureName)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.gun = Gun(initialEffects: bulletEffects, numberOfBulletsToFire: numBullets, bulletCount: bulletCount, owner: self)
self.gun.setPhysicsBody(CollisionCategories.EnemyBullet, contactBit: CollisionCategories.Player, collisionBit: CollisionCategories.None)
self.speed = speed
self.name = name
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody?.dynamic = true
self.physicsBody?.categoryBitMask = CollisionCategories.Enemy
self.physicsBody?.contactTestBitMask = CollisionCategories.PlayerBullet
self.physicsBody?.collisionBitMask = CollisionCategories.None
self.physicsBody?.usesPreciseCollisionDetection = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
//MARK: - Methods -
//Add path for movement
func addPath(path:UIBezierPath) {
self.movementPath = path
}
//MARK: - Update -
func update(deltaTime: CFTimeInterval){
gun.update(deltaTime)
//Shoot whenever you can
if gun.canShoot && !weakened {
gun.shoot()
}
}
//Function to perform when player steals this character's ability
func steal(player:Player){
}
//Function called when about to die
func willDie(){
self.removeAllActions()
self.removeFromParent()
bulletManager.returnBullets(gun.bulletPool)
}
//separate add function to add all components before being put onto screen
func addToScene(scene:SKScene){
var moveAction = SKAction.followPath(movementPath!.CGPath, asOffset: true, orientToPath: true, speed: self.speed)
var removeAction = SKAction.removeFromParent()
var onScreenActionGrp = SKAction.sequence([moveAction, removeAction])
scene.addChild(self)
self.runAction(onScreenActionGrp)
}
} | 04a9f10df5756ae4132ca2826c3666d9 | 35.843373 | 243 | 0.682368 | false | false | false | false |
dleonard00/firebase-user-signup | refs/heads/master | firebase-user-signup/ViewController.swift | mit | 1 | //
// ViewController.swift
// firebase-user-signup
//
// Created by doug on 3/11/16.
// Copyright © 2016 Weave. All rights reserved.
//
import UIKit
import Material
import Firebase
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: TextField!
@IBOutlet weak var emailTextField: TextField!
@IBOutlet weak var passwordTextField: TextField!
@IBOutlet weak var signupButton: FabButton!
override func viewDidLoad() {
super.viewDidLoad()
setTextFieldDelegates()
setupView()
}
func setupView(){
usernameTextField.placeholder = "Username"
usernameTextField.placeholderTextColor = MaterialColor.grey.base
usernameTextField.font = RobotoFont.regularWithSize(20)
usernameTextField.textColor = MaterialColor.black
usernameTextField.borderStyle = .None
usernameTextField.titleLabel = UILabel()
usernameTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
usernameTextField.titleLabelColor = MaterialColor.grey.base
usernameTextField.titleLabelActiveColor = MaterialColor.blue.accent3
emailTextField.placeholder = "Email"
emailTextField.placeholderTextColor = MaterialColor.grey.base
emailTextField.font = RobotoFont.regularWithSize(20)
emailTextField.textColor = MaterialColor.black
emailTextField.borderStyle = .None
emailTextField.titleLabel = UILabel()
emailTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
emailTextField.titleLabelColor = MaterialColor.grey.base
emailTextField.titleLabelActiveColor = MaterialColor.blue.accent3
passwordTextField.placeholder = "Password"
passwordTextField.placeholderTextColor = MaterialColor.grey.base
passwordTextField.font = RobotoFont.regularWithSize(20)
passwordTextField.textColor = MaterialColor.black
passwordTextField.borderStyle = .None
passwordTextField.titleLabel = UILabel()
passwordTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
passwordTextField.titleLabelColor = MaterialColor.grey.base
passwordTextField.titleLabelActiveColor = MaterialColor.blue.accent3
let image = UIImage(named: "ic_close_white")?.imageWithRenderingMode(.AlwaysTemplate)
let clearButton: FlatButton = FlatButton()
clearButton.pulseColor = MaterialColor.grey.base
clearButton.pulseScale = false
clearButton.tintColor = MaterialColor.grey.base
clearButton.setImage(image, forState: .Normal)
clearButton.setImage(image, forState: .Highlighted)
usernameTextField.clearButton = clearButton
emailTextField.clearButton = clearButton
passwordTextField.clearButton = clearButton
signupButton.setTitle("Sign up", forState: .Normal)
signupButton.titleLabel!.font = RobotoFont.mediumWithSize(15)
}
@IBAction func signupButtonWasTapped(sender: AnyObject) {
dismissKeyboard()
let failureClosure: (NSError) -> () = { error in
self.handleSignUpError(error)
}
guard let email = emailTextField.text, username = usernameTextField.text?.lowercaseString, password = passwordTextField.text else {
alertError("Please fill out the all fields, then try signing up again.")
return
}
if email.isEmpty || password.isEmpty || username.isEmpty {
alertError("Please fill out the all fields, then try signing up again.")
}
if username.characters.count > 15 {
alertError("Usernames must be less than 15 characters.")
return
}
//TODO check for conflicts.
if !isOnlyAlphaNumeric(username){
print("username must be only alpha numeric characters")
return
}
let usernameIndexRef = FirebaseRefManager.myRootRef.childByAppendingPath("username/\(username)")
usernameIndexRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull { //check that username doesnt already exist.
let successClosure = {
//Do something successful
}
let failureClosure: (NSError) -> () = { error in
self.handleSignUpError(error)
}
createNewUser(email, username: username, password: password, success: successClosure, failure: failureClosure)
} else {
self.alertError("Username has already been taken, please pick a new username and try again.")
return
}
})
}
func handleSignUpError(error: NSError){
if let errorCode = FAuthenticationError(rawValue: error.code) {
switch errorCode {
case .ProviderDisabled:
print("ProviderDisabled")
alertError("The requested authentication provider is currently disabled for this app.")
case .InvalidConfiguration:
print("InvalidConfiguration")
alertError("The requested authentication provider is misconfigured, and the request cannot complete.")
case .InvalidOrigin:
print("InvalidOrigin")
alertError("A security error occurred while processing the authentication request. The web origin for the request is not in your list of approved request origins.")
case .InvalidProvider:
print("InvalidProvider")
alertError("The requested authentication provider does not exist. Send mean tweets to @bettrnetHQ")
case .InvalidEmail:
print("InvalidEmail")
alertError("The specified email is not a valid email.")
case .InvalidPassword:
print("InvalidPassword")
alertError("The specified user account password is invalid.")
case .InvalidToken:
print("InvalidToken")
alertError("The specified authentication token is invalid.")
case .EmailTaken:
print("EmailTaken")
alertError("The new user account cannot be created because the specified email address is already in use.")
case .NetworkError:
print("NetworkError")
alertError("An error occurred while attempting to contact the authentication server.")
case .Unknown:
print("Unknown")
alertError("Something went wrong, please try again later.")
default:
print("error - default situation")
alertError("Something went wrong, please try again later.")
}
}
}
func isOnlyAlphaNumeric(stringInQuestion: String) -> Bool{
let regex = try! NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: NSRegularExpressionOptions())
if regex.firstMatchInString(stringInQuestion, options: NSMatchingOptions(), range:NSMakeRange(0, stringInQuestion.characters.count)) != nil {
print("could not handle special characters")
alertError("Use only alpha-numeric characters in preferred name.")
return false
}
return true
}
func alertError(message: String){
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch(textField){
case self.usernameTextField:
self.emailTextField.becomeFirstResponder()
case self.emailTextField:
self.passwordTextField.becomeFirstResponder()
case self.passwordTextField:
self.passwordTextField.resignFirstResponder()
self.signupButtonWasTapped(textField)
default:
self.signupButtonWasTapped(textField)
}
return true
}
func setTextFieldDelegates(){
emailTextField.delegate = self
passwordTextField.delegate = self
usernameTextField.delegate = self
}
func dismissKeyboard(){
self.emailTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.usernameTextField.resignFirstResponder()
}
}
| 3ee7eda0c5ab1579fdbb022d9903cbe8 | 40.809524 | 180 | 0.644077 | false | false | false | false |
coach-plus/ios | refs/heads/master | Floral/Pods/Hero/Sources/Animator/HeroAnimatorViewContext.swift | mit | 4 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
internal class HeroAnimatorViewContext {
weak var animator: HeroAnimator?
let snapshot: UIView
let appearing: Bool
var targetState: HeroTargetState
var duration: TimeInterval = 0
// computed
var currentTime: TimeInterval {
return snapshot.layer.convertTime(CACurrentMediaTime(), from: nil)
}
var container: UIView? {
return animator?.hero.context.container
}
class func canAnimate(view: UIView, state: HeroTargetState, appearing: Bool) -> Bool {
return false
}
func apply(state: HeroTargetState) {
}
func changeTarget(state: HeroTargetState, isDestination: Bool) {
}
func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval {
return 0
}
func seek(timePassed: TimeInterval) {
}
func clean() {
animator = nil
}
func startAnimations() -> TimeInterval {
return 0
}
required init(animator: HeroAnimator, snapshot: UIView, targetState: HeroTargetState, appearing: Bool) {
self.animator = animator
self.snapshot = snapshot
self.targetState = targetState
self.appearing = appearing
}
}
| b01f0482f4e2b6f7b8e5ba3e396769b4 | 30.788732 | 106 | 0.734603 | false | false | false | false |
gobetti/Swift | refs/heads/master | SQLite/SQLite/ViewController.swift | mit | 1 | //
// ViewController.swift
// SQLite
//
// Created by Carlos Butron on 06/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var statement = COpaquePointer()
var data: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
loadTabla()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadTabla(){
let db_path = NSBundle.mainBundle().pathForResource("FilmCollection", ofType: "sqlite")
print(NSBundle.mainBundle())
var db = COpaquePointer()
let status = sqlite3_open(db_path!, &db)
if(status == SQLITE_OK){
//bbdd open
print("open")
}
else{
//bbdd error
print("open error")
}
let query_stmt = "select * from film"
if(sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil) == SQLITE_OK){
data.removeAllObjects()
while(sqlite3_step(statement) == SQLITE_ROW){
let Dictionary = NSMutableDictionary()
let director = sqlite3_column_text(statement, 1)
let buf_director = String.fromCString(UnsafePointer<CChar>(director))
let image = sqlite3_column_text(statement, 2)
let buf_image = String.fromCString(UnsafePointer<CChar>(image))
let title = sqlite3_column_text(statement, 3)
let buf_title = String.fromCString(UnsafePointer<CChar>(title))
let year = sqlite3_column_text(statement, 4)
let buf_year = String.fromCString(UnsafePointer<CChar>(year))
Dictionary.setObject(buf_director!, forKey:"director")
Dictionary.setObject(buf_image!, forKey: "image")
Dictionary.setObject(buf_title!, forKey: "title")
Dictionary.setObject(buf_year!, forKey: "year")
data.addObject(Dictionary)
//process data
}
sqlite3_finalize(statement)
}
else{
print("ERROR")
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell") as! MyTableViewCell
let aux: AnyObject = data[indexPath.row]
let table_director = aux["director"]
cell.director.text = table_director as? String
//var aux1: AnyObject = data[indexPath.row]
let table_image = aux["image"]
cell.myImage.image = UIImage(named:table_image as! String)
let aux3: AnyObject = data[indexPath.row]
let table_title = aux["title"]
cell.title.text = table_title as? String
//var aux4: AnyObject = data[indexPath.row]
let table_year = aux3["year"]
cell.year.text = table_year as? String
return cell
}
}
| 35bebf7a6ad086ef69e2bfef59b65794 | 31.777778 | 121 | 0.589831 | false | false | false | false |
LYM-mg/DemoTest | refs/heads/master | 其他功能/MGBookViews/MGBookViews/表格/UICollectionGridViewController.swift | mit | 1 | // UICollectionGridViewController.swift
// MGBookViews
// Created by i-Techsys.com on 2017/11/15.
// Copyright © 2017年 i-Techsys. All rights reserved.
// https://github.com/LYM-mg
// http://www.jianshu.com/u/57b58a39b70e
import UIKit
//表格排序协议
protocol UICollectionGridViewSortDelegate {
func sort(colIndex: Int, asc: Bool, rows: [[Any]]) -> [[Any]]
}
//多列表格组件(通过CollectionView实现)
class UICollectionGridViewController: UICollectionViewController {
//表头数据
var cols: [String]! = []
//行数据
var rows: [[Any]]! = []
//排序代理
var sortDelegate: UICollectionGridViewSortDelegate!
//选中的表格列(-1表示没有选中的)
private var selectedColIdx = -1
//列排序顺序
private var asc = true
init() {
//初始化表格布局
let layout = UICollectionGridViewLayout()
super.init(collectionViewLayout: layout)
layout.viewController = self
collectionView!.backgroundColor = UIColor.white
collectionView!.register(UICollectionGridViewCell.self,
forCellWithReuseIdentifier: "cell")
collectionView!.delegate = self
collectionView!.dataSource = self
collectionView!.isDirectionalLockEnabled = true
//collectionView!.contentInset = UIEdgeInsetsMake(0, 10, 0, 10)
collectionView!.bounces = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("UICollectionGridViewController.init(coder:) has not been implemented")
}
//设置列头数据
func setColumns(columns: [String]) {
cols = columns
}
//添加行数据
func addRow(row: [Any]) {
rows.append(row)
collectionView!.collectionViewLayout.invalidateLayout()
collectionView!.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
collectionView!.frame = CGRect(x:0, y:0,
width:view.frame.width, height:view.frame.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//返回表格总行数
override func numberOfSections(in collectionView: UICollectionView) -> Int {
if cols.isEmpty {
return 0
}
//总行数是:记录数+1个表头
return rows.count + 1
}
//返回表格的列数
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return cols.count
}
//单元格内容创建
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
for: indexPath) as! UICollectionGridViewCell
//设置列头单元格,内容单元格的数据
if indexPath.section == 0 {
cell.label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
cell.label.text = cols[indexPath.row]
cell.label.textColor = UIColor.white
} else {
cell.label.font = UIFont.systemFont(ofSize: 15)
cell.label.text = "\(rows[indexPath.section-1][indexPath.row])"
cell.label.textColor = UIColor.black
}
//表头单元格背景色
if indexPath.section == 0 {
cell.backgroundColor = UIColor(red: 0x91/255, green: 0xDA/255, blue: 0x51/255, alpha: 1)
//排序列列头显示升序降序图标
if indexPath.row == selectedColIdx {
let iconType = asc ? FAType.FALongArrowUp : FAType.FALongArrowDown
cell.imageView.setFAIconWithName(icon: iconType, textColor: UIColor.white)
}else{
cell.imageView.image = nil
}
}
//内容单元格背景色
else {
cell.imageView.image = nil
//排序列的单元格背景会变色
if indexPath.row == selectedColIdx {
//排序列的单元格背景会变色
cell.backgroundColor = UIColor(red: 0xCC/255, green: 0xF8/255, blue: 0xFF/255,
alpha: 1)
}
//数据区域每行单元格背景色交替显示
else if indexPath.section % 2 == 0 {
cell.backgroundColor = UIColor(white: 242/255.0, alpha: 1)
} else {
cell.backgroundColor = UIColor.white
}
}
return cell
}
//单元格选中事件
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
//打印出点击单元格的[行,列]坐标
print("点击单元格的[行,列]坐标: [\(indexPath.section),\(indexPath.row)]")
if indexPath.section == 0 && sortDelegate != nil {
//如果点击的是表头单元格,则默认该列升序排列,再次点击则变降序排列,以此交替
asc = (selectedColIdx != indexPath.row) ? true : !asc
selectedColIdx = indexPath.row
rows = sortDelegate.sort(colIndex: indexPath.row, asc: asc, rows: rows)
collectionView.reloadData()
}
}
}
| f0f772d888810290f24c12022d5cae68 | 33.206667 | 100 | 0.578055 | false | false | false | false |
inket/stts | refs/heads/master | stts/Services/Super/PayPal.swift | mit | 1 | //
// PayPal.swift
// stts
//
import Kanna
typealias PayPal = BasePayPal & RequiredServiceProperties & RequiredPayPalProperties
enum PayPalEnvironment: String {
case sandbox
case production
}
enum PayPalComponent {
case product(PayPalEnvironment)
case api(PayPalEnvironment)
var category: String {
switch self {
case .product: return "product"
case .api: return "api"
}
}
var environment: PayPalEnvironment {
switch self {
case let .product(environment): return environment
case let .api(environment): return environment
}
}
}
protocol RequiredPayPalProperties {
var component: PayPalComponent { get }
}
class BasePayPal: BaseService {
private enum PayPalStatus: String, ComparableStatus {
case operational
case underMaintenance = "under_maintenance"
case serviceDisruption = "service_disruption"
case serviceOutage = "service_outage"
case informational
var serviceStatus: ServiceStatus {
switch self {
case .operational, .informational:
return .good
case .underMaintenance:
return .maintenance
case .serviceDisruption:
return .minor
case .serviceOutage:
return .major
}
}
var statusMessage: String {
switch self {
case .operational, .informational: return "Operational"
case .underMaintenance: return "Under Maintenance"
case .serviceDisruption: return "Service Disruption"
case .serviceOutage: return "Service Outage"
}
}
}
var url: URL {
guard let paypal = self as? PayPal else { fatalError("BasePayPal should not be used directly") }
var components = URLComponents()
components.scheme = "https"
components.host = "www.paypal-status.com"
components.path = "/\(paypal.component.category)/\(paypal.component.environment.rawValue)"
return components.url!
}
override func updateStatus(callback: @escaping (BaseService) -> Void) {
guard let realSelf = self as? PayPal else { fatalError("BasePayPal should not be used directly.") }
let apiURL = URL(string: "https://www.paypal-status.com/api/v1/components")!
loadData(with: apiURL) { [weak realSelf] data, _, error in
guard let strongSelf = realSelf else { return }
defer { callback(strongSelf) }
guard let data = data else { return strongSelf._fail(error) }
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard
let dict = json as? [String: Any],
let resultArray = dict["result"] as? [[String: Any]]
else { return strongSelf._fail("Unexpected data") }
let statuses = resultArray.compactMap {
strongSelf.status(fromResultItem: $0, component: strongSelf.component)
}
guard let highestStatus = statuses.max() else { return strongSelf._fail("Unexpected data") }
strongSelf.status = highestStatus.serviceStatus
strongSelf.message = highestStatus.statusMessage
}
}
private func status(fromResultItem resultItem: [String: Any], component: PayPalComponent) -> PayPalStatus? {
guard
let categoryDict = resultItem["category"] as? [String: Any],
categoryDict["name"] as? String == component.category,
let statusDict = resultItem["status"] as? [String: String],
let statusString = statusDict[component.environment.rawValue]
else { return nil }
let sanitizedStatusString = statusString.replacingOccurrences(of: " ", with: "_").lowercased()
return PayPalStatus(rawValue: sanitizedStatusString)
}
}
| aad668c6e6fec4556d675e698144c5fa | 32.305085 | 112 | 0.620102 | false | false | false | false |
GreenvilleCocoa/ChristmasDelivery | refs/heads/master | ChristmasDelivery/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// ChristmasDelivery
//
// Created by Marcus Smith on 12/8/14.
// Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved.
//
import UIKit
import SpriteKit
var totalScore: Int = 0
class GameViewController: UIViewController {
override func loadView() {
let skView = SKView()
view = skView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let skView: SKView = self.view as! SKView
if (skView.scene == nil) {
skView.showsFPS = true
skView.showsNodeCount = true
// skView.ignoresSiblingOrder = true
// skView.showsPhysics = true
let scene: GameScene = GameScene(size: skView.frame.size, level: 1)
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Landscape
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 8a1f529585cb0e287bde69178b20f50f | 23.172414 | 82 | 0.608417 | false | false | false | false |
karstengresch/trhs-ios | refs/heads/master | InteractiveStory/InteractiveStory/PageController.swift | unlicense | 1 | //
// PageController.swift
// InteractiveStory
//
// Created by Karsten Gresch on 15.03.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import UIKit
extension NSAttributedString {
var stringRange: NSRange {
return NSMakeRange(0, self.length)
}
}
extension Story {
var attributedText: NSAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: attributedString.stringRange)
return attributedString
}
}
extension Page {
func story(attributed: Bool) -> NSAttributedString {
if attributed {
return story.attributedText
}
else {
return NSAttributedString(string: story.text)
}
}
}
class PageController: UIViewController {
var page: Page?
let soundsEffectsPlayer = SoundsEffectsPlayer()
// MARK: User Interface Properties
lazy var artworkView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = self.page?.story.artwork
return imageView
}()
lazy var storyLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.attributedText = self.page?.story(attributed: true)
return label
}()
lazy var firstChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
let title = self.page?.firstChoice?.title ?? "Play Again"
let selector = self.page?.firstChoice != nil ? #selector(PageController.loadFirstChoice) : #selector(PageController.playAgain)
button.setTitle(title, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}()
lazy var secondChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(self.page?.secondChoice?.title, for: .normal)
button.addTarget(self, action: #selector(PageController.loadSecondChoice), for: .touchUpInside)
return button
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(xPage: Page) {
page = xPage
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.addSubview(artworkView)
NSLayoutConstraint.activate([
artworkView.topAnchor.constraint(equalTo: view.topAnchor),
artworkView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
artworkView.rightAnchor.constraint(equalTo: view.rightAnchor),
artworkView.leftAnchor.constraint(equalTo: view.leftAnchor)
])
view.addSubview(storyLabel)
NSLayoutConstraint.activate([
storyLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16.0),
storyLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16.0),
storyLabel.topAnchor.constraint(equalTo: view.centerYAnchor, constant: -48.0)
])
view.addSubview(firstChoiceButton)
firstChoiceButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
firstChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
firstChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -80.0)
])
view.addSubview(secondChoiceButton)
secondChoiceButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
secondChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
secondChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32.0)
])
}
func loadFirstChoice() {
if let page = page, let firstChoice = page.firstChoice {
let nextPage = firstChoice.page
let pageController = PageController(xPage: nextPage)
soundsEffectsPlayer.playSound(for: firstChoice.page.story)
navigationController?.pushViewController(pageController, animated: true)
}
}
func loadSecondChoice() {
if let page = page, let secondChoice = page.secondChoice {
let nextPage = secondChoice.page
let pageController = PageController(xPage: nextPage)
soundsEffectsPlayer.playSound(for: secondChoice.page.story)
navigationController?.pushViewController(pageController, animated: true)
}
}
func playAgain() {
navigationController?.popToRootViewController(animated: true)
}
}
| 2aefe24bf85af8bbc4b88b307205906d | 26.282609 | 130 | 0.705976 | false | false | false | false |
zbw209/- | refs/heads/master | StudyNotes/StudyNotes/知识点/NavigationController/SecondVC.swift | mit | 1 | //
// SecondVC.swift
// StudyNotes
//
// Created by 周必稳 on 2017/4/19.
// Copyright © 2017年 zhou. All rights reserved.
//
import UIKit
class SecondVC: UIViewController {
var abc : String?
override func viewDidLoad() {
super.viewDidLoad()
print("\((#file).components(separatedBy: "/").last!) \(#line) \(#function) \(String(describing: self.navigationController))")
var image = UIImage.init(named: "icon_back_normal")
image = image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
// image?.renderingMode = UIImageRenderingMode.alwaysOriginal
self.navigationController?.navigationBar.backIndicatorImage = image
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = image
// self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "1", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let label = UILabel.init(frame: CGRect.zero)
label.textColor = UIColor.red
label.text = "测试"
label.sizeToFit()
let barButtonItem = UIBarButtonItem.init(customView: label)
self.navigationItem.leftBarButtonItem = barButtonItem
self.navigationItem.leftItemsSupplementBackButton = true
self.navigationController?.delegate = self
}
}
extension SecondVC : UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return nil
}
}
| 06f1a281ecacc8b71330c5dcc4f274d6 | 31.653846 | 209 | 0.682568 | false | false | false | false |
rentpath/Atlas | refs/heads/master | AtlasTests/UInt+AtlasMapTests.swift | mit | 1 | //
// UInt+AtlasMapTests.swift
// Atlas
//
// Created by Jeremy Fox on 8/5/16.
// Copyright © 2016 RentPath. All rights reserved.
//
import XCTest
@testable import Atlas
class UInt_AtlasMapTests: XCTestCase {
var json: JSON!
let ui: UInt = 0
let ui8: UInt8 = 0
let ui16: UInt16 = 0
let ui32: UInt32 = 0
let ui64: UInt64 = 0
override func setUp() {
super.setUp()
let i: UInt = 702888806
let i8: UInt8 = 70
let i16: UInt16 = 7028
let i32: UInt32 = 702888806
let i64: UInt64 = 70288880664460
let dict: [String: Any] = [
"ui": NSNumber(value: i as UInt),
"ui8": NSNumber(value: i8 as UInt8),
"ui16": NSNumber(value: i16 as UInt16),
"ui32": NSNumber(value: i32 as UInt32),
"ui64": NSNumber(value: i64 as UInt64)
]
let data = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0))
json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as JSON
}
override func tearDown() {
json = nil
super.tearDown()
}
func testUIntMappingMapsIntegerValuesWithinManAndMaxRange() {
let min = UInt.min
let max = UInt.max
XCTAssertEqual(UInt(min), UInt.min)
XCTAssertEqual(UInt(max), UInt.max)
}
func testIntMappingPerformance() {
self.measure {
for _ in 0..<100_000 {
let _ = UInt(702888806)
}
}
}
func testUIntMappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt(json: (json as AnyObject)["ui"] ?? ui)!, ui)
}
func testUInt64MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt64(json: (json as AnyObject)["ui64"] ?? ui64)!, ui64)
}
func testUInt32MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt32(json: (json as AnyObject)["ui32"] ?? ui32)!, ui32)
}
func testUInt16MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt16(json: (json as AnyObject)["ui16"] ?? ui16)!, ui16)
}
func testUInt8MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt8(json: (json as AnyObject)["ui8"] ?? ui8)!, ui8)
}
}
| 088d54dfe1400853fb7119407b404bf1 | 28.658228 | 124 | 0.614597 | false | true | false | false |
gautier-gdx/Hexacon | refs/heads/master | Hexacon/HexagonalPattern.swift | mit | 1 | //
// HegagonalDirection.swift
// Hexacon
//
// Created by Gautier Gdx on 06/02/16.
// Copyright © 2016 Gautier. All rights reserved.
//
import UIKit
final class HexagonalPattern {
// MARK: - typeAlias
typealias HexagonalPosition = (center: CGPoint,ring: Int)
// MARK: - data
internal var repositionCenter: ((CGPoint, Int, Int) -> ())?
fileprivate var position: HexagonalPosition! {
didSet {
//while our position is bellow the size we can continue
guard positionIndex < size else {
reachedLastPosition = true
return
}
//each time a new center is set we are sending it back to the scrollView
repositionCenter?(position.center, position.ring, positionIndex)
positionIndex += 1
}
}
fileprivate var directionFromCenter: HexagonalDirection
fileprivate var reachedLastPosition = false
fileprivate var positionIndex = 0
fileprivate let sideNumber: Int = 6
//properties
fileprivate let size: Int
fileprivate let itemSpacing: CGFloat
fileprivate let maxRadius: Int
// MARK: - init
init(size: Int, itemSpacing: CGFloat, itemSize: CGFloat) {
self.size = size
self.itemSpacing = itemSpacing + itemSize - 8
maxRadius = size/6 + 1
directionFromCenter = .right
}
// MARK: - instance methods
/**
calculate the theorical size of the grid
- returns: the size of the grid
*/
func sizeForGridSize() -> CGFloat {
return 2*itemSpacing*CGFloat(maxRadius)
}
/**
create the grid with a circular pattern beginning from the center
in each loop we are sending back a center for a new View
*/
func createGrid(FromCenter newCenter: CGPoint) {
//initializing the algorythm
start(newCenter)
//for each radius
for radius in 0...maxRadius {
guard reachedLastPosition == false else { continue }
//we are creating a ring
createRing(withRadius: radius)
//then jumping to the next one
jumpToNextRing()
}
}
// MARK: - configuration methods
fileprivate func neighbor(origin: CGPoint,direction: HexagonalDirection) -> CGPoint {
//take the current direction
let direction = direction.direction()
//then multiply it to find the new center
return CGPoint(x: origin.x + itemSpacing*direction.x,y: origin.y + itemSpacing*direction.y)
}
fileprivate func start(_ newCenter: CGPoint) {
//initializing with the center given
position = (center: newCenter,ring: 0)
//then jump on the first ring
position = (center: neighbor(origin: position.center,direction: .leftDown),ring: 1)
}
fileprivate func createRing(withRadius radius: Int) {
//for each side of the ring
for _ in 0...(sideNumber - 1) {
//in each posion in the side
for directionIndex in 0...radius {
//stop if we are at the end of the ring
guard !(directionIndex == radius && directionFromCenter == .rightDown) else { continue }
//or add a new point
position = (center: neighbor(origin: position.center,direction: directionFromCenter),ring: radius + 1)
}
//then move to another position
directionFromCenter.move()
}
}
fileprivate func jumpToNextRing() {
//the next ring is always two position bellow the previous one
position = (center: CGPoint(x: position.center.x ,y: position.center.y + 2*itemSpacing),ring: position.ring + 1)
}
}
| 920f0e0dcccee10e58d6e1ad4e6f1595 | 29.614173 | 120 | 0.592335 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/Models/Notifications/NotificationSettings.swift | gpl-2.0 | 1 | import Foundation
/// The goal of this class is to encapsulate all of the User's Notification Settings in a generic way.
/// Settings are grouped into different Channels. A Channel is considered anything that might produce
/// Notifications: a WordPress blog, Third Party Sites or WordPress.com.
/// Each channel may support different streams, such as: Email + Push Notifications + Timeline.
///
open class NotificationSettings {
/// Represents the Channel to which the current settings are associated.
///
open let channel: Channel
/// Contains an array of the available Notification Streams.
///
open let streams: [Stream]
/// Maps to the associated blog, if any.
///
open let blog: Blog?
/// Designated Initializer
///
/// - Parameters:
/// - channel: The related Notifications Channel
/// - streams: An array of all of the involved streams
/// - blog: The associated blog, if any
///
public init(channel: Channel, streams: [Stream], blog: Blog?) {
self.channel = channel
self.streams = streams
self.blog = blog
}
/// Returns the localized description for any given preference key
///
open func localizedDescription(_ preferenceKey: String) -> String {
return Keys.localizedDescriptionMap[preferenceKey] ?? String()
}
/// Returns the details for a given preference key
///
open func localizedDetails(_ preferenceKey: String) -> String? {
return Keys.localizedDetailsMap[preferenceKey]
}
/// Returns an array of the sorted Preference Keys
///
open func sortedPreferenceKeys(_ stream: Stream?) -> [String] {
switch channel {
case .blog:
// Email Streams require a special treatment
return stream?.kind == .Email ? blogEmailPreferenceKeys : blogPreferenceKeys
case .other:
return otherPreferenceKeys
case .wordPressCom:
return wpcomPreferenceKeys
}
}
/// Represents a communication channel that may post notifications to the user.
///
public enum Channel: Equatable {
case blog(blogId: Int)
case other
case wordPressCom
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .blog:
return NSLocalizedString("WordPress Blog", comment: "Settings for a Wordpress Blog")
case .other:
return NSLocalizedString("Comments on Other Sites", comment: "Notification Settings Channel")
case .wordPressCom:
return NSLocalizedString("Email from WordPress.com", comment: "Notification Settings Channel")
}
}
}
/// Contains the Notification Settings collection for a specific communications stream.
///
open class Stream {
open var kind: Kind
open var preferences: [String : Bool]?
/// Designated Initializer
///
/// - Parameters:
/// - kind: The Kind of stream we're currently dealing with
/// - preferences: Raw remote preferences, retrieved from the backend
///
public init(kind: String, preferences: [String : Bool]?) {
self.kind = Kind(rawValue: kind) ?? .Email
self.preferences = preferences
}
/// Enumerates all of the possible Stream Kinds
///
public enum Kind: String {
case Timeline = "timeline"
case Email = "email"
case Device = "device"
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .Timeline:
return NSLocalizedString("Notifications Tab", comment: "WordPress.com Notifications Timeline")
case .Email:
return NSLocalizedString("Email", comment: "Email Notifications Channel")
case .Device:
return NSLocalizedString("Push Notifications", comment: "Mobile Push Notifications")
}
}
static let allValues = [ Timeline, Email, Device ]
}
}
// MARK: - Private Properties
fileprivate let blogPreferenceKeys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.achievement, Keys.mention]
fileprivate let blogEmailPreferenceKeys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.mention]
fileprivate let otherPreferenceKeys = [Keys.commentLiked, Keys.commentReplied]
fileprivate let wpcomPreferenceKeys = [Keys.marketing, Keys.research, Keys.community]
// MARK: - Setting Keys
fileprivate struct Keys {
static let commentAdded = "new_comment"
static let commentLiked = "comment_like"
static let commentReplied = "comment_reply"
static let postLiked = "post_like"
static let follower = "follow"
static let achievement = "achievement"
static let mention = "mentions"
static let marketing = "marketing"
static let research = "research"
static let community = "community"
static let localizedDescriptionMap = [
commentAdded: NSLocalizedString("Comments on my site",
comment: "Setting: indicates if New Comments will be notified"),
commentLiked: NSLocalizedString("Likes on my comments",
comment: "Setting: indicates if Comment Likes will be notified"),
postLiked: NSLocalizedString("Likes on my posts",
comment: "Setting: indicates if Replies to your comments will be notified"),
follower: NSLocalizedString("Site follows",
comment: "Setting: indicates if New Follows will be notified"),
achievement: NSLocalizedString("Site achievements",
comment: "Setting: indicates if Achievements will be notified"),
mention: NSLocalizedString("Username mentions",
comment: "Setting: indicates if Mentions will be notified"),
commentReplied: NSLocalizedString("Replies to your comments",
comment: "Setting: indicates if Replies to Comments will be notified"),
marketing: NSLocalizedString("Suggestions",
comment: "Setting: WordPress.com Suggestions"),
research: NSLocalizedString("Research",
comment: "Setting: WordPress.com Surveys"),
community: NSLocalizedString("Community",
comment: "Setting: WordPress.com Community")
]
static let localizedDetailsMap = [
marketing: NSLocalizedString("Tips for getting the most out of WordPress.com.",
comment: "WordPress.com Marketing Footer Text"),
research: NSLocalizedString("Opportunities to participate in WordPress.com research & surveys.",
comment: "WordPress.com Research Footer Text"),
community: NSLocalizedString("Information on WordPress.com courses and events (online & in-person).",
comment: "WordPress.com Community Footer Text")
]
}
}
/// Swift requires this method to be implemented globally. Sorry about that!
///
public func ==(first: NotificationSettings.Channel, second: NotificationSettings.Channel) -> Bool {
switch (first, second) {
case (let .blog(firstBlogId), let .blog(secondBlogId)) where firstBlogId == secondBlogId:
return true
case (.other, .other):
return true
case (.wordPressCom, .wordPressCom):
return true
default:
return false
}
}
| 6a0d0b0038b0e8e1cbb05cd15f3722a2 | 40.41206 | 147 | 0.594224 | false | false | false | false |
rmavani/SocialQP | refs/heads/master | QPrint/Controllers/NearbyStore/NearbyStoresViewController.swift | mit | 1 | //
// NearbyStoresViewController.swift
// QPrint
//
// Created by Admin on 23/02/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
// MARK: - NearbyStoresCell
class NearbyStoresCell : UITableViewCell {
// MARK: - Initialize IBOutlets
@IBOutlet var lblStoreName : UILabel!
@IBOutlet var lblStoreLocation : UILabel!
@IBOutlet var lblDistance : UILabel!
}
// MARK: - NearbyStoresViewController
class NearbyStoresViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Initialize IBOutlets
@IBOutlet var lblTitle : UILabel!
@IBOutlet var tblList : UITableView!
// MARK: - Initialize Variables
// MARK: - Initialize
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
lblTitle.layer.shadowOpacity = 0.5
lblTitle.layer.shadowOffset = CGSize(width : 0.5, height : 0.5)
lblTitle.layer.shadowColor = UIColor.darkGray.cgColor
self.getNearByData()
}
// MARK: - UIButton Click Events
//MARK: - UITableView Delegate & DataSource Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell : NearbyStoresCell = tblList.dequeueReusableCell(withIdentifier: "NearbyStoresCell", for: indexPath) as! NearbyStoresCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// MARK: - API Methods
// MARK: getNearByData
func getNearByData() {
if AppUtilities.isConnectedToNetwork() {
AppUtilities.sharedInstance.showLoader()
let strLatitude = UserDefaults.standard.object(forKey: "latitude")
let strLongitude = UserDefaults.standard.object(forKey: "longitude")
let str = NSString(format: "method=searchnear&latitude=\(strLatitude)&longitude=\(strLongitude)" as NSString)
AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in
DispatchQueue.main.async( execute: {
AppUtilities.sharedInstance.hideLoader()
if success
{
print("object ",object!)
print("move it to home page")
if(object?.value(forKeyPath: "error") as! String == "0")
{
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString)
}
}
})
})
}
else
{
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!")
}
}
// MARK: - Other Methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 00fe2faec3554808507ab21931e7c877 | 33.579439 | 138 | 0.590811 | false | false | false | false |
eraydiler/password-locker | refs/heads/master | PasswordLockerSwift/Classes/Controller/Password/PasswordCreationViewController.swift | mit | 1 | //
// PasswordCreationViewController.swift
// PasswordLockerSwift
//
// Created by Eray on 21/04/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
class PasswordCreationViewController: UIViewController {
@IBOutlet weak var passwordTextField: UITextField!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
configureView()
}
// MARK: - Configuration
func configureView() {
passwordTextField.textColor = .gray
passwordTextField.tintColor = UIColor.gray
passwordTextField.delegate = self
}
// MARK: - IBActions
@IBAction func checkButtonPressed(_ sender: AnyObject) {
guard let retrieveString = KeychainService.value(forKey: KeychainService.appPasswordKey) else {
return
}
print("\(retrieveString)")
}
@IBAction func addPassLockButtonPressed(_ sender: AnyObject) {
attemptToSavePassword()
}
@IBAction func viewTapped(_ sender: AnyObject) {
passwordTextField.resignFirstResponder()
}
// MARK: - Private methods
@discardableResult
fileprivate func attemptToSavePassword() -> Bool {
guard let text = passwordTextField.text, !text.isEmpty else {
print(">>> TEXT FIELD IS EMPTY")
return false
}
let isSaved: Bool = KeychainService.set(value: text, forKey: KeychainService.appPasswordKey)
guard isSaved else {
print(">>> AN ERROR OCCURED WHILE SAVING PASSWORD")
return false
}
print(">>> PASSWORD SAVED SUCCESSFULLY")
displaySuccessAlert()
return true
}
func displaySuccessAlert() {
fatalError("Must be implemented by subclasses")
}
// MARK: - Subclass methods
func performSuccessAction() {
fatalError("Must be implemented by subclasses")
}
}
// MARK: - Text field delegate
extension PasswordCreationViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return attemptToSavePassword()
}
}
| f8e28a778784916f75bc06d3e8abf639 | 23.806452 | 103 | 0.619419 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/decl/init/cf-types.swift | apache-2.0 | 25 | // RUN: %target-typecheck-verify-swift
// REQUIRES: OS=macosx
import CoreGraphics
extension CGMutablePath {
public convenience init(p: Bool) { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public convenience init?(maybe: Bool) { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public convenience init(toss: Bool) throws { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public init(simple: Bool) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
// expected-error @-1 {{designated initializer for 'CGMutablePath' cannot delegate (with 'self.init')}}{{none}}
self.init() // expected-note {{delegation occurs here}}
}
public init?(value: Bool) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
// expected-error @-1 {{designated initializer for 'CGMutablePath' cannot delegate (with 'self.init')}}{{none}}
self.init() // expected-note {{delegation occurs here}}
}
public init?(string: String) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
let _ = string
}
}
public func useInit() {
let _ = CGMutablePath(p: true)
let _ = CGMutablePath(maybe: true)
let _ = try! CGMutablePath(toss: true)
let _ = CGMutablePath(simple: true)
let _ = CGMutablePath(value: true)
let _ = CGMutablePath(string: "value")
}
| c481ae6e72083a0cdf459cd6b4659641 | 40.8 | 141 | 0.683014 | false | false | false | false |
dsay/POPDataSource | refs/heads/master | DataSources/Example/Models/Models.swift | mit | 1 | import UIKit
struct Artist {
var name: String
var id: Int
var albums = [Album]()
init(_ name: String, _ id: Int) {
self.name = name
self.id = id
}
}
struct Genre {
var name: String
var albums = [Album]()
init(_ genre: String) {
self.name = genre
}
}
struct Album {
var name: String
var releaseDate: Date
var trackCount: Int
var genre: String
var artistName: String
init(_ name: String, _ artistName: String, _ releaseDate: Date, _ trackCount: Int, _ genre: String) {
self.name = name
self.artistName = artistName
self.releaseDate = releaseDate
self.trackCount = trackCount
self.genre = genre
}
}
struct Parser {
var fileURL: URL
func parse() -> ([Album], [Artist])? {
let data = try? Data(contentsOf: fileURL)
var json: [[String : AnyObject]]? = nil
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String : AnyObject]]
} catch {
json = nil
}
guard let parsed = json else {
return nil
}
var albums = [Album]()
var artists = [Artist]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
for representation in parsed {
let artist = Artist(representation["artistName"] as! String,
representation["artistId"] as! Int)
artists.append(artist)
let date = representation["releaseDate"] as! String
let album = Album(representation["collectionName"] as! String,
representation["artistName"] as! String,
dateFormatter.date(from: date)!,
representation["trackCount"] as! Int,
representation["primaryGenreName"] as! String)
albums.append(album)
}
return (albums, Array(Set(artists)))
}
}
struct LedZeppelin {
fileprivate static let parser: Parser = {
let path = Bundle.main.url(forResource: "Albums", withExtension: "json")
return Parser(fileURL: path!)
}()
fileprivate static let data = LedZeppelin.parser.parse()
static let genres: [Genre] = {
let genreNames = Set(LedZeppelin.data!.0.map { $0.genre })
return genreNames.map { name -> Genre in
var genre = Genre(name)
genre.albums = LedZeppelin.data!.0.filter { $0.genre == name }
return genre
}
}()
static var artists: [Artist] {
var artists = [Artist]()
for artist in LedZeppelin.data!.1 {
var artistWithAlbums = artist
artistWithAlbums.albums = LedZeppelin.data!.0.filter { $0.artistName == artist.name }
artists.append(artistWithAlbums)
}
return artists
}
static let albums: [Album] = {
return LedZeppelin.data!.0
}()
}
func ==(lhs: Album, rhs: Album) -> Bool {
return (lhs.name == rhs.name) && (lhs.trackCount == rhs.trackCount) &&
(lhs.genre == rhs.genre) && (lhs.artistName == rhs.artistName) &&
(lhs.releaseDate == rhs.releaseDate)
}
extension Album: Hashable {
var hashValue: Int {
return self.artistName.hashValue ^ self.genre.hashValue ^ self.name.hashValue ^ self.releaseDate.hashValue ^ self.trackCount.hashValue
}
}
func ==(lhs: Artist, rhs: Artist) -> Bool {
return (lhs.name == rhs.name) && (lhs.id == rhs.id) && (lhs.albums == rhs.albums)
}
extension Artist: Hashable {
var hashValue: Int {
return self.name.hashValue ^ self.id.hashValue ^ self.albums.count.hashValue
}
}
| c8118dff30aaef889432e8d098781bb3 | 28.082707 | 142 | 0.558428 | false | false | false | false |
pksprojects/ElasticSwift | refs/heads/master | Sources/ElasticSwiftCore/Http/HTTPResponse.swift | mit | 1 | //
// HTTPResponse.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 6/16/19.
//
import Foundation
import Logging
import NIOHTTP1
// MARK: - HTTPResponse
/// Represents a HTTPResponse returned from Elasticsearch
public struct HTTPResponse {
public let request: HTTPRequest
public let status: HTTPResponseStatus
public let headers: HTTPHeaders
public var body: Data?
public init(request: HTTPRequest, status: HTTPResponseStatus, headers: HTTPHeaders, body: Data?) {
self.status = status
self.headers = headers
self.body = body
self.request = request
}
internal init(withBuilder builder: HTTPResponseBuilder) throws {
guard builder.request != nil else {
throw HTTPResponseBuilderError.missingRequiredField("request")
}
guard builder.headers != nil else {
throw HTTPResponseBuilderError.missingRequiredField("headers")
}
guard builder.status != nil else {
throw HTTPResponseBuilderError.missingRequiredField("status")
}
self.init(request: builder.request!, status: builder.status!, headers: builder.headers!, body: builder.body)
}
}
extension HTTPResponse: Equatable {}
// MARK: - HTTPResponseBuilder
/// Builder for `HTTPResponse`
public class HTTPResponseBuilder {
private var _request: HTTPRequest?
private var _status: HTTPResponseStatus?
private var _headers: HTTPHeaders?
private var _body: Data?
public init() {}
@discardableResult
public func set(headers: HTTPHeaders) -> HTTPResponseBuilder {
_headers = headers
return self
}
@discardableResult
public func set(request: HTTPRequest) -> HTTPResponseBuilder {
_request = request
return self
}
@discardableResult
public func set(status: HTTPResponseStatus) -> HTTPResponseBuilder {
_status = status
return self
}
@discardableResult
public func set(body: Data) -> HTTPResponseBuilder {
_body = body
return self
}
public var request: HTTPRequest? {
return _request
}
public var status: HTTPResponseStatus? {
return _status
}
public var headers: HTTPHeaders? {
return _headers
}
public var body: Data? {
return _body
}
public func build() throws -> HTTPResponse {
return try HTTPResponse(withBuilder: self)
}
}
// MARK: - HTTPResponseStatus
/// Helper extention for HTTPResponseStatus
public extension HTTPResponseStatus {
func is1xxInformational() -> Bool {
return code >= 100 && code < 200
}
func is2xxSuccessful() -> Bool {
return code >= 200 && code < 300
}
func is3xxRedirection() -> Bool {
return code >= 300 && code < 400
}
func is4xxClientError() -> Bool {
return code >= 400 && code < 500
}
func is5xxServerError() -> Bool {
return code >= 500 && code < 600
}
func isError() -> Bool {
return is4xxClientError() || is5xxServerError()
}
}
| 27399f1e2fd8fb0efdf87254f31038cb | 22.687023 | 116 | 0.638737 | false | false | false | false |
Chris-Perkins/Lifting-Buddy | refs/heads/master | Lifting Buddy/WorkoutSessionTableViewCell.swift | mit | 1 | //
// WorkoutSessionTableViewCell.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 9/10/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import Realm
import RealmSwift
class WorkoutSessionTableViewCell: UITableViewCell {
// MARK: View properties
// Padding between views
private static let viewPadding: CGFloat = 15.0
// IndexPath of this cell in the tableview
public var indexPath: IndexPath?
// Delegate we use to change height of cells
public var delegate: WorkoutSessionTableViewCellDelegate?
// The delegate we use to indicate that a cell was deleted
public var deletionDelegate: CellDeletionDelegate?
// Delegate we inform where to scroll
public var scrollDelegate: UITableViewScrollDelegate?
// the button we press to toggle this cell. It's invisible (basically)
private let invisButton: UIButton
// The button indicating we can expand this cell
public let expandImage: UIImageView
// the title of this cell, holds the title of the exercise name
public let cellTitle: UILabel
// Cell contents on expand
public let setLabel: UILabel
// add a set to the table
public let addSetButton: PrettyButton
// The actual table view where we input data
public let setTableView: SetTableView
// The height of our tableview
private var tableViewHeightConstraint: NSLayoutConstraint?
// Exercise assigned to this cell
private var exercise: Exercise
// Whether or not this exercise is complete
private var isComplete: Bool
// Whether or not this view is toggled
public var isToggled: Bool
// The current set we're doing
private var curSet: Int
// MARK: Init Functions
init(exercise: Exercise, style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
self.exercise = exercise
invisButton = UIButton()
cellTitle = UILabel()
expandImage = UIImageView(image: #imageLiteral(resourceName: "DownArrow"))
setLabel = UILabel()
addSetButton = PrettyButton()
setTableView = SetTableView(forExercise: exercise)
// Initialize to minimum height of the cell label + the viewPadding associated
// between the two views.
curSet = 0
isComplete = false
isToggled = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(invisButton)
addSubview(expandImage)
addSubview(cellTitle)
addSubview(setTableView)
addSubview(addSetButton)
createAndActivateInvisButtonConstraints()
createAndActivateExpandImageConstraints()
createAndActivateCellTitleConstraints()
createAndActivateAddSetButtonConstraints()
createAndActivateSetTableViewConstraints()
invisButton.addTarget( self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
addSetButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
setTableView.completedSetCountDelegate = self
setTableView.cellDeletionDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View overrides
override func layoutSubviews() {
super.layoutSubviews()
// Checks if it's safe to use exercise. Otherwise, delete this cell
if exercise.isInvalidated {
self.deletionDelegate?.deleteData(at: indexPath!.row)
}
// Self stuff
selectionStyle = .none
clipsToBounds = true
// Invis Button
// Invis Button has to be "visible" to be pressed. So, 0.001
invisButton.backgroundColor = UIColor.lightGray.withAlphaComponent(0.001)
// Cell Title
curSet = setTableView.completedSetCount
let reqSet = exercise.getSetCount()
/*
* Text depends on whether or not we have a required set amount.
* If we do, a format example is [1/2]
* If we don't, the same example is [1]
*/
cellTitle.text = reqSet > 0 ?
"[\(curSet)/\(reqSet)] \(exercise.getName()!)":
"[\(curSet)] \(exercise.getName()!)"
cellTitle.font = UIFont.boldSystemFont(ofSize: 18.0)
// Add Set button
addSetButton.setDefaultProperties()
addSetButton.setTitle(NSLocalizedString("SessionView.Button.AddSet", comment: ""), for: .normal)
// Exercisehistory table
setTableView.isScrollEnabled = false
// Different states for whether the cell is complete or not.
// If complete: cell turns green, title color turns white to be visible.
// If not complete: Cell is white
if isComplete {
backgroundColor = UIColor.niceGreen.withAlphaComponent(0.75)
cellTitle.textColor = .white
} else {
backgroundColor = .primaryBlackWhiteColor
cellTitle.textColor = .niceBlue
}
updateCompleteStatus()
}
// MARK: View functions
// Sets the exercise for this cell
public func setExercise(_ exercise: Exercise) {
self.exercise = exercise
}
// Update the complete status (call when some value changed)
public func updateCompleteStatus() {
let newComplete = setTableView.completedSetCount >= exercise.getSetCount()
// We updated our completed status! So inform the delegate.
if newComplete != isComplete {
isComplete = newComplete
delegate?.cellCompleteStatusChanged(complete: isComplete)
// We only display the message if the exercise is complete and > 0 sets to do
if isComplete && exercise.getSetCount() != 0 {
MessageQueue.shared.append(Message(type: .exerciseComplete,
identifier: exercise.getName(),
value: nil))
}
layoutSubviews()
} else if curSet != setTableView.completedSetCount {
layoutSubviews()
}
}
// Changes whether or not this cell is toggled
public func updateToggledStatus() {
if indexPath != nil {
delegate?.cellHeightDidChange(height: getHeight(),
indexPath: indexPath!)
expandImage.transform = CGAffineTransform(scaleX: 1,
y: isToggled ? -1 : 1)
}
}
// gets the height of this cell when expanded or hidden
private func getHeight() -> CGFloat {
if isToggled {
// total padding for this view. Incremement by one per each "cell" of this view
var totalPadding = 0
let titleBarHeight = UITableViewCell.defaultHeight
let addSetButtonHeight = PrettyButton.defaultHeight
let totalTableViewHeight = tableViewHeightConstraint!.constant
totalPadding += 1
return titleBarHeight + totalTableViewHeight + addSetButtonHeight +
CGFloat(totalPadding) * WorkoutSessionTableViewCell.viewPadding
} else {
return UITableViewCell.defaultHeight
}
}
// Should be called whenever the height constraint may change
public func heightConstraintConstantCouldChange() {
if let tableViewHeightConstraint = tableViewHeightConstraint
{
tableViewHeightConstraint.constant = setTableView.getHeight()
delegate?.cellHeightDidChange(height: getHeight(), indexPath: indexPath!)
UIView.animate(withDuration: 0.25, animations: {
self.layoutIfNeeded()
})
}
}
// MARK: Event functions
// Generic button press event
@objc private func buttonPress(sender: UIButton) {
switch(sender) {
case invisButton:
isToggled = !isToggled
updateToggledStatus()
scrollDelegate?.scrollToCell(atIndexPath: indexPath!,
position: .top, animated: false)
case addSetButton:
setTableView.appendDataPiece(ExerciseHistoryEntry())
heightConstraintConstantCouldChange()
// Don't animate as we would cause the tableview to scroll way down every time.
// that's bad.
scrollDelegate?.scrollToCell(atIndexPath: indexPath!,
position: .bottom, animated: false)
default:
fatalError("Button pressed did not exist?")
}
}
// MARK: Encapsulated methods
// Returns whether or not this exercise is complete (did all sets)
public func getIsComplete() -> Bool {
return isComplete
}
// MARK: Constraints
// Cling to top, left, right of self ; height default
private func createAndActivateInvisButtonConstraints() {
invisButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: invisButton,
height: UITableViewCell.defaultHeight
).isActive = true
}
// Place below view top, cling to left, right ; height of default height
private func createAndActivateCellTitleConstraints() {
cellTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .left,
plusConstant: 10).isActive = true
NSLayoutConstraint(item: expandImage,
attribute: .left,
relatedBy: .equal,
toItem: cellTitle,
attribute: .right,
multiplier: 1,
constant: 10).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitle,
height: UITableViewCell.defaultHeight).isActive = true
}
// Cling to top, right ; height 8.46 ; width 16
private func createAndActivateExpandImageConstraints() {
expandImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .top,
plusConstant: 20.77).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .right,
plusConstant: -10).isActive = true
NSLayoutConstraint.createWidthConstraintForView(view: expandImage,
width: 16).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: expandImage,
height: 8.46).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitle,
height: UITableViewCell.defaultHeight
).isActive = true
}
// center horiz to self ; width of addset ; place below addset ; height of tableviewheight
private func createAndActivateSetTableViewConstraints() {
setTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: setTableView,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: setTableView,
withCopyView: self,
attribute: .width).isActive = true
NSLayoutConstraint.createViewBelowViewConstraint(view: setTableView,
belowView: cellTitle,
withPadding: WorkoutSessionTableViewCell.viewPadding
).isActive = true
tableViewHeightConstraint =
NSLayoutConstraint.createHeightConstraintForView(view: setTableView,
height: 0)
tableViewHeightConstraint!.isActive = true
}
// Place below the input content view
private func createAndActivateAddSetButtonConstraints() {
addSetButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: addSetButton,
withCopyView: self,
attribute: .centerX).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: addSetButton,
withCopyView: setTableView,
attribute: .width).isActive = true
NSLayoutConstraint.createViewBelowViewConstraint(view: addSetButton,
belowView: setTableView).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: addSetButton,
height: PrettyButton.defaultHeight).isActive = true
}
}
// MARK: HistoryEntryDelegate Extension
extension WorkoutSessionTableViewCell: ExerciseHistoryEntryTableViewDelegate {
// Called when a cell is deleted
func dataDeleted(deletedData: ExerciseHistoryEntry) {
exercise.removeExerciseHistoryEntry(deletedData)
heightConstraintConstantCouldChange()
updateCompleteStatus()
}
}
// MARK: SetTableViewDelegate
extension WorkoutSessionTableViewCell: SetTableViewDelegate {
func completedSetCountChanged() {
updateCompleteStatus()
}
}
extension WorkoutSessionTableViewCell: CellDeletionDelegate {
func deleteData(at index: Int) {
tableViewHeightConstraint?.constant -= SetTableViewCell.getHeight(forExercise: exercise)
heightConstraintConstantCouldChange()
scrollDelegate?.scrollToCell(atIndexPath: indexPath!, position: .none, animated: false)
}
}
| 4fdad081b45b18d81e326f7432abb08f | 42.23822 | 111 | 0.567234 | false | false | false | false |
TheBudgeteers/CartTrackr | refs/heads/master | CartTrackr/Carthage/Checkouts/SwiftyCam/Source/SwiftyCamViewController.swift | mit | 1 | /*Copyright (c) 2016, Andrew Walz.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AVFoundation
// MARK: View Controller Declaration
/// A UIViewController Camera View Subclass
open class SwiftyCamViewController: UIViewController {
// MARK: Enumeration Declaration
/// Enumeration for Camera Selection
public enum CameraSelection {
/// Camera on the back of the device
case rear
/// Camera on the front of the device
case front
}
/// Enumeration for video quality of the capture session. Corresponds to a AVCaptureSessionPreset
public enum VideoQuality {
/// AVCaptureSessionPresetHigh
case high
/// AVCaptureSessionPresetMedium
case medium
/// AVCaptureSessionPresetLow
case low
/// AVCaptureSessionPreset352x288
case resolution352x288
/// AVCaptureSessionPreset640x480
case resolution640x480
/// AVCaptureSessionPreset1280x720
case resolution1280x720
/// AVCaptureSessionPreset1920x1080
case resolution1920x1080
/// AVCaptureSessionPreset3840x2160
case resolution3840x2160
/// AVCaptureSessionPresetiFrame960x540
case iframe960x540
/// AVCaptureSessionPresetiFrame1280x720
case iframe1280x720
}
/**
Result from the AVCaptureSession Setup
- success: success
- notAuthorized: User denied access to Camera of Microphone
- configurationFailed: Unknown error
*/
fileprivate enum SessionSetupResult {
case success
case notAuthorized
case configurationFailed
}
// MARK: Public Variable Declarations
/// Public Camera Delegate for the Custom View Controller Subclass
public var cameraDelegate: SwiftyCamViewControllerDelegate?
/// Maxiumum video duration if SwiftyCamButton is used
public var maximumVideoDuration : Double = 0.0
/// Video capture quality
public var videoQuality : VideoQuality = .high
/// Sets whether flash is enabled for photo and video capture
public var flashEnabled = false
/// Sets whether Pinch to Zoom is enabled for the capture session
public var pinchToZoom = true
/// Sets the maximum zoom scale allowed during Pinch gesture
public var maxZoomScale = CGFloat(4.0)
/// Sets whether Tap to Focus and Tap to Adjust Exposure is enabled for the capture session
public var tapToFocus = true
/// Sets whether the capture session should adjust to low light conditions automatically
///
/// Only supported on iPhone 5 and 5C
public var lowLightBoost = true
/// Set whether SwiftyCam should allow background audio from other applications
public var allowBackgroundAudio = true
/// Sets whether a double tap to switch cameras is supported
public var doubleTapCameraSwitch = true
/// Set default launch camera
public var defaultCamera = CameraSelection.rear
/// Sets wether the taken photo or video should be oriented according to the device orientation
public var shouldUseDeviceOrientation = false
// MARK: Public Get-only Variable Declarations
/// Returns true if video is currently being recorded
private(set) public var isVideoRecording = false
/// Returns true if the capture session is currently running
private(set) public var isSessionRunning = false
/// Returns the CameraSelection corresponding to the currently utilized camera
private(set) public var currentCamera = CameraSelection.rear
// MARK: Private Constant Declarations
/// Current Capture Session
fileprivate let session = AVCaptureSession()
/// Serial queue used for setting up session
fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: [])
// MARK: Private Variable Declarations
/// Variable for storing current zoom scale
fileprivate var zoomScale = CGFloat(1.0)
/// Variable for storing initial zoom scale before Pinch to Zoom begins
fileprivate var beginZoomScale = CGFloat(1.0)
/// Returns true if the torch (flash) is currently enabled
fileprivate var isCameraTorchOn = false
/// Variable to store result of capture session setup
fileprivate var setupResult = SessionSetupResult.success
/// BackgroundID variable for video recording
fileprivate var backgroundRecordingID : UIBackgroundTaskIdentifier? = nil
/// Video Input variable
fileprivate var videoDeviceInput : AVCaptureDeviceInput!
/// Movie File Output variable
fileprivate var movieFileOutput : AVCaptureMovieFileOutput?
/// Photo File Output variable
fileprivate var photoFileOutput : AVCaptureStillImageOutput?
/// Video Device variable
fileprivate var videoDevice : AVCaptureDevice?
/// PreviewView for the capture session
fileprivate var previewLayer : PreviewView!
/// UIView for front facing flash
fileprivate var flashView : UIView?
/// Last changed orientation
fileprivate var deviceOrientation : UIDeviceOrientation?
/// Disable view autorotation for forced portrait recorindg
override open var shouldAutorotate: Bool {
return false
}
// MARK: ViewDidLoad
/// ViewDidLoad Implementation
override open func viewDidLoad() {
super.viewDidLoad()
previewLayer = PreviewView(frame: self.view.frame)
// Add Gesture Recognizers
addGestureRecognizersTo(view: previewLayer)
self.view.addSubview(previewLayer)
previewLayer.session = session
// Test authorization status for Camera and Micophone
switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo){
case .authorized:
// already authorized
break
case .notDetermined:
// not yet determined
sessionQueue.suspend()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in
if !granted {
self.setupResult = .notAuthorized
}
self.sessionQueue.resume()
})
default:
// already been asked. Denied access
setupResult = .notAuthorized
}
sessionQueue.async { [unowned self] in
self.configureSession()
}
}
// MARK: ViewDidAppear
/// ViewDidAppear(_ animated:) Implementation
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Subscribe to device rotation notifications
if shouldUseDeviceOrientation {
subscribeToDeviceOrientationChangeNotifications()
}
// Set background audio preference
setBackgroundAudioPreference()
sessionQueue.async {
switch self.setupResult {
case .success:
// Begin Session
self.session.startRunning()
self.isSessionRunning = self.session.isRunning
case .notAuthorized:
// Prompt to App Settings
self.promptToAppSettings()
case .configurationFailed:
// Unknown Error
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
})
}
}
}
// MARK: ViewDidDisappear
/// ViewDidDisappear(_ animated:) Implementation
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If session is running, stop the session
if self.isSessionRunning == true {
self.session.stopRunning()
self.isSessionRunning = false
}
//Disble flash if it is currently enabled
disableFlash()
// Unsubscribe from device rotation notifications
if shouldUseDeviceOrientation {
unsubscribeFromDeviceOrientationChangeNotifications()
}
}
// MARK: Public Functions
/**
Capture photo from current session
UIImage will be returned with the SwiftyCamViewControllerDelegate function SwiftyCamDidTakePhoto(photo:)
*/
public func takePhoto() {
guard let device = videoDevice else {
return
}
if device.hasFlash == true && flashEnabled == true /* TODO: Add Support for Retina Flash and add front flash */ {
changeFlashSettings(device: device, mode: .on)
capturePhotoAsyncronously(completionHandler: { (_) in })
} else if device.hasFlash == false && flashEnabled == true && currentCamera == .front {
flashView = UIView(frame: view.frame)
flashView?.alpha = 0.0
flashView?.backgroundColor = UIColor.white
previewLayer.addSubview(flashView!)
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 1.0
}, completion: { (_) in
self.capturePhotoAsyncronously(completionHandler: { (success) in
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 0.0
}, completion: { (_) in
self.flashView?.removeFromSuperview()
})
})
})
} else {
if device.isFlashActive == true {
changeFlashSettings(device: device, mode: .off)
}
capturePhotoAsyncronously(completionHandler: { (_) in })
}
}
/**
Begin recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called
*/
public func startVideoRecording() {
guard let movieFileOutput = self.movieFileOutput else {
return
}
if currentCamera == .rear && flashEnabled == true {
enableFlash()
}
if currentCamera == .front && flashEnabled == true {
flashView = UIView(frame: view.frame)
flashView?.backgroundColor = UIColor.white
flashView?.alpha = 0.85
previewLayer.addSubview(flashView!)
}
sessionQueue.async { [unowned self] in
if !movieFileOutput.isRecording {
if UIDevice.current.isMultitaskingSupported {
self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
}
// Update the orientation on the movie file output video connection before starting recording.
let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo)
//flip video output if front facing camera is selected
if self.currentCamera == .front {
movieFileOutputConnection?.isVideoMirrored = true
}
movieFileOutputConnection?.videoOrientation = self.getVideoOrientation()
// Start recording to a temporary file.
let outputFileName = UUID().uuidString
let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)
self.isVideoRecording = true
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera)
}
}
else {
movieFileOutput.stopRecording()
}
}
}
/**
Stop video recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidFinishRecordingVideo() will be called
When video has finished processing, the URL to the video location will be returned by SwiftyCamDidFinishProcessingVideoAt(url:)
*/
public func stopVideoRecording() {
if self.movieFileOutput?.isRecording == true {
self.isVideoRecording = false
movieFileOutput!.stopRecording()
disableFlash()
if currentCamera == .front && flashEnabled == true && flashView != nil {
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 0.0
}, completion: { (_) in
self.flashView?.removeFromSuperview()
})
}
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishRecordingVideo: self.currentCamera)
}
}
}
/**
Switch between front and rear camera
SwiftyCamViewControllerDelegate function SwiftyCamDidSwitchCameras(camera: will be return the current camera selection
*/
public func switchCamera() {
guard isVideoRecording != true else {
//TODO: Look into switching camera during video recording
print("[SwiftyCam]: Switching between cameras while recording video is not supported")
return
}
switch currentCamera {
case .front:
currentCamera = .rear
case .rear:
currentCamera = .front
}
session.stopRunning()
sessionQueue.async { [unowned self] in
// remove and re-add inputs and outputs
for input in self.session.inputs {
self.session.removeInput(input as! AVCaptureInput)
}
self.addInputs()
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didSwitchCameras: self.currentCamera)
}
self.session.startRunning()
}
// If flash is enabled, disable it as the torch is needed for front facing camera
disableFlash()
}
// MARK: Private Functions
/// Configure session, add inputs and outputs
fileprivate func configureSession() {
guard setupResult == .success else {
return
}
// Set default camera
currentCamera = defaultCamera
// begin configuring session
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
configureVideoOutput()
configurePhotoOutput()
session.commitConfiguration()
}
/// Add inputs after changing camera()
fileprivate func addInputs() {
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
session.commitConfiguration()
}
// Front facing camera will always be set to VideoQuality.high
// If set video quality is not supported, videoQuality variable will be set to VideoQuality.high
/// Configure image quality preset
fileprivate func configureVideoPreset() {
if currentCamera == .front {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high)
} else {
if session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)) {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: videoQuality)
} else {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high)
}
}
}
/// Add Video Inputs
fileprivate func addVideoInput() {
switch currentCamera {
case .front:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .front)
case .rear:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .back)
}
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
if device.isSmoothAutoFocusSupported {
device.isSmoothAutoFocusEnabled = true
}
}
if device.isExposureModeSupported(.continuousAutoExposure) {
device.exposureMode = .continuousAutoExposure
}
if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
device.whiteBalanceMode = .continuousAutoWhiteBalance
}
if device.isLowLightBoostSupported && lowLightBoost == true {
device.automaticallyEnablesLowLightBoostWhenAvailable = true
}
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
do {
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
print("[SwiftyCam]: Could not add video device input to the session")
print(session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)))
setupResult = .configurationFailed
session.commitConfiguration()
return
}
} catch {
print("[SwiftyCam]: Could not create video device input: \(error)")
setupResult = .configurationFailed
return
}
}
/// Add Audio Inputs
fileprivate func addAudioInput() {
do {
let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if session.canAddInput(audioDeviceInput) {
session.addInput(audioDeviceInput)
}
else {
print("[SwiftyCam]: Could not add audio device input to the session")
}
}
catch {
print("[SwiftyCam]: Could not create audio device input: \(error)")
}
}
/// Configure Movie Output
fileprivate func configureVideoOutput() {
let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
self.session.addOutput(movieFileOutput)
if let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo) {
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
}
self.movieFileOutput = movieFileOutput
}
}
/// Configure Photo Output
fileprivate func configurePhotoOutput() {
let photoFileOutput = AVCaptureStillImageOutput()
if self.session.canAddOutput(photoFileOutput) {
photoFileOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
self.session.addOutput(photoFileOutput)
self.photoFileOutput = photoFileOutput
}
}
/// Orientation management
fileprivate func subscribeToDeviceOrientationChangeNotifications() {
self.deviceOrientation = UIDevice.current.orientation
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
fileprivate func unsubscribeFromDeviceOrientationChangeNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
self.deviceOrientation = nil
}
@objc fileprivate func deviceDidRotate() {
if !UIDevice.current.orientation.isFlat {
self.deviceOrientation = UIDevice.current.orientation
}
}
fileprivate func getVideoOrientation() -> AVCaptureVideoOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return previewLayer!.videoPreviewLayer.connection.videoOrientation }
switch deviceOrientation {
case .landscapeLeft:
return .landscapeRight
case .landscapeRight:
return .landscapeLeft
case .portraitUpsideDown:
return .portraitUpsideDown
default:
return .portrait
}
}
fileprivate func getImageOrientation(forCamera: CameraSelection) -> UIImageOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return forCamera == .rear ? .right : .leftMirrored }
switch deviceOrientation {
case .landscapeLeft:
return forCamera == .rear ? .up : .downMirrored
case .landscapeRight:
return forCamera == .rear ? .down : .upMirrored
case .portraitUpsideDown:
return forCamera == .rear ? .left : .rightMirrored
default:
return forCamera == .rear ? .right : .leftMirrored
}
}
/**
Returns a UIImage from Image Data.
- Parameter imageData: Image Data returned from capturing photo from the capture session.
- Returns: UIImage from the image data, adjusted for proper orientation.
*/
fileprivate func processPhoto(_ imageData: Data) -> UIImage {
let dataProvider = CGDataProvider(data: imageData as CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
// Set proper orientation for photo
// If camera is currently set to front camera, flip image
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.currentCamera))
return image
}
fileprivate func capturePhotoAsyncronously(completionHandler: @escaping(Bool) -> ()) {
if let videoConnection = photoFileOutput?.connection(withMediaType: AVMediaTypeVideo) {
photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let image = self.processPhoto(imageData!)
// Call delegate and return new image
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didTake: image)
}
completionHandler(true)
} else {
completionHandler(false)
}
})
} else {
completionHandler(false)
}
}
/// Handle Denied App Privacy Settings
fileprivate func promptToAppSettings() {
// prompt User with UIAlertView
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in
if #available(iOS 10.0, *) {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
} else {
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
}))
self.present(alertController, animated: true, completion: nil)
})
}
/**
Returns an AVCapturePreset from VideoQuality Enumeration
- Parameter quality: ViewQuality enum
- Returns: String representing a AVCapturePreset
*/
fileprivate func videoInputPresetFromVideoQuality(quality: VideoQuality) -> String {
switch quality {
case .high: return AVCaptureSessionPresetHigh
case .medium: return AVCaptureSessionPresetMedium
case .low: return AVCaptureSessionPresetLow
case .resolution352x288: return AVCaptureSessionPreset352x288
case .resolution640x480: return AVCaptureSessionPreset640x480
case .resolution1280x720: return AVCaptureSessionPreset1280x720
case .resolution1920x1080: return AVCaptureSessionPreset1920x1080
case .iframe960x540: return AVCaptureSessionPresetiFrame960x540
case .iframe1280x720: return AVCaptureSessionPresetiFrame1280x720
case .resolution3840x2160:
if #available(iOS 9.0, *) {
return AVCaptureSessionPreset3840x2160
}
else {
print("[SwiftyCam]: Resolution 3840x2160 not supported")
return AVCaptureSessionPresetHigh
}
}
}
/// Get Devices
fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
if let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] {
return devices.filter({ $0.position == position }).first
}
return nil
}
/// Enable or disable flash for photo
fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) {
do {
try device.lockForConfiguration()
device.flashMode = mode
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
/// Enable flash
fileprivate func enableFlash() {
if self.isCameraTorchOn == false {
toggleFlash()
}
}
/// Disable flash
fileprivate func disableFlash() {
if self.isCameraTorchOn == true {
toggleFlash()
}
}
/// Toggles between enabling and disabling flash
fileprivate func toggleFlash() {
guard self.currentCamera == .rear else {
// Flash is not supported for front facing camera
return
}
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// Check if device has a flash
if (device?.hasTorch)! {
do {
try device?.lockForConfiguration()
if (device?.torchMode == AVCaptureTorchMode.on) {
device?.torchMode = AVCaptureTorchMode.off
self.isCameraTorchOn = false
} else {
do {
try device?.setTorchModeOnWithLevel(1.0)
self.isCameraTorchOn = true
} catch {
print("[SwiftyCam]: \(error)")
}
}
device?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
}
/// Sets whether SwiftyCam should enable background audio from other applications or sources
fileprivate func setBackgroundAudioPreference() {
guard allowBackgroundAudio == true else {
return
}
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord,
with: [.duckOthers, .defaultToSpeaker])
session.automaticallyConfiguresApplicationAudioSession = false
}
catch {
print("[SwiftyCam]: Failed to set background audio preference")
}
}
}
extension SwiftyCamViewController : SwiftyCamButtonDelegate {
/// Sets the maximum duration of the SwiftyCamButton
public func setMaxiumVideoDuration() -> Double {
return maximumVideoDuration
}
/// Set UITapGesture to take photo
public func buttonWasTapped() {
takePhoto()
}
/// Set UILongPressGesture start to begin video
public func buttonDidBeginLongPress() {
startVideoRecording()
}
/// Set UILongPressGesture begin to begin end video
public func buttonDidEndLongPress() {
stopVideoRecording()
}
/// Called if maximum duration is reached
public func longPressDidReachMaximumDuration() {
stopVideoRecording()
}
}
// MARK: AVCaptureFileOutputRecordingDelegate
extension SwiftyCamViewController : AVCaptureFileOutputRecordingDelegate {
/// Process newly captured video and write it to temporary directory
public func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
if let currentBackgroundRecordingID = backgroundRecordingID {
backgroundRecordingID = UIBackgroundTaskInvalid
if currentBackgroundRecordingID != UIBackgroundTaskInvalid {
UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
}
}
if error != nil {
print("[SwiftyCam]: Movie file finishing error: \(error)")
} else {
//Call delegate function with the URL of the outputfile
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishProcessVideoAt: outputFileURL)
}
}
}
}
// Mark: UIGestureRecognizer Declarations
extension SwiftyCamViewController {
/// Handle pinch gesture
@objc fileprivate func zoomGesture(pinch: UIPinchGestureRecognizer) {
guard pinchToZoom == true && self.currentCamera == .rear else {
//ignore pinch if pinchToZoom is set to false
return
}
do {
let captureDevice = AVCaptureDevice.devices().first as? AVCaptureDevice
try captureDevice?.lockForConfiguration()
zoomScale = min(maxZoomScale, max(1.0, min(beginZoomScale * pinch.scale, captureDevice!.activeFormat.videoMaxZoomFactor)))
captureDevice?.videoZoomFactor = zoomScale
// Call Delegate function with current zoom scale
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale)
}
captureDevice?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
/// Handle single tap gesture
@objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) {
guard tapToFocus == true else {
// Ignore taps
return
}
let screenSize = previewLayer!.bounds.size
let tapPoint = tap.location(in: previewLayer!)
let x = tapPoint.y / screenSize.height
let y = 1.0 - tapPoint.x / screenSize.width
let focusPoint = CGPoint(x: x, y: y)
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported == true {
device.focusPointOfInterest = focusPoint
device.focusMode = .autoFocus
}
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device.unlockForConfiguration()
//Call delegate function and pass in the location of the touch
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFocusAtPoint: tapPoint)
}
}
catch {
// just ignore
}
}
}
/// Handle double tap gesture
@objc fileprivate func doubleTapGesture(tap: UITapGestureRecognizer) {
guard doubleTapCameraSwitch == true else {
return
}
switchCamera()
}
/**
Add pinch gesture recognizer and double tap gesture recognizer to currentView
- Parameter view: View to add gesture recognzier
*/
fileprivate func addGestureRecognizersTo(view: UIView) {
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(zoomGesture(pinch:)))
pinchGesture.delegate = self
view.addGestureRecognizer(pinchGesture)
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.delegate = self
view.addGestureRecognizer(singleTapGesture)
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture(tap:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.delegate = self
view.addGestureRecognizer(doubleTapGesture)
}
}
// MARK: UIGestureRecognizerDelegate
extension SwiftyCamViewController : UIGestureRecognizerDelegate {
/// Set beginZoomScale when pinch begins
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) {
beginZoomScale = zoomScale;
}
return true
}
}
| 6a5b985e2aad77ab75de71d8e1eb7e30 | 27.868101 | 189 | 0.740797 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers_2_fixed/0019-rdar21511651.swift | apache-2.0 | 10 | // RUN: not %target-swift-frontend %s -parse
internal protocol _SequenceWrapperType {
typealias Base : SequenceType
typealias Generator : GeneratorType = Base.Generator
var _base: Base {get}
}
extension SequenceType
where Self : _SequenceWrapperType, Self.Generator == Self.Base.Generator {
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> Base.Generator {
return self._base.generate()
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
public func _customContainsEquatableElement(
element: Base.Generator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(preprocess: (Self)->R) -> R? {
return _base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Generator.Element> {
return _base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _initializeTo(ptr: UnsafeMutablePointer<Base.Generator.Element>) {
return _base._initializeTo(ptr)
}
}
internal protocol _CollectionWrapperType : _SequenceWrapperType {
typealias Base : CollectionType
typealias Index : ForwardIndexType = Base.Index
var _base: Base {get}
}
extension CollectionType
where Self : _CollectionWrapperType, Self.Index == Self.Base.Index {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Generator.Element {
return _base[position]
}
}
//===--- New stuff --------------------------------------------------------===//
public protocol _prext_LazySequenceType : SequenceType {
/// A SequenceType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazySequence` layer.
typealias Elements: SequenceType = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing a `_prext_LazySequence`
/// layer.
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements {get}
/// An Array, created on-demand, containing the elements of this
/// lazy SequenceType.
///
/// Note: this property need not be implemented by conforming types, it has a
/// default implementation in a protocol extension.
var array: [Generator.Element] {get}
}
extension _prext_LazySequenceType {
/// an Array, created on-demand, containing the elements of this
/// lazy SequenceType.
public var array: [Generator.Element] {
return Array(self)
}
}
extension _prext_LazySequenceType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazySequenceType where Self : _SequenceWrapperType {
public var elements: Base { return _base }
}
/// A sequence that forwards its implementation to an underlying
/// sequence instance while exposing lazy computations as methods.
public struct _prext_LazySequence<Base_ : SequenceType> : _SequenceWrapperType {
var _base: Base_
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<S : SequenceType>(s: S) -> _prext_LazySequence<S> {
return _prext_LazySequence(_base: s)
}
public extension SequenceType
where Self.Generator == Self, Self : GeneratorType {
public func generate() -> Self {
return self
}
}
//===--- LazyCollection.swift ---------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
public protocol _prext_LazyCollectionType : CollectionType, _prext_LazySequenceType {
/// A CollectionType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazyCollection` layer.
typealias Elements: CollectionType = Self
}
extension _prext_LazyCollectionType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazyCollectionType where Self : _CollectionWrapperType {
public var elements: Base { return _base }
}
/// A collection that forwards its implementation to an underlying
/// collection instance while exposing lazy computations as methods.
public struct _prext_LazyCollection<Base_ : CollectionType>
: /*_prext_LazyCollectionType,*/ _CollectionWrapperType {
typealias Base = Base_
typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
public init(_ base: Base_) {
self._base = base
}
public var _base: Base_
// FIXME: Why is this needed?
// public var elements: Base { return _base }
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<Base: CollectionType>(s: Base) -> _prext_LazyCollection<Base> {
return _prext_LazyCollection(s)
}
//===--- New stuff --------------------------------------------------------===//
/// The `GeneratorType` used by `_prext_MapSequence` and `_prext_MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `GeneratorType` through a transform function returning `T`.
public struct _prext_MapGenerator<
Base: GeneratorType, T
> : GeneratorType, SequenceType {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
let x = _base.next()
if x != nil {
return _transform(x!)
}
return nil
}
var _base: Base
var _transform: (Base.Element)->T
}
//===--- Sequences --------------------------------------------------------===//
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapSequence<Base : SequenceType, T>
: _prext_LazySequenceType, _SequenceWrapperType {
typealias Elements = _prext_MapSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator,T> {
return _prext_MapGenerator(
_base: _base.generate(), _transform: _transform)
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapCollection<Base : CollectionType, T>
: _prext_LazyCollectionType, _CollectionWrapperType {
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> T {
return _transform(_base[position])
}
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator, T> {
return _prext_MapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Support for lazy(s) ----------------------------------------------===//
extension _prext_LazySequenceType {
/// Return a `_prext_MapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapSequence<Self.Elements, U> {
return _prext_MapSequence(_base: self.elements, _transform: transform)
}
}
extension _prext_LazyCollectionType {
/// Return a `_prext_MapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapCollection<Self.Elements, U> {
return _prext_MapCollection(_base: self.elements, _transform: transform)
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
//===--- New stuff --------------------------------------------------------===//
internal protocol __prext_ReverseCollectionType : _prext_LazyCollectionType {
typealias Base : CollectionType
var _base : Base {get}
}
/// A wrapper for a `BidirectionalIndexType` that reverses its
/// direction of traversal.
public struct _prext_ReverseIndex<I : BidirectionalIndexType> : BidirectionalIndexType {
var _base: I
init(_ _base: I) { self._base = _base }
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
public func successor() -> _prext_ReverseIndex {
return _prext_ReverseIndex(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Requires: The previous value is representable.
public func predecessor() -> _prext_ReverseIndex {
return _prext_ReverseIndex(_base.successor())
}
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseIndex` values where one value is reachable from the other.
typealias Distance = I.Distance
}
/// A wrapper for a `${IndexProtocol}` that reverses its
/// direction of traversal.
public struct _prext_ReverseRandomAccessIndex<I : RandomAccessIndexType> : RandomAccessIndexType {
var _base: I
init(_ _base: I) { self._base = _base }
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
public func successor() -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Requires: The previous value is representable.
public func predecessor() -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.successor())
}
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseRandomAccessIndex` values where one value is reachable from the other.
typealias Distance = I.Distance
/// Return the minimum number of applications of `successor` or
/// `predecessor` required to reach `other` from `self`.
///
/// - Complexity: O(1).
public func distanceTo(other: _prext_ReverseRandomAccessIndex) -> Distance {
return other._base.distanceTo(_base)
}
/// Return `self` offset by `n` steps.
///
/// - Returns: If `n > 0`, the result of applying `successor` to
/// `self` `n` times. If `n < 0`, the result of applying
/// `predecessor` to `self` `-n` times. Otherwise, `self`.
///
/// - Complexity: O(1).
public func advancedBy(amount: Distance) -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.advancedBy(-amount))
}
}
public func == <I> (lhs: _prext_ReverseIndex<I>, rhs: _prext_ReverseIndex<I>) -> Bool {
return lhs._base == rhs._base
}
public func == <I> (lhs: _prext_ReverseRandomAccessIndex<I>, rhs: _prext_ReverseRandomAccessIndex<I>) -> Bool {
return lhs._base == rhs._base
}
extension CollectionType
where Self : __prext_ReverseCollectionType, Self.Base.Index : BidirectionalIndexType {
public var startIndex : _prext_ReverseIndex<Base.Index> {
return _prext_ReverseIndex<Base.Index>(_base.endIndex)
}
public var endIndex : _prext_ReverseIndex<Base.Index> {
return _prext_ReverseIndex<Base.Index>(_base.startIndex)
}
public subscript(position: _prext_ReverseIndex<Base.Index>) -> Base.Generator.Element {
return _base[position._base.predecessor()]
}
}
extension CollectionType
where Self : __prext_ReverseCollectionType, Self.Base.Index : RandomAccessIndexType {
public var startIndex : _prext_ReverseRandomAccessIndex<Base.Index> {
return _prext_ReverseRandomAccessIndex<Base.Index>(_base.endIndex)
}
public var endIndex : _prext_ReverseRandomAccessIndex<Base.Index> {
return _prext_ReverseRandomAccessIndex<Base.Index>(_base.startIndex)
}
public subscript(position: _prext_ReverseRandomAccessIndex<Base.Index>) -> Base.Generator.Element {
return _base[position._base.predecessor()]
}
}
/// The lazy `CollectionType` returned by `reverse(c)` where `c` is a
/// `CollectionType` with an `Index` conforming to `${IndexProtocol}`.
public struct _prext_ReverseCollection<Base : CollectionType>
: CollectionType, __prext_ReverseCollectionType {
public init(_ _base: Base) {
self._base = _base
}
internal var _base: Base
}
| 915f9be1030fc8d7c66c2430484a0e2c | 32.748858 | 111 | 0.674537 | false | false | false | false |
PJayRushton/TeacherTools | refs/heads/master | TeacherTools/IAPHelper.swift | mit | 1 | //
// IAPHelper.swift
// TeacherTools
//
// Created by Parker Rushton on 12/2/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import StoreKit
public typealias ProductIdentifier = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> ()
open class IAPHelper: NSObject {
fileprivate let productIdentifiers: Set<ProductIdentifier>
fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>()
fileprivate var productsRequest: SKProductsRequest?
fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler?
var core = App.core
public init(productIds: Set<ProductIdentifier>) {
productIdentifiers = productIds
for productIdentifier in productIds {
if let user = core.state.currentUser, user.purchases.map( { $0.productId }).contains(productIdentifier) {
purchasedProductIdentifiers.insert(productIdentifier)
print("Previously purchased: \(productIdentifier)")
} else {
print("Not purchased: \(productIdentifier)")
}
}
super.init()
SKPaymentQueue.default().add(self)
}
}
// MARK: - StoreKit API
extension IAPHelper {
public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) {
productsRequest?.cancel()
productsRequestCompletionHandler = completionHandler
productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
productsRequest?.delegate = self
productsRequest?.start()
}
public func buyProduct(_ product: SKProduct) {
print("Buying \(product.productIdentifier)...")
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool {
return purchasedProductIdentifiers.contains(productIdentifier)
}
public class func canMakePayments() -> Bool {
return SKPaymentQueue.canMakePayments()
}
public func restorePurchases() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
}
// MARK: - SKProductsRequestDelegate
extension IAPHelper: SKProductsRequestDelegate {
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let products = response.products
productsRequestCompletionHandler?(true, products)
clearRequestAndHandler()
for p in products {
print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
}
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
AnalyticsHelper.logEvent(.productRequestFailure)
productsRequestCompletionHandler?(false, nil)
clearRequestAndHandler()
}
private func clearRequestAndHandler() {
productsRequest = nil
productsRequestCompletionHandler = nil
}
}
// MARK: - SKPaymentTransactionObserver
extension IAPHelper: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchased:
complete(transaction: transaction)
case .restored:
restore(transaction: transaction)
case .failed:
fail(transaction: transaction)
case .deferred, .purchasing:
break
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
print("Finished restoring completed transactions\(queue)")
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
AnalyticsHelper.logEvent(.productRestoreFailiure)
print("Restore **FAILED**\n\(queue)\n\(error)")
}
private func complete(transaction: SKPaymentTransaction) {
deliverPurchaseNotification(for: transaction.payment.productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func restore(transaction: SKPaymentTransaction) {
AnalyticsHelper.logEvent(.proRestored)
let productIdentifier = transaction.original?.payment.productIdentifier ?? transaction.payment.productIdentifier
deliverPurchaseNotification(for: productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func fail(transaction: SKPaymentTransaction) {
AnalyticsHelper.logEvent(.productPurchaseFailure)
if let transactionError = transaction.error as NSError? {
if transactionError.code != SKError.paymentCancelled.rawValue {
print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))")
}
}
SKPaymentQueue.default().finishTransaction(transaction)
}
private func deliverPurchaseNotification(for identifier: String) {
purchasedProductIdentifiers.insert(identifier)
core.fire(command: MarkUserPro())
}
}
| 0981950e809c2e16be6013abb839f52d | 34.176471 | 120 | 0.683389 | false | false | false | false |
lucascarletti/Pruuu | refs/heads/master | Pruuu/API/PRAPI.swift | mit | 1 | //
// PRAPI.swift
// Pruuu
//
// Created by Lucas Teixeira Carletti on 16/10/2017.
// Copyright © 2017 PR. All rights reserved.
//
import Alamofire
class API {
static let `default` = API()
static let MAIN_URL = ""
static internal func print(response: DataResponse<String>) {
Swift.print("===================== Response ===================")
if let absoluteURL = response.response?.url?.absoluteString {
Swift.print("URL: \(absoluteURL)")
}
if let method = response.request?.httpMethod {
Swift.print("Method: \(method)")
}
if let statusCode = response.response?.statusCode {
Swift.print("StatusCode: \(statusCode)")
}
if let httpHeader = response.request?.allHTTPHeaderFields {
Swift.print("HTTP Header: \(httpHeader)")
}
if let dataBody = response.request?.httpBody, let body = String(data: dataBody, encoding: .utf8) {
Swift.print("HTTP Body: \(body)")
}
if let value = response.result.value {
Swift.print("Response String: \(value)")
}
Swift.print("==================================================")
}
func get(endPoint: String, params: [String: Any]? = nil, headers: [String: String]? = nil) -> DataRequest {
let request = Alamofire.request(API.MAIN_URL + endPoint, parameters: params, headers: headers)
#if DEBUG
request.responseString {
response in
API.print(response: response)
}
#endif
return request
}
func post(endPoint: String, params: [String: Any]? = nil, headers: [String: String]? = nil) -> DataRequest {
let request = Alamofire.request(API.MAIN_URL + endPoint, method: .post, parameters: params, headers: headers)
#if DEBUG
request.responseString {
response in
API.print(response: response)
}
#endif
return request
}
private var defaultHeader : [String: String]? {
guard let token = PRUser.shared.token else {
return nil
}
return ["Authorization":"Bearer " + token]
}
private var defaultParams : [String: Any] {
return ["":""]
}
}
| 7ad21f80718ffbe644ecbe232fe4e971 | 30.824324 | 117 | 0.537155 | false | false | false | false |
hibu/apptentive-ios | refs/heads/master | Demo/iOSDemo/EventsViewController.swift | bsd-3-clause | 1 | //
// EventsViewController.swift
// iOS Demo
//
// Created by Frank Schmitt on 4/27/16.
// Copyright © 2016 Apptentive, Inc. All rights reserved.
//
import UIKit
private let EventsKey = "events"
class EventsViewController: UITableViewController {
private var events = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem()
updateEventList()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(EventsViewController.updateEventList), name: NSUserDefaultsDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Event", forIndexPath: indexPath)
cell.textLabel?.text = events[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
events.removeAtIndex(indexPath.row)
saveEventList()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// MARK: Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if self.editing {
if let navigationController = self.storyboard?.instantiateViewControllerWithIdentifier("StringNavigation") as? UINavigationController, let eventViewController = navigationController.viewControllers.first as? StringViewController {
eventViewController.string = self.events[indexPath.row]
eventViewController.title = "Edit Event"
self.presentViewController(navigationController, animated: true, completion: nil)
}
} else {
Apptentive.sharedConnection().engage(events[indexPath.row], fromViewController: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let navigationController = segue.destinationViewController as? UINavigationController, let eventViewController = navigationController.viewControllers.first {
eventViewController.title = "New Event"
}
}
@IBAction func returnToEventList(sender: UIStoryboardSegue) {
if let name = (sender.sourceViewController as? StringViewController)?.string {
if let selectedIndex = self.tableView.indexPathForSelectedRow?.row {
events[selectedIndex] = name
} else {
events.append(name)
}
events.sortInPlace()
saveEventList()
tableView.reloadSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
}
}
// MARK: - Private
@objc private func updateEventList() {
if let events = NSUserDefaults.standardUserDefaults().arrayForKey(EventsKey) as? [String] {
self.events = events
}
}
private func saveEventList() {
NSUserDefaults.standardUserDefaults().setObject(events, forKey: EventsKey)
}
}
| fcd867392ffd822bc7aaa51c0ceb31c3 | 31.419048 | 233 | 0.749412 | false | false | false | false |
squall09s/VegOresto | refs/heads/master | VegoResto/Comment/CreateCommentStep2UserViewController.swift | gpl-3.0 | 1 | //
// CreateCommentStep2UserViewController.swift
// VegoResto
//
// Created by Nicolas on 24/10/2017.
// Copyright © 2017 Nicolas Laurent. All rights reserved.
//
import UIKit
import SkyFloatingLabelTextField
protocol CreateCommentStep2UserViewControllerProtocol {
func getCurrentEmail() -> String
func getCurrentName() -> String
func get_tfName() -> UITextField?
func get_tfMail() -> UITextField?
}
class CreateCommentStep2UserViewController: UIViewController, CreateCommentStep2UserViewControllerProtocol, UITextFieldDelegate {
@IBOutlet weak var tf_name: SkyFloatingLabelTextFieldWithIcon?
@IBOutlet weak var tf_mail: SkyFloatingLabelTextFieldWithIcon?
func get_tfName() -> UITextField? {
return self.tf_name
}
func get_tfMail() -> UITextField? {
return self.tf_mail
}
func getCurrentEmail() -> String {
return self.tf_mail?.text ?? ""
}
func getCurrentName() -> String {
return self.tf_name?.text ?? ""
}
override func viewDidLoad() {
super.viewDidLoad()
if let _user_mail = UserDefaults.standard.string(forKey: "USER_SAVE_MAIL") as? String {
self.tf_mail?.text = _user_mail
}
if let _user_name = UserDefaults.standard.string(forKey: "USER_SAVE_NAME") as? String {
self.tf_name?.text = _user_name
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.tf_name {
textField.resignFirstResponder()
self.tf_mail?.becomeFirstResponder()
} else if textField == self.tf_mail {
textField.resignFirstResponder()
if let parent = self.parent as? AddCommentContainerViewController {
parent.nextAction(sender: nil)
}
}
return true
}
}
| a11a97cc2e7ceb09e493a96a98c1b3f5 | 23.52 | 129 | 0.647227 | false | false | false | false |
ahoppen/swift | refs/heads/main | test/SILOptimizer/inline_self.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -emit-sil -primary-file %s | %FileCheck %s
//
// This is a .swift test because the SIL parser does not support Self.
// Do not inline C.factory into main. Doing so would lose the ability
// to materialize local Self metadata.
class C {
required init() {}
}
class SubC : C {}
var g: AnyObject = SubC()
@inline(never)
func gen<R>() -> R {
return g as! R
}
extension C {
@inline(__always)
class func factory(_ z: Int) -> Self {
return gen()
}
}
// Call the function so it can be inlined.
var x = C()
var x2 = C.factory(1)
@inline(never)
func callIt(fn: () -> ()) {
fn()
}
protocol Use {
func use<T>(_ t: T)
}
var user: Use? = nil
class BaseZ {
final func baseCapturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
return self
}
}
// Do not inline C.capturesSelf() into main either. Doing so would lose the ability
// to materialize local Self metadata.
class Z : BaseZ {
@inline(__always)
final func capturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
user?.use(self)
return self
}
// Inline captureSelf into callCaptureSelf,
// because their respective Self types refer to the same type.
final func callCapturesSelf() -> Self {
return capturesSelf()
}
final func callBaseCapturesSelf() -> Self {
return baseCapturesSelf()
}
}
_ = Z().capturesSelf()
// CHECK-LABEL: sil {{.*}}@main : $@convention(c)
// CHECK: function_ref static inline_self.C.factory(Swift.Int) -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1CC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: apply [[F]](%{{.+}}, %{{.+}}) : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: [[Z:%.*]] = alloc_ref $Z
// CHECK: function_ref inline_self.Z.capturesSelf() -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1ZC12capturesSelfACXDyF : $@convention(method) (@guaranteed Z) -> @owned Z
// CHECK: apply [[F]]([[Z]]) : $@convention(method) (@guaranteed Z) -> @owned
// CHECK: return
// CHECK-LABEL: sil hidden @$s11inline_self1ZC16callCapturesSelfACXDyF : $@convention(method)
// CHECK-NOT: function_ref @$s11inline_self1ZC12capturesSelfACXDyF :
// CHECK: }
// CHECK-LABEL: sil hidden @$s11inline_self1ZC20callBaseCapturesSelfACXDyF
// CHECK-NOT: function_ref @$s11inline_self5BaseZC16baseCapturesSelfACXDyF :
// CHECK: }
| c4798f652a7d34a90a4ae0d3f96a0ec0 | 26.10989 | 141 | 0.64694 | false | false | false | false |
peferron/algo | refs/heads/master | EPI/Strings/Test palindromicity/swift/main.swift | mit | 1 | // swiftlint:disable variable_name
func isAlphanumeric(_ character: Character) -> Bool {
return "0" <= character && character <= "9" ||
"a" <= character && character <= "z" ||
"A" <= character && character <= "Z"
}
public func isPalindromeSimple(_ string: String) -> Bool {
let cleanedCharacters = string.lowercased().filter(isAlphanumeric)
return cleanedCharacters == String(cleanedCharacters.reversed())
}
public func isPalindromeSmart(_ string: String) -> Bool {
guard string != "" else {
return true
}
// Iterate from both ends of the string towards the center. Non-alphanumeric characters are
// skipped, and alphanumeric characters are compared case-insensitively.
var start = string.startIndex
var end = string.index(before: string.endIndex)
while true {
while start < end && !isAlphanumeric(string[start]) {
start = string.index(after: start)
}
while start < end && !isAlphanumeric(string[end]) {
end = string.index(before: end)
}
guard start < end else {
return true
}
guard String(string[start]).lowercased() == String(string[end]).lowercased() else {
return false
}
start = string.index(after: start)
end = string.index(before: end)
}
}
| f1ec3a5a84d4720ba5ed3783e1ff9af4 | 29.75 | 95 | 0.614191 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Services/Stories/StoryEditor.swift | gpl-2.0 | 1 | import Foundation
import Kanvas
/// An story editor which displays the Kanvas camera + editing screens.
class StoryEditor: CameraController {
var post: AbstractPost = AbstractPost()
private static let directoryName = "Stories"
/// A directory to temporarily hold imported media.
/// - Throws: Any errors resulting from URL or directory creation.
/// - Returns: A URL with the media cache directory.
static func mediaCacheDirectory() throws -> URL {
let storiesURL = try MediaFileManager.cache.directoryURL().appendingPathComponent(directoryName, isDirectory: true)
try FileManager.default.createDirectory(at: storiesURL, withIntermediateDirectories: true, attributes: nil)
return storiesURL
}
/// A directory to temporarily hold saved archives.
/// - Throws: Any errors resulting from URL or directory creation.
/// - Returns: A URL with the save directory.
static func saveDirectory() throws -> URL {
let saveDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(directoryName, isDirectory: true)
try FileManager.default.createDirectory(at: saveDirectory, withIntermediateDirectories: true, attributes: nil)
return saveDirectory
}
var onClose: ((Bool, Bool) -> Void)? = nil
var editorSession: PostEditorAnalyticsSession
let navigationBarManager: PostEditorNavigationBarManager? = nil
fileprivate(set) lazy var debouncer: Debouncer = {
return Debouncer(delay: PostEditorDebouncerConstants.autoSavingDelay, callback: debouncerCallback)
}()
private(set) lazy var postEditorStateContext: PostEditorStateContext = {
return PostEditorStateContext(post: post, delegate: self)
}()
var verificationPromptHelper: VerificationPromptHelper? = nil
var analyticsEditorSource: String {
return "stories"
}
private var cameraHandler: CameraHandler?
private var poster: StoryPoster?
private lazy var storyLoader: StoryMediaLoader = {
return StoryMediaLoader()
}()
private static let useMetal = false
static var cameraSettings: CameraSettings {
let settings = CameraSettings()
settings.features.ghostFrame = true
settings.features.metalPreview = useMetal
settings.features.metalFilters = useMetal
settings.features.openGLPreview = !useMetal
settings.features.openGLCapture = !useMetal
settings.features.cameraFilters = false
settings.features.experimentalCameraFilters = true
settings.features.editor = true
settings.features.editorGIFMaker = false
settings.features.editorFilters = false
settings.features.editorText = true
settings.features.editorMedia = true
settings.features.editorDrawing = false
settings.features.editorMedia = false
settings.features.mediaPicking = true
settings.features.editorPostOptions = false
settings.features.newCameraModes = true
settings.features.gifs = false
settings.features.multipleExports = true
settings.features.editorConfirmAtTop = true
settings.features.muteButton = true
settings.crossIconInEditor = true
settings.enabledModes = [.normal]
settings.defaultMode = .normal
settings.features.scaleMediaToFill = true
settings.features.resizesFonts = false
settings.animateEditorControls = false
settings.exportStopMotionPhotoAsVideo = false
settings.fontSelectorUsesFont = true
settings.aspectRatio = 9/16
return settings
}
enum EditorCreationError: Error {
case unsupportedDevice
}
typealias UpdateResult = Result<String, PostCoordinator.SavingError>
typealias UploadResult = Result<Void, PostCoordinator.SavingError>
static func editor(blog: Blog,
context: NSManagedObjectContext,
updated: @escaping (UpdateResult) -> Void) throws -> StoryEditor {
let post = PostService(managedObjectContext: context).createDraftPost(for: blog)
return try editor(post: post, mediaFiles: nil, publishOnCompletion: true, updated: updated)
}
static func editor(post: AbstractPost,
mediaFiles: [MediaFile]?,
publishOnCompletion: Bool = false,
updated: @escaping (UpdateResult) -> Void) throws -> StoryEditor {
guard !UIDevice.isPad() else {
throw EditorCreationError.unsupportedDevice
}
let controller = StoryEditor(post: post,
onClose: nil,
settings: cameraSettings,
stickerProvider: nil,
analyticsProvider: nil,
quickBlogSelectorCoordinator: nil,
tagCollection: nil,
mediaFiles: mediaFiles,
publishOnCompletion: publishOnCompletion,
updated: updated)
controller.modalPresentationStyle = .fullScreen
controller.modalTransitionStyle = .crossDissolve
return controller
}
init(post: AbstractPost,
onClose: ((Bool, Bool) -> Void)?,
settings: CameraSettings,
stickerProvider: StickerProvider?,
analyticsProvider: KanvasAnalyticsProvider?,
quickBlogSelectorCoordinator: KanvasQuickBlogSelectorCoordinating?,
tagCollection: UIView?,
mediaFiles: [MediaFile]?,
publishOnCompletion: Bool,
updated: @escaping (UpdateResult) -> Void) {
self.post = post
self.onClose = onClose
self.editorSession = PostEditorAnalyticsSession(editor: .stories, post: post)
Kanvas.KanvasColors.shared = KanvasCustomUI.shared.cameraColors()
Kanvas.KanvasFonts.shared = KanvasCustomUI.shared.cameraFonts()
Kanvas.KanvasImages.shared = KanvasCustomUI.shared.cameraImages()
Kanvas.KanvasStrings.shared = KanvasStrings(
cameraPermissionsTitleLabel: NSLocalizedString("Post to WordPress", comment: "Title of camera permissions screen"),
cameraPermissionsDescriptionLabel: NSLocalizedString("Allow access so you can start taking photos and videos.", comment: "Message on camera permissions screen to explain why the app needs camera and microphone permissions")
)
let saveDirectory: URL?
do {
saveDirectory = try Self.saveDirectory()
} catch let error {
assertionFailure("Should be able to create a save directory in Documents \(error)")
saveDirectory = nil
}
super.init(settings: settings,
mediaPicker: WPMediaPickerForKanvas.self,
stickerProvider: nil,
analyticsProvider: KanvasAnalyticsHandler(),
quickBlogSelectorCoordinator: nil,
tagCollection: nil,
saveDirectory: saveDirectory)
cameraHandler = CameraHandler(created: { [weak self] media in
self?.poster = StoryPoster(context: post.blog.managedObjectContext ?? ContextManager.shared.mainContext, mediaFiles: mediaFiles)
let postMedia: [StoryPoster.MediaItem] = media.compactMap { result in
switch result {
case .success(let item):
guard let item = item else { return nil }
return StoryPoster.MediaItem(url: item.output, size: item.size, archive: item.archive, original: item.unmodified)
case .failure:
return nil
}
}
guard let self = self else { return }
let uploads: (String, [Media])? = try? self.poster?.add(mediaItems: postMedia, post: post)
let content = uploads?.0 ?? ""
updated(.success(content))
if publishOnCompletion {
// Replace the contents if we are publishing a new post
post.content = content
do {
try post.managedObjectContext?.save()
} catch let error {
assertionFailure("Failed to save post during story update: \(error)")
}
self.publishPost(action: .publish, dismissWhenDone: true, analyticsStat:
.editorPublishedPost)
} else {
self.dismiss(animated: true, completion: nil)
}
})
self.delegate = cameraHandler
}
func present(on: UIViewController, with files: [MediaFile]) {
storyLoader.download(files: files, for: post) { [weak self] output in
guard let self = self else { return }
DispatchQueue.main.async {
self.show(media: output)
on.present(self, animated: true, completion: {})
}
}
}
func trackOpen() {
editorSession.start()
}
}
extension StoryEditor: PublishingEditor {
var prepublishingIdentifiers: [PrepublishingIdentifier] {
return [.title, .visibility, .schedule, .tags, .categories]
}
var prepublishingSourceView: UIView? {
return nil
}
var alertBarButtonItem: UIBarButtonItem? {
return nil
}
var isUploadingMedia: Bool {
return false
}
var postTitle: String {
get {
return post.postTitle ?? ""
}
set {
post.postTitle = newValue
}
}
func getHTML() -> String {
return post.content ?? ""
}
func cancelUploadOfAllMedia(for post: AbstractPost) {
}
func publishingDismissed() {
hideLoading()
}
var wordCount: UInt {
return post.content?.wordCount() ?? 0
}
}
extension StoryEditor: PostEditorStateContextDelegate {
func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) {
}
func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) {
}
}
| 83ebd8720ad4e4890659af204a643629 | 37.007299 | 235 | 0.623968 | false | false | false | false |
stack-this/hunter-price | refs/heads/master | ios/Store.swift | apache-2.0 | 1 | //
// Store.swift
// HunterPrice
//
// Created by Gessy on 9/10/16.
// Copyright © 2016 GetsemaniAvila. All rights reserved.
//
import Foundation
class StoreData{
class Store{
let name : String
let latitude : String
let longitude : String
let address : String
let phone : String
init(name:String,latitude:String,longitude:String,address:String,phone:String) {
self.name = name
self.latitude = latitude
self.longitude = longitude
self.address = address
self.phone = phone
}
}
}
| b20956705d9ae4b04a45b364c269e1d6 | 20.862069 | 88 | 0.563091 | false | false | false | false |
mcxiaoke/learning-ios | refs/heads/master | cocoa_programming_for_osx/33_CoreAnimation/Scattered/Scattered/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Scattered
//
// Created by mcxiaoke on 16/5/24.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
var textLayer: CATextLayer!
var text: String? {
didSet {
let font = NSFont.systemFontOfSize(textLayer.fontSize)
let attributes = [NSFontAttributeName: font]
var size = text?.sizeWithAttributes(attributes) ?? CGSize.zero
size.width = ceil(size.width)
size.height = ceil(size.height)
textLayer.bounds = CGRect(origin: CGPoint.zero, size: size)
textLayer.superlayer?.bounds = CGRect(x: 0, y: 0, width: size.width + 16, height: size.height + 20)
textLayer.string = text
}
}
func thumbImageFromImage(image: NSImage) -> NSImage {
let targetHeight: CGFloat = 200.0
let imageSize = image.size
let smallerSize = NSSize(width: targetHeight * imageSize.width / imageSize.height, height: targetHeight)
let smallerImage = NSImage(size: smallerSize, flipped: false) { (rect) -> Bool in
image.drawInRect(rect)
return true
}
return smallerImage
}
func presentImage(image: NSImage, fileName:String) {
let superLayerBounds = view.layer!.bounds
let center = CGPoint(x: superLayerBounds.midX, y: superLayerBounds.midY)
let imageBounds = CGRect(origin: CGPoint.zero, size: image.size)
let randomPoint = CGPoint(x: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxX))),
y: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxY))))
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let positionAnimation = CABasicAnimation()
positionAnimation.fromValue = NSValue(point: center)
positionAnimation.duration = 2
positionAnimation.timingFunction = timingFunction
let boundsAnimation = CABasicAnimation()
boundsAnimation.fromValue = NSValue(rect: CGRect.zero)
boundsAnimation.duration = 2
boundsAnimation.timingFunction = timingFunction
let layer = CALayer()
layer.contents = image
layer.actions = [
"position" : positionAnimation,
"bounds" : boundsAnimation
]
let nameLayer = CATextLayer()
let font = NSFont.systemFontOfSize(12)
let attributes = [NSFontAttributeName: font]
var size = fileName.sizeWithAttributes(attributes) ?? CGSize.zero
size.width = ceil(size.width)
size.height = ceil(size.height)
nameLayer.fontSize = 12
nameLayer.position = randomPoint
nameLayer.zPosition = 0
nameLayer.bounds = CGRect(origin: CGPoint.zero, size: size)
nameLayer.foregroundColor = NSColor.redColor().CGColor
nameLayer.string = fileName
layer.addSublayer(nameLayer)
CATransaction.begin()
view.layer!.addSublayer(layer)
layer.position = randomPoint
layer.bounds = imageBounds
CATransaction.commit()
}
func addImagesFromFolderURL(folderURL: NSURL) {
let t0 = NSDate.timeIntervalSinceReferenceDate()
let fileManager = NSFileManager()
let directoryEnumerator = fileManager.enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil)!
var allowedFiles = 10
while let url = directoryEnumerator.nextObject() as? NSURL {
var isDirectoryValue: AnyObject?
_ = try? url.getResourceValue(&isDirectoryValue, forKey: NSURLIsDirectoryKey)
if let isDirectory = isDirectoryValue as? NSNumber
where isDirectory.boolValue == false {
let image = NSImage(contentsOfURL:url)
if let image = image {
allowedFiles -= 1
if allowedFiles < 0 {
break
}
let thumbImage = thumbImageFromImage(image)
var fileNameValue: AnyObject?
_ = try? url.getResourceValue(&fileNameValue, forKey: NSURLNameKey)
if let fileName = fileNameValue as? String {
print("fileName: \(fileName)")
presentImage(thumbImage, fileName: fileName)
let t1 = NSDate.timeIntervalSinceReferenceDate()
let interval = t1 - t0
text = String(format: "%0.1fs", interval)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.layer = CALayer()
view.wantsLayer = true
let tc = CALayer()
tc.anchorPoint = CGPoint.zero
tc.position = CGPointMake(10, 10)
tc.zPosition = 100
tc.backgroundColor = NSColor.blackColor().CGColor
tc.borderColor = NSColor.whiteColor().CGColor
tc.borderWidth = 2
tc.cornerRadius = 15
tc.shadowOpacity = 0.5
view.layer!.addSublayer(tc)
let tl = CATextLayer()
tl.anchorPoint = CGPoint.zero
tl.position = CGPointMake(10, 6)
tl.zPosition = 100
tl.fontSize = 24
tl.foregroundColor = NSColor.whiteColor().CGColor
self.textLayer = tl
tc.addSublayer(tl)
text = "Loading..."
let url = NSURL(fileURLWithPath: "/Library/Desktop Pictures")
addImagesFromFolderURL(url)
}
}
| 900bc09ea91868ff82fa7b3cbea364c4 | 32.513158 | 178 | 0.675893 | false | false | false | false |
natecook1000/swift | refs/heads/master | stdlib/public/core/Sort.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// sorted()/sort()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Comparable {
/// Returns the elements of the sequence, sorted.
///
/// You can sort any sequence of elements that conform to the `Comparable`
/// protocol by calling this method. Elements are sorted in ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let sortedStudents = students.sorted()
/// print(sortedStudents)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your sequence in descending order, pass the
/// greater-than operator (`>`) to the `sorted(by:)` method.
///
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted() -> [Element] {
return sorted(by: <)
}
}
extension Sequence {
/// Returns the elements of the sequence, sorted using the given predicate as
/// the comparison between elements.
///
/// When you want to sort a sequence of elements that don't conform to the
/// `Comparable` protocol, pass a predicate to this method that returns
/// `true` when the first element passed should be ordered before the
/// second. The elements of the resulting array are ordered according to the
/// given predicate.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the predicate provides an ordering for an array
/// of a custom `HTTPResponse` type. The predicate orders errors before
/// successes and sorts the error responses by their error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// let sortedResponses = responses.sorted {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(sortedResponses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// You also use this method to sort elements that conform to the
/// `Comparable` protocol in descending order. To sort your sequence in
/// descending order, pass the greater-than operator (`>`) as the
/// `areInIncreasingOrder` parameter.
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// Calling the related `sorted()` method is equivalent to calling this
/// method and passing the less-than operator (`<`) as the predicate.
///
/// print(students.sorted())
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
/// print(students.sorted(by: <))
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted(
by areInIncreasingOrder:
(Element, Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray(self)
try result.sort(by: areInIncreasingOrder)
return Array(result)
}
}
extension MutableCollection
where Self: RandomAccessCollection, Element: Comparable {
/// Sorts the collection in place.
///
/// You can sort any mutable collection of elements that conform to the
/// `Comparable` protocol by calling this method. Elements are sorted in
/// ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort()
/// print(students)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your collection in descending order, pass the
/// greater-than operator (`>`) to the `sort(by:)` method.
///
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort() {
sort(by: <)
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Sorts the collection in place, using the given predicate as the
/// comparison between elements.
///
/// When you want to sort a collection of elements that doesn't conform to
/// the `Comparable` protocol, pass a closure to this method that returns
/// `true` when the first element passed should be ordered before the
/// second.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the closure provides an ordering for an array
/// of a custom enumeration that describes an HTTP response. The predicate
/// orders errors before successes and sorts the error responses by their
/// error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// responses.sort {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(responses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// Alternatively, use this method to sort a collection of elements that do
/// conform to `Comparable` when you want the sort to be descending instead
/// of ascending. Pass the greater-than operator (`>`) operator as the
/// predicate.
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`. If `areInIncreasingOrder` throws an error during
/// the sort, the elements may be in a different order, but none will be
/// lost.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let didSortUnsafeBuffer = try _withUnsafeMutableBufferPointerIfSupported {
buffer -> Void? in
try buffer.sort(by: areInIncreasingOrder)
}
if didSortUnsafeBuffer == nil {
try _introSort(within: startIndex..<endIndex, by: areInIncreasingOrder)
}
}
}
extension MutableCollection where Self: BidirectionalCollection {
@inlinable
internal mutating func _insertionSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
guard !range.isEmpty else { return }
let start = range.lowerBound
// Keep track of the end of the initial sequence of sorted elements. One
// element is trivially already-sorted, thus pre-increment Continue until
// the sorted elements cover the whole sequence
var sortedEnd = index(after: start)
while sortedEnd != range.upperBound {
// get the first unsorted element
// FIXME: by stashing the element, instead of using indexing and swapAt,
// this method won't work for collections of move-only types.
let x = self[sortedEnd]
// Look backwards for x's position in the sorted sequence,
// moving elements forward to make room.
var i = sortedEnd
repeat {
let j = index(before: i)
let predecessor = self[j]
// If closure throws, put the element at right place and rethrow.
do {
// if x doesn't belong before y, we've found its position
if try !areInIncreasingOrder(x, predecessor) {
break
}
} catch {
self[i] = x
throw error
}
// Move y forward
self[i] = predecessor
i = j
} while i != start
if i != sortedEnd {
// Plop x into position
self[i] = x
}
formIndex(after: &sortedEnd)
}
}
}
extension MutableCollection {
/// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]`.
/// Stable.
///
/// The indices passed as `a`, `b`, and `c` do not need to be consecutive, but
/// must be in strict increasing order.
///
/// - Precondition: `a < b && b < c`
/// - Postcondition: `self[a] <= self[b] && self[b] <= self[c]`
@inlinable
public // @testable
mutating func _sort3(
_ a: Index, _ b: Index, _ c: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// There are thirteen possible permutations for the original ordering of
// the elements at indices `a`, `b`, and `c`. The comments in the code below
// show the relative ordering of the three elements using a three-digit
// number as shorthand for the position and comparative relationship of
// each element. For example, "312" indicates that the element at `a` is the
// largest of the three, the element at `b` is the smallest, and the element
// at `c` is the median. This hypothetical input array has a 312 ordering for
// `a`, `b`, and `c`:
//
// [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ]
// ^ ^ ^
// a b c
//
// - If each of the three elements is distinct, they could be ordered as any
// of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321.
// - If two elements are equivalent and one is distinct, they could be
// ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211,
// 122, 212, or 221.
// - If all three elements are equivalent, they are already in order: 111.
switch try (areInIncreasingOrder(self[b], self[a]),
areInIncreasingOrder(self[c], self[b])) {
case (false, false):
// 0 swaps: 123, 112, 122, 111
break
case (true, true):
// 1 swap: 321
// swap(a, c): 312->123
swapAt(a, c)
case (true, false):
// 1 swap: 213, 212 --- 2 swaps: 312, 211
// swap(a, b): 213->123, 212->122, 312->132, 211->121
swapAt(a, b)
if try areInIncreasingOrder(self[c], self[b]) {
// 132 (started as 312), 121 (started as 211)
// swap(b, c): 132->123, 121->112
swapAt(b, c)
}
case (false, true):
// 1 swap: 132, 121 --- 2 swaps: 231, 221
// swap(b, c): 132->123, 121->112, 231->213, 221->212
swapAt(b, c)
if try areInIncreasingOrder(self[b], self[a]) {
// 213 (started as 231), 212 (started as 221)
// swap(a, b): 213->123, 212->122
swapAt(a, b)
}
}
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Reorders the collection and returns an index `p` such that every element
/// in `range.lowerBound..<p` is less than every element in
/// `p..<range.upperBound`.
///
/// - Precondition: The count of `range` must be >= 3 i.e.
/// `distance(from: range.lowerBound, to: range.upperBound) >= 3`
@inlinable
internal mutating func _partition(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Index {
var lo = range.lowerBound
var hi = index(before: range.upperBound)
// Sort the first, middle, and last elements, then use the middle value
// as the pivot for the partition.
let half = distance(from: lo, to: hi) / 2
let mid = index(lo, offsetBy: half)
try _sort3(lo, mid, hi, by: areInIncreasingOrder)
let pivot = self[mid]
// Loop invariants:
// * lo < hi
// * self[i] < pivot, for i in range.lowerBound..<lo
// * pivot <= self[i] for i in hi..<range.upperBound
Loop: while true {
FindLo: do {
formIndex(after: &lo)
while lo != hi {
if try !areInIncreasingOrder(self[lo], pivot) { break FindLo }
formIndex(after: &lo)
}
break Loop
}
FindHi: do {
formIndex(before: &hi)
while hi != lo {
if try areInIncreasingOrder(self[hi], pivot) { break FindHi }
formIndex(before: &hi)
}
break Loop
}
swapAt(lo, hi)
}
return lo
}
@inlinable
public // @testable
mutating func _introSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let n = distance(from: range.lowerBound, to: range.upperBound)
guard n > 1 else { return }
// Set max recursion depth to 2*floor(log(N)), as suggested in the introsort
// paper: http://www.cs.rpi.edu/~musser/gp/introsort.ps
let depthLimit = 2 * n._binaryLogarithm()
try _introSortImpl(
within: range,
by: areInIncreasingOrder,
depthLimit: depthLimit)
}
@inlinable
internal mutating func _introSortImpl(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool,
depthLimit: Int
) rethrows {
// Insertion sort is better at handling smaller regions.
if distance(from: range.lowerBound, to: range.upperBound) < 20 {
try _insertionSort(within: range, by: areInIncreasingOrder)
} else if depthLimit == 0 {
try _heapSort(within: range, by: areInIncreasingOrder)
} else {
// Partition and sort.
// We don't check the depthLimit variable for underflow because this
// variable is always greater than zero (see check above).
let partIdx = try _partition(within: range, by: areInIncreasingOrder)
try _introSortImpl(
within: range.lowerBound..<partIdx,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
try _introSortImpl(
within: partIdx..<range.upperBound,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
}
}
@inlinable
internal mutating func _siftDown(
_ idx: Index,
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var i = idx
var countToIndex = distance(from: range.lowerBound, to: i)
var countFromIndex = distance(from: i, to: range.upperBound)
// Check if left child is within bounds. If not, stop iterating, because
// there are no children of the given node in the heap.
while countToIndex + 1 < countFromIndex {
let left = index(i, offsetBy: countToIndex + 1)
var largest = i
if try areInIncreasingOrder(self[largest], self[left]) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = index(after: left)
if try areInIncreasingOrder(self[largest], self[right]) {
largest = right
}
}
// If a child is bigger than the current node, swap them and continue sifting
// down.
if largest != i {
swapAt(idx, largest)
i = largest
countToIndex = distance(from: range.lowerBound, to: i)
countFromIndex = distance(from: i, to: range.upperBound)
} else {
break
}
}
}
@inlinable
internal mutating func _heapify(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// Here we build a heap starting from the lowest nodes and moving to the
// root. On every step we sift down the current node to obey the max-heap
// property:
// parent >= max(leftChild, rightChild)
//
// We skip the rightmost half of the array, because these nodes don't have
// any children.
let root = range.lowerBound
let half = distance(from: range.lowerBound, to: range.upperBound) / 2
var node = index(root, offsetBy: half)
while node != root {
formIndex(before: &node)
try _siftDown(node, within: range, by: areInIncreasingOrder)
}
}
@inlinable
internal mutating func _heapSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var hi = range.upperBound
let lo = range.lowerBound
try _heapify(within: range, by: areInIncreasingOrder)
formIndex(before: &hi)
while hi != lo {
swapAt(lo, hi)
try _siftDown(lo, within: lo..<hi, by: areInIncreasingOrder)
formIndex(before: &hi)
}
}
}
| 821a78fe594b09b2d5202f3910ab87c0 | 36.217235 | 91 | 0.608249 | false | false | false | false |
eriklu/qch | refs/heads/master | View/QCHDefaultTextViewDelegate.swift | mit | 1 | import UIKit
class QCHDefaultTextViewDelegate : NSObject, UITextViewDelegate {
//按回车键退出编辑状态
var isResignFirstResponderOnReturn: Bool = true
//是否允许输入emoji
var isAllowEmoji: Bool = false
//最大允许长度. <=0:无限制;其他:允许最大长度
var maxLength: Int = 0
//错误提示函数
var funcShowTip: ((String) -> Void)?
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// if textView.markedTextRange != nil {
// return true
// }
if isResignFirstResponderOnReturn && text == "\n" {
textView.resignFirstResponder()
return false
}
if !isAllowEmoji && text.qch_containsEmoji {
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange != nil {
return
}
if maxLength > 0 {
let text = textView.text!
if text.characters.count > maxLength {
textView.text = text.substring(to: text.index(text.startIndex, offsetBy: maxLength))
funcShowTip?("内容超过最大允许长度\(maxLength)")
}
}
}
}
| 114cc7ce544a392b203d67ac985ca875 | 26 | 116 | 0.545525 | false | false | false | false |
AssistoLab/DropDown | refs/heads/master | DropDown/helpers/DPDUIView+Extension.swift | mit | 2 | //
// UIView+Constraints.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
#if os(iOS)
import UIKit
//MARK: - Constraints
internal extension UIView {
func addConstraints(format: String, options: NSLayoutConstraint.FormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views))
}
func addUniversalConstraints(format: String, options: NSLayoutConstraint.FormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(format: "H:\(format)", options: options, metrics: metrics, views: views)
addConstraints(format: "V:\(format)", options: options, metrics: metrics, views: views)
}
}
//MARK: - Bounds
internal extension UIView {
var windowFrame: CGRect? {
return superview?.convert(frame, to: nil)
}
}
internal extension UIWindow {
static func visibleWindow() -> UIWindow? {
var currentWindow = UIApplication.shared.keyWindow
if currentWindow == nil {
let frontToBackWindows = Array(UIApplication.shared.windows.reversed())
for window in frontToBackWindows {
if window.windowLevel == UIWindow.Level.normal {
currentWindow = window
break
}
}
}
return currentWindow
}
}
#endif
| fc66fe439e5bbcba1faf17a6bd524bc8 | 22.147541 | 157 | 0.705382 | false | false | false | false |
TwoRingSoft/shared-utils | refs/heads/master | Sources/PippinAdapters/XCGLogger/XCGLoggerAdapter.swift | mit | 1 | //
// XCGLoggerAdapter.swift
// Pippin
//
// Created by Andrew McKnight on 1/28/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Foundation
import Pippin
import PippinLibrary
import XCGLogger
extension LogLevel {
func xcgLogLevel() -> XCGLogger.Level {
switch self {
case .unknown: return XCGLogger.Level.info // default to info
case .verbose: return XCGLogger.Level.verbose
case .debug: return XCGLogger.Level.debug
case .info: return XCGLogger.Level.info
case .warning: return XCGLogger.Level.warning
case .error: return XCGLogger.Level.error
}
}
init?(xcgLevel: XCGLogger.Level) {
switch xcgLevel {
case .verbose: self = .verbose
case .debug: self = .debug
case .info: self = .info
case .warning: self = .warning
case .error: self = .error
case .severe: self = .error
case .none: self = .info // default to info
case .notice, .alert, .emergency: return nil
}
}
}
public final class XCGLoggerAdapter: NSObject {
public var environment: Environment?
fileprivate var _logLevel: LogLevel = .info
fileprivate var logFileURL: URL?
fileprivate var xcgLogger = XCGLogger(identifier: XCGLogger.Constants.fileDestinationIdentifier, includeDefaultDestinations: true)
public init(name: String, logLevel: LogLevel) {
super.init()
guard let logFileURL = urlForFilename(fileName: "\(name).log", inDirectoryType: .libraryDirectory) else {
reportMissingLogFile()
return
}
self.logFileURL = logFileURL
self.logLevel = logLevel
xcgLogger.setup(level: logLevel.xcgLogLevel(),
showLogIdentifier: false,
showFunctionName: false,
showThreadName: false,
showLevel: true,
showFileNames: false,
showLineNumbers: false,
showDate: true,
writeToFile: logFileURL,
fileLevel: logLevel.xcgLogLevel()
)
}
}
// MARK: Logger
extension XCGLoggerAdapter: Logger {
public var logLevel: LogLevel {
get {
return _logLevel
}
set(newValue) {
_logLevel = newValue
xcgLogger.outputLevel = newValue.xcgLogLevel()
}
}
@objc public func logDebug(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.debug)
}
@objc public func logInfo(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.info)
}
@objc public func logWarning(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.warning)
}
@objc public func logVerbose(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.verbose)
}
@objc public func logError(message: String, error: Error) {
let messageWithErrorDescription = String(format: "%@: %@", message, error as NSError)
self.log(message: messageWithErrorDescription, logLevel: XCGLogger.Level.error)
environment?.crashReporter?.recordNonfatalError(error: error, metadata: nil)
}
public func logContents() -> String? {
var logContentsString = String()
if let logContents = getContentsOfLog() {
logContentsString.append(logContents)
logContentsString.append("\n")
}
return logContentsString
}
public func resetLogs() {
resetContentsOfLog()
}
}
// MARK: Private
private extension XCGLoggerAdapter {
func resetContentsOfLog() {
guard let logFileURL = logFileURL else {
reportMissingLogFile()
return
}
do {
try FileManager.default.removeItem(at: logFileURL)
} catch {
logError(message: String(format: "[%@] failed to delete log file at %@", instanceType(self), logFileURL.absoluteString), error: error)
}
}
func getContentsOfLog() -> String? {
var contents: String?
do {
if let logFileURL = logFileURL {
contents = try String(contentsOf: logFileURL, encoding: .utf8)
}
} catch {
logError(message: String(format: "[%@] Could not read logging file: %@.", instanceType(self), error as NSError), error: error)
}
return contents
}
func log(message: String, logLevel: XCGLogger.Level) {
self.xcgLogger.logln(message, level: logLevel)
if self.logLevel.xcgLogLevel() >= logLevel {
environment?.crashReporter?.log(message: String(format: "[%@] %@", logLevel.description, message))
}
}
func reportMissingLogFile() {
logError(message: String(format: "[%@] Could not locate log file.", instanceType(self)), error: LoggerError.noLoggingFile("Could not locate log file."))
}
private func urlForFilename(fileName: String, inDirectoryType directoryType: FileManager.SearchPathDirectory) -> URL? {
return FileManager.default.urls(for: directoryType, in: .userDomainMask).last?.appendingPathComponent(fileName)
}
}
// MARK: Debuggable
extension XCGLoggerAdapter: Debuggable {
public func debuggingControlPanel() -> UIView {
let titleLabel = UILabel.label(withText: "Logger:", font: environment!.fonts.title, textColor: .black)
func makeButton(title: String, action: Selector) -> UIButton {
let button = UIButton(type: .custom)
button.setTitle(title, for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
let stack = UIStackView(arrangedSubviews: [
titleLabel,
makeButton(title: "Log Verbose", action: #selector(debugLogVerbose)),
makeButton(title: "Log Debug", action: #selector(debugLogDebug)),
makeButton(title: "Log Info", action: #selector(debugLogInfo)),
makeButton(title: "Log Warning", action: #selector(debugLogWarning)),
makeButton(title: "Log Error", action: #selector(debugLogError)),
])
stack.axis = .vertical
stack.spacing = 20
return stack
}
@objc private func debugLogVerbose() {
logVerbose(message: "Debug Verbose level log message.")
}
@objc private func debugLogDebug() {
logDebug(message: "Debug Debug level log message.")
}
@objc private func debugLogInfo() {
logInfo(message: "Debug Info level log message.")
}
@objc private func debugLogWarning() {
logWarning(message: "Debug Warning level log message.")
}
@objc private func debugLogError() {
enum Error: Swift.Error {
case debugError
}
logError(message: "Debug Error level log message.", error: Error.debugError)
}
}
| ac955dd0d2c489f3f4228a959fb19007 | 31.154545 | 160 | 0.617331 | false | false | false | false |
cbrentharris/swift | refs/heads/master | test/SILGen/properties.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -use-native-super-method -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | FileCheck %s
var zero: Int = 0
func use(_: Int) {}
func use(_: Double) {}
func getInt() -> Int { return zero }
// CHECK-LABEL: sil hidden @{{.*}}physical_tuple_lvalue
// CHECK: bb0(%0 : $Int):
func physical_tuple_lvalue(c: Int) {
var x : (Int, Int)
// CHECK: [[XADDR1:%[0-9]+]] = alloc_box $(Int, Int)
// CHECK: [[XADDR:%[0-9]+]] = mark_uninitialized [var] [[XADDR1]]
x.1 = c
// CHECK: [[X_1:%[0-9]+]] = tuple_element_addr [[XADDR]] : {{.*}}, 1
// CHECK: assign %0 to [[X_1]]
}
func tuple_rvalue() -> (Int, Int) {}
// CHECK-LABEL: sil hidden @{{.*}}physical_tuple_rvalue
func physical_tuple_rvalue() -> Int {
return tuple_rvalue().1
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties12tuple_rvalue
// CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]()
// CHECK: [[RET:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF10properties16tuple_assignment
func tuple_assignment(inout a: Int, inout b: Int) {
// CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int):
// CHECK: [[A_LOCAL:%.*]] = alloc_box $Int
// CHECK: [[B_LOCAL:%.*]] = alloc_box $Int
// CHECK: [[B:%[0-9]+]] = load [[B_LOCAL]]#1
// CHECK: [[A:%[0-9]+]] = load [[A_LOCAL]]#1
// CHECK: assign [[B]] to [[A_LOCAL]]#1
// CHECK: assign [[A]] to [[B_LOCAL]]#1
(a, b) = (b, a)
}
// CHECK-LABEL: sil hidden @_TF10properties18tuple_assignment_2
func tuple_assignment_2(inout a: Int, inout b: Int, xy: (Int, Int)) {
// CHECK: bb0([[A_ADDR:%[0-9]+]] : $*Int, [[B_ADDR:%[0-9]+]] : $*Int, [[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int):
// CHECK: [[A_LOCAL:%.*]] = alloc_box $Int
// CHECK: [[B_LOCAL:%.*]] = alloc_box $Int
(a, b) = xy
// CHECK: [[XY2:%[0-9]+]] = tuple ([[X]] : $Int, [[Y]] : $Int)
// CHECK: [[X:%[0-9]+]] = tuple_extract [[XY2]] : {{.*}}, 0
// CHECK: [[Y:%[0-9]+]] = tuple_extract [[XY2]] : {{.*}}, 1
// CHECK: assign [[X]] to [[A_LOCAL]]#1
// CHECK: assign [[Y]] to [[B_LOCAL]]#1
}
class Ref {
var x, y : Int
var ref : Ref
var z: Int { get {} set {} }
var val_prop: Val { get {} set {} }
subscript(i: Int) -> Float { get {} set {} }
init(i: Int) {
x = i
y = i
ref = self
}
}
class RefSubclass : Ref {
var w : Int
override init (i: Int) {
w = i
super.init(i: i)
}
}
struct Val {
var x, y : Int
var ref : Ref
var z: Int { get {} set {} }
var z_tuple: (Int, Int) { get {} set {} }
subscript(i: Int) -> Float { get {} set {} }
}
// CHECK-LABEL: sil hidden @_TF10properties22physical_struct_lvalue
func physical_struct_lvalue(c: Int) {
var v : Val
// CHECK: [[VADDR:%[0-9]+]] = alloc_box $Val
v.y = c
// CHECK: assign %0 to [[X_1]]
}
// CHECK-LABEL: sil hidden @_TF10properties21physical_class_lvalue
func physical_class_lvalue(r: Ref, a: Int) {
r.y = a
// CHECK: [[FN:%[0-9]+]] = class_method %0 : $Ref, #Ref.y!setter.1
// CHECK: apply [[FN]](%1, %0) : $@convention(method) (Int, @guaranteed Ref) -> ()
// CHECK: strong_release %0 : $Ref
}
// CHECK-LABEL: sil hidden @_TF10properties24physical_subclass_lvalue
func physical_subclass_lvalue(r: RefSubclass, a: Int) {
r.y = a
// strong_retain %0 : $RefSubclass
// CHECK: [[R_SUP:%[0-9]+]] = upcast %0 : $RefSubclass to $Ref
// CHECK: [[FN:%[0-9]+]] = class_method [[R_SUP]] : $Ref, #Ref.y!setter.1 : Ref -> (Int) -> () , $@convention(method) (Int, @guaranteed Ref) -> ()
// CHECK: apply [[FN]](%1, [[R_SUP]]) :
// CHECK: strong_release [[R_SUP]]
r.w = a
// CHECK: [[FN:%[0-9]+]] = class_method %0 : $RefSubclass, #RefSubclass.w!setter.1
// CHECK: apply [[FN]](%1, %0) : $@convention(method) (Int, @guaranteed RefSubclass) -> ()
}
func struct_rvalue() -> Val {}
// CHECK-LABEL: sil hidden @_TF10properties22physical_struct_rvalue
func physical_struct_rvalue() -> Int {
return struct_rvalue().y
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties13struct_rvalueFT_VS_3Val
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]()
// CHECK: [[RET:%[0-9]+]] = struct_extract [[STRUCT]] : $Val, #Val.y
// CHECK: return [[RET]]
}
func class_rvalue() -> Ref {}
// CHECK-LABEL: sil hidden @_TF10properties21physical_class_rvalue
func physical_class_rvalue() -> Int {
return class_rvalue().y
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF10properties12class_rvalueFT_CS_3Ref
// CHECK: [[CLASS:%[0-9]+]] = apply [[FUNC]]()
// CHECK: [[FN:%[0-9]+]] = class_method [[CLASS]] : $Ref, #Ref.y!getter.1
// CHECK: [[RET:%[0-9]+]] = apply [[FN]]([[CLASS]])
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF10properties18logical_struct_get
func logical_struct_get() -> Int {
return struct_rvalue().z
// CHECK: [[GET_RVAL:%[0-9]+]] = function_ref @_TF10properties13struct_rvalue
// CHECK: [[STRUCT:%[0-9]+]] = apply [[GET_RVAL]]()
// CHECK: [[GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg1z
// CHECK: [[VALUE:%[0-9]+]] = apply [[GET_METHOD]]([[STRUCT]])
// CHECK: return [[VALUE]]
}
// CHECK-LABEL: sil hidden @_TF10properties18logical_struct_set
func logical_struct_set(inout value: Val, z: Int) {
// CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z:%[0-9]+]] : $Int):
value.z = z
// CHECK: [[VAL_LOCAL:%[0-9]+]] = alloc_box $Val
// CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals1z
// CHECK: apply [[Z_SET_METHOD]]([[Z]], [[VAL_LOCAL]]#1)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF10properties27logical_struct_in_tuple_set
func logical_struct_in_tuple_set(inout value: (Int, Val), z: Int) {
// CHECK: bb0([[VAL:%[0-9]+]] : $*(Int, Val), [[Z:%[0-9]+]] : $Int):
value.1.z = z
// CHECK: [[VAL_LOCAL:%[0-9]+]] = alloc_box $(Int, Val)
// CHECK: [[VAL_1:%[0-9]+]] = tuple_element_addr [[VAL_LOCAL]]#1 : {{.*}}, 1
// CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals1z
// CHECK: apply [[Z_SET_METHOD]]([[Z]], [[VAL_1]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF10properties29logical_struct_in_reftype_set
func logical_struct_in_reftype_set(inout value: Val, z1: Int) {
// CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int):
value.ref.val_prop.z_tuple.1 = z1
// CHECK: [[VAL_LOCAL:%[0-9]+]] = alloc_box $Val
// -- val.ref
// CHECK: [[VAL_REF_ADDR:%[0-9]+]] = struct_element_addr [[VAL_LOCAL]]#1 : $*Val, #Val.ref
// CHECK: [[VAL_REF:%[0-9]+]] = load [[VAL_REF_ADDR]]
// -- getters and setters
// -- val.ref.val_prop
// CHECK: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[VAL_REF_VAL_PROP_TEMP:%.*]] = alloc_stack $Val
// CHECK: [[T0:%.*]] = address_to_pointer [[VAL_REF_VAL_PROP_TEMP]]#1 : $*Val to $Builtin.RawPointer
// CHECK: [[MAT_VAL_PROP_METHOD:%[0-9]+]] = class_method {{.*}} : $Ref, #Ref.val_prop!materializeForSet.1 : Ref -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, (@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Ref, @thick Ref.Type) -> ())?)
// CHECK: [[MAT_RESULT:%[0-9]+]] = apply [[MAT_VAL_PROP_METHOD]]([[T0]], [[STORAGE]]#1, [[VAL_REF]])
// CHECK: [[T0:%.*]] = tuple_extract [[MAT_RESULT]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Ref, @thick Ref.Type) -> ()>), 0
// CHECK: [[T1:%[0-9]+]] = pointer_to_address [[T0]] : $Builtin.RawPointer to $*Val
// CHECK: [[OPT_CALLBACK:%.*]] = tuple_extract [[MAT_RESULT]] : $(Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Ref, @thick Ref.Type) -> ()>), 1
// CHECK: [[VAL_REF_VAL_PROP_MAT:%.*]] = mark_dependence [[T1]] : $*Val on [[VAL_REF]]
// CHECK: [[V_R_VP_Z_TUPLE_MAT:%[0-9]+]] = alloc_stack $(Int, Int)
// CHECK: [[LD:%[0-9]+]] = load [[VAL_REF_VAL_PROP_MAT]]
// CHECK: retain_value [[LD]]
// -- val.ref.val_prop.z_tuple
// CHECK: [[GET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg7z_tupleT
// CHECK: [[V_R_VP_Z_TUPLE:%[0-9]+]] = apply [[GET_Z_TUPLE_METHOD]]([[LD]])
// CHECK: store [[V_R_VP_Z_TUPLE]] to [[V_R_VP_Z_TUPLE_MAT]]#1
// -- write to val.ref.val_prop.z_tuple.1
// CHECK: [[V_R_VP_Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[V_R_VP_Z_TUPLE_MAT]]#1 : {{.*}}, 1
// CHECK: assign [[Z1]] to [[V_R_VP_Z_TUPLE_1]]
// -- writeback to val.ref.val_prop.z_tuple
// CHECK: [[WB_V_R_VP_Z_TUPLE:%[0-9]+]] = load [[V_R_VP_Z_TUPLE_MAT]]#1
// CHECK: [[SET_Z_TUPLE_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals7z_tupleT
// CHECK: apply [[SET_Z_TUPLE_METHOD]]({{%[0-9]+, %[0-9]+}}, [[VAL_REF_VAL_PROP_MAT]])
// -- writeback to val.ref.val_prop
// CHECK: switch_enum [[OPT_CALLBACK]] : $Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout Ref, @thick Ref.Type) -> ()>, case #Optional.Some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.None!enumelt: [[CONT:bb[0-9]+]]
// CHECK: [[WRITEBACK]]([[CALLBACK:%.*]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Ref, @thick Ref.Type) -> ()):
// CHECK: [[REF_MAT:%.*]] = alloc_stack $Ref
// CHECK: store [[VAL_REF]] to [[REF_MAT]]#1
// CHECK: [[T0:%.*]] = metatype $@thick Ref.Type
// CHECK: [[T1:%.*]] = address_to_pointer [[VAL_REF_VAL_PROP_MAT]]
// CHECK: apply [[CALLBACK]]([[T1]], [[STORAGE]]#1, [[REF_MAT]]#1, [[T0]])
// CHECK: br [[CONT]]
// CHECK: [[CONT]]:
// -- cleanup
// CHECK: dealloc_stack [[V_R_VP_Z_TUPLE_MAT]]#0
// CHECK: dealloc_stack [[VAL_REF_VAL_PROP_TEMP]]#0
// -- don't need to write back to val.ref because it's a ref type
}
func reftype_rvalue() -> Ref {}
// CHECK-LABEL: sil hidden @_TF10properties18reftype_rvalue_set
func reftype_rvalue_set(value: Val) {
reftype_rvalue().val_prop = value
}
// CHECK-LABEL: sil hidden @_TF10properties27tuple_in_logical_struct_set
func tuple_in_logical_struct_set(inout value: Val, z1: Int) {
// CHECK: bb0([[VAL:%[0-9]+]] : $*Val, [[Z1:%[0-9]+]] : $Int):
value.z_tuple.1 = z1
// CHECK: [[VAL_LOCAL:%[0-9]+]] = alloc_box $Val
// CHECK: [[Z_TUPLE_MATERIALIZED:%[0-9]+]] = alloc_stack $(Int, Int)
// CHECK: [[VAL1:%[0-9]+]] = load [[VAL_LOCAL]]
// CHECK: retain_value [[VAL1]]
// CHECK: [[Z_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg7z_tupleT
// CHECK: [[Z_TUPLE:%[0-9]+]] = apply [[Z_GET_METHOD]]([[VAL1]])
// CHECK: store [[Z_TUPLE]] to [[Z_TUPLE_MATERIALIZED]]#1
// CHECK: [[Z_TUPLE_1:%[0-9]+]] = tuple_element_addr [[Z_TUPLE_MATERIALIZED]]#1 : {{.*}}, 1
// CHECK: assign [[Z1]] to [[Z_TUPLE_1]]
// CHECK: [[Z_TUPLE_MODIFIED:%[0-9]+]] = load [[Z_TUPLE_MATERIALIZED]]#1
// CHECK: [[Z_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals7z_tupleT
// CHECK: apply [[Z_SET_METHOD]]({{%[0-9]+, %[0-9]+}}, [[VAL_LOCAL]]#1)
// CHECK: dealloc_stack [[Z_TUPLE_MATERIALIZED]]#0
// CHECK: return
}
var global_prop : Int {
// CHECK-LABEL: sil hidden @_TF10propertiesg11global_prop
get {
return zero
}
// CHECK-LABEL: sil hidden @_TF10propertiess11global_prop
set {
use(newValue)
}
}
// CHECK-LABEL: sil hidden @_TF10properties18logical_global_get
func logical_global_get() -> Int {
return global_prop
// CHECK: [[GET:%[0-9]+]] = function_ref @_TF10propertiesg11global_prop
// CHECK: [[VALUE:%[0-9]+]] = apply [[GET]]()
// CHECK: return [[VALUE]]
}
// CHECK-LABEL: sil hidden @_TF10properties18logical_global_set
func logical_global_set(x: Int) {
global_prop = x
// CHECK: [[SET:%[0-9]+]] = function_ref @_TF10propertiess11global_prop
// CHECK: apply [[SET]](%0)
}
// CHECK-LABEL: sil hidden @_TF10properties17logical_local_get
func logical_local_get(x: Int) -> Int {
var prop : Int {
get {
return x
}
}
// CHECK: [[GET_REF:%[0-9]+]] = function_ref [[PROP_GET_CLOSURE:@_TFF10properties17logical_local_get]]
// CHECK: apply [[GET_REF]](%0)
return prop
}
// CHECK-: sil shared [[PROP_GET_CLOSURE]]
// CHECK: bb0(%{{[0-9]+}} : $Int):
// CHECK-LABEL: sil hidden @_TF10properties26logical_local_captured_get
func logical_local_captured_get(x: Int) -> Int {
var prop : Int {
get {
return x
}
}
func get_prop() -> Int {
return prop
}
return get_prop()
// CHECK: [[FUNC_REF:%[0-9]+]] = function_ref @_TFF10properties26logical_local_captured_get
// CHECK: apply [[FUNC_REF]](%0)
}
// CHECK: sil shared @_TFF10properties26logical_local_captured_get
// CHECK: bb0(%{{[0-9]+}} : $Int):
func inout_arg(inout x: Int) {}
// CHECK-LABEL: sil hidden @_TF10properties14physical_inout
func physical_inout(x: Int) {
var x = x
// CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int
inout_arg(&x)
// CHECK: [[INOUT_ARG:%[0-9]+]] = function_ref @_TF10properties9inout_arg
// CHECK: apply [[INOUT_ARG]]([[XADDR]]#1)
}
/* TODO check writeback to more complex logical prop, check that writeback
* reuses temporaries */
// CHECK-LABEL: sil hidden @_TF10properties17val_subscript_get
// CHECK: bb0([[VVAL:%[0-9]+]] : $Val, [[I:%[0-9]+]] : $Int):
func val_subscript_get(v: Val, i: Int) -> Float {
return v[i]
// CHECK: [[SUBSCRIPT_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Valg9subscript
// CHECK: [[RET:%[0-9]+]] = apply [[SUBSCRIPT_GET_METHOD]]([[I]], [[VVAL]]) : $@convention(method) (Int, @guaranteed Val)
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF10properties17val_subscript_set
// CHECK: bb0(%0 : $Val, [[I:%[0-9]+]] : $Int, [[X:%[0-9]+]] : $Float):
func val_subscript_set(v: Val, i: Int, x: Float) {
var v = v
v[i] = x
// CHECK: [[VADDR:%[0-9]+]] = alloc_box $Val
// CHECK: [[SUBSCRIPT_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties3Vals9subscript
// CHECK: apply [[SUBSCRIPT_SET_METHOD]]([[X]], [[I]], [[VADDR]]#1)
}
struct Generic<T> {
var mono_phys:Int
var mono_log: Int { get {} set {} }
var typevar_member:T
subscript(x: Int) -> Float { get {} set {} }
subscript(x: T) -> T { get {} set {} }
// CHECK-LABEL: sil hidden @_TFV10properties7Generic19copy_typevar_member
mutating
func copy_typevar_member(x: Generic<T>) {
typevar_member = x.typevar_member
}
}
// CHECK-LABEL: sil hidden @_TF10properties21generic_mono_phys_get
func generic_mono_phys_get<T>(g: Generic<T>) -> Int {
return g.mono_phys
// CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys
}
// CHECK-LABEL: sil hidden @_TF10properties20generic_mono_log_get
func generic_mono_log_get<T>(g: Generic<T>) -> Int {
return g.mono_log
// CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg8mono_log
// CHECK: apply [[GENERIC_GET_METHOD]]<
}
// CHECK-LABEL: sil hidden @_TF10properties20generic_mono_log_set
func generic_mono_log_set<T>(g: Generic<T>, x: Int) {
var g = g
g.mono_log = x
// CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Generics8mono_log
// CHECK: apply [[GENERIC_SET_METHOD]]<
}
// CHECK-LABEL: sil hidden @_TF10properties26generic_mono_subscript_get
func generic_mono_subscript_get<T>(g: Generic<T>, i: Int) -> Float {
return g[i]
// CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg9subscript
// CHECK: apply [[GENERIC_GET_METHOD]]<
}
// CHECK-LABEL: sil hidden @{{.*}}generic_mono_subscript_set
func generic_mono_subscript_set<T>(inout g: Generic<T>, i: Int, x: Float) {
g[i] = x
// CHECK: [[GENERIC_SET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Generics9subscript
// CHECK: apply [[GENERIC_SET_METHOD]]<
}
// CHECK-LABEL: sil hidden @{{.*}}bound_generic_mono_phys_get
func bound_generic_mono_phys_get(inout g: Generic<UnicodeScalar>, x: Int) -> Int {
return g.mono_phys
// CHECK: struct_element_addr %{{.*}}, #Generic.mono_phys
}
// CHECK-LABEL: sil hidden @_TF10properties26bound_generic_mono_log_get
func bound_generic_mono_log_get(g: Generic<UnicodeScalar>, x: Int) -> Int {
return g.mono_log
// CHECK: [[GENERIC_GET_METHOD:%[0-9]+]] = function_ref @_TFV10properties7Genericg8mono_log
// CHECK: apply [[GENERIC_GET_METHOD]]<
}
// CHECK-LABEL: sil hidden @_TF10properties22generic_subscript_type
func generic_subscript_type<T>(g: Generic<T>, i: T, x: T) -> T {
var g = g
g[i] = x
return g[i]
}
/*TODO: archetype and existential properties and subscripts */
struct StaticProperty {
static var foo: Int {
get {
return zero
}
set {}
}
}
// CHECK-LABEL: sil hidden @_TF10properties10static_get
// CHECK: function_ref @_TZFV10properties14StaticPropertyg3foo{{.*}} : $@convention(thin) (@thin StaticProperty.Type) -> Int
func static_get() -> Int {
return StaticProperty.foo
}
// CHECK-LABEL: sil hidden @_TF10properties10static_set
// CHECK: function_ref @_TZFV10properties14StaticPropertys3foo{{.*}} : $@convention(thin) (Int, @thin StaticProperty.Type) -> ()
func static_set(x: Int) {
StaticProperty.foo = x
}
func takeInt(a : Int) {}
protocol ForceAccessors {
var a: Int { get set }
}
struct DidSetWillSetTests: ForceAccessors {
var a: Int {
willSet(newA) {
// CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.willset
// CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestsw1a
// CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[SELFBOX:%.*]] = alloc_box $DidSetWillSetTests
// CHECK-NEXT: copy_addr %1 to [initialization] [[SELFBOX]]#1 : $*DidSetWillSetTests
takeInt(a)
// CHECK-NEXT: // function_ref properties.takeInt
// CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt
// CHECK-NEXT: [[FIELDPTR:%.*]] = struct_element_addr [[SELFBOX]]#1 : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: [[A:%.*]] = load [[FIELDPTR]] : $*Int
// CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> ()
takeInt(newA)
// CHECK-NEXT: // function_ref properties.takeInt (Swift.Int) -> ()
// CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt
// CHECK-NEXT: apply [[TAKEINTFN]](%0) : $@convention(thin) (Int) -> ()
// CHECK-NEXT: copy_addr [[SELFBOX]]#1 to %1 : $*DidSetWillSetTests
}
didSet {
// CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.didset
// CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestsW1a
// CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests):
// CHECK-NEXT: debug
// CHECK-NEXT: [[SELFBOX:%.*]] = alloc_box $DidSetWillSetTests
// CHECK-NEXT: copy_addr %1 to [initialization] [[SELFBOX:%.*]]#1 : $*DidSetWillSetTests
takeInt(a)
// CHECK-NEXT: // function_ref properties.takeInt (Swift.Int) -> ()
// CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @_TF10properties7takeInt
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[SELFBOX:%.*]]#1 : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: [[A:%.*]] = load [[AADDR]] : $*Int
// CHECK-NEXT: apply %5([[A]]) : $@convention(thin) (Int) -> ()
a = zero // reassign, but don't infinite loop.
// CHECK-NEXT: // function_ref properties.zero.unsafeMutableAddressor : Swift.Int
// CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @_TF10propertiesau4zero
// CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer
// CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to $*Int
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[SELFBOX:%.*]]#1 : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: copy_addr [[ZEROADDR]] to [[AADDR]] : $*Int
// CHECK-NEXT: copy_addr [[SELFBOX]]#1 to %1 : $*DidSetWillSetTests
}
}
init(x : Int) {
// Accesses to didset/willset variables are direct in init methods and dtors.
a = x
a = x
}
// These are the synthesized getter and setter for the willset/didset variable.
// CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.getter
// CHECK-NEXT: sil hidden [transparent] @_TFV10properties18DidSetWillSetTestsg1a
// CHECK: bb0(%0 : $DidSetWillSetTests):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: return %2 : $Int // id: %3
// CHECK-LABEL: // {{.*}}.DidSetWillSetTests.a.setter
// CHECK-NEXT: sil hidden @_TFV10properties18DidSetWillSetTestss1a
// CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[SELFBOX:%.*]] = alloc_box $DidSetWillSetTests
// CHECK-NEXT: copy_addr %1 to [initialization] [[SELFBOX]]#1 : $*DidSetWillSetTests
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[SELFBOX:%.*]]#1 : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: [[OLDVAL:%.*]] = load [[AADDR]] : $*Int
// CHECK-NEXT: debug_value [[OLDVAL]] : $Int // let tmp
// CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.willset : Swift.Int
// CHECK-NEXT: [[WILLSETFN:%.*]] = function_ref @_TFV10properties18DidSetWillSetTestsw1a
// CHECK-NEXT: apply [[WILLSETFN]](%0, [[SELFBOX]]#1) : $@convention(method) (Int, @inout DidSetWillSetTests) -> ()
// CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[SELFBOX:%.*]]#1 : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign %0 to [[AADDR]] : $*Int
// CHECK-NEXT: // function_ref {{.*}}.DidSetWillSetTests.a.didset : Swift.Int
// CHECK-NEXT: [[DIDSETFN:%.*]] = function_ref @_TFV10properties18DidSetWillSetTestsW1a{{.*}} : $@convention(method) (Int, @inout DidSetWillSetTests) -> ()
// CHECK-NEXT: apply [[DIDSETFN]]([[OLDVAL]], [[SELFBOX]]#1) : $@convention(method) (Int, @inout DidSetWillSetTests) -> ()
// CHECK-NEXT: copy_addr [[SELFBOX]]#1 to %1 : $*DidSetWillSetTests
// CHECK-LABEL: sil hidden @_TFV10properties18DidSetWillSetTestsC
// CHECK: bb0(%0 : $Int, %1 : $@thin DidSetWillSetTests.Type):
// CHECK: [[SELF:%.*]] = mark_uninitialized [rootself]
// CHECK: [[P1:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign %0 to [[P1]]
// CHECK: [[P2:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests, #DidSetWillSetTests.a
// CHECK-NEXT: assign %0 to [[P2]]
}
// Test global observing properties.
var global_observing_property : Int = zero {
didSet {
takeInt(global_observing_property)
}
}
func force_global_observing_property_setter() {
let x = global_observing_property
global_observing_property = x
}
// The property is initialized with "zero".
// CHECK-LABEL: sil private @globalinit_{{.*}}_func1 : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK-NEXT: %0 = global_addr @_Tv10properties25global_observing_propertySi : $*Int
// CHECK: properties.zero.unsafeMutableAddressor
// CHECK: return
// The didSet implementation needs to call takeInt.
// CHECK-LABEL: sil hidden @_TF10propertiesW25global_observing_property
// CHECK: function_ref properties.takeInt
// CHECK-NEXT: function_ref @_TF10properties7takeInt
// The setter needs to call didSet implementation.
// CHECK-LABEL: sil hidden @_TF10propertiess25global_observing_property
// CHECK: function_ref properties.global_observing_property.unsafeMutableAddressor
// CHECK-NEXT: function_ref @_TF10propertiesau25global_observing_property
// CHECK: function_ref properties.global_observing_property.didset
// CHECK-NEXT: function_ref @_TF10propertiesW25global_observing_property
// Test local observing properties.
func local_observing_property(arg: Int) {
var localproperty: Int = arg {
didSet {
takeInt(localproperty)
}
}
takeInt(localproperty)
localproperty = arg
}
// This is the local_observing_property function itself. First alloc and
// initialize the property to the argument value.
// CHECK-LABEL: sil hidden @{{.*}}local_observing_property
// CHECK: bb0([[ARG:%[0-9]+]] : $Int)
// CHECK: [[BOX:%[0-9]+]] = alloc_box $Int
// CHECK: store [[ARG]] to [[BOX]]#1
// <rdar://problem/16006333> observing properties don't work in @objc classes
@objc
class ObservingPropertyInObjCClass {
var bounds: Int {
willSet {}
didSet {}
}
init(b: Int) { bounds = b }
}
// Superclass init methods should not get direct access to be class properties.
// rdar://16151899
class rdar16151899Base {
var x: Int = zero {
willSet {
use(x)
}
}
}
class rdar16151899Derived : rdar16151899Base {
// CHECK-LABEL: sil hidden @_TFC10properties19rdar16151899Derivedc
override init() {
super.init()
// CHECK: upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base
// CHECK-NEXT: super_method {{%[0-9]+}} : $rdar16151899Derived, #rdar16151899Base.init!initializer.1
// This should not be a direct access, it should call the setter in the
// base.
x = zero
// CHECK: [[BASEPTR:%[0-9]+]] = upcast {{.*}} : $rdar16151899Derived to $rdar16151899Base
// CHECK: load{{.*}}Int
// CHECK-NEXT: [[SETTER:%[0-9]+]] = class_method {{.*}} : $rdar16151899Base, #rdar16151899Base.x!setter.1 : rdar16151899Base
// CHECK-NEXT: apply [[SETTER]]({{.*}}, [[BASEPTR]])
}
}
func propertyWithDidSetTakingOldValue() {
var p : Int = zero {
didSet(oldValue) {
// access to oldValue
use(oldValue)
// and newValue.
use(p)
}
}
p = zero
}
// CHECK: // properties.(propertyWithDidSetTakingOldValue () -> ()).(p #1).setter : Swift.Int
// CHECK-NEXT: sil {{.*}} @_TFF10properties32propertyWithDidSetTakingOldValue
// CHECK: bb0(%0 : $Int, %1 : $@box Int, %2 : $*Int):
// CHECK-NEXT: debug_value %0 : $Int // let newValue, argno: 1
// CHECK-NEXT: debug_value_addr %2 : $*Int // var p, argno: 2
// CHECK-NEXT: %5 = load %2 : $*Int
// CHECK-NEXT: debug_value %5 : $Int
// CHECK-NEXT: assign %0 to %2 : $*Int
// CHECK-NEXT: strong_retain %1 : $@box Int
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %9 = function_ref @_TFF10properties32propertyWithDidSetTakingOldValueFT_T_WL_1pSi : $@convention(thin) (Int, @owned @box Int, @inout Int) -> ()
// CHECK-NEXT: %10 = apply %9(%5, %1, %2) : $@convention(thin) (Int, @owned @box Int, @inout Int) -> ()
// CHECK-NEXT: strong_release %1 : $@box Int
// CHECK-NEXT: %12 = tuple ()
// CHECK-NEXT: return %12 : $()
// CHECK-NEXT:}
class BaseProperty {
var x : Int { get {} set {} }
}
class DerivedProperty : BaseProperty {
override var x : Int { get {} set {} }
func super_property_reference() -> Int {
return super.x
}
}
// rdar://16381392 - Super property references in non-objc classes should be direct.
// CHECK: sil hidden @_TFC10properties15DerivedProperty24super_property_reference
// CHECK: bb0(%0 : $DerivedProperty):
// CHECK: [[BASEPTR:%[0-9]+]] = upcast %0 : $DerivedProperty to $BaseProperty
// CHECK: [[FN:%[0-9]+]] = super_method %0 : $DerivedProperty, #BaseProperty.x!getter.1
// CHECK: apply [[FN]]([[BASEPTR]]) : $@convention(method) (@guaranteed BaseProperty) -> Int // user: %7
// <rdar://problem/16411449> ownership qualifiers don't work with non-mutating struct property
struct ReferenceStorageTypeRValues {
unowned var p1 : Ref
func testRValueUnowned() -> Ref {
return p1
}
// CHECK: sil hidden @{{.*}}testRValueUnowned
// CHECK: bb0(%0 : $ReferenceStorageTypeRValues):
// CHECK-NEXT: debug_value %0 : $ReferenceStorageTypeRValues
// CHECK-NEXT: %2 = struct_extract %0 : $ReferenceStorageTypeRValues, #ReferenceStorageTypeRValues.p1
// CHECK-NEXT: strong_retain_unowned %2 : $@sil_unowned Ref
// CHECK-NEXT: %4 = unowned_to_ref %2 : $@sil_unowned Ref to $Ref
// CHECK-NEXT: return %4 : $Ref
init() {
}
}
// <rdar://problem/16406886> Observing properties don't work with ownership types
struct ObservingPropertiesWithOwnershipTypes {
unowned var alwaysPresent : Ref {
didSet {
}
}
init(res: Ref) {
alwaysPresent = res
}
}
struct ObservingPropertiesWithOwnershipTypesInferred {
unowned var alwaysPresent = Ref(i: 0) {
didSet {
}
}
weak var maybePresent = nil as Ref? {
willSet {
}
}
}
// <rdar://problem/16554876> property accessor synthesization of weak variables doesn't work
protocol WeakPropertyProtocol {
weak var maybePresent : Ref? { get set }
}
struct WeakPropertyStruct : WeakPropertyProtocol {
weak var maybePresent : Ref?
init() {
maybePresent = nil
}
}
// <rdar://problem/16629598> direct property accesses to generic struct
// properties were being mischecked as computed property accesses.
struct SomeGenericStruct<T> {
var x: Int
}
// CHECK-LABEL: sil hidden @_TF10properties4getX
// CHECK: struct_extract {{%.*}} : $SomeGenericStruct<T>, #SomeGenericStruct.x
func getX<T>(g: SomeGenericStruct<T>) -> Int {
return g.x
}
// <rdar://problem/16189360> [DF] Assert on subscript with variadic parameter
struct VariadicSubscript {
subscript(subs: Int...) -> Int {
get {
return 42
}
}
func test() {
var s = VariadicSubscript()
var x = s[0, 1, 2]
}
}
//<rdar://problem/16620121> Initializing constructor tries to initialize computed property overridden with willSet/didSet
class ObservedBase {
var printInfo: Ref!
}
class ObservedDerived : ObservedBase {
override init() {}
override var printInfo: Ref! {
didSet { }
}
}
/// <rdar://problem/16953517> Class properties should be allowed in protocols, even without stored class properties
protocol ProtoWithClassProp {
static var x: Int { get }
}
class ClassWithClassProp : ProtoWithClassProp {
class var x: Int {
return 42
}
}
struct StructWithClassProp : ProtoWithClassProp {
static var x: Int {
return 19
}
}
func getX<T : ProtoWithClassProp>(a : T) -> Int {
return T.x
}
func testClassPropertiesInProtocol() -> Int {
return getX(ClassWithClassProp())+getX(StructWithClassProp())
}
class GenericClass<T> {
var x: T
var y: Int
final let z: T
init() { fatalError("scaffold") }
}
// CHECK-LABEL: sil hidden @_TF10properties12genericPropsFGCS_12GenericClassSS_T_
func genericProps(x: GenericClass<String>) {
// CHECK: class_method %0 : $GenericClass<String>, #GenericClass.x!getter.1
let _ = x.x
// CHECK: class_method %0 : $GenericClass<String>, #GenericClass.y!getter.1
let _ = x.y
// CHECK: [[Z:%.*]] = ref_element_addr %0 : $GenericClass<String>, #GenericClass.z
// CHECK: load [[Z]] : $*String
let _ = x.z
}
// CHECK-LABEL: sil hidden @_TF10properties28genericPropsInGenericContext
func genericPropsInGenericContext<U>(x: GenericClass<U>) {
// CHECK: [[Z:%.*]] = ref_element_addr %0 : $GenericClass<U>, #GenericClass.z
// CHECK: copy_addr [[Z]] {{.*}} : $*U
let _ = x.z
}
// <rdar://problem/18275556> 'let' properties in a class should be implicitly final
class ClassWithLetProperty {
let p = 42
dynamic let q = 97
// We shouldn't have any dynamic dispatch within this method, just load p.
func ReturnConstant() -> Int { return p }
// CHECK-LABEL: sil hidden @_TFC10properties20ClassWithLetProperty14ReturnConstant
// CHECK: bb0(%0 : $ClassWithLetProperty):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[PTR:%[0-9]+]] = ref_element_addr %0 : $ClassWithLetProperty, #ClassWithLetProperty.p
// CHECK-NEXT: [[VAL:%[0-9]+]] = load [[PTR]] : $*Int
// CHECK-NEXT: return [[VAL]] : $Int
// This property is marked dynamic, so go through the getter, always.
func ReturnDynamicConstant() -> Int { return q }
// CHECK-LABEL: sil hidden @_TFC10properties20ClassWithLetProperty21ReturnDynamicConstant
// CHECK: class_method [volatile] %0 : $ClassWithLetProperty, #ClassWithLetProperty.q!getter.1.foreign
}
// <rdar://problem/19254812> DI bug when referencing let member of a class
class r19254812Base {}
class r19254812Derived: r19254812Base{
let pi = 3.14159265359
init(x : ()) {
use(pi)
}
// Accessing the "pi" property should not retain/release self.
// CHECK-LABEL: sil hidden @_TFC10properties16r19254812Derivedc
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [derivedself]
// Initialization of the pi field: no retains/releases.
// CHECK: [[SELF:%[0-9]+]] = load [[SELFMUI]] : $*r19254812Derived
// CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi
// CHECK-NEXT: assign {{.*}} to [[PIPTR]] : $*Double
// CHECK-NOT: strong_release
// CHECK-NOT: strong_retain
// Load of the pi field: no retains/releases.
// CHECK: [[SELF:%[0-9]+]] = load [[SELFMUI]] : $*r19254812Derived
// CHECK-NEXT: [[PIPTR:%[0-9]+]] = ref_element_addr [[SELF]] : $r19254812Derived, #r19254812Derived.pi
// CHECK-NEXT: {{.*}} = load [[PIPTR]] : $*Double
// CHECK: return
}
class RedundantSelfRetains {
final var f : RedundantSelfRetains
init() {
f = RedundantSelfRetains()
}
// <rdar://problem/19275047> Extraneous retains/releases of self are bad
func testMethod1() {
f = RedundantSelfRetains()
}
// CHECK-LABEL: sil hidden @_TFC10properties20RedundantSelfRetains11testMethod1
// CHECK: bb0(%0 : $RedundantSelfRetains):
// CHECK-NOT: strong_retain
// CHECK: [[FPTR:%[0-9]+]] = ref_element_addr %0 : $RedundantSelfRetains, #RedundantSelfRetains.f
// CHECK-NEXT: assign {{.*}} to [[FPTR]] : $*RedundantSelfRetains
// CHECK: return
}
class RedundantRetains {
final var field = 0
}
func testRedundantRetains() {
let a = RedundantRetains()
a.field = 4 // no retain/release of a necessary here.
}
// CHECK-LABEL: sil hidden @_TF10properties20testRedundantRetainsFT_T_ : $@convention(thin) () -> () {
// CHECK: [[A:%[0-9]+]] = apply
// CHECK-NOT: strong_retain
// CHECK: strong_release [[A]] : $RedundantRetains
// CHECK-NOT: strong_retain
// CHECK-NOT: strong_release
// CHECK: return
struct AddressOnlyNonmutatingSet<T> {
var x: T
init(x: T) { self.x = x }
var prop: Int {
get { return 0 }
nonmutating set { }
}
}
func addressOnlyNonmutatingProperty<T>(x: AddressOnlyNonmutatingSet<T>)
-> Int {
x.prop = 0
return x.prop
}
// CHECK-LABEL: sil hidden @_TF10properties30addressOnlyNonmutatingProperty
// CHECK: [[SET:%.*]] = function_ref @_TFV10properties25AddressOnlyNonmutatingSets4propSi
// CHECK: apply [[SET]]<T>({{%.*}}, [[TMP:%.*]]#1)
// CHECK: destroy_addr [[TMP]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: [[GET:%.*]] = function_ref @_TFV10properties25AddressOnlyNonmutatingSetg4propSi
// CHECK: apply [[GET]]<T>([[TMP:%.*]]#1)
// CHECK: destroy_addr [[TMP]]
// CHECK: dealloc_stack [[TMP]]
protocol MakeAddressOnly {}
struct AddressOnlyReadOnlySubscript {
var x: MakeAddressOnly?
subscript(z: Int) -> Int { return z }
}
// CHECK-LABEL: sil hidden @_TF10properties43addressOnlyReadOnlySubscriptFromMutableBase
// CHECK: [[BASE:%.*]] = alloc_box $AddressOnlyReadOnlySubscript
// CHECK: copy_addr [[BASE:%.*]]#1 to [initialization] [[COPY:%.*]]#1
// CHECK: [[GETTER:%.*]] = function_ref @_TFV10properties28AddressOnlyReadOnlySubscriptg9subscript
// CHECK: apply [[GETTER]]({{%.*}}, [[COPY]]#1)
func addressOnlyReadOnlySubscriptFromMutableBase(x: Int) {
var base = AddressOnlyReadOnlySubscript()
_ = base[x]
}
/// <rdar://problem/20912019> passing unmaterialized r-value as inout argument
struct MutatingGetterStruct {
var write: Int {
mutating get { }
}
// CHECK-LABEL: sil hidden @_TZFV10properties20MutatingGetterStruct4test
// CHECK: [[X:%.*]] = alloc_box $MutatingGetterStruct // var x
// CHECK: store {{.*}} to [[X]]#1 : $*MutatingGetterStruct
// CHECK: apply {{%.*}}([[X]]#1) : $@convention(method) (@inout MutatingGetterStruct) -> Int
static func test() {
var x = MutatingGetterStruct()
_ = x.write
}
}
| 56786e1876e46b04df9fe35d538a315b | 34.483615 | 304 | 0.628652 | false | true | false | false |
wangzheng0822/algo | refs/heads/master | swift/08_stack/StackBasedOnLinkedList.swift | apache-2.0 | 1 | //
// Created by Jiandan on 2018/10/12.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
struct StackBasedOnLinkedList<Element>: Stack {
private var head = Node<Element>() // 哨兵结点,不存储内容
// MARK: Protocol: Stack
var isEmpty: Bool { return head.next == nil }
var size: Int {
var count = 0
var cur = head.next
while cur != nil {
count += 1
cur = cur?.next
}
return count
}
var peek: Element? { return head.next?.value }
func push(newElement: Element) -> Bool {
let node = Node(value: newElement)
node.next = head.next
head.next = node
return true
}
func pop() -> Element? {
let node = head.next
head.next = node?.next
return node?.value
}
}
| 000c9df62cbaa75c3b6cded272103233 | 20.897436 | 52 | 0.537471 | false | false | false | false |
Nykho/Swifternalization | refs/heads/master | SwifternalizationTests/RegexExpressionMatcherTests.swift | mit | 4 | //
// RegexExpressionMatcherTests.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import UIKit
import XCTest
class RegexExpressionMatcherTests: XCTestCase {
func testValidation1() {
let matcher = InequalityExpressionParser("ie:x=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertFalse(matcher.validate("5"), "should be true")
}
func testValidation2() {
let matcher = InequalityExpressionParser("ie:x<=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertTrue(matcher.validate("2"), "should be true")
}
func testValidation3() {
let matcher = InequalityExpressionParser("ie:x>=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertTrue(matcher.validate("4"), "should be true")
}
func testValidation4() {
let matcher = InequalityExpressionParser("ie:x>3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("4"), "should be true")
XCTAssertFalse(matcher.validate("3"), "should be true")
}
func testValidation5() {
let matcher = InequalityExpressionParser("ie:x<3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("2"), "should be true")
XCTAssertFalse(matcher.validate("3"), "should be true")
}
}
| 380a430923b63faafba3bcd1f78c8f14 | 35.674419 | 99 | 0.673431 | false | true | false | false |
VojtechBartos/Weather-App | refs/heads/master | WeatherApp/Classes/Controller/WEAForecastTableViewController.swift | mit | 1 | //
// WEAForecastTableViewController.swift
// WeatherApp
//
// Created by Vojta Bartos on 13/04/15.
// Copyright (c) 2015 Vojta Bartos. All rights reserved.
//
import UIKit
let WEA_FORECAST_CELL_IDENTIFIER = "WEAForecastCell"
class WEAForecastTableViewController: UITableViewController {
let config: WEAConfig = WEAConfig.sharedInstance
var days: [WEAForecast] = []
// MARK: - Screen life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.reload()
}
// MARK: - Setup
func setup() {
let cellNib: UINib = UINib(nibName: "WEATableViewCell", bundle: nil)
self.tableView.registerNib(cellNib, forCellReuseIdentifier: WEA_FORECAST_CELL_IDENTIFIER)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.allowsSelection = false
self.tableView.editing = false
}
func setupObservers() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reload", name: "cz.vojtechbartos.WeatherApp.locationDidChange", object: nil
)
}
// MARK: - Helpers
func reload() {
if let city: WEACity = WEACity.getCurrent() {
// set navigation title
self.navigationItem.title = city.name
// load updated forecast for next days
self.days = city.orderedForecast()
self.tableView.reloadData()
}
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.days.count
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: WEAForecastTableViewCell = tableView.dequeueReusableCellWithIdentifier(
WEA_FORECAST_CELL_IDENTIFIER, forIndexPath: indexPath
) as! WEAForecastTableViewCell
return self.configure(cell, indexPath: indexPath)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
// MARK: - Helpers
func configure(cell: WEAForecastTableViewCell, indexPath: NSIndexPath) -> WEAForecastTableViewCell {
var forecast: WEAForecast = self.days[indexPath.row]
cell.imageIconView.image = forecast.imageIcon(WEAImage.Small)
cell.titleLabel.text = forecast.day
cell.descriptionLabel.text = forecast.info
cell.temperatureLabel.text = NSString(format: "%iº", forecast.temperatureIn(self.config.temperatureUnit).integerValue) as String
cell.userInteractionEnabled = false
return cell
}
// MARK: - System
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| 873430c9881d2dffe5637d50f92a2b0c | 29.336538 | 136 | 0.657369 | false | true | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | refs/heads/master | UberGoCore/UberGoCore/ReceiptObj.swift | mit | 1 | //
// ReceiptObj.swift
// UberGoCore
//
// Created by Nghia Tran on 8/17/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Unbox
public final class ReceiptObj: Unboxable {
// MARK: - Variable
public let requestID: String
public let totalCharge: String
public let totalOwed: Float?
public let totalFare: String
public let currencyCode: String
public let chargeAdjustments: [String]
public let duration: String
public let distance: String
public let distanceLabel: String
// MARK: - Init
public required init(unboxer: Unboxer) throws {
requestID = try unboxer.unbox(key: Constants.Object.Receipt.RequestID)
totalCharge = try unboxer.unbox(key: Constants.Object.Receipt.TotalCharged)
totalOwed = unboxer.unbox(key: Constants.Object.Receipt.TotalOwed)
totalFare = try unboxer.unbox(key: Constants.Object.Receipt.TotalFare)
currencyCode = try unboxer.unbox(key: Constants.Object.Receipt.CurrencyCode)
chargeAdjustments = try unboxer.unbox(key: Constants.Object.Receipt.ChargeAdjustments)
duration = try unboxer.unbox(key: Constants.Object.Receipt.Duration)
distance = try unboxer.unbox(key: Constants.Object.Receipt.Distance)
distanceLabel = try unboxer.unbox(key: Constants.Object.Receipt.DistanceLabel)
}
}
| 8c32d565cf7f5ff57c2ac1830ef8fb27 | 36.583333 | 94 | 0.719143 | false | false | false | false |
xdkoooo/LiveDemo | refs/heads/master | LiveDemo/LiveDemo/Classes/Main/Model/AnchorModel.swift | mit | 1 | //
// AnchorModel.swift
// LiveDemo
//
// Created by BillBear on 2017/3/9.
// Copyright © 2017年 xdkoo. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间ID
var room_id : String = ""
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
/// 0 : 电脑 1 : 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 在线人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| ec4f8d40af2abae2b797d1b12afb782b | 19.4 | 73 | 0.557423 | false | false | false | false |
xuephil/Perfect | refs/heads/master | Examples/Authenticator/Authenticator/LoginHandler.swift | agpl-3.0 | 1 | //
// LoginHandler.swift
// Authenticator
//
// Created by Kyle Jessup on 2015-11-10.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
import PerfectLib
import Foundation
// Handler class
// When referenced in a mustache template, this class will be instantiated to handle the request
// and provide a set of values which will be used to complete the template.
class LoginHandler: AuthenticatingHandler { // all template handlers must inherit from PageHandler
// This is the function which all handlers must impliment.
// It is called by the system to allow the handler to return the set of values which will be used when populating the template.
// - parameter context: The MustacheEvaluationContext which provides access to the WebRequest containing all the information pertaining to the request
// - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded.
override func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType {
var values = try super.valuesForResponse(context, collector: collector)
if let acceptStr = context.webRequest?.httpAccept() {
if acceptStr.contains("json") {
values["json"] = true
}
}
guard let user = self.authenticatedUser else {
// Our parent class will have set the web response code to trigger authentication.
values["message"] = "Not authenticated"
values["resultCode"] = 401
return values
}
// This handler is responsible for taking a user supplied username and the associated
// digest authentication information and validating it against the information in the database.
values["resultCode"] = 0
values["first"] = user.firstName
values["last"] = user.lastName
values["email"] = user.email
values["title"] = "Perfect Project Template"
values["message"] = "Logged in successfully!"
// Return the values
// These will be used to populate the template
return values
}
}
| 29b9e8d69a98e45c72be70fffe7e4868 | 42.771429 | 211 | 0.758159 | false | false | false | false |
bartekchlebek/SwiftHelpers | refs/heads/master | Example/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift | mit | 1 | import Foundation
public func allPass<T,U>
(_ passFunc: @escaping (T) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass { (v: T?) -> Bool in v.map(passFunc) ?? false }
}
public func allPass<T,U>
(_ passName: String, _ passFunc: @escaping (T) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass(passName) { (v: T?) -> Bool in v.map(passFunc) ?? false }
}
public func allPass<T,U>
(_ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass("pass a condition", passFunc)
}
public func allPass<T,U>
(_ passName: String, _ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return createAllPassMatcher() {
expression, failureMessage in
failureMessage.postfixMessage = passName
return passFunc(try expression.evaluate())
}
}
public func allPass<U,V>
(_ matcher: V) -> NonNilMatcherFunc<U>
where U: Sequence, V: Matcher, U.Iterator.Element == V.ValueType
{
return createAllPassMatcher() {
try matcher.matches($0, failureMessage: $1)
}
}
private func createAllPassMatcher<T,U>
(_ elementEvaluator: @escaping (Expression<T>, FailureMessage) throws -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.actualValue = nil
if let actualValue = try actualExpression.evaluate() {
for currentElement in actualValue {
let exp = Expression(
expression: {currentElement}, location: actualExpression.location)
if try !elementEvaluator(exp, failureMessage) {
failureMessage.postfixMessage =
"all \(failureMessage.postfixMessage),"
+ " but failed first at element <\(stringify(currentElement))>"
+ " in <\(stringify(actualValue))>"
return false
}
}
failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)"
} else {
failureMessage.postfixMessage = "all pass (use beNil() to match nils)"
return false
}
return true
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func allPassMatcher(_ matcher: NMBObjCMatcher) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
var nsObjects = [NSObject]()
var collectionIsUsable = true
if let value = actualValue as? NSFastEnumeration {
let generator = NSFastEnumerationIterator(value)
while let obj = generator.next() {
if let nsObject = obj as? NSObject {
nsObjects.append(nsObject)
} else {
collectionIsUsable = false
break
}
}
} else {
collectionIsUsable = false
}
if !collectionIsUsable {
failureMessage.postfixMessage =
"allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects"
failureMessage.expected = ""
failureMessage.to = ""
return false
}
let expr = Expression(expression: ({ nsObjects }), location: location)
let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = {
expression, failureMessage in
return matcher.matches(
{try! expression.evaluate()}, failureMessage: failureMessage, location: expr.location)
}
return try! createAllPassMatcher(elementEvaluator).matches(
expr, failureMessage: failureMessage)
}
}
}
#endif
| e6e0f6dcedf903ee1628e15b9629f2a3 | 36.026316 | 106 | 0.579957 | false | false | false | false |
noprom/Cocktail-Pro | refs/heads/master | smartmixer/smartmixer/UserCenter/UserHome.swift | apache-2.0 | 1 | //
// UserHome.swift
// smartmixer
//
// Created by 姚俊光 on 14/9/29.
// Copyright (c) 2014年 smarthito. All rights reserved.
//
import UIKit
import CoreData
class UserHome: UIViewController,UIScrollViewDelegate,UITableViewDelegate,HistoryCellDelegate,NSFetchedResultsControllerDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
//用户信息的View
@IBOutlet var userInfoLayer:UIView!
//用户背景图片
@IBOutlet var userInfoBg:UIImageView!
//用户信息距顶部的控制
@IBOutlet var userInfoframe: UIView!
//信息的滚动
@IBOutlet var scollViewMap:UIScrollView!
//概览信息
@IBOutlet var sumInfo:UILabel!
//用户名字
@IBOutlet var userName:UILabel!
//用户头像
@IBOutlet var userImage:UIImageView!
//点击还原的我按钮
@IBOutlet var myButton:UIButton!
//没有数据时的提示
@IBOutlet var nodataTip:UILabel!
//历史信息的table
@IBOutlet var historyTableView:UITableView!
var clickGesture:UITapGestureRecognizer!
class func UserHomeRoot()->UIViewController{
let userCenterController = UIStoryboard(name:"UserCenter"+deviceDefine,bundle:nil).instantiateInitialViewController() as! UserHome
return userCenterController
}
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = NSFileManager.defaultManager()
if(fileManager.isReadableFileAtPath(applicationDocumentsPath+"/mybg.png")){
userInfoBg.image = UIImage(contentsOfFile: applicationDocumentsPath+"/mybg.png")
}
userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png")
userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
self.userInfoframe.userInteractionEnabled = true
clickGesture = UITapGestureRecognizer()
clickGesture.addTarget(self, action: Selector("changeHomebg:"))
clickGesture?.delegate = self
self.userInfoframe.addGestureRecognizer(clickGesture!)
scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50))
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController?.tabBar.hidden = true
self.hidesBottomBarWhenPushed = true
self.navigationController?.setNavigationBarHidden(true, animated: true)
let UserCook = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")
let UserFavor = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")
let UserHave = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")
let UserContainer = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")
sumInfo.text = "\(UserFavor)个收藏,\(UserCook)次制作,\(UserHave)种材料,\(UserContainer)种器具"
userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png")
userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50))
rootController.showOrhideToolbar(true)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
//@MARK:修改主页的背景选取照片
var imagePicker:UIImagePickerController!
var popview:UIPopoverController!
//修改主页的背景图片
func changeHomebg(sender:UITapGestureRecognizer){
if(scollViewMap.contentOffset.y>10){
UIView.animateWithDuration(0.3, animations: {
self.userInfoframe.frame = CGRect(x: self.userInfoframe.frame.origin.x, y: 0, width: self.userInfoframe.frame.width, height: self.userInfoframe.frame.height)
self.userInfoLayer.alpha = 1
self.myButton.hidden = true
self.setalpha = false
self.view.layoutIfNeeded()
})
self.scollViewMap.contentOffset.y = 0
}else{
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
imagePicker.tabBarItem.title="请选择背景图片"
if(deviceDefine==""){
self.presentViewController(imagePicker, animated: true, completion: nil)
}else{
popview = UIPopoverController(contentViewController: imagePicker)
popview.presentPopoverFromRect(CGRect(x: 512, y: 50, width: 10, height: 10), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
}
//写入Document中
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
userInfoBg.image = image
let imageData = UIImagePNGRepresentation(image)
imageData!.writeToFile(applicationDocumentsPath+"/mybg.png", atomically: false)
self.dismissViewControllerAnimated(true, completion: nil)
if(osVersion<8 && deviceDefine != ""){
popview.dismissPopoverAnimated(true)
}
}
//@MARK:点击商城
@IBAction func OnStoreClick(sender:UIButton){
let baike:WebView = WebView.WebViewInit()
baike.myWebTitle = "商城"
baike.WebUrl="http://www.smarthito.com"
rootController.showOrhideToolbar(false)
baike.showToolbar = true
self.navigationController?.pushViewController(baike, animated: true)
}
//@MARK:点击设置
var aboutview:UIViewController!
@IBAction func OnSettingClick(sender:UIButton){
if(deviceDefine==""){
aboutview = AboutViewPhone.AboutViewPhoneInit()
}else{
aboutview = AboutViewPad.AboutViewPadInit()
}
self.navigationController?.pushViewController(aboutview, animated: true)
rootController.showOrhideToolbar(false)
}
//#MARK:这里是处理滚动的处理向下向上滚动影藏控制栏
var lastPos:CGFloat = 0
//滚动开始记录开始偏移
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastPos = scrollView.contentOffset.y
}
var setalpha:Bool=false
func scrollViewDidScroll(scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
if(off<=240 && off>0){//在区间0~240需要渐变处理
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -off, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
userInfoLayer.alpha = 1-off/240
myButton.hidden = true
setalpha = false
}else if(off>240 && setalpha==false){//大于240区域
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -240, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
userInfoLayer.alpha = 0
myButton.hidden = false
setalpha = true
}else if(off<0){
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: 0, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
self.userInfoLayer.alpha = 1
self.myButton.hidden = true
self.setalpha = false
}
/**/
if((off-lastPos)>50 && off>50){//向下了
lastPos = off
rootController.showOrhideToolbar(false)
}else if((lastPos-off)>70){
lastPos = off
rootController.showOrhideToolbar(true)
}
}
var numberOfObjects:Int=0
//@MARK:这里是处理显示数据的
//告知窗口现在有多少个item需要添加
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
let sectionInfo = self.fetchedResultsController.sections!
let item = sectionInfo[section]
numberOfObjects = item.numberOfObjects
if(numberOfObjects==0){
nodataTip.hidden = false
}else{
nodataTip.hidden = true
}
historyTableView.contentSize = CGSize(width: 0, height: CGFloat(numberOfObjects*50))
return item.numberOfObjects
}
//处理单个View的添加
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
var indentifier = "his-cook"
if(item.type==1){
indentifier="his-addfaver"
}else if(item.type==2){
indentifier="his-addhave"
}else if(item.type==3){
indentifier="his-addhave"
}
let cell :HistoryCell = tableView.dequeueReusableCellWithIdentifier(indentifier) as! HistoryCell
if(deviceDefine==""){
cell.scroll.contentSize = CGSize(width: 380, height: 50)
}else{
//cell.scroll.contentSize = CGSize(width: 1104, height: 50)
}
cell.name.text = item.name
cell.thumb.image = UIImage(named: item.thumb)
cell.time.text = formatDateString(item.addtime)
cell.delegate = self
return cell
}
var lastDayString:String!=nil
func formatDateString(date:NSDate)->String{
let formatter = NSDateFormatter()
formatter.dateFormat="yyyy.MM.dd"
let newstring = formatter.stringFromDate(date)
if(newstring != lastDayString){
lastDayString = newstring
return lastDayString
}else{
return "."
}
}
//要删除某个
func historyCell(sender:HistoryCell){
skipUpdate = true
let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)!
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
managedObjectContext.deleteObject(item)
do {
try managedObjectContext.save()
}catch{
abort()
}
// if !managedObjectContext.save(&error) {
// abort()
// }
self.historyTableView?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}
//选中某个需要显示
func historyCell(sender:HistoryCell,show ShowCell:Bool){
self.navigationController?.setNavigationBarHidden(false, animated: false)
rootController.showOrhideToolbar(false)
let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)!
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
if(item.type==0||item.type==1){
let recipe=DataDAO.getOneRecipe(item.refid.integerValue)
if(deviceDefine==""){
let recipeDetail = RecipeDetailPhone.RecipesDetailPhoneInit()
recipeDetail.CurrentData = recipe
self.navigationController?.pushViewController(recipeDetail, animated: true)
}else{
let recipeDetail = RecipeDetailPad.RecipeDetailPadInit()
recipeDetail.CurrentData = recipe
self.navigationController?.pushViewController(recipeDetail, animated: true)
}
}else if(item.type==2){
let materials = IngredientDetail.IngredientDetailInit()
materials.ingridient=DataDAO.getOneIngridient(item.refid.integerValue)
self.navigationController?.pushViewController(materials, animated: true)
}else if(item.type==3){
let container = ContainerDetail.ContainerDetailInit()
container.CurrentContainer = DataDAO.getOneContainer(item.refid.integerValue)
self.navigationController?.pushViewController(container, animated: true)
}
}
//@MARK:历史数据的添加处理
class func addHistory(type:Int,id refId:Int,thumb imageThumb:String,name showName:String){
let history = NSEntityDescription.insertNewObjectForEntityForName("History", inManagedObjectContext: managedObjectContext) as! History
history.type = type
history.refid = refId
history.thumb = imageThumb
history.name = showName
history.addtime = NSDate()
if(type==0){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook")
do {
try managedObjectContext.save()
}catch{
abort()
}
// var error: NSError? = nil
// if !managedObjectContext.save(&error) {
// abort()
// }
}else if(type==1){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor")
}else if(type==2){//添加了材料的拥有
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave")
DataDAO.updateRecipeCoverd(refId, SetHave: true)
}else{
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer")
}
}
//历史数据的删除
class func removeHistory(type:Int,id refId:Int){
if(type==0){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook")
}else if(type==1){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor")
}else if(type==2){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave")
DataDAO.updateRecipeCoverd(refId, SetHave: false)
}else{
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer")
}
}
//@MARK:数据的读取
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("History", inManagedObjectContext: managedObjectContext)
fetchRequest.fetchBatchSize = 30
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "addtime", ascending: false)]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
_fetchedResultsController = aFetchedResultsController
_fetchedResultsController?.delegate = self
do {
try self.fetchedResultsController.performFetch()
}catch{
abort()
}
// var error: NSError? = nil
// if !_fetchedResultsController!.performFetch(&error) {
// abort()
// }
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
var skipUpdate:Bool=false
func controllerDidChangeContent(controller: NSFetchedResultsController) {
if(skipUpdate){
skipUpdate=false
}else{
_fetchedResultsController = nil
historyTableView.reloadData()
lastDayString=nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| dc5b83882e5be4455553cd857af09640 | 40.426357 | 220 | 0.658496 | false | false | false | false |
vanshg/MacAssistant | refs/heads/master | MacAssistant/Assistant/AssistantViewController.swift | mit | 1 | //
// AssistantViewController.swift
// MacAssistant
//
// Created by Vansh Gandhi on 8/3/18.
// Copyright © 2018 Vansh Gandhi. All rights reserved.
//
import Cocoa
import Log
import SwiftGRPC
import WebKit
import SwiftyUserDefaults
// Eventual TODO: AssistantViewController should only interact with views
// Current Assistant.swift should be renamed to API.swift
// New Assistant.swift should handle business logic of mic/follow up/audio/
class AssistantViewController: NSViewController, AssistantDelegate, AudioDelegate {
let Log = Logger()
let assistant = Assistant()
var conversation: [ConversationEntry] = []
var currentAssistantCall: AssistCallContainer?
var followUpRequired = false
var micWasUsed = false
lazy var audioEngine = AudioEngine(delegate: self)
let conversationItemIdentifier = NSUserInterfaceItemIdentifier(rawValue: "ConversationItem")
@IBOutlet weak var initialPromptLabel: NSTextField!
@IBOutlet weak var conversationCollectionView: NSCollectionView!
@IBOutlet weak var keyboardInputField: NSTextField!
override func viewDidLoad() {
conversationCollectionView.dataSource = self
conversationCollectionView.delegate = self
conversationCollectionView.register(NSNib(nibNamed: "ConversationItem", bundle: nil), forItemWithIdentifier: conversationItemIdentifier)
}
override func viewDidAppear() {
if Defaults[.shouldListenOnMenuClick] {
onMicClicked()
}
}
override func viewDidDisappear() {
cancelCurrentRequest()
}
func onAssistantCallCompleted(result: CallResult) {
currentAssistantCall = nil
Log.debug("Assistant Call Completed. Description: \(result.description)")
if !result.success {
// TODO: show error (Create ErrorConversationEntry)
}
if let statusMessage = result.statusMessage {
Log.debug(statusMessage)
}
}
func onDoneListening() {
Log.debug("Done Listening")
audioEngine.stopRecording()
currentAssistantCall?.doneSpeaking = true
}
// Received text to display
func onDisplayText(text: String) {
Log.debug("Received display text: \(text)")
conversation.append(ConversationEntry(isFromUser: false, text: text))
conversationCollectionView.reloadBackground()
}
func onScreenOut(htmlData: String) {
// TODO: supplementalView to display screen out?
// TODO: Handle HTML Screen Out data
Log.info(htmlData)
}
func onTranscriptUpdate(transcript: String) {
Log.debug("Transcript update: \(transcript)")
conversation[conversation.count - 1].text = transcript
conversationCollectionView.reloadBackground()
}
func onAudioOut(audio: Data) {
Log.debug("Got audio")
audioEngine.playResponse(data: audio) { success in
if !success {
self.Log.error("Error playing audio out")
}
// Regardless of audio error, still follow up
if self.followUpRequired {
self.followUpRequired = false
if self.micWasUsed {
self.Log.debug("Following up with mic")
self.onMicClicked()
} // else, use text input
}
}
}
func onFollowUpRequired() {
Log.debug("Follow up needed")
followUpRequired = true // Will follow up after completion of audio out
}
func onError(error: Error) {
Log.error("Got error \(error.localizedDescription)")
}
// Called from AudioEngine (delegate method)
func onMicrophoneInputAudio(audioData: Data) {
if let call = currentAssistantCall {
// We don't want to continue sending data to servers once endOfUtterance has been received
if !call.doneSpeaking {
assistant.sendAudioChunk(streamCall: call.call, audio: audioData, delegate: self)
}
}
}
func cancelCurrentRequest() {
followUpRequired = false
audioEngine.stopPlayingResponse()
if let call = currentAssistantCall {
Log.debug("Cancelling current request")
call.call.cancel()
if (!call.doneSpeaking) {
conversation.removeLast()
conversationCollectionView.reloadBackground()
}
currentAssistantCall = nil
onDoneListening()
}
}
}
// UI Actions
extension AssistantViewController {
@IBAction func onEnterClicked(_ sender: Any) {
let query = keyboardInputField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isNotEmpty {
Log.debug("Processing text query: \(query)")
micWasUsed = false
conversation.append(ConversationEntry(isFromUser: true, text: query))
conversationCollectionView.reloadData()
let lastIndexPath = Set([IndexPath(item: conversation.count-1, section: 0)])
conversationCollectionView.scrollToItems(at: lastIndexPath, scrollPosition: .bottom)
assistant.sendTextQuery(text: query, delegate: self)
keyboardInputField.stringValue = ""
}
}
@IBAction func onMicClicked(_ sender: Any? = nil) {
Log.debug("Mic clicked")
audioEngine.playBeginPrompt()
micWasUsed = true
audioEngine.stopPlayingResponse()
currentAssistantCall = AssistCallContainer(call: assistant.initiateSpokenRequest(delegate: self))
audioEngine.startRecording()
conversation.append(ConversationEntry(isFromUser: true, text: "..."))
conversationCollectionView.reloadData()
}
// TODO: Link this up with the Mic Graph (Another TODO: Get the Mic Waveform working)
func onWaveformClicked(_ sender: Any?) {
Log.debug("Listening manually stopped")
audioEngine.stopRecording()
try? currentAssistantCall?.call.closeSend()
}
}
// CollectionView related methods
extension AssistantViewController: NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return conversation.count
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: conversationItemIdentifier, for: indexPath) as! ConversationItem
item.loadData(data: conversation[indexPath.item])
return item
}
// func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
//
//
// let myNib = NSNib(nibNamed: "ConversationItem", bundle: nil)!
// var myArray: NSArray!
// myNib.instantiate(withOwner: ConversationItem.self, topLevelObjects: &myArray) // instantiate view and put in myArray
// var item: ConversationItem? = nil
// for i in myArray {
// if let i = i as? ConversationItem {
// item = i
// }
// }
//// let item = myArray[2] as! ConversationItem
//
//// Bundle.main.loadNibNamed("ConversationItem", owner: self, topLevelObjects: &myArray)
//// let picker = NSBundle.mainBundle().loadNibNamed("advancedCellView", owner: nil, options: nil)
//// let item = myArray[0] as! ConversationItem
//
//// let item = collectionView.makeItem(withIdentifier: conversationItemIdentifier, for: IndexPath(item: 0, section: 0)) as! ConversationItem
//// let item = collectionView.item(at: indexPath)
// if let item = item as ConversationItem? {
// item.loadData(data: conversation[indexPath.item])
// let width = item.textField!.frame.size.width
// let newSize = item.textField!.sizeThatFits(NSSize(width: width, height: .greatestFiniteMagnitude))
// item.textField?.frame.size = NSSize(width: 300, height: newSize.height)
// print(item.textField!.frame.size)
// return item.textField!.frame.size
// }
//
// print("here 2")
// return NSSize(width: 300, height: 30)
//
// }
}
| e7f1912c2a9e4738670c95d157298f69 | 37.209821 | 166 | 0.642832 | false | false | false | false |
cuappdev/tempo | refs/heads/master | Tempo/Controllers/LoginFlowViewController.swift | mit | 1 |
import UIKit
protocol LoginFlowViewControllerDelegate: class {
func didFinishLoggingIn()
}
class LoginFlowViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageVCOffset: CGFloat = 40
var pageViewController: UIPageViewController!
var facebookLoginViewController: FacebookLoginViewController!
var createUsernameViewController: CreateUsernameViewController!
var spotifyLoginViewController: SpotifyLoginViewController!
var pages = [UIViewController]()
var pageControl: UIPageControl?
weak var delegate: LoginFlowViewControllerDelegate?
var currentlyDisplayingPageIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageViewController.dataSource = self
pageViewController.delegate = self
facebookLoginViewController = FacebookLoginViewController()
facebookLoginViewController.delegate = self
createUsernameViewController = CreateUsernameViewController()
createUsernameViewController.delegate = self
spotifyLoginViewController = SpotifyLoginViewController()
spotifyLoginViewController.delegate = self
pages = [facebookLoginViewController, createUsernameViewController, spotifyLoginViewController]
pageViewController.setViewControllers([facebookLoginViewController], direction: .forward, animated: false, completion: nil)
// Disable swiping and hide page control
pageViewController.disablePageViewControllerSwipeGesture()
pageViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height + pageVCOffset)
pageViewController.hidePageControl()
addChildViewController(pageViewController)
view.addSubview(pageViewController.view)
pageViewController.didMove(toParentViewController: self)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = pages.index(of: viewController), index < pages.count - 1 {
return pages[index + 1]
}
return nil
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pages.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return currentlyDisplayingPageIndex
}
}
extension LoginFlowViewController: FacebookLoginViewControllerDelegate {
func facebookLoginViewController(facebookLoginViewController: FacebookLoginViewController, didFinishLoggingInWithNewUserNamed name: String, withFacebookID fbid: String) {
createUsernameViewController.name = name
createUsernameViewController.fbid = fbid
currentlyDisplayingPageIndex += 1
pageViewController.setViewControllers([createUsernameViewController], direction: .forward, animated: true, completion: nil)
}
func facebookLoginViewController(facebookLoginViewController: FacebookLoginViewController, didFinishLoggingInWithPreviouslyRegisteredUserNamed name: String, withFacebookID fbid: String) {
delegate?.didFinishLoggingIn()
}
}
extension LoginFlowViewController: CreateUsernameViewControllerDelegate {
func createUsernameViewController(createUsernameViewController: CreateUsernameViewController, didFinishCreatingUsername username: String) {
currentlyDisplayingPageIndex += 1
pageViewController.setViewControllers([spotifyLoginViewController], direction: .forward, animated: true, completion: nil)
}
}
extension LoginFlowViewController: SpotifyLoginViewControllerDelegate {
func spotifyLoginViewController(spotifyLoginViewController: SpotifyLoginViewController, didFinishLoggingIntoSpotifyWithAccessToken token: String?) {
delegate?.didFinishLoggingIn()
}
}
extension UIPageViewController {
func disablePageViewControllerSwipeGesture() {
for subview in view.subviews {
if let scrollView = subview as? UIScrollView {
scrollView.isScrollEnabled = false
}
}
}
func hidePageControl() {
for subview in view.subviews {
if subview is UIPageControl {
subview.isHidden = true
}
}
}
}
| f99aa635f5bf149bfa0b17864b04e64a | 32.330769 | 188 | 0.811678 | false | false | false | false |
swiftingio/SwiftyStrings | refs/heads/master | SwiftyStrings/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwiftyStrings
//
// Created by Maciej Piotrowski on 20/11/16.
// Copyright © 2016 Maciej Piotrowski. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationItem()
configureViews()
configureConstraints()
}
}
extension ViewController {
fileprivate func configureViews() {
view.backgroundColor = .white
let color = UIColor(red:0.13, green:0.56, blue:0.93, alpha:1.00)
button = UIButton(frame: .zero)
button.setTitle(.ImpressMe, for: .normal)
button.setTitleColor(color, for: .normal)
button.sizeToFit()
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
view.addSubview(button)
}
fileprivate func configureConstraints() {
view.subviews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
let constraints: [NSLayoutConstraint] = NSLayoutConstraint.centerInSuperview(button)
NSLayoutConstraint.activate(constraints)
}
fileprivate func configureNavigationItem() {
title = .Hello
}
@objc fileprivate func buttonTapped(sender: UIButton) {
let alert = UIAlertController(title: .ThisApplicationIsCreated, message: .OpsNoFeature, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: .OK, style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| 7ecd1fff054204639cf738c69cad1fd9 | 31.02 | 119 | 0.674578 | false | true | false | false |
icotting/Phocalstream.iOS | refs/heads/master | Phocalstream/CreateSiteController.swift | apache-2.0 | 1 | //
// CreateSiteController.swift
// Phocalstream
//
// Created by Zach Christensen on 9/18/15.
// Copyright © 2015 JS Raikes School. All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
class CreateSiteController : UIViewController, CLLocationManagerDelegate, UITextFieldDelegate, RequestManagerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var createButton: UIBarButtonItem!
@IBOutlet weak var closeButton: UIBarButtonItem!
@IBOutlet weak var siteNameField: UITextField!
@IBOutlet weak var siteLocationField: UITextField!
@IBOutlet weak var siteImageThumbnail: UIImageView!
var siteId: Int!
var siteName: String!
var siteLat: Double!
var siteLong: Double!
var county: String!
var state: String!
var siteImage: UIImage!
var dialog: LoadingDialog!
var geocoder: CLGeocoder!
var manager: CLLocationManager!
var mgr: RequestManager!
override func viewDidLoad() {
siteNameField.delegate = self
// Setup our Location Manager
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
// Init Geocoder
geocoder = CLGeocoder()
mgr = RequestManager(delegate: self)
}
override func viewDidAppear(animated: Bool) {
manager.startUpdatingLocation()
}
override func viewDidDisappear(animated: Bool) {
manager.stopUpdatingLocation()
}
func isSiteValid() -> Bool {
return (siteName != nil && siteLat != nil && siteLong != nil && county != nil && state != nil && siteImage != nil)
}
// MARK: Toolbar Actions
@IBAction func close(sender: AnyObject) {
}
@IBAction func create(sender: AnyObject) {
self.dialog = LoadingDialog(title: "Creating Site")
self.dialog.presentFromView(self.view)
//string siteName, double latitude, double longitude, string county, string state
let dictionary = NSMutableDictionary()
dictionary.setValue(self.siteName, forKeyPath: "SiteName")
dictionary.setValue(String(self.siteLat), forKeyPath: "Latitude")
dictionary.setValue(String(self.siteLong), forKeyPath: "Longitude")
dictionary.setValue("\(self.county) County", forKeyPath: "County")
dictionary.setValue(self.state, forKeyPath: "State")
self.mgr.postWithData("http://images.plattebasintimelapse.org/api/usercollection/CreateUserCameraSite", data: dictionary)
}
// MARK: Photo Capture
@IBAction func addPhoto(sender: AnyObject) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
self.capturePhoto()
} else {
self.noCamera()
}
}
func choosePhotofromLibrary() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = false
presentViewController(imagePicker, animated: true, completion: nil)
}
func capturePhoto() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.delegate = self
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func noCamera(){
let alert = UIAlertView(title: "No Camera", message: "Sorry, this device does not have a camera. Choose an image from photo library?", delegate: self, cancelButtonTitle: "No")
alert.addButtonWithTitle("Yes")
alert.show()
}
// MARK: UIImagePickerController Delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
self.siteImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.siteImageThumbnail.image = self.siteImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
self.siteImage = nil
self.siteImageThumbnail.image = nil
}
// MARK: UIAlertView Delegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.title == "Upload a photo?" {
if buttonIndex == 1 {
self.capturePhoto()
}
}
else if alertView.title == "No Camera" {
if buttonIndex == 1 {
self.choosePhotofromLibrary()
}
}
}
// MARK: RequestManager Delegate Methods
func didFailWithResponseCode(code: Int, message: String?) {
dispatch_async(dispatch_get_main_queue(), {
print("\(code): \(message!)")
self.dialog.clearFromView()
})
}
func didSucceedWithBody(body: Array<AnyObject>?) {
// If the body is not nil, it is the first call to create the site
if body != nil {
let id = (body!.first as! String!)
self.siteId = Int(id)
self.dialog.updateTitle("Uploading Photo")
self.mgr.uploadPhoto("http://images.plattebasintimelapse.org/api/upload/upload?selectedCollectionID=\(self.siteId)", image: self.siteImage!)
}
}
func didSucceedWithObjectId(id: Int64) {
dispatch_async(dispatch_get_main_queue(), {
self.dialog.clearFromView()
})
performSegueWithIdentifier("UNWINDANDRELOAD", sender: self)
}
// MARK: CLLocationManagerDelete Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.siteLat = locations[0].coordinate.latitude
self.siteLong = locations[0].coordinate.longitude
siteLocationField.text = "( \(locations[0].coordinate.latitude), \(locations[0].coordinate.longitude) )"
self.geocoder.reverseGeocodeLocation(locations[0], completionHandler: {(placemarks, error) in
if let placemark: CLPlacemark = placemarks?[0] {
self.county = placemark.subAdministrativeArea!
self.state = placemark.administrativeArea!
self.createButton.enabled = self.isSiteValid()
}
})
}
//MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
}
func textFieldDidEndEditing(textField: UITextField) {
self.siteName = siteNameField.text
createButton.enabled = isSiteValid()
}
} | d75a476e8eca37635704c2b1489a9a94 | 31.95283 | 184 | 0.645956 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | refs/heads/master | VietNamToGo/DPDConstants.swift | mit | 1 | //
// Constants.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
internal struct DPDConstant {
internal struct KeyPath {
static let Frame = "frame"
}
internal struct ReusableIdentifier {
static let DropDownCell = "DropDownCell"
}
internal struct UI {
static let BackgroundColor = colorBlue
static let SelectionBackgroundColor = UIColor(white: 0.89, alpha: 1)
static let SeparatorColor = UIColor.clearColor()
static let SeparatorStyle = UITableViewCellSeparatorStyle.None
static let SeparatorInsets = UIEdgeInsetsZero
static let CornerRadius: CGFloat = 0
static let RowHeight: CGFloat = 44
static let HeightPadding: CGFloat = 20
struct Shadow {
static let Color = UIColor.darkGrayColor().CGColor
static let Offset = CGSizeZero
static let Opacity: Float = 0.4
static let Radius: CGFloat = 8
}
}
internal struct Animation {
static let Duration = 0.15
static let EntranceOptions: UIViewAnimationOptions = [.AllowUserInteraction, .CurveEaseOut]
static let ExitOptions: UIViewAnimationOptions = [.AllowUserInteraction, .CurveEaseIn]
static let DownScaleTransform = CGAffineTransformMakeScale(0.9, 0.9)
}
} | dd90f0326235c4ce29a427a21e9de9f6 | 22 | 93 | 0.725719 | false | false | false | false |
kfix/MacPin | refs/heads/main | Sources/MacPinOSX/OmniBoxController.swift | gpl-3.0 | 1 | /// MacPin OmniBoxController
///
/// Controls a textfield that displays a WebViewController's current URL and accepts editing to change loaded URL in WebView
import AppKit
import WebKit
extension WKWebView {
@objc override open func setValue(_ value: Any?, forUndefinedKey key: String) {
if key != "URL" { super.setValue(value, forUndefinedKey: key) } //prevents URLbox from trying to directly rewrite webView.URL
// copy by ref?
}
}
class URLAddressField: NSTextField { // FIXMEios UILabel + UITextField
@objc dynamic var isLoading: Bool = false { didSet { needsDisplay = true } } // cell.needsDisplay = true
@objc dynamic var progress: Double = Double(0.0) { didSet { needsDisplay = true } }
let thickness = CGFloat(3) // progress line thickness
//var baselineOffsetFromBottom: CGFloat { get } // http://www.openradar.me/36672952
//override init(frame frameRect: NSRect) {
// self.super(frame: frameRect)
func viewDidLoad() {
isSelectable = true
isEditable = true
}
override func draw(_ dirtyRect: NSRect) {
var bezel: NSBezierPath = NSBezierPath(roundedRect: NSInsetRect(bounds, 2, 2), xRadius: 5, yRadius: 5)
// approximating the geo of 10.10's .roundedBezel
NSColor.darkGray.set(); bezel.stroke() // draw bezel
bezel.addClip() // constrain further drawing within bezel
if isLoading {
// draw a Safari style progress-line along edge of the text box's focus ring
//var progressRect = NSOffsetRect(bounds, 0, 4) // top edge of bezel
var progressRect = NSOffsetRect(bounds, 0, NSMaxY(bounds) - (thickness + 2)) // bottom edge of bezel
progressRect.size.height = thickness
progressRect.size.width *= progress == 1.0 ? 0 : CGFloat(progress) // only draw line when downloading
//NSColor(calibratedRed:0.0, green: 0.0, blue: 1.0, alpha: 0.4).set() // transparent blue line
// FIXME alpha get overwhelmed when bg/appearance is light
NSColor.systemBlue.set() // matches "Highlight Color: Blue" from SysPrefs:General
progressRect.fill(using: .sourceOver)
} else {
NSColor.clear.setFill() // clear background
bounds.fill(using: .copy) // .clear
}
super.draw(dirtyRect) // draw control's built-in bezel, background (if not a rounded bezel), & text
}
// NSControl
override func validateProposedFirstResponder(_ responder: NSResponder, for event: NSEvent?) -> Bool {
//warn(event?.description ?? "")
//warn(obj: responder)
//warn(obj: event)
return true
}
// NSTextDelegate
//override func textShouldBeginEditing(_ textObject: NSText) -> Bool { warn(); return true } //allow editing
}
/* iOS progbar: http://stackoverflow.com/questions/29410849/unable-to-display-subview-added-to-wkwebview?rq=1
webview?.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
let progressView = UIProgressView(progressViewStyle: .Bar)
progressView.center = view.center
progressView.progress = 20.0/30.0
progressView.trackTintColor = UIColor.lightGrayColor()
progressView.tintColor = UIColor.blueColor()
webview?.addSubview(progressView)
*/
@objc class OmniBoxController: NSViewController {
let urlbox = URLAddressField()
@objc weak var webview: MPWebView? = nil {
didSet { //KVC to copy updates to webviews url & title (user navigations, history.pushState(), window.title=)
if let wv = webview {
view.bind(NSBindingName.toolTip, to: wv, withKeyPath: #keyPath(MPWebView.title), options: nil)
view.bind(NSBindingName.value, to: wv, withKeyPath: #keyPath(MPWebView.url), options: nil)
view.bind(NSBindingName.fontBold, to: wv, withKeyPath: #keyPath(MPWebView.hasOnlySecureContent), options: nil)
// TODO: mimic Safari UX for SSL sites: https://www.globalsign.com/en/blog/how-to-view-ssl-certificate-details/#safari
view.bind(NSBindingName("isLoading"), to: wv, withKeyPath: #keyPath(MPWebView.isLoading), options: nil)
view.bind(NSBindingName("progress"), to: wv, withKeyPath: #keyPath(MPWebView.estimatedProgress), options: nil)
view.nextResponder = wv // passthru uncaptured selectors from omnibox tf to webview
view.nextKeyView = wv
}
}
willSet(newwv) {
if let _ = webview {
// we had one already set, so unwind all its entanglements
view.nextResponder = nil
view.nextKeyView = nil
view.unbind(NSBindingName.toolTip)
view.unbind(NSBindingName.value)
view.unbind(NSBindingName.fontBold)
view.unbind(NSBindingName("progress"))
view.unbind(NSBindingName("isLoading"))
}
}
}
required init?(coder: NSCoder) { super.init(coder: coder) }
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView()
override func loadView() { view = urlbox } // NIBless
func popup(_ webview: MPWebView?) {
guard let webview = webview else { return }
MacPinApp.shared.appDelegate?.browserController.tabSelected = webview // EWW
}
/*
convenience init(webViewController: WebViewController?) {
self.init()
preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this!
if let wvc = webViewController { representedObject = wvc }
}
*/
convenience init() {
self.init(nibName:nil, bundle:nil)
preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this!
}
override func viewDidLoad() {
super.viewDidLoad()
// prepareForReuse() {...} ?
urlbox.isBezeled = true
urlbox.bezelStyle = .roundedBezel
let appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light"
if appearance == "Dark" {
urlbox.textColor = NSColor.labelColor
// BUG: 10.11 dark-dock + high-constrast mode set a black textColor on a black-menu-bar-bg
}
urlbox.toolTip = ""
urlbox.maximumNumberOfLines = 1
urlbox.importsGraphics = false
urlbox.allowsEditingTextAttributes = false
//urlbox.menu = NSMenu //ctrl-click context menu
// search with DuckDuckGo
// go to URL
// js: addOmniBoxActionHandler('send to app',handleCustomOmniAction)
// tab menu?
urlbox.delegate = self
if let cell = urlbox.cell as? NSTextFieldCell {
cell.placeholderString = "Navigate to URL"
cell.isScrollable = true
cell.action = #selector(OmniBoxController.userEnteredURL)
cell.target = self
cell.sendsActionOnEndEditing = false //only send action when Return is pressed
cell.usesSingleLineMode = true
cell.focusRingType = .none
//cell.currentEditor()?.delegate = self // do live validation of input URL before Enter is pressed
}
// should have a grid of all tabs below the urlbox, safari style. NSCollectionView?
// https://developer.apple.com/library/mac/samplecode/GridMenu/Listings/ReadMe_txt.html#//apple_ref/doc/uid/DTS40010559-ReadMe_txt-DontLinkElementID_14
// or just show a segmented tabcontrol if clicking in the urlbox?
}
override func viewWillAppear() {
super.viewWillAppear()
}
override func viewDidAppear() {
super.viewDidAppear()
}
@objc func userEnteredURL() {
if let tf = view as? NSTextField, let url = validateURL(tf.stringValue, fallback: { [unowned self] (urlstr: String) -> URL? in
if AppScriptRuntime.shared.anyHandled(.handleUserInputtedInvalidURL, urlstr as NSString, self.webview!) { return nil } // app.js did its own thing
if AppScriptRuntime.shared.anyHandled(.handleUserInputtedKeywords, urlstr as NSString, self.webview!) { return nil } // app.js did its own thing
//FIXME: it should be able to return URL<->NSURL
return searchForKeywords(urlstr)
}){
if let wv = webview { // FIXME: Selector(gotoURL:) to nextResponder
wv.notifier?.authorizeNotifications(fromOrigin: url) // user typed this address in so they "trust" it to not be spammy?
view.window?.makeFirstResponder(wv) // no effect if this vc was brought up as a modal sheet
warn(url.description)
wv.gotoURL(url)
cancelOperation(self)
} else if let parent = parent { // tab-less browser window ...
parent.addChild(WebViewControllerOSX(webview: MPWebView(url: url))) // is parentVC the toolbar or contentView VC??
} else if let presenter = presentingViewController { // urlbox is a popover/sheet ...
presenter.addChild(WebViewControllerOSX(webview: MPWebView(url: url)))
// need parent of the presenter?
} else {
warn("no webviews-tabs and no parentVC ... WTF!!")
if let win = view.window {
// win.performSelector(onMainThread: #selector(BrowserViewControllerOSX.newTabPrompt), with: nil, waitUntilDone: false, modes: nil)
// win's responderChain is useless ...
}
}
} else {
warn("invalid url was requested!")
//displayAlert
//NSBeep()
}
}
override func cancelOperation(_ sender: Any?) {
warn()
view.resignFirstResponder() // relinquish key focus to webview
presentingViewController?.dismiss(self) //if a thoust art a popover, close thyself
}
deinit { webview = nil; representedObject = nil }
}
extension OmniBoxController: NSTextFieldDelegate { //NSControl
//func controlTextDidBeginEditing(_ obj: NSNotification)
//func controlTextDidChange(_ obj: NSNotification)
//func controlTextDidEndEditing(_ obj: NSNotification)
}
/*
replace textvalue with URL value, might be bound to title
"smart search" behavior:
if url was a common search provider query...
duckduckgo.com/?q=...
www.google.com/search?q=...
then extract the first query param, decode, and set the text value to that
*/
/*
//func textDidChange(aNotification: NSNotification)
@objc func textShouldEndEditing(_ textObject: NSText) -> Bool { //user attempting to focus out of field
if let _ = validateURL(textObject.string) { return true } //allow focusout
warn("invalid url entered: \(textObject.string)")
return false //NSBeep()s, keeps focus
}
//func textDidEndEditing(aNotification: NSNotification) { }
*/
@objc extension OmniBoxController: NSControlTextEditingDelegate {
//func control(_ control: NSControl, isValidObject obj: AnyObject) -> Bool
//func control(_ control: NSControl, didFailToFormatString string: String, errorDescription error: String?) -> Bool
func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool { warn(); return true }
//func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool
//func control(_ control: NSControl, textView textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String]
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
warn(commandSelector.description)
switch commandSelector {
case "noop:":
if let event = Application.shared.currentEvent, event.modifierFlags.contains(.command) {
guard let url = validateURL(control.stringValue) else { return false }
popup(webview?.wkclone(.URL(url))) // cmd-enter pops open a new tab
}
fallthrough
//case "insertLineBreak:":
// .ShiftKeyMask gotoURL privately (Safari opens new window with Shift)
// .AltKeyMask // gotoURL w/ new session privately (Safari downloads with Alt
// when Selector("insertTab:"):
// scrollToBeginningOfDocument: scrollToEndOfDocument:
default: return false
}
}
}
extension OmniBoxController: NSPopoverDelegate {
func popoverWillShow(_ notification: Notification) {
//urlbox.sizeToFit() //fixme: makes the box undersized sometimes
}
}
| b7c9eafea5494468987a68771bd60840 | 40.810219 | 202 | 0.72486 | false | false | false | false |
buscarini/miscel | refs/heads/master | Miscel/Classes/Extensions/String.swift | mit | 1 | //
// String.swift
// Miscel
//
// Created by Jose Manuel Sánchez Peñarroja on 11/11/15.
// Copyright © 2015 vitaminew. All rights reserved.
//
import UIKit
public extension String {
public static func length(_ string: String) -> Int {
return string.characters.count
}
public static func empty(_ string: String) -> Bool {
return self.length(string) == 0
}
public static func isBlank(_ string: String?) -> Bool {
guard let string = string else { return true }
return trimmed(string).characters.count == 0
}
public static func trimmed(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
public static func joined(_ components: [String?], separator: String = "\n") -> String {
return components.flatMap {$0}
.filter(not(isBlank))
.joined(separator: separator)
}
public static func plainString(_ htmlString: String) -> String {
return htmlString.withBRsAsNewLines().convertingHTMLToPlainText()
}
public static func localize(_ string: String) -> String {
return string.localized()
}
public func localized() -> String {
return NSLocalizedString(self, comment: "")
}
public static func wholeRange(_ string: String) -> Range<Index> {
return string.characters.startIndex..<string.characters.endIndex
}
public static func words(_ string: String) -> [String] {
var results : [String] = []
string.enumerateLinguisticTags(in: self.wholeRange(string), scheme: NSLinguisticTagScheme.lemma.rawValue, options: [], orthography: nil) {
// string.enumerateLinguisticTagsInRange(self.wholeRange(string), scheme: NSLinguisticTagWord, options: [], orthography: nil) {
(tag, tokenRange, sentenceRange,_) in
results.append(String(string[tokenRange]))
// results.append(string.substring(with: tokenRange))
// results.append(string.substringWithRange(tokenRange))
}
return results
}
}
| c5728492cdbce5f41aaab720c768a0b4 | 26.855072 | 140 | 0.708117 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.