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
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/QMUIKit/UIComponents/QMUIMarqueeLabel.swift
mit
1
// // QMUIMarqueeLabel.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // /** * 简易的跑马灯 label 控件,在文字超过 label 可视区域时会自动开启跑马灯效果展示文字,文字滚动时是首尾连接的效果(参考播放音乐时系统锁屏界面顶部的音乐标题)。 * @warning lineBreakMode 默认为 NSLineBreakByClipping(UILabel 默认值为 NSLineBreakByTruncatingTail)。 * @warning textAlignment 暂不支持 NSTextAlignmentJustified 和 NSTextAlignmentNatural。 * @warning 会忽略 numberOfLines 属性,强制以 1 来展示。 */ class QMUIMarqueeLabel: UILabel { /// 控制滚动的速度,1 表示一帧滚动 1pt,10 表示一帧滚动 10pt,默认为 .5,与系统一致。 var speed: CGFloat = 0.5 /// 当文字第一次显示在界面上,以及重复滚动到开头时都要停顿一下,这个属性控制停顿的时长,默认为 2.5(也是与系统一致),单位为秒。 var pauseDurationWhenMoveToEdge: TimeInterval = 2.5 /// 用于控制首尾连接的文字之间的间距,默认为 40pt。 var spacingBetweenHeadToTail: CGFloat = 40 /** * 自动判断 label 的 frame 是否超出当前的 UIWindow 可视范围,超出则自动停止动画。默认为 YES。 * @warning 某些场景并无法触发这个自动检测(例如直接调整 label.superview 的 frame 而不是 label 自身的 frame),这种情况暂不处理。 */ var automaticallyValidateVisibleFrame = true /// 在文字滚动到左右边缘时,是否要显示一个阴影渐变遮罩,默认为 true。 var shouldFadeAtEdge = true { didSet { if shouldFadeAtEdge { initFadeLayersIfNeeded() } updateFadeLayersHidden() } } /// 渐变遮罩的宽度,默认为 20。 var fadeWidth: CGFloat = 20 /// 渐变遮罩外边缘的颜色,请使用带 Alpha 通道的颜色 var fadeStartColor: UIColor? = UIColor(r: 255, g: 255, b: 255) { didSet { updateFadeLayerColors() } } /// 渐变遮罩内边缘的颜色,一般是 fadeStartColor 的 alpha 通道为 0 的色值 var fadeEndColor: UIColor? = UIColor(r: 255, g: 255, b: 255, a: 1) { didSet { updateFadeLayerColors() } } /// YES 表示文字会在打开 shouldFadeAtEdge 的情况下,从左边的渐隐区域之后显示,NO 表示不管有没有打开 shouldFadeAtEdge,都会从 label 的边缘开始显示。默认为 NO。 /// @note 如果文字宽度本身就没超过 label 宽度(也即无需滚动),此时必定不会显示渐隐,则这个属性不会影响文字的显示位置。 var textStartAfterFade = false private var displayLink: CADisplayLink? private var offsetX: CGFloat = 0 { didSet { updateFadeLayersHidden() } } private var textWidth: CGFloat = 0 private var fadeLeftLayer: CAGradientLayer? private var fadeRightLayer: CAGradientLayer? private var isFirstDisplay: Bool = true /// 绘制文本时重复绘制的次数,用于实现首尾连接的滚动效果,1 表示不首尾连接,大于 1 表示首尾连接。 private var textRepeatCount: Int = 2 override init(frame: CGRect) { super.init(frame: frame) lineBreakMode = .byClipping clipsToBounds = true // 显示非英文字符时,滚动的时候字符会稍微露出两端,所以这里直接裁剪掉 } deinit { displayLink?.invalidate() displayLink = nil } override func didMoveToWindow() { super.didMoveToWindow() if window != nil { displayLink = CADisplayLink(target: self, selector: #selector(handleDisplayLink)) displayLink?.add(to: RunLoop.current, forMode: RunLoop.Mode.common) } else { displayLink?.invalidate() displayLink = nil } offsetX = 0 displayLink?.isPaused = !shouldPlayDisplayLink } override var text: String? { didSet { offsetX = 0 textWidth = sizeThatFits(CGSize(width: .max, height: .max)).width displayLink?.isPaused = !shouldPlayDisplayLink } } override var attributedText: NSAttributedString? { didSet { offsetX = 0 textWidth = sizeThatFits(CGSize(width: .max, height: .max)).width displayLink?.isPaused = !shouldPlayDisplayLink } } override var frame: CGRect { didSet { let isSizeChanged = frame.size != oldValue.size if isSizeChanged { offsetX = 0 displayLink?.isPaused = !shouldPlayDisplayLink } } } override func drawText(in rect: CGRect) { var textInitialX: CGFloat = 0 if textAlignment == .left { textInitialX = 0 } else if textAlignment == .center { textInitialX = fmax(0, bounds.width.center(textWidth)) } else if textAlignment == .right { textInitialX = fmax(0, bounds.width - textWidth) } // 考虑渐变遮罩的偏移 var textOffsetXByFade: CGFloat = 0 let shouldTextStartAfterFade = shouldFadeAtEdge && textStartAfterFade && textWidth > bounds.width if shouldTextStartAfterFade && textInitialX < fadeWidth { textOffsetXByFade = fadeWidth } textInitialX += textOffsetXByFade for i in 0 ..< textRepeatCountConsiderTextWidth { attributedText?.draw(in: CGRect(x: offsetX + (textWidth + spacingBetweenHeadToTail) * CGFloat(i) + textInitialX, y: 0, width: textWidth, height: rect.height)) } // 自定义绘制就不需要调用 super // [super drawTextInRect:rectToDrawAfterAnimated]; } override func layoutSubviews() { super.layoutSubviews() if let fadeLeftLayer = fadeLeftLayer { fadeLeftLayer.frame = CGSize(width: fadeWidth, height: bounds.height).rect layer.qmui_bringSublayerToFront(fadeLeftLayer) // 显示非英文字符时,UILabel 内部会额外多出一层 layer 盖住了这里的 fadeLayer,所以要手动提到最前面 } if let fadeRightLayer = fadeRightLayer { fadeRightLayer.frame = CGRect(x: bounds.width - fadeWidth, y: 0, width: fadeWidth, height: bounds.height) layer.qmui_bringSublayerToFront(fadeRightLayer) // 显示非英文字符时,UILabel 内部会额外多出一层 layer 盖住了这里的 fadeLayer,所以要手动提到最前面 } } private var textRepeatCountConsiderTextWidth: Int { if textWidth < bounds.width { return 1 } return textRepeatCount } @objc func handleDisplayLink(_ displayLink: CADisplayLink) { if offsetX == 0 { displayLink.isPaused = true setNeedsDisplay() let delay = (isFirstDisplay || textRepeatCount <= 1) ? pauseDurationWhenMoveToEdge : 0 DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { displayLink.isPaused = !self.shouldPlayDisplayLink if !displayLink.isPaused { self.offsetX -= self.speed } }) if delay > 0 && textRepeatCount > 1 { isFirstDisplay = false } return } offsetX -= speed setNeedsDisplay() if -offsetX >= textWidth + (textRepeatCountConsiderTextWidth > 1 ? spacingBetweenHeadToTail : 0) { displayLink.isPaused = true let delay = textRepeatCount > 1 ? pauseDurationWhenMoveToEdge : 0 DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { self.offsetX = 0 self.handleDisplayLink(displayLink) }) } } private var shouldPlayDisplayLink: Bool { let result = window != nil && bounds.width > 0 && textWidth > (bounds.width - ((shouldFadeAtEdge && textStartAfterFade) ? fadeWidth : 0)) // 如果 label.frame 在 window 可视区域之外,也视为不可见,暂停掉 displayLink if result && automaticallyValidateVisibleFrame { let rectInWindow = window?.convert(frame, from: superview) ?? .zero let bounds = window?.bounds ?? .zero if !bounds.intersects(rectInWindow) { return false } } return result } private func updateFadeLayerColors() { func setColor(with layer: CAGradientLayer?) { guard let layer = layer else { return } if let fadeStartColor = fadeStartColor, let fadeEndColor = fadeEndColor { layer.colors = [ fadeStartColor.cgColor, fadeEndColor.cgColor, ] } else { layer.colors = nil } } setColor(with: fadeLeftLayer) setColor(with: fadeRightLayer) } private func updateFadeLayersHidden() { if fadeLeftLayer == nil || fadeRightLayer == nil { return } let shouldShowFadeLeftLayer = shouldFadeAtEdge && (offsetX < 0 || (offsetX == 0 && !isFirstDisplay)) fadeLeftLayer?.isHidden = !shouldShowFadeLeftLayer let shouldShowFadeRightLayer = shouldFadeAtEdge && (textWidth > bounds.width && offsetX != textWidth - bounds.width) fadeRightLayer?.isHidden = !shouldShowFadeRightLayer } private func initFadeLayersIfNeeded() { if fadeLeftLayer == nil { fadeLeftLayer = CAGradientLayer() // 请保留自带的 hidden 动画 fadeLeftLayer?.startPoint = CGPoint(x: 0, y: 0.5) fadeLeftLayer?.endPoint = CGPoint(x: 1, y: 0.5) layer.addSublayer(fadeLeftLayer!) setNeedsLayout() } if fadeRightLayer == nil { fadeRightLayer = CAGradientLayer() // 请保留自带的 hidden 动画 fadeRightLayer?.startPoint = CGPoint(x: 1, y: 0.5) fadeRightLayer?.endPoint = CGPoint(x: 0, y: 0.5) layer.addSublayer(fadeRightLayer!) setNeedsLayout() } updateFadeLayerColors() } // MARK: - Superclass override var numberOfLines: Int { didSet { numberOfLines = 1 } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - ReusableView /// 如果在可复用的 UIView 里使用(例如 UITableViewCell、UICollectionViewCell),由于 UIView 可能重复被使用,因此需要在某些显示/隐藏的时机去手动开启/关闭 label 的动画。如果在普通的 UIView 里使用则无需关注这一部分的代码。 extension QMUIMarqueeLabel { /** * 尝试开启 label 的滚动动画 * @return 是否成功开启 */ var requestToStartAnimation: Bool { automaticallyValidateVisibleFrame = false if shouldPlayDisplayLink { displayLink?.isPaused = false } return shouldPlayDisplayLink } /** * 尝试停止 label 的滚动动画 * @return 是否成功停止 */ var requestToStopAnimation: Bool { displayLink?.isPaused = true return true } }
d2e00fea87417a4676b4bcd7fb96a071
31.228296
170
0.607503
false
false
false
false
CalebeEmerick/Checkout
refs/heads/master
Source/Checkout/StoresController.swift
mit
1
// // StoresController.swift // Checkout // // Created by Calebe Emerick on 30/11/16. // Copyright © 2016 CalebeEmerick. All rights reserved. // import UIKit // MARK: - Variables & Outlets - final class StoresController : UIViewController { @IBOutlet fileprivate weak var container: UIView! @IBOutlet fileprivate weak var collectionView: UICollectionView! @IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView! fileprivate let storeError = StoreError.makeXib() fileprivate let dataSource = StoreDataSource() fileprivate let delegate = StoreDelegate() fileprivate let layout = StoreLayout() fileprivate var presenter: StorePresenter? } // MARK: - Life Cycle - extension StoresController { override func viewDidLoad() { super.viewDidLoad() changeNavigationBarBackButton() presenter = StorePresenter(storeView: self) delegate.selectedStore = { [weak self] store in self?.openTransactionController(with: store) } layout.setupCollectionView(for: collectionView, dataSource: dataSource, delegate: delegate) setErrorViewConstraints() presenter?.getStores() } } // MARK: - Methods - extension StoresController { fileprivate func setErrorViewConstraints() { DispatchQueue.main.async { self.storeError.alpha = 0 self.storeError.triedAgain = { self.tryLoadStoresAgain() } self.view.addSubview(self.storeError) self.storeError.translatesAutoresizingMaskIntoConstraints = false self.storeError.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true self.storeError.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true self.storeError.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8).isActive = true self.storeError.heightAnchor.constraint(equalToConstant: self.storeError.bounds.height).isActive = true } } fileprivate func changeStoreError(alpha: CGFloat) { UIView.animate(withDuration: 0.4) { self.storeError.alpha = alpha } } } // MARK: - StoresView Protocol - extension StoresController : StoresView { func showLoading() { activityIndicator.startAnimating() } func hideLoading() { activityIndicator.stopAnimating() } func showContainer() { hideLoading() UIView.animate(withDuration: 0.4) { self.container.alpha = 1 } } func update(stores: [Store]) { DispatchQueue.main.async { self.dataSource.stores = stores self.collectionView.reloadData() } } func showError(message: String) { storeError.message = message changeStoreError(alpha: 1) } func hideError() { changeStoreError(alpha: 0) } func tryLoadStoresAgain() { hideError() showLoading() presenter?.getStores() } func openTransactionController(with store: Store) { TransactionRouter.openCreditCardTransactionController(from: self, with: store) } }
2aaa9e8547acf6d7b348d774bb509ea0
26.314516
118
0.633009
false
false
false
false
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/Demo/Modules/Demos/Components/QDMultipleImagePickerPreviewViewController.swift
mit
1
// // QDMultipleImagePickerPreviewViewController.swift // QMUI.swift // // Created by qd-hxt on 2018/5/14. // Copyright © 2018年 伯驹 黄. All rights reserved. // import UIKit protocol QDMultipleImagePickerPreviewViewControllerDelegate: QMUIImagePickerPreviewViewControllerDelegate { func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QDMultipleImagePickerPreviewViewController, sendImageWithImagesAssetArray imagesAssetArray: [QMUIAsset]) } private let ImageCountLabelSize = CGSize(width: 18, height: 18) class QDMultipleImagePickerPreviewViewController: QMUIImagePickerPreviewViewController { weak var multipleDelegate: QDMultipleImagePickerPreviewViewControllerDelegate? { get { return delegate as? QDMultipleImagePickerPreviewViewControllerDelegate } set { delegate = newValue } } var imageCountLabel: QMUILabel! var assetsGroup: QMUIAssetsGroup? var shouldUseOriginImage: Bool = false private var sendButton: QMUIButton! private var originImageCheckboxButton: QMUIButton! private var bottomToolBarView: UIView! override func initSubviews() { super.initSubviews() bottomToolBarView = UIView() bottomToolBarView.backgroundColor = toolBarBackgroundColor view.addSubview(bottomToolBarView) sendButton = QMUIButton() sendButton.adjustsTitleTintColorAutomatically = true sendButton.adjustsImageTintColorAutomatically = true sendButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) sendButton.setTitle("发送", for: .normal) sendButton.titleLabel?.font = UIFontMake(16) sendButton.sizeToFit() sendButton.addTarget(self, action: #selector(handleSendButtonClick(_:)), for: .touchUpInside) bottomToolBarView.addSubview(sendButton) imageCountLabel = QMUILabel() imageCountLabel.backgroundColor = toolBarTintColor imageCountLabel.textColor = toolBarTintColor.qmui_colorIsDark ? UIColorWhite : UIColorBlack imageCountLabel.font = UIFontMake(12) imageCountLabel.textAlignment = .center imageCountLabel.lineBreakMode = .byCharWrapping imageCountLabel.layer.masksToBounds = true imageCountLabel.layer.cornerRadius = ImageCountLabelSize.width / 2 imageCountLabel.isHidden = true bottomToolBarView.addSubview(imageCountLabel) originImageCheckboxButton = QMUIButton() originImageCheckboxButton.adjustsTitleTintColorAutomatically = true originImageCheckboxButton.adjustsImageTintColorAutomatically = true originImageCheckboxButton.titleLabel?.font = UIFontMake(14) originImageCheckboxButton.setImage(UIImageMake("origin_image_checkbox"), for: .normal) originImageCheckboxButton.setImage(UIImageMake("origin_image_checkbox_checked"), for: .selected) originImageCheckboxButton.setImage(UIImageMake("origin_image_checkbox_checked"), for: [.selected, .highlighted]) originImageCheckboxButton.setTitle("原图", for: .normal) originImageCheckboxButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 5) originImageCheckboxButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) originImageCheckboxButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) originImageCheckboxButton.sizeToFit() originImageCheckboxButton.addTarget(self, action: #selector(handleOriginImageCheckboxButtonClick(_:)), for: .touchUpInside) bottomToolBarView.addSubview(originImageCheckboxButton) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let imagePreviewView = imagePreviewView { updateOriginImageCheckboxButton(with: imagePreviewView.currentImageIndex) } if selectedImageAssetArray.pointee.count > 0 { let selectedCount = selectedImageAssetArray.pointee.count imageCountLabel.text = "\(selectedCount)" imageCountLabel.isHidden = false } else { imageCountLabel.isHidden = true } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let bottomToolBarPaddingHorizontal: CGFloat = 12 let bottomToolBarContentHeight: CGFloat = 44 let bottomToolBarHeight = bottomToolBarContentHeight + view.qmui_safeAreaInsets.bottom bottomToolBarView.frame = CGRect(x: 0, y: view.bounds.height - bottomToolBarHeight, width: view.bounds.width, height: bottomToolBarHeight) sendButton.frame = sendButton.frame.setXY(bottomToolBarView.frame.width - bottomToolBarPaddingHorizontal - sendButton.frame.width, bottomToolBarContentHeight.center(sendButton.frame.height)) imageCountLabel.frame = CGRect(x: sendButton.frame.minX - 5 - ImageCountLabelSize.width, y: sendButton.frame.minY + sendButton.frame.height.center(ImageCountLabelSize.height), width: ImageCountLabelSize.width, height: ImageCountLabelSize.height) originImageCheckboxButton.frame = originImageCheckboxButton.frame.setXY(bottomToolBarPaddingHorizontal, bottomToolBarContentHeight.center(originImageCheckboxButton.frame.height)) } override var toolBarTintColor: UIColor { didSet { bottomToolBarView.tintColor = toolBarTintColor imageCountLabel.backgroundColor = toolBarTintColor imageCountLabel.textColor = toolBarTintColor.qmui_colorIsDark ? UIColorWhite : UIColorBlack } } override func singleTouch(in zoomImageView: QMUIZoomImageView, location: CGPoint) { super.singleTouch(in: zoomImageView, location: location) bottomToolBarView.isHidden = !bottomToolBarView.isHidden } override func zoomImageView(_ imageView: QMUIZoomImageView, didHideVideoToolbar didHide: Bool) { super.zoomImageView(imageView, didHideVideoToolbar: didHide) bottomToolBarView.isHidden = didHide } private func updateOriginImageCheckboxButton(with index: Int) { let asset = imagesAssetArray[index] if asset.assetType == .audio || asset.assetType == .video { originImageCheckboxButton.isHidden = true } else { originImageCheckboxButton.isHidden = false if originImageCheckboxButton.isSelected { asset.assetSize { (size) in self.originImageCheckboxButton.setTitle("原图(\(QDUIHelper.humanReadableFileSize(size)))", for: .normal) self.originImageCheckboxButton.sizeToFit() self.bottomToolBarView.setNeedsLayout() } } } } @objc private func handleSendButtonClick(_ sender: Any) { navigationController?.dismiss(animated: true, completion: { if self.selectedImageAssetArray.pointee.count == 0 , let imagePreviewView = self.imagePreviewView { // 如果没选中任何一张,则点击发送按钮直接发送当前这张大图 let currentAsset = self.imagesAssetArray[imagePreviewView.currentImageIndex] self.selectedImageAssetArray.pointee.append(currentAsset) } self.multipleDelegate?.imagePickerPreviewViewController(self, sendImageWithImagesAssetArray: self.selectedImageAssetArray.pointee) }) } @objc private func handleOriginImageCheckboxButtonClick(_ button: UIButton) { if button.isSelected { button.isSelected = false button.setTitle("原图", for: .normal) button.sizeToFit() bottomToolBarView.setNeedsLayout() } else { button.isSelected = true if let imagePreviewView = imagePreviewView { updateOriginImageCheckboxButton(with: imagePreviewView.currentImageIndex) } if !checkboxButton.isSelected { checkboxButton.sendActions(for: .touchUpInside) } } shouldUseOriginImage = button.isSelected } } extension QDMultipleImagePickerPreviewViewController { override func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, renderZoomImageView zoomImageView: QMUIZoomImageView, at index: Int) { super.imagePreviewView(imagePreviewView, renderZoomImageView: zoomImageView, at: index) // videToolbarMargins 是利用 UIAppearance 赋值的,也即意味着要在 addSubview 之后才会被赋值,而在 renderZoomImageView 里,zoomImageView 可能尚未被添加到 view 层级里,所以无法通过 zoomImageView.videoToolbarMargins 获取到原来的值,因此只能通过 [QMUIZoomImageView appearance] 的方式获取 // zoomImageView.videoToolbarMargins = // zoomImageView.videoCenteredPlayButtonImage } override func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, willScrollHalfTo index: Int) { super.imagePreviewView(imagePreviewView, willScrollHalfTo: index) updateOriginImageCheckboxButton(with: index) } }
bc0bbec2dee83462e84b66316e873c1d
46.333333
253
0.709067
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/CommentViewController.swift
apache-2.0
1
// // CommentViewController.swift // Slide for Reddit // // Created by Carlos Crane on 12/30/16. // Copyright © 2016 Haptic Apps. All rights reserved. // import Anchorage import AudioToolbox.AudioServices import MaterialComponents.MDCActivityIndicator import RealmSwift import reddift import RLBAlertsPickers import SDCAlertView import UIKit import YYText class CommentViewController: MediaViewController, UITableViewDelegate, UITableViewDataSource, TTTAttributedCellDelegate, LinkCellViewDelegate, UISearchBarDelegate, SubmissionMoreDelegate, ReplyDelegate, UIScrollViewDelegate { var version = 0 var first = true var swipeBackAdded = false var shouldSetupSwipe = false var fullWidthBackGestureRecognizer: UIPanGestureRecognizer! var cellGestureRecognizer: UIPanGestureRecognizer! var liveView: UILabel? var liveNewCount = 0 func hide(index: Int) { if index >= 0 { self.navigationController?.popViewController(animated: true) } } func subscribe(link: RSubmission) { let sub = link.subreddit let alrController = UIAlertController.init(title: "Follow r/\(sub)", message: nil, preferredStyle: .alert) if AccountController.isLoggedIn { let somethingAction = UIAlertAction(title: "Subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in Subscriptions.subscribe(sub, true, session: self.session!) self.subChanged = true BannerUtil.makeBanner(text: "Subscribed to r/\(sub)", color: ColorUtil.accentColorForSub(sub: sub), seconds: 3, context: self, top: true) }) alrController.addAction(somethingAction) } let somethingAction = UIAlertAction(title: "Casually subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in Subscriptions.subscribe(sub, false, session: self.session!) self.subChanged = true BannerUtil.makeBanner(text: "r/\(sub) added to your subreddit list", color: ColorUtil.accentColorForSub(sub: sub), seconds: 3, context: self, top: true) }) alrController.addAction(somethingAction) alrController.addCancelButton() alrController.modalPresentationStyle = .fullScreen self.present(alrController, animated: true, completion: {}) } override var prefersStatusBarHidden: Bool { return SettingValues.fullyHideNavbar } func textChanged(_ string: String) { self.savedText = string } override var keyCommands: [UIKeyCommand]? { if isReply || UIResponder.isFirstResponderTextField { return nil } else { return [ UIKeyCommand(input: " ", modifierFlags: [], action: #selector(spacePressed)), UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(spacePressed)), UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(spacePressedUp)), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(upvote(_:)), discoverabilityTitle: "Like post"), UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(reply(_:)), discoverabilityTitle: "Reply to post"), UIKeyCommand(input: "s", modifierFlags: .command, action: #selector(save(_:)), discoverabilityTitle: "Save post"), ] } } var menuCell: CommentDepthCell? var menuId: String? var savedText: String? public var inHeadView = UIView() var commentDepthColors = [UIColor]() var panGesture: UIPanGestureRecognizer! var translatingCell: CommentDepthCell? var didDisappearCompletely = false var live = false var liveTimer = Timer() var refreshControl: UIRefreshControl! var tableView: UITableView! var sortButton = UIButton() var jump: UIView! func isMenuShown() -> Bool { return menuCell != nil } func getMenuShown() -> String? { return menuId } func createJumpButton(_ forced: Bool = false) { if SettingValues.commentJumpButton == .DISABLED { return } if self.navigationController?.view != nil { let view = self.navigationController!.view! if jump != nil && forced { jump.removeFromSuperview() jump = nil } if jump == nil { jump = UIView.init(frame: CGRect.init(x: 70, y: 70, width: 0, height: 0)).then { $0.clipsToBounds = true $0.backgroundColor = ColorUtil.theme.backgroundColor $0.layer.cornerRadius = 20 } let image = UIImageView.init(frame: CGRect.init(x: 50, y: 50, width: 0, height: 0)).then { $0.image = UIImage(sfString: SFSymbol.chevronDown, overrideString: "down")?.getCopy(withSize: CGSize.square(size: 30), withColor: ColorUtil.theme.navIconColor) $0.contentMode = .center } jump.addSubview(image) image.edgeAnchors == jump.edgeAnchors jump.addTapGestureRecognizer { self.goDown(self.jump) } jump.addLongTapGestureRecognizer { self.goUp(self.jump) } } view.addSubview(jump) jump.bottomAnchor == view.bottomAnchor - 24 if SettingValues.commentJumpButton == .RIGHT { jump.rightAnchor == view.rightAnchor - 24 } else { jump.leftAnchor == view.leftAnchor + 24 } jump.widthAnchor == 40 jump.heightAnchor == 40 jump.transform = CGAffineTransform(translationX: 0, y: 70) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { self.jump?.transform = .identity }, completion: nil) } } func removeJumpButton() { if SettingValues.commentJumpButton == .DISABLED { return } if self.jump != nil { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { self.jump?.transform = CGAffineTransform(translationX: 0, y: 70) }, completion: { _ in self.jump?.removeFromSuperview() }) } } override func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { self.setAlphaOfBackgroundViews(alpha: 0.25) // self.setBackgroundView() } func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool { self.setAlphaOfBackgroundViews(alpha: 1) return true } func showFilterMenu(_ cell: LinkCellView) { //Not implemented } func setLive() { self.sort = .new self.live = true self.reset = true self.activityIndicator.removeFromSuperview() let barButton = UIBarButtonItem(customView: self.activityIndicator) self.navigationItem.rightBarButtonItems = [barButton] self.activityIndicator.startAnimating() self.refresh(self) } var progressDot = UIView() func startPulse() { self.progressDot = UIView() progressDot.alpha = 0.7 progressDot.backgroundColor = .clear let startAngle = -CGFloat.pi / 2 let center = CGPoint(x: 20 / 2, y: 20 / 2) let radius = CGFloat(20 / 2) let arc = CGFloat.pi * CGFloat(2) * 1 let cPath = UIBezierPath() cPath.move(to: center) cPath.addLine(to: CGPoint(x: center.x + radius * cos(startAngle), y: center.y + radius * sin(startAngle))) cPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: arc + startAngle, clockwise: true) cPath.addLine(to: CGPoint(x: center.x, y: center.y)) let circleShape = CAShapeLayer() circleShape.path = cPath.cgPath circleShape.strokeColor = GMColor.red500Color().cgColor circleShape.fillColor = GMColor.red500Color().cgColor circleShape.lineWidth = 1.5 // add sublayer for layer in progressDot.layer.sublayers ?? [CALayer]() { layer.removeFromSuperlayer() } progressDot.layer.removeAllAnimations() progressDot.layer.addSublayer(circleShape) let pulseAnimation = CABasicAnimation(keyPath: "transform.scale") pulseAnimation.duration = 0.5 pulseAnimation.toValue = 1.2 pulseAnimation.fromValue = 0.2 pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) pulseAnimation.autoreverses = false pulseAnimation.repeatCount = Float.greatestFiniteMagnitude let fadeAnimation = CABasicAnimation(keyPath: "opacity") fadeAnimation.duration = 0.5 fadeAnimation.toValue = 0 fadeAnimation.fromValue = 2.5 fadeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) fadeAnimation.autoreverses = false fadeAnimation.repeatCount = Float.greatestFiniteMagnitude progressDot.frame = CGRect(x: 0, y: 0, width: 20, height: 20) liveB = UIBarButtonItem.init(customView: progressDot) self.navigationItem.rightBarButtonItems = [self.sortB, self.searchB, self.liveB] progressDot.layer.add(pulseAnimation, forKey: "scale") progressDot.layer.add(fadeAnimation, forKey: "fade") } @objc func loadNewComments() { var name = submission!.name if name.contains("t3_") { name = name.replacingOccurrences(of: "t3_", with: "") } do { try session?.getArticles(name, sort: .new, limit: SettingValues.commentLimit, completion: { (result) in switch result { case .failure(let error): print(error) case .success(let tuple): DispatchQueue.main.async(execute: { () -> Void in var queue: [Object] = [] let startDepth = 1 let listing = tuple.1 for child in listing.children { let incoming = self.extendKeepMore(in: child, current: startDepth) for i in incoming { if i.1 == 1 { let item = RealmDataWrapper.commentToRealm(comment: i.0, depth: i.1) if self.content[item.getIdentifier()] == nil { self.content[item.getIdentifier()] = item self.cDepth[item.getIdentifier()] = i.1 queue.append(item) self.updateStrings([i]) } } } } let datasetPosition = 0 let realPosition = 0 var ids: [String] = [] for item in queue { let id = item.getIdentifier() ids.append(id) self.content[id] = item } if queue.count != 0 { self.dataArray.insert(contentsOf: ids, at: datasetPosition) self.comments.insert(contentsOf: ids, at: realPosition) self.doArrays() var paths: [IndexPath] = [] for i in stride(from: datasetPosition, to: datasetPosition + queue.count, by: 1) { self.liveNewCount += 1 paths.append(IndexPath.init(row: i, section: 0)) } let contentHeight = self.tableView.contentSize.height let offsetY = self.tableView.contentOffset.y let bottomOffset = contentHeight - offsetY if #available(iOS 11.0, *) { CATransaction.begin() CATransaction.setDisableActions(true) self.isHiding = true self.tableView.performBatchUpdates({ self.tableView.insertRows(at: paths, with: .fade) }, completion: { (_) in self.lastY = self.tableView.contentOffset.y self.olderY = self.tableView.contentOffset.y self.isHiding = false if self.tableView.contentOffset.y > (self.tableView.tableHeaderView?.frame.size.height ?? 60) + 64 + 10 { if self.liveView == nil { self.liveView = UILabel().then { $0.textColor = .white $0.font = UIFont.boldSystemFont(ofSize: 10) $0.backgroundColor = ColorUtil.getColorForSub(sub: self.subreddit) $0.layer.cornerRadius = 20 $0.clipsToBounds = true $0.textAlignment = .center $0.addTapGestureRecognizer { UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: { self.tableView.contentOffset.y = (self.tableView.tableHeaderView?.frame.size.height ?? 60) + 64 }, completion: { (_) in self.lastY = self.tableView.contentOffset.y self.olderY = self.tableView.contentOffset.y }) } } self.view.addSubview(self.liveView!) self.liveView!.topAnchor == self.view.safeTopAnchor + 20 self.liveView!.centerXAnchor == self.view.centerXAnchor self.liveView!.heightAnchor == 40 self.liveView!.widthAnchor == 130 } self.liveView!.text = "\(self.liveNewCount) NEW COMMENT\((self.liveNewCount > 1) ? "S" : "")" self.liveView!.setNeedsLayout() } //self.tableView.contentOffset = CGPoint(x: 0, y: self.tableView.contentSize.height - bottomOffset) CATransaction.commit() }) } else { self.tableView.insertRows(at: paths, with: .fade) } } }) } }) } catch { } } func applyFilters() { if PostFilter.filter([submission!], previous: nil, baseSubreddit: "all").isEmpty { self.navigationController?.popViewController(animated: true) } } init(submission: RSubmission, single: Bool) { self.submission = submission self.sort = SettingValues.getCommentSorting(forSubreddit: submission.subreddit) self.single = single self.text = [:] super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: submission.subreddit)) } init(submission: RSubmission) { self.submission = submission self.sort = SettingValues.getCommentSorting(forSubreddit: submission.subreddit) self.text = [:] super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: submission.subreddit)) } init(submission: String, subreddit: String?, np: Bool = false) { self.submission = RSubmission() self.np = np self.submission!.name = submission self.submission!.id = submission.startsWith("t3") ? submission : ("t3_" + submission) hasSubmission = false if subreddit != nil { self.subreddit = subreddit! self.sort = SettingValues.getCommentSorting(forSubreddit: self.subreddit) self.submission!.subreddit = subreddit! } self.text = [:] super.init(nibName: nil, bundle: nil) if subreddit != nil { self.title = subreddit! setBarColors(color: ColorUtil.getColorForSub(sub: subreddit!)) } } init(submission: String, comment: String, context: Int, subreddit: String, np: Bool = false) { self.submission = RSubmission() self.sort = SettingValues.getCommentSorting(forSubreddit: self.submission!.subreddit) self.submission!.name = submission self.submission!.subreddit = subreddit hasSubmission = false self.context = comment self.np = np self.text = [:] self.contextNumber = context super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: subreddit)) } var parents: [String: String] = [:] var approved: [String] = [] var removed: [String] = [] var offline = false var np = false var modLink = "" var authorColor: UIColor = ColorUtil.theme.fontColor func replySent(comment: Comment?, cell: CommentDepthCell?) { if comment != nil && cell != nil { DispatchQueue.main.async(execute: { () -> Void in let startDepth = (self.cDepth[cell!.comment!.getIdentifier()] ?? 0) + 1 let queue: [Object] = [RealmDataWrapper.commentToRComment(comment: comment!, depth: startDepth)] self.cDepth[comment!.getId()] = startDepth var realPosition = 0 for c in self.comments { let id = c if id == cell!.comment!.getIdentifier() { break } realPosition += 1 } var insertIndex = 0 for c in self.dataArray { let id = c if id == cell!.comment!.getIdentifier() { break } insertIndex += 1 } var ids: [String] = [] for item in queue { let id = item.getIdentifier() ids.append(id) self.content[id] = item } self.dataArray.insert(contentsOf: ids, at: insertIndex + 1) self.comments.insert(contentsOf: ids, at: realPosition + 1) self.updateStringsSingle(queue) self.doArrays() self.isReply = false self.isEditing = false self.tableView.reloadData() }) } else if comment != nil && cell == nil { DispatchQueue.main.async(execute: { () -> Void in let startDepth = 1 let queue: [Object] = [RealmDataWrapper.commentToRComment(comment: comment!, depth: startDepth)] self.cDepth[comment!.getId()] = startDepth let realPosition = 0 self.menuId = nil var ids: [String] = [] for item in queue { let id = item.getIdentifier() ids.append(id) self.content[id] = item } self.dataArray.insert(contentsOf: ids, at: 0) self.comments.insert(contentsOf: ids, at: realPosition == 0 ? 0 : realPosition + 1) self.updateStringsSingle(queue) self.doArrays() self.isReply = false self.isEditing = false self.tableView.reloadData() }) } } func openComments(id: String, subreddit: String?) { //don't do anything } func editSent(cr: Comment?, cell: CommentDepthCell) { if cr != nil { DispatchQueue.main.async(execute: { () -> Void in var realPosition = 0 var comment = cell.comment! for c in self.comments { let id = c if id == comment.getIdentifier() { break } realPosition += 1 } var insertIndex = 0 for c in self.dataArray { let id = c if id == comment.getIdentifier() { break } insertIndex += 1 } comment = RealmDataWrapper.commentToRComment(comment: cr!, depth: self.cDepth[comment.getIdentifier()] ?? 1) self.dataArray.remove(at: insertIndex) self.dataArray.insert(comment.getIdentifier(), at: insertIndex) self.comments.remove(at: realPosition) self.comments.insert(comment.getIdentifier(), at: realPosition) self.content[comment.getIdentifier()] = comment self.updateStringsSingle([comment]) self.doArrays() self.isEditing = false self.isReply = false self.tableView.reloadData() self.discard() }) } } func discard() { } func updateHeight(textView: UITextView) { UIView.setAnimationsEnabled(false) self.tableView.beginUpdates() self.tableView.endUpdates() UIView.setAnimationsEnabled(true) } internal func pushedMoreButton(_ cell: CommentDepthCell) { } @objc func save(_ cell: LinkCellView) { do { let state = !ActionStates.isSaved(s: cell.link!) print(cell.link!.id) try session?.setSave(state, name: (cell.link?.id)!, completion: { (result) in if result.error != nil { print(result.error!) } DispatchQueue.main.async { BannerUtil.makeBanner(text: state ? "Saved" : "Unsaved", color: ColorUtil.accentColorForSub(sub: self.subreddit), seconds: 1, context: self) } }) ActionStates.setSaved(s: cell.link!, saved: !ActionStates.isSaved(s: cell.link!)) History.addSeen(s: cell.link!, skipDuplicates: true) cell.refresh() if parent is PagingCommentViewController { (parent as! PagingCommentViewController).reloadCallback?() } } catch { } } func doHeadView(_ size: CGSize) { inHeadView.removeFromSuperview() var statusBarHeight = UIApplication.shared.statusBarUIView?.frame.size.height ?? 0 if statusBarHeight == 0 { statusBarHeight = (self.navigationController?.navigationBar.frame.minY ?? 20) } inHeadView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: max(self.view.frame.size.width, self.view.frame.size.height), height: statusBarHeight)) if submission != nil { self.inHeadView.backgroundColor = SettingValues.fullyHideNavbar ? .clear : (!SettingValues.reduceColor ? ColorUtil.getColorForSub(sub: submission!.subreddit) : ColorUtil.theme.foregroundColor) } let landscape = size.width > size.height || (self.navigationController is TapBehindModalViewController && self.navigationController!.modalPresentationStyle == .pageSheet) if navigationController?.viewControllers.first != self && !landscape { self.navigationController?.view.addSubview(inHeadView) } } func saveComment(_ comment: RComment) { do { let state = !ActionStates.isSaved(s: comment) try session?.setSave(state, name: comment.id, completion: { (_) in DispatchQueue.main.async { BannerUtil.makeBanner(text: state ? "Saved" : "Unsaved", color: ColorUtil.accentColorForSub(sub: self.sub), seconds: 1, context: self) } }) ActionStates.setSaved(s: comment, saved: !ActionStates.isSaved(s: comment)) } catch { } } var searchBar = UISearchBar() func reloadHeights() { //UIView.performWithoutAnimation { tableView.beginUpdates() tableView.endUpdates() // } } func reloadHeightsNone() { UIView.performWithoutAnimation { tableView.beginUpdates() tableView.endUpdates() } } func prepareReply() { tableView.beginUpdates() tableView.endUpdates() /*var index = 0 for comment in self.comments { if (comment.contains(getMenuShown()!)) { let indexPath = IndexPath.init(row: index, section: 0) self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.none, animated: true) break } else { index += 1 } }*/ } func hide(_ cell: LinkCellView) { } @objc func reply(_ cell: LinkCellView) { if !offline { VCPresenter.presentAlert(TapBehindModalViewController.init(rootViewController: ReplyViewController.init(submission: cell.link!, sub: cell.link!.subreddit, delegate: self)), parentVC: self) } } @objc func upvote(_ cell: LinkCellView) { do { try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up, name: (cell.link?.id)!, completion: { (_) in }) ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up) History.addSeen(s: cell.link!, skipDuplicates: true) cell.refresh() if parent is PagingCommentViewController { _ = (parent as! PagingCommentViewController).reloadCallback?() } _ = CachedTitle.getTitle(submission: cell.link!, full: false, true, gallery: false) } catch { } } func deleteSelf(_ cell: LinkCellView) { if !offline { do { try session?.deleteCommentOrLink(cell.link!.getId(), completion: { (_) in DispatchQueue.main.async { if (self.navigationController?.modalPresentationStyle ?? .formSheet) == .formSheet { self.navigationController?.dismiss(animated: true) } else { self.navigationController?.popViewController(animated: true) } } }) } catch { } } } var oldPosition: CGPoint = CGPoint.zero func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { if scrollView.contentOffset.y > oldPosition.y { oldPosition = scrollView.contentOffset return true } else { tableView.setContentOffset(oldPosition, animated: true) oldPosition = CGPoint.zero } return false } var shouldAnimateLoad = false func downvote(_ cell: LinkCellView) { do { try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down, name: (cell.link?.id)!, completion: { (_) in }) ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down) History.addSeen(s: cell.link!, skipDuplicates: true) cell.refresh() if parent is PagingCommentViewController { (parent as! PagingCommentViewController).reloadCallback?() } } catch { } } func more(_ cell: LinkCellView) { if !offline { PostActions.showMoreMenu(cell: cell, parent: self, nav: self.navigationController, mutableList: false, delegate: self, index: 0) } } func readLater(_ cell: LinkCellView) { guard let link = cell.link else { return } ReadLater.toggleReadLater(link: link) if parent is PagingCommentViewController { (parent as! PagingCommentViewController).reloadCallback?() } cell.refresh() } var submission: RSubmission? var session: Session? var cDepth: Dictionary = [String: Int]() var comments: [String] = [] var hiddenPersons = Set<String>() var hidden: Set<String> = Set<String>() var headerCell: LinkCellView! var hasSubmission = true var paginator: Paginator? = Paginator() var context: String = "" var contextNumber: Int = 3 var dataArray: [String] = [] var filteredData: [String] = [] var content: Dictionary = [String: Object]() func doArrays() { dataArray = comments.filter({ (s) -> Bool in !hidden.contains(s) }) } var sort: CommentSort = SettingValues.defaultCommentSorting func getSelf() -> CommentViewController { return self } var reset = false var indicatorSet = false func loadOffline() { self.loaded = true DispatchQueue.main.async { self.offline = true do { let realm = try Realm() if let listing = realm.objects(RSubmission.self).filter({ (item) -> Bool in return item.id == self.submission!.id }).first { self.comments = [] self.hiddenPersons = [] var temp: [Object] = [] self.hidden = [] self.text = [:] var currentIndex = 0 self.parents = [:] var currentOP = "" for child in listing.comments { if child.depth == 1 { currentOP = child.author } self.parents[child.getIdentifier()] = currentOP currentIndex += 1 temp.append(child) self.content[child.getIdentifier()] = child self.comments.append(child.getIdentifier()) self.cDepth[child.getIdentifier()] = child.depth } if !self.comments.isEmpty { self.updateStringsSingle(temp) self.doArrays() if !self.offline { self.lastSeen = (self.context.isEmpty ? History.getSeenTime(s: self.submission!) : Double(0)) } } DispatchQueue.main.async(execute: { () -> Void in self.refreshControl?.endRefreshing() self.indicator.stopAnimating() if !self.comments.isEmpty { var time = timeval(tv_sec: 0, tv_usec: 0) gettimeofday(&time, nil) self.tableView.reloadData() } if self.comments.isEmpty { BannerUtil.makeBanner(text: "No cached comments found!", color: ColorUtil.accentColorForSub(sub: self.subreddit), seconds: 3, context: self) } else { // BannerUtil.makeBanner(text: "Showing cached comments", color: ColorUtil.accentColorForSub(sub: self.subreddit), seconds: 5, context: self) } }) } } catch { BannerUtil.makeBanner(text: "No cached comments found!", color: ColorUtil.accentColorForSub(sub: self.subreddit), seconds: 3, context: self) } } } @objc func refresh(_ sender: AnyObject) { self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y - (self.refreshControl!.frame.size.height)), animated: true) session = (UIApplication.shared.delegate as! AppDelegate).session approved.removeAll() removed.removeAll() self.shouldAnimateLoad = false content.removeAll() self.liveTimer.invalidate() text.removeAll() dataArray.removeAll() cDepth.removeAll() comments.removeAll() hidden.removeAll() tableView.reloadData() if let link = self.submission { sub = link.subreddit self.setupTitleView(link.subreddit, icon: link.subreddit_icon) reset = false do { var name = link.name if name.contains("t3_") { name = name.replacingOccurrences(of: "t3_", with: "") } if offline { self.loadOffline() } else { try session?.getArticles(name, sort: sort == .suggested ? nil : sort, comments: (context.isEmpty ? nil : [context]), context: 3, limit: SettingValues.commentLimit, completion: { (result) -> Void in switch result { case .failure(let error): print(error) self.loadOffline() case .success(let tuple): let startDepth = 1 let listing = tuple.1 self.comments = [] self.hiddenPersons = [] self.hidden = [] self.text = [:] self.content = [:] if self.submission == nil || self.submission!.id.isEmpty() { self.submission = RealmDataWrapper.linkToRSubmission(submission: tuple.0.children[0] as! Link) } else { self.submission = RealmDataWrapper.updateSubmission(self.submission!, tuple.0.children[0] as! Link) } var allIncoming: [(Thing, Int)] = [] self.submission!.comments.removeAll() self.parents = [:] for child in listing.children { let incoming = self.extendKeepMore(in: child, current: startDepth) allIncoming.append(contentsOf: incoming) var currentIndex = 0 var currentOP = "" for i in incoming { let item = RealmDataWrapper.commentToRealm(comment: i.0, depth: i.1) self.content[item.getIdentifier()] = item self.comments.append(item.getIdentifier()) if item is RComment { self.submission!.comments.append(item as! RComment) } if i.1 == 1 && item is RComment { currentOP = (item as! RComment).author } self.parents[item.getIdentifier()] = currentOP currentIndex += 1 self.cDepth[item.getIdentifier()] = i.1 } } var time = timeval(tv_sec: 0, tv_usec: 0) gettimeofday(&time, nil) self.paginator = listing.paginator if !self.comments.isEmpty { do { let realm = try Realm() // TODO: - insert realm.beginWrite() for comment in self.comments { if let content = self.content[comment] { if content is RComment { realm.create(RComment.self, value: content, update: .all) } else { realm.create(RMore.self, value: content, update: .all) } if content is RComment { self.submission!.comments.append(content as! RComment) } } } realm.create(type(of: self.submission!), value: self.submission!, update: .all) try realm.commitWrite() } catch { } } if !allIncoming.isEmpty { self.updateStrings(allIncoming) } self.doArrays() self.lastSeen = (self.context.isEmpty ? History.getSeenTime(s: self.submission!) : Double(0)) History.setComments(s: link) History.addSeen(s: link, skipDuplicates: false) DispatchQueue.main.async(execute: { () -> Void in if !self.hasSubmission { self.headerCell = FullLinkCellView() self.headerCell?.del = self self.headerCell?.parentViewController = self self.hasDone = true self.headerCell?.aspectWidth = self.tableView.bounds.size.width self.headerCell?.configure(submission: self.submission!, parent: self, nav: self.navigationController, baseSub: self.submission!.subreddit, parentWidth: self.view.frame.size.width, np: self.np) if self.submission!.isSelf { self.headerCell?.showBody(width: self.view.frame.size.width - 24) } self.tableView.tableHeaderView = UIView(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.width, height: 0.01)) if let tableHeaderView = self.headerCell { var frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: tableHeaderView.estimateHeight(true, np: self.np)) // Add safe area insets to left and right if available if #available(iOS 11.0, *) { frame = frame.insetBy(dx: max(self.view.safeAreaInsets.left, self.view.safeAreaInsets.right), dy: 0) } if self.tableView.tableHeaderView == nil || !frame.equalTo(tableHeaderView.frame) { tableHeaderView.frame = frame tableHeaderView.layoutIfNeeded() let view = UIView(frame: tableHeaderView.frame) view.addSubview(tableHeaderView) self.tableView.tableHeaderView = view self.setupFullSwipeView(self.tableView.tableHeaderView) } } self.setupTitleView(self.submission!.subreddit, icon: self.submission!.subreddit_icon) self.navigationItem.backBarButtonItem?.title = "" self.setBarColors(color: ColorUtil.getColorForSub(sub: self.submission!.subreddit)) } else { self.headerCell?.aspectWidth = self.tableView.bounds.size.width self.headerCell?.refreshLink(self.submission!, np: self.np) if self.submission!.isSelf { self.headerCell?.showBody(width: self.view.frame.size.width - 24) } var frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.headerCell!.estimateHeight(true, true, np: self.np)) // Add safe area insets to left and right if available if #available(iOS 11.0, *) { frame = frame.insetBy(dx: max(self.view.safeAreaInsets.left, self.view.safeAreaInsets.right), dy: 0) } self.headerCell!.contentView.frame = frame self.headerCell!.contentView.layoutIfNeeded() let view = UIView(frame: self.headerCell!.contentView.frame) view.addSubview(self.headerCell!.contentView) self.tableView.tableHeaderView = view self.setupFullSwipeView(self.tableView.tableHeaderView) } self.refreshControl?.endRefreshing() self.activityIndicator.stopAnimating() if self.live { self.liveTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.loadNewComments), userInfo: nil, repeats: true) self.startPulse() } else { if self.sortB != nil && self.searchB != nil { self.navigationItem.rightBarButtonItems = [self.sortB, self.searchB] } } self.indicator.stopAnimating() self.indicator.isHidden = true var index = 0 var loaded = true if SettingValues.hideAutomod && self.context.isEmpty() && self.submission!.author != AccountController.currentName && !self.comments.isEmpty { if let comment = self.content[self.comments[0]] as? RComment { if comment.author == "AutoModerator" { var toRemove = [String]() toRemove.append(comment.getIdentifier()) self.modLink = comment.permalink self.hidden.insert(comment.getIdentifier()) for next in self.walkTreeFlat(n: comment.getIdentifier()) { toRemove.append(next) self.hidden.insert(next) } self.dataArray = self.dataArray.filter({ (comment) -> Bool in return !toRemove.contains(comment) }) self.modB.customView?.alpha = 1 } } } if !self.context.isEmpty() { for comment in self.comments { if comment.contains(self.context) { self.menuId = comment self.tableView.reloadData() loaded = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.55) { self.goToCell(i: index) } break } else { index += 1 } } if !loaded { self.tableView.reloadData() } } else if SettingValues.collapseDefault { self.tableView.reloadData() self.collapseAll() } else { if self.finishedPush { self.reloadTableViewAnimated() } else { self.shouldAnimateLoad = true } } self.loaded = true }) } }) } } catch { print(error) } } } var loaded = false var lastSeen: Double = NSDate().timeIntervalSince1970 var savedTitleView: UIView? var savedHeaderView: UIView? override var navigationItem: UINavigationItem { if parent != nil && parent! is PagingCommentViewController { return parent!.navigationItem } else { return super.navigationItem } } func setupTitleView(_ sub: String, icon: String) { let label = UILabel() label.text = " \(SettingValues.reduceColor ? " " : "")\(sub)" label.textColor = SettingValues.reduceColor ? ColorUtil.theme.fontColor : .white label.adjustsFontSizeToFitWidth = true label.font = UIFont.boldSystemFont(ofSize: 20) if SettingValues.reduceColor { let sideView = UIImageView(frame: CGRect(x: 5, y: 5, width: 30, height: 30)) let subreddit = sub sideView.backgroundColor = ColorUtil.getColorForSub(sub: subreddit) if let icon = Subscriptions.icon(for: subreddit) { sideView.contentMode = .scaleAspectFill sideView.image = UIImage() sideView.sd_setImage(with: URL(string: icon.unescapeHTML), completed: nil) } else { sideView.contentMode = .center if subreddit.contains("m/") { sideView.image = SubredditCellView.defaultIconMulti } else if subreddit.lowercased() == "all" { sideView.image = SubredditCellView.allIcon sideView.backgroundColor = GMColor.blue500Color() } else if subreddit.lowercased() == "frontpage" { sideView.image = SubredditCellView.frontpageIcon sideView.backgroundColor = GMColor.green500Color() } else if subreddit.lowercased() == "popular" { sideView.image = SubredditCellView.popularIcon sideView.backgroundColor = GMColor.purple500Color() } else { sideView.image = SubredditCellView.defaultIcon } } label.addSubview(sideView) sideView.sizeAnchors == CGSize.square(size: 30) sideView.centerYAnchor == label.centerYAnchor sideView.leftAnchor == label.leftAnchor sideView.layer.cornerRadius = 15 sideView.clipsToBounds = true } label.sizeToFit() self.navigationItem.titleView = label label.accessibilityHint = "Opens the sub red it r \(sub)" label.accessibilityLabel = "Sub red it: r \(sub)" label.addTapGestureRecognizer(action: { VCPresenter.openRedditLink("/r/\(sub)", self.navigationController, self) }) setupBaseBarColors(ColorUtil.getColorForSub(sub: sub, true)) } var savedBack: UIBarButtonItem? func showSearchBar() { searchBar.alpha = 0 let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal) isSearch = true savedHeaderView = tableView.tableHeaderView tableView.tableHeaderView = UIView() savedTitleView = navigationItem.titleView navigationItem.titleView = searchBar savedBack = navigationItem.leftBarButtonItem navigationItem.setRightBarButtonItems(nil, animated: true) navigationItem.setLeftBarButtonItems(nil, animated: true) self.navigationItem.setHidesBackButton(true, animated: false) // Add cancel button (iPad doesn't show standard one) let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let cancelButton = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(cancelTapped)) navigationItem.setRightBarButton(cancelButton, animated: false) UIView.animate(withDuration: 0.5, animations: { self.searchBar.alpha = 1 }, completion: { _ in if !ColorUtil.theme.isLight { self.searchBar.keyboardAppearance = .dark } self.searchBar.becomeFirstResponder() }) } var moreB = UIBarButtonItem() var modB = UIBarButtonItem() func hideSearchBar() { if let header = savedHeaderView { navigationController?.setNavigationBarHidden(false, animated: true) tableView.tableHeaderView = header } isSearch = false searchBar.tintColor = ColorUtil.theme.fontColor sortButton = UIButton.init(type: .custom) sortButton.addTarget(self, action: #selector(self.sort(_:)), for: UIControl.Event.touchUpInside) sortButton.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) let sortB = UIBarButtonItem.init(customView: sortButton) doSortImage(sortButton) let search = UIButton.init(type: .custom) search.setImage(UIImage.init(sfString: SFSymbol.magnifyingglass, overrideString: "search")?.navIcon(), for: UIControl.State.normal) search.addTarget(self, action: #selector(self.search(_:)), for: UIControl.Event.touchUpInside) search.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) let searchB = UIBarButtonItem.init(customView: search) navigationItem.rightBarButtonItems = [sortB, searchB] navigationItem.leftBarButtonItem = savedBack navigationItem.titleView = savedTitleView isSearching = false tableView.reloadData() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { hideSearchBar() } @objc func sort(_ selector: UIButton?) { if !offline { let isDefault = UISwitch() isDefault.onTintColor = ColorUtil.accentColorForSub(sub: self.sub) let defaultLabel = UILabel() defaultLabel.text = "Default for sub" let group = UIView() group.isUserInteractionEnabled = true group.addSubviews(isDefault, defaultLabel) defaultLabel.textColor = ColorUtil.accentColorForSub(sub: self.sub) defaultLabel.centerYAnchor == group.centerYAnchor isDefault.leftAnchor == group.leftAnchor isDefault.centerYAnchor == group.centerYAnchor defaultLabel.leftAnchor == isDefault.rightAnchor + 10 defaultLabel.rightAnchor == group.rightAnchor let actionSheetController = DragDownAlertMenu(title: "Comment sorting", subtitle: "", icon: nil, extraView: group, themeColor: ColorUtil.accentColorForSub(sub: submission?.subreddit ?? ""), full: true) for c in CommentSort.cases { if c == .suggested { continue } var sortIcon = UIImage() if c == .controversial { actionSheetController.addAction(title: "Sort by Live", icon: UIImage(sfString: SFSymbol.playFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage(), primary: live) { self.setLive() } } switch c { case .suggested, .confidence: sortIcon = UIImage(sfString: SFSymbol.handThumbsupFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() case .hot: sortIcon = UIImage(sfString: SFSymbol.flameFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() case .controversial: sortIcon = UIImage(sfString: SFSymbol.boltFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() case .new: sortIcon = UIImage(sfString: SFSymbol.tagFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() case .old: sortIcon = UIImage(sfString: SFSymbol.clockFill, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() case .top: sortIcon = UIImage(sfString: SFSymbol.arrowUp, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() default: sortIcon = UIImage(sfString: SFSymbol.questionmark, overrideString: "ic_sort_white")?.navIcon() ?? UIImage() } actionSheetController.addAction(title: c.description, icon: sortIcon, primary: sort == c) { self.sort = c self.reset = true self.live = false if isDefault.isOn { SettingValues.setCommentSorting(forSubreddit: self.sub, commentSorting: c) } self.activityIndicator.removeFromSuperview() let barButton = UIBarButtonItem(customView: self.activityIndicator) self.navigationItem.rightBarButtonItems = [barButton] self.activityIndicator.startAnimating() self.doSortImage(self.sortButton) self.refresh(self) } } actionSheetController.addAction(title: "Q&A", icon: UIImage(sfString: SFSymbol.questionmark, overrideString: "ic_sort_white")?.navIcon() ?? UIImage(), primary: sort == .qa) { self.sort = .qa self.reset = true self.live = false if isDefault.isOn { SettingValues.setCommentSorting(forSubreddit: self.sub, commentSorting: .qa) } self.activityIndicator.removeFromSuperview() let barButton = UIBarButtonItem(customView: self.activityIndicator) self.navigationItem.rightBarButtonItems = [barButton] self.activityIndicator.startAnimating() self.doSortImage(self.sortButton) self.refresh(self) } actionSheetController.show(self) } } var indicator: MDCActivityIndicator = MDCActivityIndicator() deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: CGRect.zero, style: UITableView.Style.plain) self.tableView.delegate = self self.tableView.dataSource = self self.view = UIView.init(frame: CGRect.zero) self.view.addSubview(tableView) tableView.verticalAnchors == view.verticalAnchors tableView.horizontalAnchors == view.safeHorizontalAnchors self.automaticallyAdjustsScrollViewInsets = false self.registerForPreviewing(with: self, sourceView: self.tableView) self.tableView.allowsSelection = false //self.tableView.layer.speed = 1.5 self.view.backgroundColor = ColorUtil.theme.backgroundColor self.tableView.backgroundColor = ColorUtil.theme.backgroundColor self.navigationController?.view.backgroundColor = ColorUtil.theme.foregroundColor refreshControl = UIRefreshControl() refreshControl?.tintColor = ColorUtil.theme.fontColor refreshControl?.attributedTitle = NSAttributedString(string: "") refreshControl?.addTarget(self, action: #selector(CommentViewController.refresh(_:)), for: UIControl.Event.valueChanged) var top = CGFloat(64) let bottom = CGFloat(45) if #available(iOS 11.0, *) { top = 0 } tableView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) tableView.addSubview(refreshControl!) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil) searchBar.delegate = self searchBar.searchBarStyle = UISearchBar.Style.minimal searchBar.textColor = SettingValues.reduceColor && ColorUtil.theme.isLight ? ColorUtil.theme.fontColor : .white searchBar.showsCancelButton = false if !ColorUtil.theme.isLight { searchBar.keyboardAppearance = .dark } UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = UIColor.white tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableView.automaticDimension self.tableView.register(CommentDepthCell.classForCoder(), forCellReuseIdentifier: "Cell\(version)") self.tableView.register(CommentDepthCell.classForCoder(), forCellReuseIdentifier: "MoreCell\(version)") tableView.separatorStyle = .none NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) headerCell = FullLinkCellView() headerCell!.del = self headerCell!.parentViewController = self headerCell!.aspectWidth = self.tableView.bounds.size.width if SettingValues.commentGesturesMode != .NONE { setupGestures() } self.presentationController?.delegate = self if !loaded && (single || forceLoad) { refresh(self) } NotificationCenter.default.addObserver(self, selector: #selector(onThemeChanged), name: .onThemeChanged, object: nil) } @objc func onThemeChanged() { version += 1 self.headerCell = FullLinkCellView() self.headerCell?.del = self self.headerCell?.parentViewController = self self.hasDone = true self.headerCell?.aspectWidth = self.tableView.bounds.size.width self.headerCell?.configure(submission: self.submission!, parent: self, nav: self.navigationController, baseSub: self.submission!.subreddit, parentWidth: self.view.frame.size.width, np: self.np) if self.submission!.isSelf { self.headerCell?.showBody(width: self.view.frame.size.width - 24) } self.tableView.tableHeaderView = UIView(frame: CGRect.init(x: 0, y: 0, width: self.tableView.frame.width, height: 0.01)) if let tableHeaderView = self.headerCell { var frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: tableHeaderView.estimateHeight(true, np: self.np)) // Add safe area insets to left and right if available if #available(iOS 11.0, *) { frame = frame.insetBy(dx: max(self.view.safeAreaInsets.left, self.view.safeAreaInsets.right), dy: 0) } if self.tableView.tableHeaderView == nil || !frame.equalTo(tableHeaderView.frame) { tableHeaderView.frame = frame tableHeaderView.layoutIfNeeded() let view = UIView(frame: tableHeaderView.frame) view.addSubview(tableHeaderView) self.tableView.tableHeaderView = view } } self.setupTitleView(self.submission!.subreddit, icon: self.submission!.subreddit_icon) self.navigationItem.backBarButtonItem?.title = "" self.setBarColors(color: ColorUtil.getColorForSub(sub: self.submission!.subreddit)) self.tableView.register(CommentDepthCell.classForCoder(), forCellReuseIdentifier: "Cell\(version)") self.tableView.register(CommentDepthCell.classForCoder(), forCellReuseIdentifier: "MoreCell\(version)") updateStringsTheme(self.content.map { (k, v) in v} ) self.tableView.reloadData() sortButton = UIButton.init(type: .custom) sortButton.addTarget(self, action: #selector(self.sort(_:)), for: UIControl.Event.touchUpInside) sortButton.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) let sortB = UIBarButtonItem.init(customView: sortButton) doSortImage(sortButton) let search = UIButton.init(type: .custom) search.setImage(UIImage.init(sfString: SFSymbol.magnifyingglass, overrideString: "search")?.navIcon(), for: UIControl.State.normal) search.addTarget(self, action: #selector(self.search(_:)), for: UIControl.Event.touchUpInside) search.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) let searchB = UIBarButtonItem.init(customView: search) navigationItem.rightBarButtonItems = [sortB, searchB] doHeadView(self.view.frame.size) self.createJumpButton(true) if let submission = self.submission { self.setupTitleView(submission.subreddit, icon: submission.subreddit_icon) } self.updateToolbar() self.view.backgroundColor = ColorUtil.theme.backgroundColor self.tableView.backgroundColor = ColorUtil.theme.backgroundColor self.navigationController?.view.backgroundColor = ColorUtil.theme.foregroundColor } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if #available(iOS 14.0, *) { if previousTraitCollection?.userInterfaceStyle != traitCollection.userInterfaceStyle { ColorUtil.matchTraitCollection() } } else { if let themeChanged = previousTraitCollection?.hasDifferentColorAppearance(comparedTo: traitCollection) { if themeChanged { ColorUtil.matchTraitCollection() } } } } } @objc func cancelTapped() { hideSearchBar() } // func handlePop(_ panGesture: UIPanGestureRecognizer) { // // let percent = max(panGesture.translation(in: view).x, 0) / view.frame.width // // switch panGesture.state { // // case .began: // navigationController?.delegate = self // navigationController?.popViewController(animated: true) // // case .changed: // UIPercentDrivenInteractiveTransition.update(percent) // // case .ended: // let velocity = panGesture.velocity(in: view).x // // // Continue if drag more than 50% of screen width or velocity is higher than 1000 // if percent > 0.5 || velocity > 1000 { // UIPercentDrivenInteractiveTransition.finish(<#T##UIPercentDrivenInteractiveTransition#>) // } else { // UIPercentDrivenInteractiveTransition.cancelInteractiveTransition() // } // // case .cancelled, .failed: // UIPercentDrivenInteractiveTransition.cancelInteractiveTransition() // // default: // break // } // } var keyboardHeight = CGFloat(0) @objc func keyboardWillShow(_ notification: Notification) { if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { let keyboardRectangle = keyboardFrame.cgRectValue let keyboardHeight = keyboardRectangle.height if keyboardHeight != 0 { var top = CGFloat(64) let bottom = CGFloat(45) if #available(iOS 11.0, *) { top = 0 } tableView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: bottom + keyboardHeight, right: 0) } } } var normalInsets = UIEdgeInsets(top: 0, left: 0, bottom: 45, right: 0) @objc func keyboardWillHide(_ notification: Notification) { var top = CGFloat(64) let bottom = CGFloat(45) if #available(iOS 11.0, *) { top = 0 } tableView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) } var single = true var hasDone = false var configuredOnce = false override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if hasSubmission && self.view.frame.size.width != 0 { guard let headerCell = headerCell else { return } if !configuredOnce { headerCell.aspectWidth = self.view.frame.size.width headerCell.configure(submission: submission!, parent: self, nav: self.navigationController, baseSub: submission!.subreddit, parentWidth: self.navigationController?.view.bounds.size.width ?? self.tableView.frame.size.width, np: np) if submission!.isSelf { headerCell.showBody(width: self.view.frame.size.width - 24) } configuredOnce = true } var frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: headerCell.estimateHeight(true, np: self.np)) // Add safe area insets to left and right if available if #available(iOS 11.0, *) { frame = frame.insetBy(dx: max(view.safeAreaInsets.left, view.safeAreaInsets.right), dy: 0) } if self.tableView.tableHeaderView == nil || !frame.equalTo(headerCell.contentView.frame) { headerCell.contentView.frame = frame headerCell.contentView.layoutIfNeeded() let view = UIView(frame: headerCell.contentView.frame) view.addSubview(headerCell.contentView) self.tableView.tableHeaderView = view } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var subreddit = "" // MARK: - Table view data source var forceLoad = false var startedOnce = false func doStartupItems() { if !startedOnce { startedOnce = true (navigationController)?.setNavigationBarHidden(false, animated: false) self.edgesForExtendedLayout = UIRectEdge.all self.extendedLayoutIncludesOpaqueBars = true self.commentDepthColors = ColorUtil.getCommentDepthColors() self.setupTitleView(submission == nil ? subreddit : submission!.subreddit, icon: submission!.subreddit_icon) self.navigationItem.backBarButtonItem?.title = "" if submission != nil { self.setBarColors(color: ColorUtil.getColorForSub(sub: submission == nil ? subreddit : submission!.subreddit)) } self.authorColor = ColorUtil.getCommentNameColor(submission == nil ? subreddit : submission!.subreddit) navigationController?.setToolbarHidden(false, animated: true) self.isToolbarHidden = false } } var sortB: UIBarButtonItem! var searchB: UIBarButtonItem! var liveB: UIBarButtonItem! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.isHiding = true if navigationController != nil { sortButton = UIButton.init(type: .custom) sortButton.accessibilityLabel = "Change sort type" sortButton.addTarget(self, action: #selector(self.sort(_:)), for: UIControl.Event.touchUpInside) sortButton.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) sortB = UIBarButtonItem.init(customView: sortButton) doSortImage(sortButton) let search = UIButton.init(type: .custom) search.accessibilityLabel = "Search" search.setImage(UIImage.init(sfString: SFSymbol.magnifyingglass, overrideString: "search")?.navIcon(), for: UIControl.State.normal) search.addTarget(self, action: #selector(self.search(_:)), for: UIControl.Event.touchUpInside) search.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) searchB = UIBarButtonItem.init(customView: search) navigationItem.rightBarButtonItem?.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -20) if !loaded { activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) activityIndicator.color = SettingValues.reduceColor && ColorUtil.theme.isLight ? ColorUtil.theme.fontColor : .white if self.navigationController == nil { self.view.addSubview(activityIndicator) activityIndicator.centerAnchors == self.view.centerAnchors } else { let barButton = UIBarButtonItem(customView: activityIndicator) navigationItem.rightBarButtonItems = [barButton] } activityIndicator.startAnimating() } else { navigationItem.rightBarButtonItems = [sortB, searchB] } } else { if !loaded { activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) activityIndicator.color = ColorUtil.theme.navIconColor self.view.addSubview(activityIndicator) activityIndicator.centerAnchors == self.view.centerAnchors activityIndicator.startAnimating() } } doStartupItems() if headerCell.videoView != nil && !(headerCell?.videoView?.isHidden ?? true) { headerCell.videoView?.player?.play() } if isSearching { isSearching = false tableView.reloadData() } setNeedsStatusBarAppearanceUpdate() if navigationController != nil && (didDisappearCompletely || !loaded) { self.setupTitleView(submission == nil ? subreddit : submission!.subreddit, icon: submission!.subreddit_icon) self.updateToolbar() } } var activityIndicator = UIActivityIndicatorView() override var preferredStatusBarStyle: UIStatusBarStyle { if ColorUtil.theme.isLight && SettingValues.reduceColor { if #available(iOS 13, *) { return .darkContent } else { return .default } } else { return .lightContent } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshControl.setValue(100, forKey: "_snappingHeight") if UIScreen.main.traitCollection.userInterfaceIdiom == .pad && Int(round(self.view.bounds.width / CGFloat(320))) > 1 && false { self.navigationController!.view.backgroundColor = .clear } self.isHiding = false didDisappearCompletely = false let isModal = navigationController?.presentingViewController != nil || self.modalPresentationStyle == .fullScreen if isModal && self.navigationController is TapBehindModalViewController { self.navigationController?.delegate = self (self.navigationController as! TapBehindModalViewController).del = self } self.navigationController?.setNavigationBarHidden(false, animated: true) if loaded && finishedPush == false && first { self.reloadTableViewAnimated() } self.finishedPush = true } var duringAnimation = false var finishedPush = false func reloadTableViewAnimated() { self.tableView.reloadData() first = false let cells = self.tableView.visibleCells for cell in cells { cell.alpha = 0 } var row = Double(0) for cell in cells { UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: { cell.alpha = 1 }, completion: nil) row += 1 } } @objc func close(_ sender: AnyObject) { self.navigationController?.popViewController(animated: true) } @objc func showMod(_ sender: AnyObject) { if !modLink.isEmpty() { VCPresenter.openRedditLink(self.modLink, self.navigationController, self) } } @objc func showMenu(_ sender: AnyObject) { if !offline { let link = submission! let alertController = DragDownAlertMenu(title: "Comment actions", subtitle: self.submission?.title ?? "", icon: self.submission?.thumbnailUrl) alertController.addAction(title: "Refresh comments", icon: UIImage(sfString: SFSymbol.arrowClockwise, overrideString: "sync")!.menuIcon()) { self.reset = true self.refresh(self) } alertController.addAction(title: "Reply to submission", icon: UIImage(sfString: SFSymbol.arrowshapeTurnUpLeftFill, overrideString: "reply")!.menuIcon()) { self.reply(self.headerCell) } alertController.addAction(title: "Go to r/\(link.subreddit)", icon: UIImage(sfString: .rCircleFill, overrideString: "subs")!.menuIcon()) { VCPresenter.openRedditLink("www.reddit.com/r/\(link.subreddit)", self.navigationController, self) } alertController.addAction(title: "View related submissions", icon: UIImage(sfString: SFSymbol.squareStackFill, overrideString: "size")!.menuIcon()) { let related = RelatedViewController.init(thing: self.submission!) VCPresenter.showVC(viewController: related, popupIfPossible: false, parentNavigationController: self.navigationController, parentViewController: self) } alertController.addAction(title: "View r/\(link.subreddit)'s sidebar", icon: UIImage(sfString: SFSymbol.infoCircle, overrideString: "info")!.menuIcon()) { Sidebar.init(parent: self, subname: self.submission!.subreddit).displaySidebar() } alertController.addAction(title: allCollapsed ? "Expand child comments" : "Collapse child comments", icon: UIImage(sfString: SFSymbol.bubbleLeftAndBubbleRightFill, overrideString: "comments")!.menuIcon()) { if self.allCollapsed { self.expandAll() } else { self.collapseAll() } } alertController.show(self) } } var sub: String = "" var allCollapsed = false var subInfo: Subreddit? @objc func search(_ sender: AnyObject) { if !dataArray.isEmpty { expandAll() showSearchBar() } // Todo future loadAllMore() } public func extendKeepMore(in comment: Thing, current depth: Int) -> ([(Thing, Int)]) { var buf: [(Thing, Int)] = [] if let comment = comment as? Comment { buf.append((comment, depth)) for obj in comment.replies.children { buf.append(contentsOf: extendKeepMore(in: obj, current: depth + 1)) } } else if let more = comment as? More { buf.append((more, depth)) } return buf } public func extendForMore(parentId: String, comments: [Thing], current depth: Int) -> ([(Thing, Int)]) { var buf: [(Thing, Int)] = [] for thing in comments { let pId = thing is Comment ? (thing as! Comment).parentId : (thing as! More).parentId if pId == parentId { if let comment = thing as? Comment { var relativeDepth = 0 for parent in buf { if comment.parentId == parentId { relativeDepth = parent.1 - depth break } } buf.append((comment, depth + relativeDepth)) buf.append(contentsOf: extendForMore(parentId: comment.getId(), comments: comments, current: depth + relativeDepth + 1)) } else if let more = thing as? More { var relativeDepth = 0 for parent in buf { let parentId = parent.0 is Comment ? (parent.0 as! Comment).parentId : (parent.0 as! More).parentId if more.parentId == parentId { relativeDepth = parent.1 - depth break } } buf.append((more, depth + relativeDepth)) } } } return buf } private var blurView: UIVisualEffectView? private let blurEffect = (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init() private var blackView = UIView() func setBackgroundView() { blackView.backgroundColor = .black blackView.alpha = 0 blurView = UIVisualEffectView(frame: self.navigationController!.view!.bounds) self.blurView!.effect = self.blurEffect self.blurEffect.setValue(10, forKeyPath: "blurRadius") self.navigationController!.view!.insertSubview(blackView, at: self.navigationController!.view!.subviews.count) self.navigationController!.view!.insertSubview(blurView!, at: self.navigationController!.view!.subviews.count) blurView!.edgeAnchors == self.navigationController!.view!.edgeAnchors blackView.edgeAnchors == self.navigationController!.view!.edgeAnchors UIView.animate(withDuration: 0.2, delay: 1, options: .curveEaseInOut, animations: { self.blackView.alpha = 0.2 }) } func updateStrings(_ newComments: [(Thing, Int)]) { var color = UIColor.black var first = true for thing in newComments { if first && thing.0 is Comment { color = ColorUtil.accentColorForSub(sub: ((newComments[0].0 as! Comment).subreddit)) first = false } if let comment = thing.0 as? Comment { self.text[comment.getId()] = TextDisplayStackView.createAttributedChunk(baseHTML: comment.bodyHtml, fontSize: 16, submission: false, accentColor: color, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } else { let attr = NSMutableAttributedString(string: "more") self.text[(thing.0 as! More).getId()] = LinkParser.parse(attr, color, font: UIFont.systemFont(ofSize: 16), fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } } } func updateStringsTheme(_ comments: [AnyObject]) { var color = UIColor.black var first = true for thing in comments { if let comment = thing as? RComment, first { color = ColorUtil.accentColorForSub(sub: comment.subreddit) first = false } if let comment = thing as? RComment { self.text[comment.getId()] = TextDisplayStackView.createAttributedChunk(baseHTML: comment.htmlText, fontSize: 16, submission: false, accentColor: color, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } else if let more = thing as? RMore { let attr = NSMutableAttributedString(string: "more") self.text[more.getId()] = LinkParser.parse(attr, color, font: UIFont.systemFont(ofSize: 16), fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } } } var text: [String: NSAttributedString] func updateStringsSingle(_ newComments: [Object]) { let color = ColorUtil.accentColorForSub(sub: ((newComments[0] as! RComment).subreddit)) for thing in newComments { if let comment = thing as? RComment { let html = comment.htmlText self.text[comment.getIdentifier()] = TextDisplayStackView.createAttributedChunk(baseHTML: html, fontSize: 16, submission: false, accentColor: color, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } else { let attr = NSMutableAttributedString(string: "more") self.text[(thing as! RMore).getIdentifier()] = LinkParser.parse(attr, color, font: UIFont.systemFont(ofSize: 16), fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) } } } func vote(_ direction: VoteDirection) { if let link = self.submission { do { try session?.setVote(direction, name: link.id, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let check): print(check) } }) } catch { print(error) } } } @objc func downVote(_ sender: AnyObject?) { vote(.down) } @objc func upVote(_ sender: AnyObject?) { vote(.up) } @objc func cancelVote(_ sender: AnyObject?) { vote(.none) } @objc func loadAll(_ sender: AnyObject) { context = "" reset = true refreshControl?.beginRefreshing() refresh(sender) updateToolbar() } var currentSort: CommentNavType = .PARENTS enum CommentNavType { case PARENTS case GILDED case OP case LINK case YOU } func getCount(sort: CommentNavType) -> Int { var count = 0 for comment in dataArray { let contents = content[comment] if contents is RComment && matches(comment: contents as! RComment, sort: sort) { count += 1 } } return count } override var prefersHomeIndicatorAutoHidden: Bool { return true } @objc func showNavTypes(_ sender: UIView) { if !loaded { return } let alertController = DragDownAlertMenu(title: "Comment navigation", subtitle: "Select a navigation type", icon: nil) let link = getCount(sort: .LINK) let parents = getCount(sort: .PARENTS) let op = getCount(sort: .OP) let gilded = getCount(sort: .GILDED) let you = getCount(sort: .YOU) alertController.addAction(title: "Top-level comments (\(parents))", icon: UIImage()) { self.currentSort = .PARENTS } alertController.addAction(title: "Submission OP (\(op))", icon: UIImage()) { self.currentSort = .OP } alertController.addAction(title: "Links in comment (\(link))", icon: UIImage()) { self.currentSort = .LINK } alertController.addAction(title: "Your comments (\(you))", icon: UIImage()) { self.currentSort = .YOU } alertController.addAction(title: "Gilded comments (\(gilded))", icon: UIImage()) { self.currentSort = .GILDED } alertController.show(self) } func goToCell(i: Int) { let indexPath = IndexPath(row: i, section: 0) self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) } var goingToCell = false func goToCellTop(i: Int) { isGoingDown = true let indexPath = IndexPath(row: i, section: 0) goingToCell = true self.tableView.scrollToRow(at: indexPath, at: .top, animated: true) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.goingToCell = false self.isGoingDown = false } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.goingToCell = false self.isGoingDown = false } @objc func goUp(_ sender: AnyObject) { if !loaded || content.isEmpty { return } var topCell = 0 if let top = tableView.indexPathsForVisibleRows { if top.count > 0 { topCell = top[0].row } } if #available(iOS 10.0, *) { HapticUtility.hapticActionWeak() } var contents = content[dataArray[topCell]] while (contents is RComment ? !matches(comment: contents as! RComment, sort: currentSort) : true ) && dataArray.count > topCell && topCell - 1 >= 0 { topCell -= 1 contents = content[dataArray[topCell]] } goToCellTop(i: topCell) lastMoved = topCell } var lastMoved = -1 var isGoingDown = false @objc func goDown(_ sender: AnyObject) { if !loaded || content.isEmpty { return } var topCell = 0 if let top = tableView.indexPathsForVisibleRows { if top.count > 0 { topCell = top[0].row } } if #available(iOS 10.0, *) { HapticUtility.hapticActionWeak() } if topCell <= 0 && lastMoved < 0 { goToCellTop(i: 0) lastMoved = 0 } else { var contents = content[dataArray[topCell]] while (contents is RMore || (contents as! RComment).depth > 1) && dataArray.count > topCell + 1 { topCell += 1 contents = content[dataArray[topCell]] } if (topCell + 1) > (dataArray.count - 1) { return } for i in (topCell + 1)..<(dataArray.count - 1) { contents = content[dataArray[i]] if contents is RComment && matches(comment: contents as! RComment, sort: currentSort) && i > lastMoved { goToCellTop(i: i) lastMoved = i break } } } } func matches(comment: RComment, sort: CommentNavType) -> Bool { switch sort { case .PARENTS: if cDepth[comment.getIdentifier()]! == 1 { return true } else { return false } case .GILDED: if comment.gilded { return true } else { return false } case .OP: if comment.author == submission?.author { return true } else { return false } case .LINK: if comment.htmlText.contains("<a") { return true } else { return false } case .YOU: if AccountController.isLoggedIn && comment.author == AccountController.currentName { return true } else { return false } } } func updateToolbar() { navigationController?.setToolbarHidden(false, animated: false) self.isToolbarHidden = false let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) var items: [UIBarButtonItem] = [] if !context.isEmpty() { items.append(space) let loadFullThreadButton = UIBarButtonItem.init(title: "Load full thread", style: .plain, target: self, action: #selector(CommentViewController.loadAll(_:))) loadFullThreadButton.accessibilityLabel = "Load full thread" items.append(loadFullThreadButton) items.append(space) } else { let up = UIButton(type: .custom) up.accessibilityLabel = "Navigate up one comment thread" up.setImage(UIImage(sfString: SFSymbol.chevronCompactUp, overrideString: "up")?.toolbarIcon(), for: UIControl.State.normal) up.addTarget(self, action: #selector(CommentViewController.goUp(_:)), for: UIControl.Event.touchUpInside) up.frame = CGRect(x: 0, y: 0, width: 40, height: 40) let upB = UIBarButtonItem(customView: up) let nav = UIButton(type: .custom) nav.accessibilityLabel = "Change criteria for comment thread navigation" nav.setImage(UIImage(sfString: SFSymbol.safariFill, overrideString: "nav")?.toolbarIcon(), for: UIControl.State.normal) nav.addTarget(self, action: #selector(CommentViewController.showNavTypes(_:)), for: UIControl.Event.touchUpInside) nav.frame = CGRect(x: 0, y: 0, width: 40, height: 40) let navB = UIBarButtonItem(customView: nav) let down = UIButton(type: .custom) down.accessibilityLabel = "Navigate down one comment thread" down.setImage(UIImage(sfString: SFSymbol.chevronCompactDown, overrideString: "down")?.toolbarIcon(), for: UIControl.State.normal) down.addTarget(self, action: #selector(CommentViewController.goDown(_:)), for: UIControl.Event.touchUpInside) down.frame = CGRect(x: 0, y: 0, width: 40, height: 40) let downB = UIBarButtonItem(customView: down) let more = UIButton(type: .custom) more.accessibilityLabel = "Post options" more.setImage(UIImage(sfString: SFSymbol.ellipsis, overrideString: "moreh")?.toolbarIcon(), for: UIControl.State.normal) more.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControl.Event.touchUpInside) more.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) moreB = UIBarButtonItem(customView: more) let mod = UIButton(type: .custom) mod.accessibilityLabel = "Moderator options" mod.setImage(UIImage(sfString: SFSymbol.shieldLefthalfFill, overrideString: "mod")?.toolbarIcon(), for: UIControl.State.normal) mod.addTarget(self, action: #selector(self.showMod(_:)), for: UIControl.Event.touchUpInside) mod.frame = CGRect(x: 0, y: 0, width: 40, height: 40) modB = UIBarButtonItem(customView: mod) if modLink.isEmpty() && modB.customView != nil { modB.customView? = UIView(frame: modB.customView!.frame) } items.append(modB) items.append(space) items.append(upB) items.append(space) items.append(navB) items.append(space) items.append(downB) items.append(space) items.append(moreB) } self.navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = false if parent != nil && parent is PagingCommentViewController { parent?.toolbarItems = items parent?.navigationController?.toolbar.barTintColor = ColorUtil.theme.backgroundColor parent?.navigationController?.toolbar.tintColor = ColorUtil.theme.fontColor } else { toolbarItems = items navigationController?.toolbar.barTintColor = ColorUtil.theme.backgroundColor navigationController?.toolbar.tintColor = ColorUtil.theme.fontColor } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (isSearching ? self.filteredData.count : self.comments.count - self.hidden.count) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if SettingValues.collapseFully { let datasetPosition = (indexPath as NSIndexPath).row if dataArray.isEmpty { return UITableView.automaticDimension } let thing = isSearching ? filteredData[datasetPosition] : dataArray[datasetPosition] if !hiddenPersons.contains(thing) && thing != self.menuId { if let height = oldHeights[thing] { return height } } } return UITableView.automaticDimension } var tagText: String? func tagUser(name: String) { let alert = DragDownAlertMenu(title: AccountController.formatUsername(input: name, small: true), subtitle: "Tag profile", icon: nil, full: true) alert.addTextInput(title: "Set tag", icon: UIImage(sfString: SFSymbol.tagFill, overrideString: "save-1")?.menuIcon(), action: { alert.dismiss(animated: true) { [weak self] in guard let self = self else { return } ColorUtil.setTagForUser(name: name, tag: alert.getText() ?? "") self.tableView.reloadData() } }, inputPlaceholder: "Enter a tag...", inputValue: ColorUtil.getTagForUser(name: name), inputIcon: UIImage(sfString: SFSymbol.tagFill, overrideString: "subs")!.menuIcon(), textRequired: true, exitOnAction: true) if !(ColorUtil.getTagForUser(name: name) ?? "").isEmpty { alert.addAction(title: "Remove tag", icon: UIImage(sfString: SFSymbol.trashFill, overrideString: "delete")?.menuIcon(), enabled: true) { ColorUtil.removeTagForUser(name: name) self.tableView.reloadData() } } alert.show(self) } func blockUser(name: String) { let alert = AlertController(title: "", message: nil, preferredStyle: .alert) let confirmAction = AlertAction(title: "Block", style: .preferred, handler: {(_) in PostFilter.profiles.append(name as NSString) PostFilter.saveAndUpdate() BannerUtil.makeBanner(text: "User blocked", color: GMColor.red500Color(), seconds: 3, context: self, top: true, callback: nil) if AccountController.isLoggedIn { do { try (UIApplication.shared.delegate as! AppDelegate).session?.blockViaUsername(name, completion: { (result) in print(result) }) } catch { print(error) } } }) alert.setupTheme() alert.attributedTitle = NSAttributedString(string: "Are you sure you want to block u/\(name)?", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor]) alert.addAction(confirmAction) alert.addCancelButton() alert.addBlurView() self.present(alert, animated: true, completion: nil) } var isCurrentlyChanging = false override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) inHeadView.removeFromSuperview() headerCell.endVideos() self.didDisappearCompletely = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.isHiding = true self.liveTimer.invalidate() self.removeJumpButton() } func collapseAll() { self.allCollapsed = true if dataArray.count > 0 { for i in 0...dataArray.count - 1 { if content[dataArray[i]] is RComment && matches(comment: content[dataArray[i]] as! RComment, sort: .PARENTS) { _ = hideNumber(n: dataArray[i], iB: i) let t = content[dataArray[i]] let id = (t is RComment) ? (t as! RComment).getIdentifier() : (t as! RMore).getIdentifier() if !hiddenPersons.contains(id) { hiddenPersons.insert(id) } } } doArrays() tableView.reloadData() } } func expandAll() { self.allCollapsed = false if dataArray.count > 0 { for i in 0...dataArray.count - 1 { if content[dataArray[i]] is RComment && matches(comment: content[dataArray[i]] as! RComment, sort: .PARENTS) { _ = unhideNumber(n: dataArray[i], iB: i) let t = content[dataArray[i]] let id = (t is RComment) ? (t as! RComment).getIdentifier() : (t as! RMore).getIdentifier() if hiddenPersons.contains(id) { hiddenPersons.remove(id) } } } doArrays() tableView.reloadData() } } func hideAll(comment: String, i: Int) { if !isCurrentlyChanging { isCurrentlyChanging = true DispatchQueue.global(qos: .background).async { [weak self] in guard let strongSelf = self else { return } let counter = strongSelf.hideNumber(n: comment, iB: i) - 1 strongSelf.doArrays() DispatchQueue.main.async { strongSelf.tableView.beginUpdates() var indexPaths: [IndexPath] = [] for row in i...counter { //TODO ...< indexPaths.append(IndexPath(row: row, section: 0)) } strongSelf.tableView.deleteRows(at: indexPaths, with: .fade) strongSelf.tableView.endUpdates() strongSelf.isCurrentlyChanging = false } } } } func doSortImage(_ sortButton: UIButton) { switch sort { case .suggested, .confidence: sortButton.setImage(UIImage(sfString: SFSymbol.arrowUpArrowDown, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) case .hot: sortButton.setImage(UIImage(sfString: SFSymbol.flameFill, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) case .controversial: sortButton.setImage(UIImage(sfString: SFSymbol.boltFill, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) case .new: sortButton.setImage(UIImage(sfString: SFSymbol.tagFill, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) case .old: sortButton.setImage(UIImage(sfString: SFSymbol.clockFill, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) case .top: sortButton.setImage(UIImage(sfString: SFSymbol.arrowUp, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) default: sortButton.setImage(UIImage(sfString: SFSymbol.questionmark, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal) } } func unhideAll(comment: String, i: Int) { if !isCurrentlyChanging { isCurrentlyChanging = true DispatchQueue.global(qos: .background).async { [weak self] in guard let strongSelf = self else { return } let counter = strongSelf.unhideNumber(n: comment, iB: i) strongSelf.doArrays() DispatchQueue.main.async { strongSelf.tableView.beginUpdates() var indexPaths: [IndexPath] = [] for row in (i + 1)...counter { indexPaths.append(IndexPath(row: row, section: 0)) } strongSelf.tableView.insertRows(at: indexPaths, with: .fade) strongSelf.tableView.endUpdates() strongSelf.isCurrentlyChanging = false } } } } func parentHidden(comment: Object) -> Bool { var n: String = "" if comment is RComment { n = (comment as! RComment).parentId } else { n = (comment as! RMore).parentId } return hiddenPersons.contains(n) || hidden.contains(n) } func walkTree(n: String) -> [String] { var toReturn: [String] = [] if content[n] is RComment { let bounds = comments.firstIndex(where: { ($0 == n) })! + 1 let parentDepth = (cDepth[n] ?? 0) for obj in stride(from: bounds, to: comments.count, by: 1) { if (cDepth[comments[obj]] ?? 0) > parentDepth { toReturn.append(comments[obj]) } else { return toReturn } } } return toReturn } func walkTreeFlat(n: String) -> [String] { var toReturn: [String] = [] if content[n] is RComment { let bounds = comments.firstIndex(where: { ($0 == n) })! + 1 let parentDepth = (cDepth[n] ?? 0) for obj in stride(from: bounds, to: comments.count, by: 1) { let depth = (cDepth[comments[obj]] ?? 0) if depth == 1 + parentDepth { toReturn.append(comments[obj]) } else if depth == parentDepth { return toReturn } } } return toReturn } func walkTreeFully(n: String) -> [String] { var toReturn: [String] = [] toReturn.append(n) if content[n] is RComment { let bounds = comments.firstIndex(where: { $0 == n })! + 1 let parentDepth = (cDepth[n] ?? 0) for obj in stride(from: bounds, to: comments.count, by: 1) { let currentDepth = cDepth[comments[obj]] ?? 0 if currentDepth > parentDepth { if currentDepth == parentDepth + 1 { toReturn.append(contentsOf: walkTreeFully(n: comments[obj])) } } else { return toReturn } } } return toReturn } func vote(comment: RComment, dir: VoteDirection) { var direction = dir switch ActionStates.getVoteDirection(s: comment) { case .up: if dir == .up { direction = .none } case .down: if dir == .down { direction = .none } default: break } do { try session?.setVote(direction, name: comment.id, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let check): print(check) } }) } catch { print(error) } ActionStates.setVoteDirection(s: comment, direction: direction) } func moreComment(_ cell: CommentDepthCell) { cell.more(self) } func modMenu(_ cell: CommentDepthCell) { cell.mod(self) } func deleteComment(cell: CommentDepthCell) { let alert = UIAlertController.init(title: "Really delete this comment?", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in do { try self.session?.deleteCommentOrLink(cell.comment!.getIdentifier(), completion: { (_) in DispatchQueue.main.async { var realPosition = 0 for c in self.comments { let id = c if id == cell.comment!.getIdentifier() { break } realPosition += 1 } self.text[cell.comment!.getIdentifier()] = NSAttributedString(string: "[deleted]") self.doArrays() self.tableView.reloadData() } }) } catch { } })) alert.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: nil)) VCPresenter.presentAlert(alert, parentVC: self) } override func becomeFirstResponder() -> Bool { return true } @objc func spacePressed() { if !isReply { UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: { self.tableView.contentOffset.y = min(self.tableView.contentOffset.y + 350, self.tableView.contentSize.height - self.tableView.frame.size.height) }, completion: nil) } } @objc func spacePressedUp() { if !isReply { UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: { self.tableView.contentOffset.y = max(self.tableView.contentOffset.y - 350, -64) }, completion: nil) } } func unhideNumber(n: String, iB: Int) -> Int { var i = iB let children = walkTreeFlat(n: n) var toHide: [String] = [] for name in children { if hidden.contains(name) { i += 1 } toHide.append(name) if !hiddenPersons.contains(name) { i += unhideNumber(n: name, iB: 0) } } for s in hidden { if toHide.contains(s) { hidden.remove(s) } } return i } func hideNumber(n: String, iB: Int) -> Int { var i = iB let children = walkTreeFlat(n: n) for name in children { if !hidden.contains(name) { i += 1 hidden.insert(name) } i += hideNumber(n: name, iB: 0) } return i } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate( alongsideTransition: { [unowned self] _ in if let header = self.tableView.tableHeaderView { var frame = header.frame var leftInset: CGFloat = 0 var rightInset: CGFloat = 0 if #available(iOS 11.0, *) { leftInset = self.tableView.safeAreaInsets.left rightInset = self.tableView.safeAreaInsets.right frame.origin.x = leftInset } else { // Fallback on earlier versions } self.headerCell!.aspectWidth = size.width - (leftInset + rightInset) frame.size.width = size.width - (leftInset + rightInset) frame.size.height = self.headerCell!.estimateHeight(true, true, np: self.np) self.headerCell!.contentView.frame = frame self.tableView.tableHeaderView!.frame = frame //self.tableView.reloadData(with: .none) self.doHeadView(size) self.view.setNeedsLayout() } }, completion: nil) } var isToolbarHidden = false var isHiding = false var lastY = CGFloat(0) var olderY = CGFloat(0) var isSearch = false func scrollViewDidScroll(_ scrollView: UIScrollView) { var currentY = scrollView.contentOffset.y //Sometimes the ScrollView will jump one time in the wrong direction. Unsure why this is happening, but this //will check for that case and ignore it if currentY > lastY && lastY < olderY { currentY = lastY } if !SettingValues.pinToolbar && !isReply && !isSearch { if currentY <= (tableView.tableHeaderView?.frame.size.height ?? 20) + 64 + 10 { liveView?.removeFromSuperview() liveView = nil liveNewCount = 0 } if currentY > lastY && currentY > 60 { if navigationController != nil && !isHiding && !isToolbarHidden && !(scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) { hideUI(inHeader: true) } } else if (currentY < lastY - 15 || currentY < 100) && !isHiding && navigationController != nil && (isToolbarHidden) { showUI() } } olderY = lastY lastY = currentY } func hideUI(inHeader: Bool) { isHiding = true //self.tableView.endEditing(true) if inHeadView.superview == nil { doHeadView(self.view.frame.size) } if !isGoingDown { (navigationController)?.setNavigationBarHidden(true, animated: true) if SettingValues.totallyCollapse { (self.navigationController)?.setToolbarHidden(true, animated: true) } } self.isToolbarHidden = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in guard let strongSelf = self else { return } strongSelf.createJumpButton() strongSelf.isHiding = false } } func showUI() { (navigationController)?.setNavigationBarHidden(false, animated: true) (navigationController)?.setToolbarHidden(false, animated: true) if live { progressDot.layer.removeAllAnimations() let pulseAnimation = CABasicAnimation(keyPath: "transform.scale") pulseAnimation.duration = 0.5 pulseAnimation.toValue = 1.2 pulseAnimation.fromValue = 0.2 pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) pulseAnimation.autoreverses = false pulseAnimation.repeatCount = Float.greatestFiniteMagnitude let fadeAnimation = CABasicAnimation(keyPath: "opacity") fadeAnimation.duration = 0.5 fadeAnimation.toValue = 0 fadeAnimation.fromValue = 2.5 fadeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) fadeAnimation.autoreverses = false fadeAnimation.repeatCount = Float.greatestFiniteMagnitude progressDot.layer.add(pulseAnimation, forKey: "scale") progressDot.layer.add(fadeAnimation, forKey: "fade") } self.isToolbarHidden = false self.removeJumpButton() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell! = nil let datasetPosition = (indexPath as NSIndexPath).row cell = tableView.dequeueReusableCell(withIdentifier: "Cell\(version)", for: indexPath) as UITableViewCell if content.isEmpty || text.isEmpty || cDepth.isEmpty || dataArray.isEmpty { self.refresh(self) return cell } let thing = isSearching ? filteredData[datasetPosition] : dataArray[datasetPosition] let parentOP = parents[thing] if let cell = cell as? CommentDepthCell { let innerContent = content[thing] if innerContent is RComment { var count = 0 let hiddenP = hiddenPersons.contains(thing) if hiddenP { count = getChildNumber(n: innerContent!.getIdentifier()) } var t = text[thing]! if isSearching { t = highlight(t) } cell.setComment(comment: innerContent as! RComment, depth: cDepth[thing]!, parent: self, hiddenCount: count, date: lastSeen, author: submission?.author, text: t, isCollapsed: hiddenP, parentOP: parentOP ?? "", depthColors: commentDepthColors, indexPath: indexPath, width: self.tableView.frame.size.width) } else { cell.setMore(more: (innerContent as! RMore), depth: cDepth[thing]!, depthColors: commentDepthColors, parent: self) } cell.content = content[thing] } return cell } // @available(iOS 11.0, *) // override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // let cell = tableView.cellForRow(at: indexPath) // if cell is CommentDepthCell && (cell as! CommentDepthCell).comment != nil && (SettingValues.commentActionRightLeft != .NONE || SettingValues.commentActionRightRight != .NONE) { // HapticUtility.hapticActionWeak() // var actions = [UIContextualAction]() // if SettingValues.commentActionRightRight != .NONE { // let action = UIContextualAction.init(style: .normal, title: "", handler: { (action, _, b) in // b(true) // self.doAction(cell: cell as! CommentDepthCell, action: SettingValues.commentActionRightRight, indexPath: indexPath) // }) // action.backgroundColor = SettingValues.commentActionRightRight.getColor() // action.image = UIImage(named: SettingValues.commentActionRightRight.getPhoto())?.navIcon() // // actions.append(action) // } // if SettingValues.commentActionRightLeft != .NONE { // let action = UIContextualAction.init(style: .normal, title: "", handler: { (action, _, b) in // b(true) // self.doAction(cell: cell as! CommentDepthCell, action: SettingValues.commentActionRightLeft, indexPath: indexPath) // }) // action.backgroundColor = SettingValues.commentActionRightLeft.getColor() // action.image = UIImage(named: SettingValues.commentActionRightLeft.getPhoto())?.navIcon() // // actions.append(action) // } // let config = UISwipeActionsConfiguration.init(actions: actions) // // return config // // } else { // return UISwipeActionsConfiguration.init() // } // } // // @available(iOS 11.0, *) // override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // let cell = tableView.cellForRow(at: indexPath) // if cell is CommentDepthCell && (cell as! CommentDepthCell).comment != nil && SettingValues.commentGesturesEnabled && (SettingValues.commentActionLeftLeft != .NONE || SettingValues.commentActionLeftRight != .NONE) { // HapticUtility.hapticActionWeak() // var actions = [UIContextualAction]() // if SettingValues.commentActionLeftLeft != .NONE { // let action = UIContextualAction.init(style: .normal, title: "", handler: { (action, _, b) in // b(true) // self.doAction(cell: cell as! CommentDepthCell, action: SettingValues.commentActionLeftLeft, indexPath: indexPath) // }) // action.backgroundColor = SettingValues.commentActionLeftLeft.getColor() // action.image = UIImage(named: SettingValues.commentActionLeftLeft.getPhoto())?.navIcon() // // actions.append(action) // } // if SettingValues.commentActionLeftRight != .NONE { // let action = UIContextualAction.init(style: .normal, title: "", handler: { (action, _, b) in // b(true) // self.doAction(cell: cell as! CommentDepthCell, action: SettingValues.commentActionLeftRight, indexPath: indexPath) // }) // action.backgroundColor = SettingValues.commentActionLeftRight.getColor() // action.image = UIImage(named: SettingValues.commentActionLeftRight.getPhoto())?.navIcon() // // actions.append(action) // } // let config = UISwipeActionsConfiguration.init(actions: actions) // // return config // // } else { // return UISwipeActionsConfiguration.init() // } // } func doAction(cell: CommentDepthCell, action: SettingValues.CommentAction, indexPath: IndexPath) { switch action { case .UPVOTE: cell.upvote(cell) case .DOWNVOTE: cell.downvote(cell) case .SAVE: cell.save(cell) case .MENU: cell.menu(cell) case .COLLAPSE: collapseParent(indexPath, baseCell: cell) case .REPLY: cell.reply(cell) case .EXIT: self.close(cell) case .NEXT: if parent is PagingCommentViewController { (parent as! PagingCommentViewController).next() } case .NONE: break case .PARENT_PREVIEW: break } } func collapseParent(_ indexPath: IndexPath, baseCell: CommentDepthCell) { var topCell = indexPath.row var contents = content[dataArray[topCell]] var id = "" if contents is RComment && (contents as! RComment).depth == 1 { //collapse self id = baseCell.comment!.getIdentifier() } else { while (contents is RMore || (contents as! RComment).depth > 1) && 0 <= topCell { topCell -= 1 contents = content[dataArray[topCell]] } var skipTop = false let indexPath = IndexPath.init(row: topCell, section: 0) for index in tableView.indexPathsForVisibleRows ?? [] { if index.row == topCell { skipTop = true break } } if !skipTop { self.tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: false) } id = (contents as! RComment).getIdentifier() } let childNumber = getChildNumber(n: id) let indexPath = IndexPath.init(row: topCell, section: 0) if let c = tableView.cellForRow(at: indexPath) { let cell = c as! CommentDepthCell if childNumber == 0 { if !SettingValues.collapseFully { } else if cell.isCollapsed { } else { oldHeights[cell.comment!.getIdentifier()] = cell.contentView.frame.size.height if !hiddenPersons.contains(cell.comment!.getIdentifier()) { hiddenPersons.insert(cell.comment!.getIdentifier()) } self.tableView.beginUpdates() oldHeights[cell.comment!.getIdentifier()] = cell.contentView.frame.size.height cell.collapse(childNumber: 0) self.tableView.endUpdates() } } else { oldHeights[cell.comment!.getIdentifier()] = cell.contentView.frame.size.height cell.collapse(childNumber: childNumber) if hiddenPersons.contains((id)) && childNumber > 0 { } else { if childNumber > 0 { hideAll(comment: id, i: topCell + 1) if !hiddenPersons.contains(id) { hiddenPersons.insert(id) } } } } } } var oldHeights = [String: CGFloat]() func getChildNumber(n: String) -> Int { let children = walkTreeFully(n: n) return children.count - 1 } func loadAllMore() { expandAll() loadMoreWithCallback(0) } func loadMoreWithCallback(_ datasetPosition: Int) { if datasetPosition > dataArray.count { return } if let more = content[dataArray[datasetPosition]] as? RMore, let link = self.submission { if more.children.isEmpty { loadMoreWithCallback(datasetPosition + 1) } else { do { var strings: [String] = [] for c in more.children { strings.append(c.value) } try session?.getMoreChildren(strings, name: link.id, sort: .top, id: more.id, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let list): DispatchQueue.main.async(execute: { () -> Void in let startDepth = self.cDepth[more.getIdentifier()] ?? 0 var queue: [Object] = [] for i in self.extendForMore(parentId: more.parentId, comments: list, current: startDepth) { let item = i.0 is Comment ? RealmDataWrapper.commentToRComment(comment: i.0 as! Comment, depth: i.1) : RealmDataWrapper.moreToRMore(more: i.0 as! More) queue.append(item) self.cDepth[item.getIdentifier()] = i.1 self.updateStrings([i]) } var realPosition = 0 for comment in self.comments { if comment == more.getIdentifier() { break } realPosition += 1 } if self.comments.count > realPosition && self.comments[realPosition] != nil { self.comments.remove(at: realPosition) } else { return } self.dataArray.remove(at: datasetPosition) let currentParent = self.parents[more.getIdentifier()] var ids: [String] = [] for item in queue { let id = item.getIdentifier() self.parents[id] = currentParent ids.append(id) self.content[id] = item } if queue.count != 0 { self.tableView.beginUpdates() self.tableView.deleteRows(at: [IndexPath.init(row: datasetPosition, section: 0)], with: .fade) self.dataArray.insert(contentsOf: ids, at: datasetPosition) self.comments.insert(contentsOf: ids, at: realPosition) self.doArrays() var paths: [IndexPath] = [] for i in stride(from: datasetPosition, to: datasetPosition + queue.count, by: 1) { paths.append(IndexPath.init(row: i, section: 0)) } self.tableView.insertRows(at: paths, with: .left) self.tableView.endUpdates() self.loadMoreWithCallback(datasetPosition + 1) } else { self.doArrays() self.tableView.reloadData() self.loadMoreWithCallback(datasetPosition + 1) } }) } }) } catch { loadMoreWithCallback(datasetPosition + 1) print(error) } } } else { loadMoreWithCallback(datasetPosition + 1) } } func highlight(_ cc: NSAttributedString) -> NSAttributedString { let base = NSMutableAttributedString.init(attributedString: cc) let r = base.mutableString.range(of: "\(searchBar.text!)", options: .caseInsensitive, range: NSRange(location: 0, length: base.string.length)) if r.length > 0 { base.addAttribute(NSAttributedString.Key.foregroundColor, value: ColorUtil.accentColorForSub(sub: subreddit), range: r) } return base.attributedSubstring(from: NSRange.init(location: 0, length: base.length)) } var isSearching = false func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) { filteredData = [] if textSearched.length != 0 { isSearching = true searchTableList() } else { isSearching = false } tableView.reloadData() } func searchTableList() { let searchString = searchBar.text var count = 0 for p in dataArray { let s = content[p] if s is RComment { if (s as! RComment).htmlText.localizedCaseInsensitiveContains(searchString!) { filteredData.append(p) } } count += 1 } } var isReply = false func pushedSingleTap(_ cell: CommentDepthCell) { if !isReply { if isSearching { hideSearchBar() context = (cell.content as! RComment).getIdentifier() var index = 0 if !self.context.isEmpty() { for c in self.dataArray { let comment = content[c] if comment is RComment && (comment as! RComment).getIdentifier().contains(self.context) { self.menuId = comment!.getIdentifier() self.tableView.reloadData() DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.goToCell(i: index) } break } else { index += 1 } } } } else { if let comment = cell.content as? RComment { let row = tableView.indexPath(for: cell)?.row let id = comment.getIdentifier() let childNumber = getChildNumber(n: comment.getIdentifier()) if childNumber == 0 { if !SettingValues.collapseFully { cell.showMenu(nil) } else if cell.isCollapsed { if hiddenPersons.contains((id)) { hiddenPersons.remove(at: hiddenPersons.firstIndex(of: id)!) } if let oldHeight = oldHeights[id] { UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: { cell.contentView.frame = CGRect(x: 0, y: 0, width: cell.contentView.frame.size.width, height: oldHeight) }, completion: { (_) in cell.expandSingle() self.oldHeights.removeValue(forKey: id) }) tableView.beginUpdates() tableView.endUpdates() } else { cell.expandSingle() tableView.beginUpdates() tableView.endUpdates() } } else { oldHeights[id] = cell.contentView.frame.size.height if !hiddenPersons.contains(id) { hiddenPersons.insert(id) } self.tableView.beginUpdates() cell.collapse(childNumber: 0) self.tableView.endUpdates() /* disable for now if SettingValues.collapseFully, let path = tableView.indexPath(for: cell) { self.tableView.scrollToRow(at: path, at: UITableView.ScrollPosition.none, animated: true) }*/ } } else { if hiddenPersons.contains((id)) && childNumber > 0 { hiddenPersons.remove(at: hiddenPersons.firstIndex(of: id)!) if let oldHeight = oldHeights[id] { UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: { cell.contentView.frame = CGRect(x: 0, y: 0, width: cell.contentView.frame.size.width, height: oldHeight) }, completion: { (_) in cell.expand() self.oldHeights.removeValue(forKey: id) }) } else { cell.expand() tableView.beginUpdates() tableView.endUpdates() } unhideAll(comment: comment.getId(), i: row!) // TODO: - hide child number } else { if childNumber > 0 { if childNumber > 0 { oldHeights[id] = cell.contentView.frame.size.height cell.collapse(childNumber: childNumber) /* disable for now if SettingValues.collapseFully, let path = tableView.indexPath(for: cell) { self.tableView.scrollToRow(at: path, at: UITableView.ScrollPosition.none, animated: false) }*/ } if row != nil { hideAll(comment: comment.getIdentifier(), i: row! + 1) } if !hiddenPersons.contains(id) { hiddenPersons.insert(id) } } } } } else { let datasetPosition = tableView.indexPath(for: cell)?.row ?? -1 if datasetPosition == -1 { return } if let more = content[dataArray[datasetPosition]] as? RMore, let link = self.submission { if more.children.isEmpty { VCPresenter.openRedditLink("https://www.reddit.com" + submission!.permalink + more.parentId.substring(3, length: more.parentId.length - 3), self.navigationController, self) } else { do { var strings: [String] = [] for c in more.children { strings.append(c.value) } cell.animateMore() try session?.getMoreChildren(strings, name: link.id, sort: .top, id: more.id, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let list): DispatchQueue.main.async(execute: { () -> Void in let startDepth = self.cDepth[more.getIdentifier()] ?? 0 var queue: [Object] = [] for i in self.extendForMore(parentId: more.parentId, comments: list, current: startDepth) { let item = i.0 is Comment ? RealmDataWrapper.commentToRComment(comment: i.0 as! Comment, depth: i.1) : RealmDataWrapper.moreToRMore(more: i.0 as! More) queue.append(item) self.cDepth[item.getIdentifier()] = i.1 self.updateStrings([i]) } var realPosition = 0 for comment in self.comments { if comment == more.getIdentifier() { break } realPosition += 1 } if self.comments.count > realPosition && self.comments[realPosition] != nil { self.comments.remove(at: realPosition) } else { return } self.dataArray.remove(at: datasetPosition) let currentParent = self.parents[more.getIdentifier()] var ids: [String] = [] for item in queue { let id = item.getIdentifier() self.parents[id] = currentParent ids.append(id) self.content[id] = item } if queue.count != 0 { self.tableView.beginUpdates() self.tableView.deleteRows(at: [IndexPath.init(row: datasetPosition, section: 0)], with: .fade) self.dataArray.insert(contentsOf: ids, at: datasetPosition) self.comments.insert(contentsOf: ids, at: realPosition) self.doArrays() var paths: [IndexPath] = [] for i in stride(from: datasetPosition, to: datasetPosition + queue.count, by: 1) { paths.append(IndexPath.init(row: i, section: 0)) } self.tableView.insertRows(at: paths, with: .left) self.tableView.endUpdates() } else { self.doArrays() self.tableView.reloadData() } }) } }) } catch { print(error) } } } } } } } func mod(_ cell: LinkCellView) { PostActions.showModMenu(cell, parent: self) } } extension Thing { func getId() -> String { return Self.kind + "_" + id } } extension CommentViewController: UIGestureRecognizerDelegate { func setupGestures() { cellGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panCell(_:))) cellGestureRecognizer.delegate = self cellGestureRecognizer.maximumNumberOfTouches = 1 tableView.addGestureRecognizer(cellGestureRecognizer) if UIDevice.current.userInterfaceIdiom != .pad { // cellGestureRecognizer.require(toFail: tableView.panGestureRecognizer) } if let parent = parent as? ColorMuxPagingViewController { parent.requireFailureOf(cellGestureRecognizer) } if let nav = self.navigationController as? SwipeForwardNavigationController { nav.fullWidthBackGestureRecognizer.require(toFail: cellGestureRecognizer) if let interactivePop = nav.interactivePopGestureRecognizer { cellGestureRecognizer.require(toFail: interactivePop) } } } func setupSwipeGesture() { shouldSetupSwipe = true if swipeBackAdded { return } if UIDevice.current.userInterfaceIdiom == .pad && SettingValues.appMode != .SINGLE { if #available(iOS 14, *) { return } } if SettingValues.commentGesturesMode == .FULL { if let full = fullWidthBackGestureRecognizer { full.view?.removeGestureRecognizer(full) } //setupFullSwipeView(self.tableView.tableHeaderView) return } setupFullSwipeView(self.tableView) shouldSetupSwipe = false swipeBackAdded = true } func setupFullSwipeView(_ view: UIView?) { if shouldSetupSwipe == false || SettingValues.commentGesturesMode == .FULL { return } if let full = fullWidthBackGestureRecognizer { full.view?.removeGestureRecognizer(full) } fullWidthBackGestureRecognizer = UIPanGestureRecognizer() if let interactivePopGestureRecognizer = parent?.navigationController?.interactivePopGestureRecognizer, let targets = interactivePopGestureRecognizer.value(forKey: "targets"), parent is ColorMuxPagingViewController, !swipeBackAdded { fullWidthBackGestureRecognizer.require(toFail: tableView.panGestureRecognizer) if let navGesture = self.navigationController?.interactivePopGestureRecognizer { fullWidthBackGestureRecognizer.require(toFail: navGesture) } fullWidthBackGestureRecognizer.require(toFail: interactivePopGestureRecognizer) for view in parent?.view.subviews ?? [] { if view is UIScrollView { (view as! UIScrollView).panGestureRecognizer.require(toFail: fullWidthBackGestureRecognizer) } } fullWidthBackGestureRecognizer.setValue(targets, forKey: "targets") fullWidthBackGestureRecognizer.delegate = self //parent.requireFailureOf(fullWidthBackGestureRecognizer) view?.addGestureRecognizer(fullWidthBackGestureRecognizer) if #available(iOS 13.4, *) { fullWidthBackGestureRecognizer.allowedScrollTypesMask = .continuous } } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return !(otherGestureRecognizer == cellGestureRecognizer && otherGestureRecognizer.state != .ended) } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = panGestureRecognizer.translation(in: tableView) if panGestureRecognizer == cellGestureRecognizer { if abs(translation.y) >= abs(translation.x) { return false } if translation.x < 0 { if gestureRecognizer.location(in: tableView).x > tableView.frame.width * 0.5 || SettingValues.commentGesturesMode == .FULL { return true } } else if SettingValues.commentGesturesMode == .FULL && abs(translation.x) > abs(translation.y) { return gestureRecognizer.location(in: tableView).x > tableView.frame.width * 0.1 } return false } if panGestureRecognizer == fullWidthBackGestureRecognizer && translation.x >= 0 { return true } return false } return false } @objc func panCell(_ recognizer: UIPanGestureRecognizer) { if recognizer.view != nil { let velocity = recognizer.velocity(in: recognizer.view!) if (velocity.x < 0 && (SettingValues.commentActionLeftLeft == .NONE && SettingValues.commentActionLeftRight == .NONE) && translatingCell == nil) || (velocity.x > 0 && (SettingValues.commentGesturesMode == .HALF || (SettingValues.commentActionRightLeft == .NONE && SettingValues.commentActionRightRight == .NONE)) && translatingCell == nil) { return } } if recognizer.state == .began || translatingCell == nil { let point = recognizer.location(in: self.tableView) let indexpath = self.tableView.indexPathForRow(at: point) if indexpath == nil { recognizer.cancel() return } guard let cell = self.tableView.cellForRow(at: indexpath!) as? CommentDepthCell else { return } for view in cell.commentBody.recursiveSubviews { let cellPoint = recognizer.location(in: view) if (view is UIScrollView || view is CodeDisplayView || view is TableDisplayView) && view.bounds.contains(cellPoint) { recognizer.cancel() return } } tableView.panGestureRecognizer.cancel() disableDismissalRecognizers() translatingCell = cell } translatingCell?.handlePan(recognizer) if recognizer.state == .ended || recognizer.state == .cancelled { translatingCell = nil enableDismissalRecognizers() } } } // Helper function inserted by Swift 4.2 migrator. private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } class ParentCommentViewController: UIViewController { var childView = UIView() var scrollView = UIScrollView() var estimatedSize: CGSize var parentContext: String = "" var dismissHandler: (() -> Void)? init(view: UIView, size: CGSize) { self.estimatedSize = size super.init(nibName: nil, bundle: nil) self.childView = view } override func viewDidLoad() { super.viewDidLoad() scrollView = UIScrollView().then { $0.backgroundColor = ColorUtil.theme.foregroundColor $0.isUserInteractionEnabled = true } self.view.addSubview(scrollView) scrollView.edgeAnchors == self.view.edgeAnchors } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scrollView.addSubview(childView) childView.widthAnchor == estimatedSize.width childView.heightAnchor == estimatedSize.height childView.topAnchor == scrollView.topAnchor scrollView.contentSize = estimatedSize } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) dismissHandler?() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CommentViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = self.tableView.indexPathForRow(at: location) else { return nil } guard let cell = self.tableView.cellForRow(at: indexPath) as? CommentDepthCell else { return nil } if SettingValues.commentActionForceTouch != .PARENT_PREVIEW { // TODO: - maybe /*let textView = let locationInTextView = textView.convert(location, to: textView) if let (url, rect) = getInfo(locationInTextView: locationInTextView) { previewingContext.sourceRect = textView.convert(rect, from: textView) if let controller = parentViewController?.getControllerForUrl(baseUrl: url) { return controller } }*/ return nil } if cell.depth == 1 { return nil } self.setAlphaOfBackgroundViews(alpha: 0.5) var topCell = (indexPath as NSIndexPath).row var contents = content[dataArray[topCell]] while (contents is RComment ? (contents as! RComment).depth >= cell.depth : true) && dataArray.count > topCell && topCell - 1 >= 0 { topCell -= 1 contents = content[dataArray[topCell]] } let parentCell = CommentDepthCell(style: .default, reuseIdentifier: "test") if let comment = contents as? RComment { parentCell.contentView.layer.cornerRadius = 10 parentCell.contentView.clipsToBounds = true parentCell.commentBody.ignoreHeight = false parentCell.commentBody.estimatedWidth = UIScreen.main.bounds.size.width * 0.85 - 36 if contents is RComment { var count = 0 let hiddenP = hiddenPersons.contains(comment.getIdentifier()) if hiddenP { count = getChildNumber(n: comment.getIdentifier()) } var t = text[comment.getIdentifier()]! if isSearching { t = highlight(t) } parentCell.setComment(comment: contents as! RComment, depth: 0, parent: self, hiddenCount: count, date: lastSeen, author: submission?.author, text: t, isCollapsed: hiddenP, parentOP: "", depthColors: commentDepthColors, indexPath: indexPath, width: UIScreen.main.bounds.size.width * 0.85) } else { parentCell.setMore(more: (contents as! RMore), depth: cDepth[comment.getIdentifier()]!, depthColors: commentDepthColors, parent: self) } parentCell.content = comment parentCell.contentView.isUserInteractionEnabled = false var size = CGSize(width: UIScreen.main.bounds.size.width * 0.85, height: CGFloat.greatestFiniteMagnitude) let layout = YYTextLayout(containerSize: size, text: parentCell.title.attributedText!)! let textSize = layout.textBoundingSize size = CGSize(width: UIScreen.main.bounds.size.width * 0.85, height: parentCell.commentBody.estimatedHeight + 24 + textSize.height)// TODO: - fix height let detailViewController = ParentCommentViewController(view: parentCell.contentView, size: size) detailViewController.preferredContentSize = CGSize(width: size.width, height: min(size.height, 300)) previewingContext.sourceRect = cell.frame detailViewController.dismissHandler = {() in self.setAlphaOfBackgroundViews(alpha: 1) } return detailViewController } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { viewControllerToCommit.modalPresentationStyle = .popover if let popover = viewControllerToCommit.popoverPresentationController { popover.sourceView = self.tableView popover.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0) popover.backgroundColor = ColorUtil.theme.foregroundColor popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) //detailViewController.frame = CGRect(x: (self.view.frame.bounds.width / 2 - (UIScreen.main.bounds.size.width * 0.85)), y: (self.view.frame.bounds.height / 2 - (cell2.title.estimatedHeight + 12)), width: UIScreen.main.bounds.size.width * 0.85, height: cell2.title.estimatedHeight + 12) popover.delegate = self viewControllerToCommit.preferredContentSize = (viewControllerToCommit as! ParentCommentViewController).estimatedSize } self.present(viewControllerToCommit, animated: true, completion: { }) } } extension CommentViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { // Fixes bug with corrupt nav stack // https://stackoverflow.com/a/39457751/7138792 navigationController.interactivePopGestureRecognizer?.isEnabled = navigationController.viewControllers.count > 1 if navigationController.viewControllers.count == 1 { self.navigationController?.interactivePopGestureRecognizer?.delegate = nil } } } extension CommentViewController: TapBehindModalViewControllerDelegate { func shouldDismiss() -> Bool { return false } }
875b24d6b95225b4fc1dfbafb55813ca
43.131101
354
0.532073
false
false
false
false
Samiabo/Weibo
refs/heads/master
Weibo/Weibo/Classes/Home/StatusModel.swift
mit
1
// // StatusModel.swift // Weibo // // Created by han xuelong on 2017/1/4. // Copyright © 2017年 han xuelong. All rights reserved. // import UIKit class StatusModel: NSObject { var created_at: String? var source: String? var text: String? var mid: Int = 0 var user: User? var pic_urls: [[String: String]]? var retweeted_status: StatusModel? // MARK: - 自定义构造方法 init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) if let userDict = dict["user"] as? [String: AnyObject] { user = User(dict: userDict) } if let retweetedStatusDict = dict["retweeted_status"] as? [String: AnyObject] { retweeted_status = StatusModel(dict: retweetedStatusDict) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
6827d86a03487315599cd98de9c6db48
23.583333
87
0.59209
false
false
false
false
AlbertXYZ/HDCP
refs/heads/develop
Example/Pods/ObjectMapper/Sources/ToJSON.swift
mit
4
// // ToJSON.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-13. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation private func setValue(_ value: Any, map: Map) { setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, delimiter: map.nestedKeyDelimiter, dictionary: &map.JSON) } private func setValue(_ value: Any, key: String, checkForNestedKeys: Bool, delimiter: String, dictionary: inout [String : Any]) { if checkForNestedKeys { let keyComponents = ArraySlice(key.components(separatedBy: delimiter).filter { !$0.isEmpty }.map { $0 }) setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary) } else { dictionary[key] = value } } private func setValue(_ value: Any, forKeyPathComponents components: ArraySlice<String>, dictionary: inout [String : Any]) { if components.isEmpty { return } let head = components.first! if components.count == 1 { dictionary[String(head)] = value } else { var child = dictionary[String(head)] as? [String : Any] if child == nil { child = [:] } let tail = components.dropFirst() setValue(value, forKeyPathComponents: tail, dictionary: &child!) dictionary[String(head)] = child } } internal final class ToJSON { class func basicType<N>(_ field: N, map: Map) { if let x = field as Any? , false || x is NSNumber // Basic types || x is Bool || x is Int || x is Double || x is Float || x is String || x is NSNull || x is Array<NSNumber> // Arrays || x is Array<Bool> || x is Array<Int> || x is Array<Double> || x is Array<Float> || x is Array<String> || x is Array<Any> || x is Array<Dictionary<String, Any>> || x is Dictionary<String, NSNumber> // Dictionaries || x is Dictionary<String, Bool> || x is Dictionary<String, Int> || x is Dictionary<String, Double> || x is Dictionary<String, Float> || x is Dictionary<String, String> || x is Dictionary<String, Any> { setValue(x, map: map) } } class func optionalBasicType<N>(_ field: N?, map: Map) { if let field = field { basicType(field, map: map) } else if map.shouldIncludeNilValues { basicType(NSNull(), map: map) //If BasicType is nil, emit NSNull into the JSON output } } class func object<N: BaseMappable>(_ field: N, map: Map) { if let result = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSON(field) as Any? { setValue(result, map: map) } } class func optionalObject<N: BaseMappable>(_ field: N?, map: Map) { if let field = field { object(field, map: map) } else if map.shouldIncludeNilValues { basicType(NSNull(), map: map) //If field is nil, emit NSNull into the JSON output } } class func objectArray<N: BaseMappable>(_ field: Array<N>, map: Map) { let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONArray(field) setValue(JSONObjects, map: map) } class func optionalObjectArray<N: BaseMappable>(_ field: Array<N>?, map: Map) { if let field = field { objectArray(field, map: map) } } class func twoDimensionalObjectArray<N: BaseMappable>(_ field: Array<Array<N>>, map: Map) { var array = [[[String: Any]]]() for innerArray in field { let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONArray(innerArray) array.append(JSONObjects) } setValue(array, map: map) } class func optionalTwoDimensionalObjectArray<N: BaseMappable>(_ field: Array<Array<N>>?, map: Map) { if let field = field { twoDimensionalObjectArray(field, map: map) } } class func objectSet<N: BaseMappable>(_ field: Set<N>, map: Map) { let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONSet(field) setValue(JSONObjects, map: map) } class func optionalObjectSet<N: BaseMappable>(_ field: Set<N>?, map: Map) { if let field = field { objectSet(field, map: map) } } class func objectDictionary<N: BaseMappable>(_ field: Dictionary<String, N>, map: Map) { let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONDictionary(field) setValue(JSONObjects, map: map) } class func optionalObjectDictionary<N: BaseMappable>(_ field: Dictionary<String, N>?, map: Map) { if let field = field { objectDictionary(field, map: map) } } class func objectDictionaryOfArrays<N: BaseMappable>(_ field: Dictionary<String, [N]>, map: Map) { let JSONObjects = Mapper(context: map.context, shouldIncludeNilValues: map.shouldIncludeNilValues).toJSONDictionaryOfArrays(field) setValue(JSONObjects, map: map) } class func optionalObjectDictionaryOfArrays<N: BaseMappable>(_ field: Dictionary<String, [N]>?, map: Map) { if let field = field { objectDictionaryOfArrays(field, map: map) } } }
b61543eb2845450de254f1a496f6c0ce
32.287293
133
0.703071
false
false
false
false
zorn/BusyBoard
refs/heads/master
BusyBoard/MainWindowController.swift
mit
1
import Cocoa class MainWindowController: NSWindowController { //MARK - Outlets @IBOutlet weak var sliderDirectionLabel: NSTextField! @IBOutlet weak var verticalSlider: NSSlider! @IBOutlet weak var showTickMarksButton: NSButton! @IBOutlet weak var hideTickMarksButton: NSButton! @IBOutlet weak var checkmarkButton: NSButton! @IBOutlet weak var secureTextField: NSSecureTextField! @IBOutlet weak var normalTextField: NSTextField! //MARK: - Properties var lastKnownSliderValue: Double = 0.0 var showTickMarks: Bool = false var checkmarkIsChecked: Bool = true override var windowNibName: String? { return "MainWindowController" } //MARK: - NSWindowController override func windowDidLoad() { super.windowDidLoad() updateUI() } //MARK - Actions @IBAction func sliderAction(sender: NSSlider) { if verticalSlider.doubleValue > lastKnownSliderValue { sliderDirectionLabel.stringValue = "Slider is going up" } else { sliderDirectionLabel.stringValue = "Slider is going down" } lastKnownSliderValue = verticalSlider.doubleValue } @IBAction func toggleShowTickMarks(sender: NSButton) { if sender.tag == 1 { showTickMarks = true } else { showTickMarks = false } updateUI() } @IBAction func checkmarkButtonAction(sender: NSButton) { if sender.state == NSOnState { checkmarkIsChecked = true } else { checkmarkIsChecked = false } updateUI() } @IBAction func revealSecretMessage(sender: NSButton) { updateUI() } @IBAction func resetWindow(sender: NSButton) { lastKnownSliderValue = 0.0 showTickMarks = false checkmarkIsChecked = true secureTextField.stringValue = "" updateUI() } //MARK: - Private func updateUI() { verticalSlider.doubleValue = lastKnownSliderValue sliderDirectionLabel.stringValue = "" updateCheckmark() updateSecureTextFieldToMatchNormalTextField() updateSliderPreferenceRadioButtons() } func updateCheckmark() { if checkmarkIsChecked { checkmarkButton.state = NSOnState checkmarkButton.title = "Uncheck me" } else { checkmarkButton.state = NSOffState checkmarkButton.title = "Check me" } } func updateSecureTextFieldToMatchNormalTextField() { normalTextField.stringValue = secureTextField.stringValue } func updateSliderPreferenceRadioButtons() { if showTickMarks { verticalSlider.numberOfTickMarks = 15 showTickMarksButton.state = NSOnState hideTickMarksButton.state = NSOffState } else { verticalSlider.numberOfTickMarks = 0 showTickMarksButton.state = NSOffState hideTickMarksButton.state = NSOnState } } }
9da2a7592d29a18d6f25ccc4d6cd5097
27.777778
69
0.625804
false
false
false
false
jpvasquez/Eureka
refs/heads/master
Source/Core/SwipeActions.swift
mit
1
// // Swipe.swift // Eureka // // Created by Marco Betschart on 14.06.17. // Copyright © 2017 Xmartlabs. All rights reserved. // import Foundation import UIKit public typealias SwipeActionHandler = (SwipeAction, BaseRow, ((Bool) -> Void)?) -> Void public class SwipeAction: ContextualAction { let handler: SwipeActionHandler let style: Style public var actionBackgroundColor: UIColor? public var image: UIImage? public var title: String? @available (*, deprecated, message: "Use actionBackgroundColor instead") public var backgroundColor: UIColor? { get { return actionBackgroundColor } set { self.actionBackgroundColor = newValue } } public init(style: Style, title: String?, handler: @escaping SwipeActionHandler){ self.style = style self.title = title self.handler = handler } func contextualAction(forRow: BaseRow) -> ContextualAction { var action: ContextualAction if #available(iOS 11, *){ action = UIContextualAction(style: style.contextualStyle as! UIContextualAction.Style, title: title){ [weak self] action, view, completion -> Void in guard let strongSelf = self else{ return } strongSelf.handler(strongSelf, forRow, completion) } } else { action = UITableViewRowAction(style: style.contextualStyle as! UITableViewRowAction.Style,title: title){ [weak self] (action, indexPath) -> Void in guard let strongSelf = self else{ return } strongSelf.handler(strongSelf, forRow) { _ in DispatchQueue.main.async { guard action.style == .destructive else { forRow.baseCell?.formViewController()?.tableView?.setEditing(false, animated: true) return } forRow.section?.remove(at: indexPath.row) } } } } if let color = self.actionBackgroundColor { action.actionBackgroundColor = color } if let image = self.image { action.image = image } return action } public enum Style { case normal case destructive var contextualStyle: ContextualStyle { if #available(iOS 11, *){ switch self{ case .normal: return UIContextualAction.Style.normal case .destructive: return UIContextualAction.Style.destructive } } else { switch self{ case .normal: return UITableViewRowAction.Style.normal case .destructive: return UITableViewRowAction.Style.destructive } } } } } public struct SwipeConfiguration { unowned var row: BaseRow init(_ row: BaseRow){ self.row = row } public var performsFirstActionWithFullSwipe = false public var actions: [SwipeAction] = [] } extension SwipeConfiguration { @available(iOS 11.0, *) var contextualConfiguration: UISwipeActionsConfiguration? { let contextualConfiguration = UISwipeActionsConfiguration(actions: self.contextualActions as! [UIContextualAction]) contextualConfiguration.performsFirstActionWithFullSwipe = self.performsFirstActionWithFullSwipe return contextualConfiguration } var contextualActions: [ContextualAction]{ return self.actions.map { $0.contextualAction(forRow: self.row) } } } protocol ContextualAction { var actionBackgroundColor: UIColor? { get set } var image: UIImage? { get set } var title: String? { get set } } extension UITableViewRowAction: ContextualAction { public var image: UIImage? { get { return nil } set { return } } public var actionBackgroundColor: UIColor? { get { return backgroundColor } set { self.backgroundColor = newValue } } } @available(iOS 11.0, *) extension UIContextualAction: ContextualAction { public var actionBackgroundColor: UIColor? { get { return backgroundColor } set { self.backgroundColor = newValue } } } public protocol ContextualStyle{} extension UITableViewRowAction.Style: ContextualStyle {} @available(iOS 11.0, *) extension UIContextualAction.Style: ContextualStyle {}
00e424ebfc201e990cc6f9545f9ade00
29.034483
161
0.637658
false
true
false
false
younata/RSSClient
refs/heads/master
TethysKit/Use Cases/UpdateUseCase.swift
mit
1
import CBGPromise import Result protocol UpdateUseCase { func updateFeeds(_ feeds: [Feed]) -> Future<Result<Void, TethysError>> } final class DefaultUpdateUseCase: UpdateUseCase { private let updateService: UpdateService private let mainQueue: OperationQueue private let userDefaults: UserDefaults init(updateService: UpdateService, mainQueue: OperationQueue, userDefaults: UserDefaults) { self.updateService = updateService self.mainQueue = mainQueue self.userDefaults = userDefaults } func updateFeeds(_ feeds: [Feed]) -> Future<Result<Void, TethysError>> { var feedsLeft = feeds.count let promise = Promise<Result<Void, TethysError>>() guard feedsLeft != 0 else { promise.resolve(.failure(.unknown)) return promise.future } var updatedFeeds: [Feed] = [] var currentProgress = 0 for feed in feeds { _ = self.updateService.updateFeed(feed).then { if case let .success(updatedFeed) = $0 { updatedFeeds.append(updatedFeed) } else { updatedFeeds.append(feed) } currentProgress += 1 feedsLeft -= 1 if feedsLeft == 0 { promise.resolve(.success(())) } } } return promise.future } }
f31b88fed05b28423084159caa28cfc5
26.942308
76
0.569855
false
false
false
false
trill-lang/LLVMSwift
refs/heads/master
Sources/LLVM/ArrayType.swift
mit
1
#if SWIFT_PACKAGE import cllvm #endif /// `ArrayType` is a very simple derived type that arranges elements /// sequentially in memory. `ArrayType` requires a size (number of elements) and /// an underlying data type. public struct ArrayType: IRType { /// The type of elements in this array. public let elementType: IRType /// The number of elements in this array. public let count: Int /// Creates an array type from an underlying element type and count. /// - note: The context of this type is taken from it's `elementType` public init(elementType: IRType, count: Int) { self.elementType = elementType self.count = count } /// Creates a constant array value from a list of IR values of a common type. /// /// - parameter values: A list of IR values of the same type. /// - parameter type: The type of the provided IR values. /// /// - returns: A constant array value containing the given values. public static func constant(_ values: [IRValue], type: IRType) -> IRConstant { var vals = values.map { $0.asLLVM() as Optional } return vals.withUnsafeMutableBufferPointer { buf in return Constant<Struct>(llvm: LLVMConstArray(type.asLLVM(), buf.baseAddress, UInt32(buf.count))) } } /// Creates a constant, null terminated array value of UTF-8 bytes from /// string's `utf8` member. /// /// - parameter string: A string to create a null terminated array from. /// - parameter context: The context to create the string in. /// /// - returns: A null terminated constant array value containing /// `string.utf8.count + 1` i8's. public static func constant(string: String, in context: Context = .global) -> IRConstant { let length = string.utf8.count return Constant<Struct>(llvm: LLVMConstStringInContext(context.llvm, string, UInt32(length), 0)) } /// Retrieves the underlying LLVM type object. public func asLLVM() -> LLVMTypeRef { return LLVMArrayType(elementType.asLLVM(), UInt32(count)) } } extension ArrayType: Equatable { public static func == (lhs: ArrayType, rhs: ArrayType) -> Bool { return lhs.asLLVM() == rhs.asLLVM() } }
bb99959b21061df38097947a00f6b2d9
36.526316
102
0.695185
false
false
false
false
Agent-4/MOPhotoPreviewer
refs/heads/master
MOPhotoPreviewer/MOPhotoPreviewer/MOPhotoPreviewer.swift
mit
1
// // MoPhotoPreviewer.swift // Mo // // Created by moxiaohao on 2017/3/24. // Copyright © 2017年 moxiaohao. All rights reserved. // import UIKit import Photos class MOPhotoPreviewer: UIView, UIScrollViewDelegate { var blurBackground: UIVisualEffectView? // 模糊背景 var scrollView: UIScrollView? // UIScrollView var containerView: UIView? // 存放 imageView 容器 var imageView: UIImageView? // 显示的图片 var fromTheImageView: UIImageView? // 传递过来的小图片 override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { frame = UIScreen.main.bounds backgroundColor = UIColor.clear // 单击 let singleTap = UITapGestureRecognizer(target: self, action: #selector(self.singleTap(_:))) addGestureRecognizer(singleTap) // 双击 let doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.doubleTap(_:))) doubleTap.numberOfTapsRequired = 2 singleTap.require(toFail: doubleTap) addGestureRecognizer(doubleTap) // 长按 let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(_:))) addGestureRecognizer(longPress) // 设置模糊背景 blurBackground = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) blurBackground?.frame = frame addSubview(blurBackground!) // 设置 UIScrollView 相关属性 scrollView = UIScrollView(frame: UIScreen.main.bounds) scrollView?.delegate = self scrollView?.bouncesZoom = true scrollView?.maximumZoomScale = 3.0 scrollView?.isMultipleTouchEnabled = true scrollView?.alwaysBounceVertical = false scrollView?.showsVerticalScrollIndicator = false scrollView?.showsHorizontalScrollIndicator = false addSubview(scrollView!) // containerView 容器视图 containerView = UIView() scrollView?.addSubview(containerView!) // imageView 图片视图 imageView = UIImageView() imageView?.clipsToBounds = true imageView?.backgroundColor = UIColor(white: CGFloat(1.0), alpha: CGFloat(0.5)) containerView?.addSubview(imageView!) } func preview(fromImageView: UIImageView, container: UIView) { fromTheImageView = fromImageView fromTheImageView?.isHidden = true container.addSubview(self) // 将 PhotoPreviewer 添加到 container 上 containerView?.mo_origin = CGPoint.zero containerView?.mo_width = mo_width // containerView 的宽度是屏幕的宽度 let image: UIImage? = fromTheImageView?.image // 计算 containerView 的高度 if (image?.size.height)! / (image?.size.height)! > self.mo_height / mo_width { containerView?.mo_height = floor((image?.size.height)! / ((image?.size.width)! / mo_width)) }else { var height: CGFloat? = (image?.size.height)! / (image?.size.width)! * mo_width if (height! < CGFloat(1) || (height?.isNaN)!) { height = self.mo_height } height = floor(height!) containerView?.mo_height = height! containerView?.mo_centerY = self.mo_height / 2 } if (containerView?.mo_height)! > self.mo_height && (containerView?.mo_height)! - self.mo_height <= 1 { containerView?.mo_height = self.mo_height } scrollView?.contentSize = CGSize(width: CGFloat(mo_width), height: CGFloat(max((containerView?.mo_height)!, self.mo_height))) scrollView?.scrollRectToVisible(bounds, animated: false) if (containerView?.mo_height)! <= self.mo_height { scrollView?.alwaysBounceVertical = false }else { scrollView?.alwaysBounceVertical = true } let fromRect: CGRect = (self.fromTheImageView?.convert((self.fromTheImageView?.bounds)!, to: self.containerView))! imageView?.frame = fromRect imageView?.contentMode = .scaleAspectFill imageView?.image = image UIView.animate(withDuration: 0.18, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {() -> Void in self.imageView?.frame = (self.containerView?.bounds)! self.imageView?.transform = CGAffineTransform(scaleX: 1.01, y: 1.01) }, completion: {(_ finished: Bool) -> Void in UIView.animate(withDuration: 0.18, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {() -> Void in self.imageView?.transform = CGAffineTransform(scaleX: 1.00, y: 1.00) }, completion: nil) }) } // 返回 func dismiss() { UIView.animate(withDuration: 0.18, delay: 0.0, options: .curveEaseInOut, animations: {() -> Void in let fromRect: CGRect = (self.fromTheImageView?.convert((self.fromTheImageView?.bounds)!, to: self.containerView))! self.imageView?.contentMode = (self.fromTheImageView?.contentMode)! self.imageView?.frame = fromRect self.blurBackground?.alpha = 0.01 }, completion: {(_ finished: Bool) -> Void in UIView.animate(withDuration: 0.10, delay: 0, options: .curveEaseInOut, animations: {() -> Void in self.fromTheImageView?.isHidden = false self.alpha = 0 }, completion: {(_ finished: Bool) -> Void in self.removeFromSuperview() }) }) } // MARK: - <UIScrollViewDelegate> func viewForZooming(in scrollView: UIScrollView) -> UIView? { return containerView! } func scrollViewDidZoom(_ scrollView: UIScrollView) { let subView: UIView? = containerView let offsetX: CGFloat = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0 let offsetY: CGFloat = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0 subView?.center = CGPoint(x: CGFloat(scrollView.contentSize.width * 0.5 + offsetX), y: CGFloat(scrollView.contentSize.height * 0.5 + offsetY)) } // MARK: - GestureRecognizer // 单击 ** dismiss ** @objc func singleTap(_ recognizer: UITapGestureRecognizer) { dismiss() } // 双击 ** 放大 ** @objc func doubleTap(_ recognizer: UITapGestureRecognizer) { if (scrollView?.zoomScale)! > CGFloat(1.0) { scrollView?.setZoomScale(1.0, animated: true) }else { let touchPoint: CGPoint = recognizer.location(in: imageView) let newZoomScale: CGFloat = scrollView!.maximumZoomScale let xSize: CGFloat = mo_width / newZoomScale let ySize: CGFloat = mo_height / newZoomScale scrollView?.zoom(to: CGRect(x: CGFloat(touchPoint.x - xSize / 2), y: CGFloat(touchPoint.y - ySize / 2), width: xSize, height: ySize), animated: true) } } // 长按 ** 保存图片到相册 ** @objc func longPress(_ recognizer: UILongPressGestureRecognizer) { // 最好加入状态判断 if recognizer.state == .began { let image = fromTheImageView?.image let alertController = UIAlertController(title: "保存图片", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "保存", style: .default, handler: {(_ action: UIAlertAction) -> Void in PHPhotoLibrary.shared().performChanges({() -> Void in //写入图片到相册 PHAssetChangeRequest.creationRequestForAsset(from: image!) }, completionHandler: {(succeeded, error) -> Void in // 最好是异步操作,否则可能会阻塞主线程或引起奇怪的崩溃 DispatchQueue.main.async { if succeeded { // 保存成功的提示 ** 自己可以自定义加入 HUD 提示 ** print("保存成功!") }else { // 保存失败的提示 ** 自己可以自定义加入 HUD 提示 ** print("保存失败!") } } }) })) alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) let vc: UIViewController? = currentViewController() vc?.present(alertController, animated: true, completion: nil) } } }
8a353887d8f758981b22643498cf4a15
42.248756
172
0.597837
false
false
false
false
apple/swift-format
refs/heads/main
Sources/SwiftFormatRules/OnlyOneTrailingClosureArgument.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftFormatCore import SwiftSyntax /// Function calls should never mix normal closure arguments and trailing closures. /// /// Lint: If a function call with a trailing closure also contains a non-trailing closure argument, /// a lint error is raised. public final class OnlyOneTrailingClosureArgument: SyntaxLintRule { public override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { guard (node.argumentList.contains { $0.expression.is(ClosureExprSyntax.self) }) else { return .skipChildren } guard node.trailingClosure != nil else { return .skipChildren } diagnose(.removeTrailingClosure, on: node) return .skipChildren } } extension Finding.Message { public static let removeTrailingClosure: Finding.Message = "revise function call to avoid using both closure arguments and a trailing closure" }
b25cb14f4af42c019e94306c7d504f3b
38.885714
99
0.666905
false
false
false
false
TVGSoft/Architecture-iOS
refs/heads/master
Model/Model/FoodModel.swift
mit
1
// // FoodModel.swift // Model // // Created by Giáp Trần on 9/8/16. // Copyright © 2016 TVG Soft, Inc. All rights reserved. // import RealmSwift public class FoodModel: BaseModel { // MARK: Property public override var tableName: String { return Food.className() } // MARK: Public method public func getFoodOfRestaurant(restaurantId: Int) -> [Food]? { let realm = try! Realm() let results = realm.objects(Food.self) .filter("restaurantId = \(restaurantId)") .sorted("updatedAt", ascending: true) if results.count <= 0 { return nil } var foods = [Food]() for result in results { foods.append(result) } return foods } public func getFoodOfCategory(categoryId: Int) -> [Food]? { let realm = try! Realm() let results = realm.objects(Food.self) .filter("categoryId = \(categoryId)") .sorted("updatedAt", ascending: true) if results.count <= 0 { return nil } var foods = [Food]() for result in results { foods.append(result) } return foods } }
ed2d380b0fc3da17841540e07e5ea95b
21.483871
68
0.477762
false
false
false
false
GrandCentralBoard/GrandCentralBoard
refs/heads/develop
GrandCentralBoardTests/Widgets/Slack/SlackSourceTests.swift
gpl-3.0
2
// // SlackSourceTests.swift // GrandCentralBoard // // Created by Michał Laskowski on 12.05.2016. // Copyright © 2016 Macoscope. All rights reserved. // import XCTest import Nimble import SlackKit @testable import GrandCentralBoard private struct TestSlackClient: SlackDataProviding { let author, avatar, channel: String? func userNameForUserID(id: String) -> String? { return author } func userAvatarPathForUserID(id: String) -> String? { return avatar } func channelNameForChannelID(id: String) -> String? { return channel} } final class SlackSourceTests: XCTestCase { func testSlackMessageIsComplete() { let channelName = "test_channel_name" let userName = "test_user_name" let avatarPath = "http://image.url" let client = TestSlackClient(author: userName, avatar: avatarPath, channel: channelName) let source = SlackSource(slackClient: client) let timestamp = NSDate().timeIntervalSince1970 let messageTimestamp = "\(Int(timestamp)).0001" let messageText = "<!here> test_message_text" let fakeMessage = Message(message: [ "ts": messageTimestamp, "user": "user_id", "channel": "channel_id", "text": messageText ])! waitUntil { done in source.subscriptionBlock = { message in expect(message.text) == messageText.stringByReplacingOccurrencesOfString("<!here> ", withString: "") expect(message.timestamp.timeIntervalSince1970).to(beCloseTo(timestamp, within: 1.0)) expect(message.author) == userName expect(message.channel) == channelName expect(message.avatarPath) == avatarPath done() } source.messageReceived(fakeMessage) } } }
f455b6044fb03f174937b6810e56eef4
32.618182
116
0.63656
false
true
false
false
manavgabhawala/swift
refs/heads/master
test/IRGen/objc_extensions.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-objc-attr-requires-foundation-module -emit-module %S/Inputs/objc_extension_base.swift -o %t // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo import objc_extension_base // Check that metadata for nested enums added in extensions to imported classes // gets emitted concretely. // CHECK: [[CATEGORY_NAME:@.*]] = private unnamed_addr constant [16 x i8] c"objc_extensions\00" // CHECK: [[METHOD_TYPE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK-LABEL: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions" = private constant // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP15objc_extensions11NewProtocol_ // CHECK-LABEL: @"_CATEGORY_Gizmo_$_objc_extensions" = private constant // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK: @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions", // CHECK: @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions", // CHECK: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions", // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 @objc protocol NewProtocol { func brandNewInstanceMethod() } extension NSObject { func someMethod() -> String { return "Hello" } } extension Gizmo: NewProtocol { func brandNewInstanceMethod() { } class func brandNewClassMethod() { } // Overrides an instance method of NSObject override func someMethod() -> String { return super.someMethod() } // Overrides a class method of NSObject open override class func initialize() { } } /* * Make sure that two extensions of the same ObjC class in the same module can * coexist by having different category names. */ // CHECK: [[CATEGORY_NAME_1:@.*]] = private unnamed_addr constant [17 x i8] c"objc_extensions1\00" // CHECK: @"_CATEGORY_Gizmo_$_objc_extensions1" = private constant // CHECK: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[CATEGORY_NAME_1]], i64 0, i64 0), // CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions1", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions1", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 extension Gizmo { func brandSpankingNewInstanceMethod() { } class func brandSpankingNewClassMethod() { } } /* * Check that extensions of Swift subclasses of ObjC objects get categories. */ class Hoozit : NSObject { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR:@.*]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:%.*]]*, i8*)* @_T015objc_extensions6HoozitC7blibbleyyFTo to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-LABEL: @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blobble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @_T015objc_extensions6HoozitC7blobbleyyFZTo to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-LABEL: @"_CATEGORY__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK: %swift.type* {{.*}} @_T015objc_extensions6HoozitCMf, // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 extension Hoozit { func blibble() { } class func blobble() { } } class SwiftOnly { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions9SwiftOnly_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @_T015objc_extensions9SwiftOnlyC6wibbleyyFTo to i8*) // CHECK: }] }, section "__DATA, __objc_const", align 8 extension SwiftOnly { @objc func wibble() { } } class Wotsit: Hoozit {} extension Hoozit { @objc func overriddenByExtensionInSubclass() {} } extension Wotsit { @objc override func overriddenByExtensionInSubclass() {} } extension NSObject { private enum SomeEnum { case X } public func needMetadataOfSomeEnum() { print(NSObject.SomeEnum.X) } } /* * Make sure that @NSManaged causes a category to be generated. */ class NSDogcow : NSObject {} // CHECK: [[NAME:@.*]] = private unnamed_addr constant [5 x i8] c"woof\00" // CHECK: [[ATTR:@.*]] = private unnamed_addr constant [7 x i8] c"Tq,N,D\00" // CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_extensions8NSDogcow_$_objc_extensions" = private constant {{.*}} [[NAME]], {{.*}} [[ATTR]], {{.*}}, section "__DATA, __objc_const", align 8 extension NSDogcow { @NSManaged var woof: Int } // CHECK: @_T0So8NSObjectC15objc_extensionsE8SomeEnum33_1F05E59585E0BB585FCA206FBFF1A92DLLOs9EquatableACWP = class SwiftSubGizmo : SwiftBaseGizmo { // Don't crash on this call. Emit an objC method call to super. // // CHECK-LABEL: define {{.*}} @_T015objc_extensions13SwiftSubGizmoC4frobyyF // CHECK: _T015objc_extensions13SwiftSubGizmoCMa // CHECK: objc_msgSendSuper2 // CHECK: ret public override func frob() { super.frob() } }
6715c3cadef47d82fffb34ee6f41a5d9
34.618785
183
0.658601
false
false
false
false
ThumbWorks/i-meditated
refs/heads/master
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift
mit
6
// // SingleAsync.swift // Rx // // Created by Junior B. on 09/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class SingleAsyncSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SingleAsync<ElementType> typealias E = ElementType private let _parent: Parent private var _seenValue: Bool = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<E>) { switch event { case .next(let value): do { let forward = try _parent._predicate?(value) ?? true if !forward { return } } catch let error { forwardOn(.error(error as Swift.Error)) dispose() return } if _seenValue == false { _seenValue = true forwardOn(.next(value)) } else { forwardOn(.error(RxError.moreThanOneElement)) dispose() } case .error: forwardOn(event) dispose() case .completed: if (!_seenValue) { forwardOn(.error(RxError.noElements)) } else { forwardOn(.completed) } dispose() } } } class SingleAsync<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate? init(source: Observable<Element>, predicate: Predicate? = nil) { _source = source _predicate = predicate } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = SingleAsyncSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
8f78fd114299b1f136e2e68c23cdba26
26.171053
102
0.527361
false
false
false
false
AaronBratcher/ALBPeerConnection
refs/heads/master
ALBPeerConnection/ALBPeerConnection/ALBPeerConnection.swift
mit
1
// // ALBPeerConnection.swift // ALBPeerConnection // // Created by Aaron Bratcher on 3/13/15. // Copyright (c) 2015 Aaron Bratcher. All rights reserved. // import Foundation public protocol ALBPeerConnectionDelegate { /** Called when the connection to the remote has been broken. - parameter connection: The connection that has been disconnected. - parameter byRequest: Is true if the disconnect was by request. */ func disconnected(_ connection: ALBPeerConnection, byRequest: Bool) /** Called when text has been received from the remote. - parameter connection: The connection that received the text. - parameter text: The text that was received. */ func textReceived(_ connection: ALBPeerConnection, text: String) /** Called when data has been received from the remote. - parameter connection: The connection that received the data. - parameter data: The data that was received. */ func dataReceived(_ connection: ALBPeerConnection, data: Data) /** Called when this connection has started to receive a resource from the remote. - parameter connection: The connection that is receiving the resource. - parameter atURL: The location of the resource. - parameter name: The given name of the resource. - parameter resourceID: The unique identifier of the resource - parameter progress: An NSProgress object that is updated as the file is received. This cannot be canceled at this time. */ func startedReceivingResource(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String, progress: Progress) /** Called when this connection has finished receiving a resource from the remote. - parameter connection: The connection that is receiving the resource. - parameter atURL: The location of the resource. - parameter name: The given name of the resource. - parameter resourceID: The unique identifier of the resource */ func resourceReceived(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String) } let ALBPeerConnectionQueue = DispatchQueue(label: "com.AaronLBratcher.ALBPeerConnectionQueue") let ALBPeerPacketDelimiter = Data(bytes: UnsafePointer<UInt8>([0x0B, 0x1B, 0x1B] as [UInt8]), count: 3) // VerticalTab Esc Esc let ALBPeerMaxDataSize = 65536 let ALBPeerWriteTimeout = TimeInterval(60) public final class ALBPeerConnection: NSObject, GCDAsyncSocketDelegate { public var delegate: ALBPeerConnectionDelegate? { didSet { _socket.readData(to: ALBPeerPacketDelimiter, withTimeout: -1, tag: 0) } } public var delegateQueue = DispatchQueue.main public var remotNode: ALBPeer fileprivate var _socket: GCDAsyncSocket fileprivate var _disconnecting = false fileprivate var _pendingPackets = [Int: ALBPeerPacket]() fileprivate var _lastTag = 0 fileprivate var _cachedData: Data? fileprivate var _resourceFiles = [String: Resource]() class Resource { var handle: FileHandle var path: String var name: String var progress = Progress() init(handle: FileHandle, path: String, name: String) { self.handle = handle self.path = path self.name = name self.progress.isCancellable = false } } // MARK: - Initializers /* this is called by the client or server class. Do not call this directly. */ public init(socket: GCDAsyncSocket, remoteNode: ALBPeer) { _socket = socket self.remotNode = remoteNode super.init() socket.delegate = self } // MARK: - Public Methods /* Disconnect from the remote. If there are pending packets to be sent, they will be sent before disconnecting. */ public func disconnect() { _disconnecting = true if _pendingPackets.count == 0 { _socket.disconnect() } } /** Send a text string to the remote. - parameter text: The text to send. */ public func sendText(_ text: String) { let packet = ALBPeerPacket(type: .text) let data = text.data(using: String.Encoding.utf8, allowLossyConversion: false) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(data), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } /** Send data to the remote. - parameter data: The data to send. */ public func sendData(_ data: Data) { let packet = ALBPeerPacket(type: .data) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(data), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } /** Send a file to the remote. - parameter url: The URL path to the file. - parameter name: The name of the file. - parameter resourceID: A unique string identifier to this resource. - parameter onCompletion: A block of code that will be called when the resource has been sent - returns: NSProgress This will be updated as the file is sent. Currently, a send cannot be canceled. */ public func sendResourceAtURL(_ url: URL, name: String, resourceID: String, onCompletion: @escaping completionHandler) -> Progress { let data = try! Data(contentsOf: url, options: NSData.ReadingOptions.mappedRead) var resource = ALBPeerResource(identity: resourceID, name: name, url: url, data: data) resource.onCompletion = onCompletion resource.progress = Progress(totalUnitCount: Int64(resource.length)) resource.progress?.isCancellable = false sendResourcePacket(resource) return resource.progress! } private func sendResourcePacket(_ resource: ALBPeerResource) { var resource = resource var packet = ALBPeerPacket(type: .resource) let dataSize = max(ALBPeerMaxDataSize, resource.length - resource.offset) resource.offset += dataSize if resource.offset >= resource.length { packet.isFinal = true } if let progress = resource.progress { progress.completedUnitCount = Int64(resource.offset) } packet.resource = resource let range = 0..<resource.offset + dataSize let subData = resource.mappedData!.subdata(in: range) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(subData), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } // MARK: - Socket Delegate /** This is for internal use only **/ public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { if let packet = _pendingPackets[tag] { _pendingPackets.removeValue(forKey: tag) if _disconnecting && _pendingPackets.count == 0 && (packet.type == .data || packet.isFinal) { _socket.disconnectAfterWriting() return } // if this is a resource packet... send next packet if packet.type == .resource { if !packet.isFinal { sendResourcePacket(packet.resource!) } else { if let resource = packet.resource, let completionHandler = resource.onCompletion { completionHandler(true) } } } } } /** This is for internal use only **/ public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { if let packet = ALBPeerPacket(packetData: data) { processPacket(packet) } else { // store data from this read and append to it with data from next read if _cachedData == nil { _cachedData = Data() } _cachedData!.append(data) if _cachedData!.count > ALBPeerMaxDataSize * 4 { _socket.disconnect() return } if let packet = ALBPeerPacket(packetData: _cachedData!) { processPacket(packet) } } _socket.readData(to: ALBPeerPacketDelimiter, withTimeout: -1, tag: 0) } private func processPacket(_ packet: ALBPeerPacket) { _cachedData = nil switch packet.type { case .text: delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { guard let data = packet.data , let text = String(data: data, encoding: .utf8) else { return } delegate.textReceived(self, text: text) } else { print("Connection delegate is not assigned") } }) case .data: delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.dataReceived(self, data: packet.data! as Data) } else { print("Connection delegate is not assigned") } }) case .resource: if let resourceID = packet.resource?.identity, let name = packet.resource?.name, let resourceLength = packet.resource?.length, let packetLength = packet.data?.count { let handle: FileHandle var resourcePath: String var resource = _resourceFiles[packet.resource!.identity] if let resource = resource { handle = resource.handle resourcePath = resource.path } else { // create file let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentFolderPath = searchPaths[0] resourcePath = "\(documentFolderPath)/\(name)" var nameIndex = 1 while FileManager.default.fileExists(atPath: resourcePath) { let parts = resourcePath.components(separatedBy: ".") resourcePath = "" if parts.count > 1 { let partCount = parts.count - 1 for partIndex in 0..<partCount { resourcePath = "\(resourcePath).\(parts[partIndex])" } resourcePath = "\(resourcePath)-\(nameIndex)" resourcePath = "\(resourcePath).\(parts[parts.count-1])" } else { resourcePath = "\(resourcePath)\(nameIndex)" } nameIndex = nameIndex + 1 } FileManager.default.createFile(atPath: resourcePath, contents: nil, attributes: nil) if let fileHandle = FileHandle(forWritingAtPath: resourcePath) { resource = Resource(handle: fileHandle, path: resourcePath, name: name) let progress = Progress(totalUnitCount: Int64(resourceLength)) resource?.progress = progress _resourceFiles[resourceID] = resource handle = fileHandle } else { resourceCopyError(resourceID, name: name) return } delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.startedReceivingResource(self, atURL: URL(fileURLWithPath: resourcePath), name: packet.resource!.name, resourceID: resourceID, progress: resource!.progress) } else { print("Connection delegate is not assigned") } }) } if let progress = resource?.progress { progress.completedUnitCount = progress.completedUnitCount + Int64(packetLength) } handle.write(packet.data! as Data) if packet.isFinal { handle.closeFile() let resource = _resourceFiles[resourceID]! _resourceFiles.removeValue(forKey: resourceID) delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.resourceReceived(self, atURL: URL(fileURLWithPath: resourcePath), name: resource.name, resourceID: resourceID) } else { print("Connection delegate is not assigned") } }) } } else { resourceCopyError("**Unknown**", name: "**Unknown**") return } case .resourceError: if let resource = packet.resource, let completionHandler = resource.onCompletion { completionHandler(false) } default: // other cases handled elsewhere break } } private func resourceCopyError(_ resourceID: String, name: String) { let resource = ALBPeerResource(identity: resourceID, name: name) var packet = ALBPeerPacket(type: .resourceError) packet.resource = resource _socket.write(packet.packetDataUsingData(nil), withTimeout: ALBPeerWriteTimeout, tag: 0) } /** This is for internal use only **/ public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.disconnected(self, byRequest: self._disconnecting) } else { print("Connection delegate is not assigned") } }) } }
c2e5cdbbeacfcb6bf1f4440941b6a2bd
31.385246
173
0.698642
false
false
false
false
lanjing99/RxSwiftDemo
refs/heads/master
12-beginning-rxcocoa/challenge/Wundercast/ViewController.swift
mit
1
/* * Copyright (c) 2014-2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var searchCityName: UITextField! @IBOutlet weak var tempLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var iconLabel: UILabel! @IBOutlet weak var cityNameLabel: UILabel! @IBOutlet weak var tempSwitch: UISwitch! let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. style() //MARK: - Part 1 // searchCityName.rx.text // .filter { ($0 ?? "").characters.count > 0 } // .flatMapLatest { text in // return ApiController.shared.currentWeather(city: text ?? "Error") // .catchErrorJustReturn(ApiController.Weather.empty) // } // .observeOn(MainScheduler.instance) // .subscribe(onNext: { data in // self.tempLabel.text = "\(data.temperature)° C" // self.iconLabel.text = data.icon // self.humidityLabel.text = "\(data.humidity)%" // self.cityNameLabel.text = data.cityName // }).addDisposableTo(bag) //MARK: - Part 2 // let search = searchCityName.rx.text // .filter { ($0 ?? "").characters.count > 0 } // .flatMapLatest { text in // return ApiController.shared.currentWeather(city: text ?? "Error") // .catchErrorJustReturn(ApiController.Weather.empty) // }.observeOn(MainScheduler.instance) // // // search.map { "\($0.temperature)° C" } // .bindTo(tempLabel.rx.text) // .addDisposableTo(bag) // // search.map { $0.icon } // .bindTo(iconLabel.rx.text) // .addDisposableTo(bag) // // search.map { "\($0.humidity)%" } // .bindTo(humidityLabel.rx.text) // .addDisposableTo(bag) // // search.map { $0.cityName } // .bindTo(cityNameLabel.rx.text) // .addDisposableTo(bag) //MARK: - Part 3 // let search = searchCityName.rx.text // .filter { ($0 ?? "").characters.count > 0 } // .flatMap { text in // return ApiController.shared.currentWeather(city: text ?? "Error") // .catchErrorJustReturn(ApiController.Weather.empty) // }.asDriver(onErrorJustReturn: ApiController.Weather.empty) // // search.map { "\($0.temperature)° C" } // .drive(tempLabel.rx.text) // .addDisposableTo(bag) // // search.map { $0.icon } // .drive(iconLabel.rx.text) // .addDisposableTo(bag) // // search.map { "\($0.humidity)%" } // .drive(humidityLabel.rx.text) // .addDisposableTo(bag) // // search.map { $0.cityName } // .drive(cityNameLabel.rx.text) // .addDisposableTo(bag) //MARK: - Part 4 let textSearch = searchCityName.rx.controlEvent(.editingDidEndOnExit).asObservable() let temperature = tempSwitch.rx.controlEvent(.valueChanged).asObservable() let search = Observable.from([textSearch, temperature]) .merge() .map { self.searchCityName.text } .filter { ($0 ?? "").characters.count > 0 } .flatMap { text in return ApiController.shared.currentWeather(city: text ?? "Error") .catchErrorJustReturn(ApiController.Weather.empty) }.asDriver(onErrorJustReturn: ApiController.Weather.empty) search.map { w in if self.tempSwitch.isOn { return "\(Int(Double(w.temperature) * 1.8 + 32))° F" } return "\(w.temperature)° C" } .drive(tempLabel.rx.text) .addDisposableTo(bag) search.map { $0.icon } .drive(iconLabel.rx.text) .addDisposableTo(bag) search.map { "\($0.humidity)%" } .drive(humidityLabel.rx.text) .addDisposableTo(bag) search.map { $0.cityName } .drive(cityNameLabel.rx.text) .addDisposableTo(bag) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Appearance.applyBottomLine(to: searchCityName) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Style private func style() { view.backgroundColor = UIColor.aztec searchCityName.textColor = UIColor.ufoGreen tempLabel.textColor = UIColor.cream humidityLabel.textColor = UIColor.cream iconLabel.textColor = UIColor.cream cityNameLabel.textColor = UIColor.cream } }
602f6f5d703bff2cd78c9967c31d6804
30.747191
88
0.66413
false
false
false
false
alexpotter1/Weight-Tracker
refs/heads/master
Project/Weight Tracker/External Libraries/CorePlot_2.0r1/Source/examples/CPTTestApp-iPhone/Classes/ScatterPlotController.swift
apache-2.0
2
import UIKit class ScatterPlotController : UIViewController, CPTScatterPlotDataSource { private var scatterGraph : CPTXYGraph? = nil typealias plotDataType = [CPTScatterPlotField : Double] private var dataForPlot = [plotDataType]() // MARK: Initialization override func viewDidAppear(animated : Bool) { super.viewDidAppear(animated) // Create graph from theme let newGraph = CPTXYGraph(frame: CGRectZero) newGraph.applyTheme(CPTTheme(named: kCPTDarkGradientTheme)) let hostingView = self.view as! CPTGraphHostingView hostingView.hostedGraph = newGraph // Paddings newGraph.paddingLeft = 10.0 newGraph.paddingRight = 10.0 newGraph.paddingTop = 10.0 newGraph.paddingBottom = 10.0 // Plot space let plotSpace = newGraph.defaultPlotSpace as! CPTXYPlotSpace plotSpace.allowsUserInteraction = true plotSpace.yRange = CPTPlotRange(location:1.0, length:2.0) plotSpace.xRange = CPTPlotRange(location:1.0, length:3.0) // Axes let axisSet = newGraph.axisSet as! CPTXYAxisSet if let x = axisSet.xAxis { x.majorIntervalLength = 0.5 x.orthogonalPosition = 2.0 x.minorTicksPerInterval = 2 x.labelExclusionRanges = [ CPTPlotRange(location: 0.99, length: 0.02), CPTPlotRange(location: 1.99, length: 0.02), CPTPlotRange(location: 2.99, length: 0.02) ] } if let y = axisSet.xAxis { y.majorIntervalLength = 0.5 y.minorTicksPerInterval = 5 y.orthogonalPosition = 2.0 y.labelExclusionRanges = [ CPTPlotRange(location: 0.99, length: 0.02), CPTPlotRange(location: 1.99, length: 0.02), CPTPlotRange(location: 3.99, length: 0.02) ] y.delegate = self } // Create a blue plot area let boundLinePlot = CPTScatterPlot(frame: CGRectZero) let blueLineStyle = CPTMutableLineStyle() blueLineStyle.miterLimit = 1.0 blueLineStyle.lineWidth = 3.0 blueLineStyle.lineColor = CPTColor.blueColor() boundLinePlot.dataLineStyle = blueLineStyle boundLinePlot.identifier = "Blue Plot" boundLinePlot.dataSource = self newGraph.addPlot(boundLinePlot) let fillImage = CPTImage(named:"BlueTexture") fillImage.tiled = true boundLinePlot.areaFill = CPTFill(image: fillImage) boundLinePlot.areaBaseValue = 0.0 // Add plot symbols let symbolLineStyle = CPTMutableLineStyle() symbolLineStyle.lineColor = CPTColor.blackColor() let plotSymbol = CPTPlotSymbol.ellipsePlotSymbol() plotSymbol.fill = CPTFill(color: CPTColor.blueColor()) plotSymbol.lineStyle = symbolLineStyle plotSymbol.size = CGSize(width: 10.0, height: 10.0) boundLinePlot.plotSymbol = plotSymbol // Create a green plot area let dataSourceLinePlot = CPTScatterPlot(frame: CGRectZero) let greenLineStyle = CPTMutableLineStyle() greenLineStyle.lineWidth = 3.0 greenLineStyle.lineColor = CPTColor.greenColor() greenLineStyle.dashPattern = [5.0, 5.0] dataSourceLinePlot.dataLineStyle = greenLineStyle dataSourceLinePlot.identifier = "Green Plot" dataSourceLinePlot.dataSource = self // Put an area gradient under the plot above let areaColor = CPTColor(componentRed: 0.3, green: 1.0, blue: 0.3, alpha: 0.8) let areaGradient = CPTGradient(beginningColor: areaColor, endingColor: CPTColor.clearColor()) areaGradient.angle = -90.0 let areaGradientFill = CPTFill(gradient: areaGradient) dataSourceLinePlot.areaFill = areaGradientFill dataSourceLinePlot.areaBaseValue = 1.75 // Animate in the new plot, as an example dataSourceLinePlot.opacity = 0.0 newGraph.addPlot(dataSourceLinePlot) let fadeInAnimation = CABasicAnimation(keyPath: "opacity") fadeInAnimation.duration = 1.0 fadeInAnimation.removedOnCompletion = false fadeInAnimation.fillMode = kCAFillModeForwards fadeInAnimation.toValue = 1.0 dataSourceLinePlot.addAnimation(fadeInAnimation, forKey: "animateOpacity") // Add some initial data var contentArray = [plotDataType]() for i in 0 ..< 60 { let x = 1.0 + Double(i) * 0.05 let y = 1.2 * Double(arc4random()) / Double(UInt32.max) + 1.2 let dataPoint: plotDataType = [.X: x, .Y: y] contentArray.append(dataPoint) } self.dataForPlot = contentArray self.scatterGraph = newGraph } // MARK: - Plot Data Source Methods func numberOfRecordsForPlot(plot: CPTPlot) -> UInt { return UInt(self.dataForPlot.count) } func numberForPlot(plot: CPTPlot, field: UInt, recordIndex: UInt) -> AnyObject? { let plotField = CPTScatterPlotField(rawValue: Int(field)) if let num = self.dataForPlot[Int(recordIndex)][plotField!] { let plotID = plot.identifier as! String if (plotField! == .Y) && (plotID == "Green Plot") { return (num + 1.0) as NSNumber } else { return num as NSNumber } } else { return nil } } // MARK: - Axis Delegate Methods func axis(axis: CPTAxis, shouldUpdateAxisLabelsAtLocations locations: NSSet!) -> Bool { if let formatter = axis.labelFormatter { let labelOffset = axis.labelOffset var newLabels = Set<CPTAxisLabel>() for tickLocation in locations { if let labelTextStyle = axis.labelTextStyle?.mutableCopy() as? CPTMutableTextStyle { if tickLocation.doubleValue >= 0.0 { labelTextStyle.color = CPTColor.greenColor() } else { labelTextStyle.color = CPTColor.redColor() } let labelString = formatter.stringForObjectValue(tickLocation) let newLabelLayer = CPTTextLayer(text: labelString, style: labelTextStyle) let newLabel = CPTAxisLabel(contentLayer: newLabelLayer) newLabel.tickLocation = tickLocation as? NSNumber newLabel.offset = labelOffset newLabels.insert(newLabel) } axis.axisLabels = newLabels } } return false } }
a853b206ec5ea40084ac1757309d43ae
36.101604
101
0.593399
false
false
false
false
hydrantwiki/hwIOSApp
refs/heads/master
hwIOSApp/hwIOSApp/UIFormatHelper.swift
mit
1
// // UIFormatHelper.swift // hwIOSApp // // Created by Brian Nelson on 3/5/16. // Copyright © 2016 Brian Nelson. All rights reserved. // import Foundation import UIKit import MapKit public class UIFormatHelper { static func Format(control:UIButton) { control.backgroundColor = UIConstants.HydrantWikiGray; control.setTitleColor( UIConstants.ButtonTextColor, forState: UIControlState.Normal); control.setTitleColor( UIConstants.ButtonTextDisabledColor, forState: UIControlState.Disabled); control.titleLabel?.font = UIFont(name: UIConstants.ButtonFontName, size: UIConstants.ButtonTextHeight); control.layer.cornerRadius = 10; control.clipsToBounds = true; } static func Format(control:UIBarButtonItem) { var attributes = [String:AnyObject](); attributes[NSForegroundColorAttributeName] = UIConstants.HydrantWikiBlack; control.setTitleTextAttributes(attributes, forState: UIControlState.Normal) var attributes2 = [String:AnyObject]() attributes2[NSForegroundColorAttributeName] = UIConstants.HydrantWikiGray control.setTitleTextAttributes(attributes2, forState: UIControlState.Disabled) } static func Format(control:UIBarButtonItem, image:String) { var attributes = [String:AnyObject]() attributes[NSForegroundColorAttributeName] = UIConstants.HydrantWikiRed; control.setTitleTextAttributes(attributes, forState: UIControlState.Normal) var attributes2 = [String:AnyObject]() attributes2[NSForegroundColorAttributeName] = UIConstants.HydrantWikiWhite control.setTitleTextAttributes(attributes2, forState: UIControlState.Disabled) } static func Format(control:UITextView) { control.backgroundColor = UIConstants.HydrantWikiWhite; control.layer.borderColor = UIColor.blackColor().CGColor; control.layer.borderWidth = 1; } static func GetFrame( x:Double, y:Double, width:Double, height:Double) -> CGRect { let rect = CGRect( x: x, y: y, width: width, height: height ); return rect; } static func GetFrameTopWithMargin( top:Double, margin:Double) -> CGRect { let screenWidth:Double = GetScreenWidthAsDouble(); let screenHeight:Double = GetScreenHeightAsDouble(); let height:Double = screenHeight - (top + margin); let width:Double = screenWidth - 2 * margin; let rect = CGRect( x: margin, y: top, width: width, height: height ); return rect; } static func GetFrameTopWithMarginMaxHeight( top:Double, margin:Double, maxHeightPercent:Double) -> CGRect { let screenWidth:Double = GetScreenWidthAsDouble(); let screenHeight:Double = GetScreenHeightAsDouble(); let width:Double = screenWidth - 2 * margin; var height:Double = screenHeight - (top + margin); let maxHeight:Double = screenHeight * maxHeightPercent; if (height > maxHeight) { height = maxHeight; } let rect = CGRect( x: margin, y: top, width: width, height: height ); return rect; } static func GetFrameByPercent( xPercent:Double, yPercent:Double, widthPercent:Double, heightPercent:Double) -> CGRect { let width:Double = GetScreenWidthAsDouble(); let height:Double = GetScreenHeightAsDouble(); let rect = CGRect( x: width * xPercent, y: height * yPercent, width: width * widthPercent, height: height * heightPercent ); return rect; } static func FormatAsHeader(control:UILabel) { control.font = UIFont(name: "Heiti TC", size: UIConstants.HeaderHeight); control.backgroundColor = UIConstants.HydrantWikiWhite; control.textAlignment = NSTextAlignment.Center; control.baselineAdjustment = .AlignCenters; control.textColor = UIColor.blackColor(); control.numberOfLines = 0; control.minimumScaleFactor = 0.2; control.adjustsFontSizeToFitWidth = true; } static func Format(control:UILabel) { control.backgroundColor = UIConstants.HydrantWikiWhite; } static func Format(control:UINavigationBar) { control.backgroundColor = UIConstants.HydrantWikiDarkGray; } static func Format(control:UIToolbar) { control.backgroundColor = UIConstants.HydrantWikiDarkGray; } static func Format(control:UITableView) { } static func Format(control:MKMapView) { } static func Format(control:UITextField) { let paddingView = UIView(frame: CGRectMake(0, 0, 15, control.frame.height)) control.leftView = paddingView control.leftViewMode = UITextFieldViewMode.Always control.backgroundColor = UIConstants.HydrantWikiWhite; control.layer.borderColor = UIColor.grayColor().CGColor; control.layer.borderWidth = 1; control.layer.cornerRadius = 5; } static func GetScreenWidthAsDouble() -> Double { let screenSize: CGRect = UIScreen.mainScreen().bounds let screenWidth = screenSize.width; return Double(screenWidth); } static func GetScreenHeightAsDouble() -> Double { let screenSize: CGRect = UIScreen.mainScreen().bounds let screenHeight = screenSize.height; return Double(screenHeight); } static func GetScreenWidth() -> Float { let screenSize: CGRect = UIScreen.mainScreen().bounds let screenWidth = screenSize.width; return Float(screenWidth); } static func GetScreenHeight() -> Float { let screenSize: CGRect = UIScreen.mainScreen().bounds let screenHeight = screenSize.height; return Float(screenHeight); } static func CreateNavBarButton( buttonTitle:String, targetView:UIViewController, buttonAction:Selector) -> UIBarButtonItem { let button = UIBarButtonItem( title:buttonTitle, style:UIBarButtonItemStyle.Plain, target:targetView, action:buttonAction); return button; } static func CreateNavBar(barTitle:String, leftButton:UIBarButtonItem?, rightButton:UIBarButtonItem?) -> UINavigationBar { let navFrame = CGRect(x: 0, y: 0, width: Int(UIFormatHelper.GetScreenWidth()), height: UIConstants.NavBarHeight); //Setup the title bar let NavBar = UINavigationBar(frame: navFrame); let navItem = UINavigationItem(); navItem.title = barTitle; if (leftButton != nil) { navItem.leftBarButtonItem = leftButton; } if (rightButton != nil) { navItem.rightBarButtonItem = rightButton; } NavBar.setItems([navItem], animated: false); return NavBar; } }
ab18e25c355835ee697f1402572869ec
28.206226
123
0.611592
false
false
false
false
sudeepunnikrishnan/ios-sdk
refs/heads/master
Instamojo/Order.swift
lgpl-3.0
1
// // Order.swift // Instamojo // // Created by Sukanya Raj on 14/02/17. // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit public class Order: NSObject { public var id: String? public var transactionID: String? public var buyerName: String? public var buyerEmail: String? public var buyerPhone: String? public var amount: String? public var orderDescription: String? public var currency: String? public var redirectionUrl: String? public var webhook: String? public var mode: String? public var authToken: String? public var resourceURI: String? public var clientID: String? public var cardOptions: CardOptions! public var netBankingOptions: NetBankingOptions! public var emiOptions: EMIOptions! public var walletOptions: WalletOptions! public var upiOptions: UPIOptions! override init() {} public init(authToken: String, transactionID: String, buyerName: String, buyerEmail: String, buyerPhone: String, amount: String, description: String, webhook: String ) { self.authToken = authToken self.transactionID = transactionID self.buyerName = buyerName self.buyerEmail = buyerEmail self.buyerPhone = buyerPhone self.amount = amount self.currency = "INR" self.mode = "IOS_SDK" self.redirectionUrl = Urls.getDefaultRedirectUrl() self.orderDescription = description self.webhook = webhook if Urls.getBaseUrl().contains("test") { self.clientID = Constants.TestClientId } else { self.clientID = Constants.ProdClientId } } public func isValid() -> (validity: Bool, error: String) { let space = "," return (isValidName().validity && isValidEmail().validity && isValidPhone().validity && isValidAmount().validity && isValidWebhook().validity && isValidDescription().validity && isValidTransactionID().validity, isValidName().error + space + isValidEmail().error + space + isValidPhone().error + space + isValidAmount().error + space + isValidWebhook().error + space + isValidTransactionID().error) } public func isValid() -> Bool { return isValidName().validity && isValidEmail().validity && isValidPhone().validity && isValidAmount().validity && isValidWebhook().validity && isValidDescription().validity && isValidRedirectURL().validity && isValidTransactionID().validity } /** * @return false if the buyer name is empty or has greater than 100 characters. Else true. */ public func isValidName() -> (validity: Bool, error: String) { if (self.buyerName?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if ((self.buyerName?.characters.count)! > 100) { return (false, "The buyer name is greater than 100 characters") } else { return (true, "Valid Name") } } //Tuples are not supported by Objective-C public func isValidName() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerName?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if ((self.buyerName?.characters.count)! > 100) { dictonary.setValue("The buyer name is greater than 100 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Name", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the buyer email is empty or has greater than 75 characters. Else true. */ public func isValidEmail() -> (validity: Bool, error: String) { if (self.buyerEmail?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if (self.buyerEmail?.characters.count)! > 75 { return (false, "The buyer email is greater than 75 characters") } else if !validateEmail(email: self.buyerEmail!) { return (false, "Invalid Email") } else { return (true, "Valid Email") } } public func isValidEmail() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerEmail?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.buyerEmail?.characters.count)! > 75 { dictonary.setValue("The buyer email is greater than 75 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if !validateEmail(email: self.buyerEmail!) { dictonary.setValue("Invalid Email", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Email", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } func validateEmail(email: String) -> Bool { let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat) return emailPredicate.evaluate(with: email) } /** * @return false if the phone number is empty. Else true. */ public func isValidPhone() -> (validity: Bool, error: String) { if (self.buyerPhone?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else { return (true, "Valid Phone Number") } } public func isValidPhone() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.buyerPhone?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Phone Number", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the amount is empty or less than Rs. 9 or has more than 2 decimal places. */ public func isValidAmount() -> (validity: Bool, error: String) { if (self.amount?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else { let amountArray = self.amount?.components(separatedBy: ".") if amountArray?.count != 2 { return (false, "Invalid Amount") } else { let amount = Int((amountArray?[0])!) if amount! < 9 { return (false, "Invalid Amount") } else { return (true, "Valid Amount") } } } } public func isValidAmount() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.amount?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { let amountArray = self.amount?.components(separatedBy: ".") if amountArray?.count != 2 { dictonary.setValue("Invalid Amount", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { let amount = Int((amountArray?[0])!) if amount! < 9 { dictonary.setValue("Invalid Amount", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Amount", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } } } /** * @return false if the description is empty or has greater than 255 characters. Else true. */ public func isValidDescription()-> (validity: Bool, error: String) { if (self.orderDescription?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Required") } else if (self.orderDescription?.characters.count)! > 255 { return (true, "Description is greater than 255 characters") } else { return (true, "Valid Description") } } public func isValidDescription() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.orderDescription?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Required", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.orderDescription?.characters.count)! > 255 { dictonary.setValue("Description is greater than 255 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Description", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the transaction ID is empty or has greater than 64 characters. */ public func isValidTransactionID() -> (validity: Bool, error: String) { if (self.transactionID?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Transaction ID is a mandatory parameter") } else if (self.transactionID?.characters.count)! > 64 { return (true, "Transaction ID is greater than 64 characters") } else { return (true, "Valid Transaction ID") } } public func isValidTransactionID() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.transactionID?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Transaction ID is a mandatory parameter", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if (self.transactionID?.characters.count)! > 64 { dictonary.setValue("Transaction ID is greater than 64 characters", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Transaction ID", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if the redirection URL is empty or contains any query parameters. */ public func isValidRedirectURL() -> (validity: Bool, error: String) { if (self.redirectionUrl?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (true, "Invalid Redirection URL") } else if !isValidURL(urlString: (self.redirectionUrl)!) { return (true, "Invalid Redirection URL") } else { return (true, "Valid Redirection URL") } } public func isValidRedirectURL() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.redirectionUrl?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Invalid Redirection URL", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else if !isValidURL(urlString: (self.redirectionUrl)!) { dictonary.setValue("Invalid Redirection URL", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Redirection URL", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } /** * @return false if webhook is set and not a valid url or has query parameters */ public func isValidWebhook() -> (validity: Bool, error: String) { if (self.webhook?.trimmingCharacters(in: .whitespaces).isEmpty)! { return (false, "Webhook is a mandatory parameter.") } else { return (true, "Valid Webhook") } } public func isValidWebhook() -> NSDictionary { let dictonary = NSMutableDictionary() if (self.webhook?.trimmingCharacters(in: .whitespaces).isEmpty)! { dictonary.setValue("Webhook is a mandatory parameter.", forKey: "error") dictonary.setValue(false, forKey: "validity") return dictonary } else { dictonary.setValue("Valid Webhook", forKey: "error") dictonary.setValue(true, forKey: "validity") return dictonary } } public func isValidURL(urlString: String) -> Bool { let url: NSURL = NSURL(string: urlString)! if url.query != nil { return false } else { return true } } }
444ef1d8b254391ef18622b6c1524bba
39.381381
406
0.600059
false
false
false
false
RiBj1993/CodeRoute
refs/heads/master
LoginForm/PopupViewController.swift
apache-2.0
1
// // PopupViewController.swift // MIBlurPopup // // Created by Mario on 14/01/2017. // Copyright © 2017 Mario. All rights reserved. // import UIKit import MIBlurPopup class PopupViewController: UIViewController { // MARK: - IBOutlets var text:String! @IBOutlet weak var dismissButton: UIButton! { didSet { dismissButton.layer.cornerRadius = dismissButton.frame.height/2 } } @IBOutlet weak var popupContentContainerView: UIView! @IBOutlet weak var popupMainView: UIView! { didSet { popupMainView.layer.cornerRadius = 10 } } var customBlurEffectStyle: UIBlurEffectStyle! var customInitialScaleAmmount: CGFloat! var customAnimationDuration: TimeInterval! override var preferredStatusBarStyle: UIStatusBarStyle { return customBlurEffectStyle == .dark ? .lightContent : .default } // MARK: - IBActions @IBAction func dismissButtonTapped(_ sender: Any) { // dismiss(animated: true) } override func viewDidLoad() { super.viewDidLoad() let someVar :String? = UserDefaults.standard.string(forKey: "yourIdentifier") print("********** esm el cour ******************") print(someVar) print("********** ******************") } } // MARK: - MIBlurPopupDelegate extension PopupViewController: MIBlurPopupDelegate { var popupView: UIView { return popupContentContainerView ?? UIView() } var blurEffectStyle: UIBlurEffectStyle { return customBlurEffectStyle } var initialScaleAmmount: CGFloat { return customInitialScaleAmmount } var animationDuration: TimeInterval { return customAnimationDuration } }
7b4e07691693b75db62d71b3c67d523d
21.962963
85
0.606989
false
false
false
false
BenziAhamed/Nevergrid
refs/heads/master
NeverGrid/Source/OutroScene.swift
isc
1
// // OutroScene.swift // NeverGrid // // Created by Benzi on 15/03/15. // Copyright (c) 2015 Benzi Ahamed. All rights reserved. // import Foundation import UIKit import SpriteKit class OutroScene: CutScene { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(context:NavigationContext) { self.context = context super.init() } var context:NavigationContext! var background:SKSpriteNode! var curtain:SKSpriteNode! var nextButton:WobbleButton! var hints:HintNode! var theEnd:SKSpriteNode! var forNode:SKSpriteNode! var nowNode:SKSpriteNode! override func didMoveToView(view: SKView) { super.didMoveToView(view) // curtain curtain = SKSpriteNode(texture: nil, color: UIColor.blackColor(), size: frame.size) curtain.position = frame.mid() hudNode.addChild(curtain) // background background = SKSpriteNode(imageNamed: "background_cutscene") background.anchorPoint = CGPointMake(0.5, 0.0) background.position = CGPointMake(frame.midX, 0.0) background.size = background.size.aspectFillTo(frame.size) backgroundNode.addChild(background) // hints node hints = HintNode(hints: [ "message_ending_1", "message_ending_2", "message_ending_3", "message_ending_4", "message_ending_5" ], frame: self.frame) worldNode.addChild(hints) // next button let next = textSprite("okay") nextButton = WobbleButton(node: next, action: Callback(self,OutroScene.handleNext)) nextButton.position = CGPointMake( frame.maxX - next.frame.width - 10.0, next.frame.height ) // animations on(CutSceneNotifications.SceneCreated,Callback(self, OutroScene.removeCurtain)) //{ [weak self] in self!.removeCurtain() } on(CutSceneNotifications.SceneVisible,Callback(self, OutroScene.showMessage))//,"showMessage") //{ [weak self] in self!.showMessage() } on(CutSceneNotifications.MessageShown,Callback(self, OutroScene.moveBackground))//,"moveBackground") //{ [weak self] in self!.moveBackground() } on(CutSceneNotifications.BackgroundMoved,Callback(self, OutroScene.showTheEnd))//,"showTheEnd") //{ [weak self] in self!.showTheEnd() } on(CutSceneNotifications.TheEndShown,Callback(self, OutroScene.setupNextButton))//,"setupNextButton") //{ [weak self] in self!.setupNextButton() } raise(CutSceneNotifications.SceneCreated) } func removeCurtain() { curtain.runAction( SKAction.fadeOutWithDuration(2.0) .followedBy(SKAction.runBlock{ [weak self] in self!.raise(CutSceneNotifications.SceneVisible) }) .followedBy(SKAction.removeFromParent()) ) } func showMessage() { hudNode.addChild(nextButton) hints.displayHint() } func handleNext() { if hints.hasFurtherHints() { hints.displayHint() } else { hints.runAction(SKAction.moveByX(0.0, y: -frame.height, duration: 0.4)) raise(CutSceneNotifications.MessageShown) } } func moveBackground() { // hide button nextButton.runAction(SKAction.fadeOutWithDuration(0.0)) // move background background.runAction( SKAction.moveByX(0.0, y: -(background.frame.height-frame.height), duration: 2.0) .followedBy(SKAction.runBlock{ [weak self] in self!.raise(CutSceneNotifications.BackgroundMoved) }) ) // move in the end alond with background theEnd = textSprite("the_end") theEnd.position = CGPointMake(frame.midX, frame.height + theEnd.frame.height) worldNode.addChild(theEnd) let moveAction = SKAction.moveTo(frame.mid(), duration: 2.5) moveAction.timingMode = SKActionTimingMode.EaseOut theEnd.runAction(moveAction) } func showTheEnd() { forNode = textSprite("the_end_for") nowNode = textSprite("the_end_now") forNode.position = CGPointMake(frame.midX - forNode.frame.width/2.0 - 5.0, 0.3 * frame.height) nowNode.position = CGPointMake(frame.midX + nowNode.frame.width/2.0 + 5.0, 0.3 * frame.height) forNode.alpha = 0.0 nowNode.alpha = 0.0 worldNode.addChild(forNode) worldNode.addChild(nowNode) forNode.runAction(SKAction.waitForDuration(0.5).followedBy(SKAction.fadeInWithDuration(0.0))) nowNode.runAction(SKAction.waitForDuration(1.0).followedBy(SKAction.fadeInWithDuration(0.0))) self.runAction(SKAction.waitForDuration(2.0).followedBy(SKAction.runBlock{[weak self] in self!.raise(CutSceneNotifications.TheEndShown)})) } func setupNextButton() { nextButton.action = Callback(self, OutroScene.gotoLastLevel) nextButton.runAction(SKAction.fadeInWithDuration(0.5)) } var handlingScene = false func gotoLastLevel() { if handlingScene { return } handlingScene = true let settings = GameSettings() settings.outroSeen = true settings.save() let scene = GameScene(level: LevelParser.parse(GameLevelData.shared.chapters.last!.levels.last!), context: self.context) navigation.displayGameScene(scene) } }
48ce5db2228aee1a8844e8ce56452e19
33.679012
154
0.627559
false
false
false
false
MengTo/Spring
refs/heads/master
SpringApp/CodeViewController.swift
mit
2
// // CodeViewController.swift // DesignerNewsApp // // Created by Meng To on 2015-01-05. // Copyright (c) 2015 Meng To. All rights reserved. // import UIKit import Spring class CodeViewController: UIViewController { @IBOutlet weak var modalView: SpringView! @IBOutlet weak var codeTextView: UITextView! @IBOutlet weak var titleLabel: UILabel! var codeText: String = "" var data: SpringView! override func viewDidLoad() { super.viewDidLoad() modalView.transform = CGAffineTransform(translationX: -300, y: 0) if data.animation != "" { codeText += "layer.animation = \"\(data.animation)\"\n" } if data.curve != "" { codeText += "layer.curve = \"\(data.curve)\"\n" } if data.force != 1 { codeText += String(format: "layer.force = %.1f\n", Double(data.force)) } if data.duration != 0.7 { codeText += String(format: "layer.duration = %.1f\n", Double(data.duration)) } if data.delay != 0 { codeText += String(format: "layer.delay = %.1f\n", Double(data.delay)) } if data.scaleX != 1 { codeText += String(format: "layer.scaleX = %.1f\n", Double(data.scaleX)) } if data.scaleY != 1 { codeText += String(format: "layer.scaleY = %.1f\n", Double(data.scaleY)) } if data.rotate != 0 { codeText += String(format: "layer.rotate = %.1f\n", Double(data.rotate)) } if data.damping != 0.7 { codeText += String(format: "layer.damping = %.1f\n", Double(data.damping)) } if data.velocity != 0.7 { codeText += String(format: "layer.velocity = %.1f\n", Double(data.velocity)) } codeText += "layer.animate()" codeTextView.text = codeText } @IBAction func closeButtonPressed(_ sender: AnyObject) { UIApplication.shared.sendAction(#selector(SpringViewController.maximizeView(_:)), to: nil, from: self, for: nil) modalView.animation = "slideRight" modalView.animateFrom = false modalView.animateToNext(completion: { self.dismiss(animated: false, completion: nil) }) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) modalView.animate() UIApplication.shared.sendAction(#selector(SpringViewController.minimizeView(_:)), to: nil, from: self, for: nil) } }
19eb363eda6bb04feb7b1c64014e1b83
31.531646
120
0.567315
false
false
false
false
optimizely/swift-sdk
refs/heads/master
Sources/Utils/AtomicProperty.swift
apache-2.0
1
// // Copyright 2019, 2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class AtomicProperty<T> { private var _property: T? var property: T? { get { var retVal: T? lock.sync { retVal = _property } return retVal } set { lock.async(flags: DispatchWorkItemFlags.barrier) { self._property = newValue } } } private let lock: DispatchQueue init(property: T?, lock: DispatchQueue? = nil) { self._property = property self.lock = lock ?? { var name = "AtomicProperty" + String(Int.random(in: 0...100000)) let className = String(describing: T.self) name += className return DispatchQueue(label: name, attributes: .concurrent) }() } convenience init() { self.init(property: nil, lock: nil) } // perform an atomic operation on the atomic property // the operation will not run if the property is nil. func performAtomic(atomicOperation: (_ prop:inout T) -> Void) { lock.sync(flags: DispatchWorkItemFlags.barrier) { if var prop = _property { atomicOperation(&prop) _property = prop } } } }
d2dccf3ee328426212ffc4dbf7f9efaf
29.5
76
0.597567
false
false
false
false
22377832/swiftdemo
refs/heads/master
BitcoinSwift/Sources/3rd/CryptoSwift/SHA2.swift
apache-2.0
13
// // SHA2.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 24/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // // TODO: generic for process32/64 (UInt32/UInt64) // public final class SHA2: DigestType { let variant: Variant let size: Int let blockSize: Int let digestLength: Int private let k: Array<UInt64> fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash32 = Array<UInt32>() fileprivate var accumulatedHash64 = Array<UInt64>() public enum Variant: RawRepresentable { case sha224, sha256, sha384, sha512 public var digestLength: Int { return self.rawValue / 8 } public var blockSize: Int { switch self { case .sha224, .sha256: return 64 case .sha384, .sha512: return 128 } } public typealias RawValue = Int public var rawValue: RawValue { switch self { case .sha224: return 224 case .sha256: return 256 case .sha384: return 384 case .sha512: return 512 } } public init?(rawValue: RawValue) { switch (rawValue) { case 224: self = .sha224 break case 256: self = .sha256 break case 384: self = .sha384 break case 512: self = .sha512 break default: return nil } } fileprivate var h: Array<UInt64> { switch self { case .sha224: return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] case .sha256: return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] case .sha384: return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] case .sha512: return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] } } fileprivate var finalLength: Int { switch (self) { case .sha224: return 7 case .sha384: return 6 default: return Int.max } } } public init(variant: SHA2.Variant) { self.variant = variant switch self.variant { case .sha224, .sha256: self.accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 self.blockSize = variant.blockSize self.size = variant.rawValue self.digestLength = variant.digestLength self.k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] case .sha384, .sha512: self.accumulatedHash64 = variant.h self.blockSize = variant.blockSize self.size = variant.rawValue self.digestLength = variant.digestLength self.k = [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817] } } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try self.update(withBytes: bytes, isLast: true) } catch { return [] } } fileprivate func process64(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt64>) { // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 64-bit words into eighty 64-bit words: var M = Array<UInt64>(repeating: 0, count: self.k.count) for x in 0 ..< M.count { switch (x) { case 0 ... 15: let start = chunk.startIndex.advanced(by: x * 8) // * MemoryLayout<UInt64>.size M[x] = UInt64(bytes: chunk, fromIndex: start) break default: let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0 ..< self.k.count { let s0 = rotateRight(A, by: 28) ^ rotateRight(A, by: 34) ^ rotateRight(A, by: 39) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 14) ^ rotateRight(E, by: 18) ^ rotateRight(E, by: 41) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ self.k[j] &+ UInt64(M[j]) H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = (hh[0] &+ A) hh[1] = (hh[1] &+ B) hh[2] = (hh[2] &+ C) hh[3] = (hh[3] &+ D) hh[4] = (hh[4] &+ E) hh[5] = (hh[5] &+ F) hh[6] = (hh[6] &+ G) hh[7] = (hh[7] &+ H) } // mutating currentHash in place is way faster than returning new result fileprivate func process32(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt32>) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into sixty-four 32-bit words: var M = Array<UInt32>(repeating: 0, count: self.k.count) for x in 0 ..< M.count { switch (x) { case 0 ... 15: let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size M[x] = UInt32(bytes: chunk, fromIndex: start) break default: let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0 ..< self.k.count { let s0 = rotateRight(A, by: 2) ^ rotateRight(A, by: 13) ^ rotateRight(A, by: 22) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 6) ^ rotateRight(E, by: 11) ^ rotateRight(E, by: 25) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ UInt32(self.k[j]) &+ M[j] H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D hh[4] = hh[4] &+ E hh[5] = hh[5] &+ F hh[6] = hh[6] &+ G hh[7] = hh[7] &+ H } } extension SHA2: Updatable { public func update<T: Collection>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 { self.accumulated += bytes if isLast { let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: self.blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. // Step 1. Append padding bitPadding(to: &self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8) // Step 2. Append Length a 64-bit representation of lengthInBits self.accumulated += lengthBytes } var processedBytes = 0 for chunk in self.accumulated.batched(by: self.blockSize) { if (isLast || (self.accumulated.count - processedBytes) >= self.blockSize) { switch self.variant { case .sha224, .sha256: self.process32(block: chunk, currentHash: &self.accumulatedHash32) case .sha384, .sha512: self.process64(block: chunk, currentHash: &self.accumulatedHash64) } processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) self.processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>(repeating: 0, count: self.variant.digestLength) switch self.variant { case .sha224, .sha256: var pos = 0 for idx in 0 ..< self.accumulatedHash32.count where idx < self.variant.finalLength { let h = self.accumulatedHash32[idx].bigEndian result[pos] = UInt8(h & 0xff) result[pos + 1] = UInt8((h >> 8) & 0xff) result[pos + 2] = UInt8((h >> 16) & 0xff) result[pos + 3] = UInt8((h >> 24) & 0xff) pos += 4 } case .sha384, .sha512: var pos = 0 for idx in 0 ..< self.accumulatedHash64.count where idx < self.variant.finalLength { let h = self.accumulatedHash64[idx].bigEndian result[pos] = UInt8(h & 0xff) result[pos + 1] = UInt8((h >> 8) & 0xff) result[pos + 2] = UInt8((h >> 16) & 0xff) result[pos + 3] = UInt8((h >> 24) & 0xff) result[pos + 4] = UInt8((h >> 32) & 0xff) result[pos + 5] = UInt8((h >> 40) & 0xff) result[pos + 6] = UInt8((h >> 48) & 0xff) result[pos + 7] = UInt8((h >> 56) & 0xff) pos += 8 } } // reset hash value for instance if isLast { switch self.variant { case .sha224, .sha256: self.accumulatedHash32 = variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 case .sha384, .sha512: self.accumulatedHash64 = variant.h } } return result } }
927a6c61cc6dce3150c839601dd969f4
40.069486
183
0.539208
false
false
false
false
rowungiles/SwiftTech
refs/heads/master
SwiftTech/SwiftTech/Utilities/Networking/Networking.swift
gpl-3.0
1
// // Networking.swift // SwiftTech // // Created by Rowun Giles on 26/03/2015. // Copyright (c) 2015 Rowun Giles. All rights reserved. // import Foundation enum NetworkingError: ErrorType { case UnexpectedResponseStatusCode } enum NetworkingResult { case Success(NSData) case Failure(ErrorType) } typealias NetworkingCompletion = (result: NetworkingResult) -> Void protocol Networking : class { func fetchDataFromURL(url: NSURL, session: NSURLSession, startImmediately: Bool, completion: NetworkingCompletion) -> NSURLSessionDataTask } extension Networking { func fetchDataFromURL(url: NSURL, session: NSURLSession, startImmediately: Bool = true, completion: NetworkingCompletion) -> NSURLSessionDataTask { let task = session.dataTaskWithURL(url, completionHandler: { [weak self] ( data, response, error) in self?.dataFetchCompleted(data, response: response, error: error, completion: completion) }) if startImmediately { task.resume() } return task } private func dataFetchCompleted(data: NSData?, response: NSURLResponse?, error: NSError?, @noescape completion: NetworkingCompletion) { guard error == nil else { // error, reports on client side errors, not server side errors completion(result: NetworkingResult.Failure(error!)) return } guard let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200 else { // now check for server side errors completion(result: NetworkingResult.Failure(NetworkingError.UnexpectedResponseStatusCode)) return } completion(result: NetworkingResult.Success(data!)) } }
2fc4488344743d40321206f89d1427f5
29.728814
151
0.669057
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
refs/heads/main
snippets/MapsSnippets/MapsSnippets/Swift/MapStyling.swift
apache-2.0
1
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START maps_ios_map_styling_json_file] import GoogleMaps class MapStyling: UIViewController { // Set the status bar style to complement night-mode. override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func loadView() { let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) do { // Set the map style by passing the URL of the local file. if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") { mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL) } else { NSLog("Unable to find style.json") } } catch { NSLog("One or more of the map styles failed to load. \(error)") } self.view = mapView } } // [END maps_ios_map_styling_json_file] // [START maps_ios_map_styling_string_resource] class MapStylingStringResource: UIViewController { let MapStyle = "JSON_STYLE_GOES_HERE" // Set the status bar style to complement night-mode. override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func loadView() { let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 14.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) do { // Set the map style by passing a valid JSON string. mapView.mapStyle = try GMSMapStyle(jsonString: MapStyle) } catch { NSLog("One or more of the map styles failed to load. \(error)") } self.view = mapView } } // [END maps_ios_map_styling_string_resource]
489ac125066f952323c5c1b0524aeb44
31.956522
94
0.701847
false
false
false
false
devincoughlin/swift
refs/heads/master
test/expr/cast/metatype_casts.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift func use<T>(_: T) {} class C {} class D: C {} class E: P {} class X {} protocol P {} protocol Q {} protocol CP: class {} let any: Any.Type = Int.self use(any as! Int.Type) use(any as! C.Type) use(any as! D.Type) use(any as! AnyObject.Type) use(any as! AnyObject.Protocol) use(any as! P.Type) use(any as! P.Protocol) let anyP: Any.Protocol = Any.self use(anyP is Any.Type) // expected-warning{{always true}} use(anyP as! Int.Type) // expected-warning{{always fails}} let anyObj: AnyObject.Type = D.self use(anyObj as! Int.Type) // expected-warning{{always fails}} use(anyObj as! C.Type) use(anyObj as! D.Type) use(anyObj as! AnyObject.Protocol) // expected-warning{{always fails}} use(anyObj as! P.Type) use(anyObj as! P.Protocol) // expected-warning{{always fails}} let c: C.Type = D.self use(c as! D.Type) use(c as! X.Type) // expected-warning{{always fails}} use(c is AnyObject.Type) // expected-warning{{always true}} use(c as! AnyObject.Type) // expected-warning{{always succeeds}} {{7-10=as}} use(c as! AnyObject.Protocol) // expected-warning{{always fails}} use(c as! CP.Type) use(c as! CP.Protocol) // expected-warning{{always fails}} use(c as! Int.Type) // expected-warning{{always fails}} use(C.self as AnyObject.Protocol) // expected-error{{cannot convert value of type 'C.Type' to type 'AnyObject.Protocol' in coercion}} use(C.self as AnyObject.Type) use(C.self as P.Type) // expected-error{{'C.Type' is not convertible to 'P.Type'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}} use(E.self as P.Protocol) // expected-error{{cannot convert value of type 'E.Type' to type 'P.Protocol' in coercion}} use(E.self as P.Type)
7b9e85770d1774923641e30b8a0ecc1b
32.215686
142
0.697757
false
false
false
false
bbheck/BHToastSwift
refs/heads/master
Pod/Classes/BHToastOptions.swift
mit
1
// // BHToastOptions.swift // Pods // // Created by Bruno Hecktheuer on 1/12/16. // // import UIKit /** The BHToastViewTag is used to guarantee only one instance. *If necessary, change it before create the first BHToast instance*. */ public var BHToastViewTag = 3091990 /// Represents the view position (Bottom, Middle, Top) public enum BHToastPosition { case Bottom, Middle, Top } /// Represents the image position (Left or Right) public enum BHToastImagePosition { case Left, Right } /// The struct of customization options. public struct BHToastOptions { // Default properties (change if necessary) public static var defaultDuration: NSTimeInterval = 5.0 public static var defaultAnimationDuration: NSTimeInterval = 0.4 public static var defaultBackgroundColor = UIColor.lightGrayColor() public static var defaultBorderColor = UIColor.darkGrayColor() public static var defaultBorderWidth: CGFloat = 1.0 public static var defaultCornerRadius: CGFloat = 5.0 /// Only applies when the position is Top or Bottom. public static var defaultMargin: CGFloat = 8.0 public static var defaultContentInsets = UIEdgeInsets( top: 8.0, left: 8.0, bottom: 8.0, right: 8.0 ) public static var defaultMinHeight: CGFloat = 30.0 public static var defaultMaxHeight: CGFloat = 50.0 public static var defaultMessageAlignment: NSTextAlignment = .Center public static var defaultMessageColor = UIColor.whiteColor() public static var defaultMessageFont = UIFont.systemFontOfSize(14.0) public static var defaultPosition: BHToastPosition = .Bottom public static var defaultImagePosition: BHToastImagePosition = .Left // MARK: - Properties /// The duration that the Toast stays in View (*in seconds*). public let duration: NSTimeInterval /// The animation time (*in seconds*). public let animationDuration: NSTimeInterval /// Toast background color. public let backgroundColor: UIColor // Border options public let borderColor: UIColor public let cornerRadius: CGFloat public let borderWidth: CGFloat // View size options public let margin: CGFloat public let contentInsets: UIEdgeInsets public let minHeight: CGFloat public let maxHeight: CGFloat // Message options public let messageAlignment: NSTextAlignment public let messageColor: UIColor public let messageFont: UIFont // View position public let position: BHToastPosition // Image options public let imagePosition: BHToastImagePosition // MARK: - Init method /** Create an instance of BHToastOptions with some customizations. If necessary, change the default values to apply the customization for all new BHToastOptions instance. */ public init(duration: NSTimeInterval = defaultDuration, animationDuration: NSTimeInterval = defaultAnimationDuration, backgroundColor: UIColor = defaultBackgroundColor, borderColor: UIColor = defaultBorderColor, borderWidth: CGFloat = defaultBorderWidth, cornerRadius: CGFloat = defaultCornerRadius, margin: CGFloat = defaultMargin, contentInsets: UIEdgeInsets = defaultContentInsets, minHeight: CGFloat = defaultMinHeight, maxHeight: CGFloat = defaultMaxHeight, messageAlignment: NSTextAlignment = defaultMessageAlignment, messageColor: UIColor = defaultMessageColor, messageFont: UIFont = defaultMessageFont, position: BHToastPosition = defaultPosition, imagePosition: BHToastImagePosition = defaultImagePosition) { self.duration = duration self.animationDuration = animationDuration self.backgroundColor = backgroundColor self.borderColor = borderColor self.borderWidth = borderWidth self.cornerRadius = cornerRadius self.margin = margin self.contentInsets = contentInsets self.minHeight = minHeight self.maxHeight = maxHeight self.messageAlignment = messageAlignment self.messageColor = messageColor self.messageFont = messageFont self.position = position self.imagePosition = imagePosition } }
665d65ec5cf18d9bf11c991d34d68261
34.32
108
0.691053
false
false
false
false
mahuiying0126/MDemo
refs/heads/master
BangDemo/BangDemo/Modules/HomeDetail/view/cell/TeacherTableViewCell.swift
mit
1
// // TeacherTableViewCell.swift // BangDemo // // Created by yizhilu on 2017/6/2. // Copyright © 2017年 Magic. All rights reserved. // import UIKit class TeacherTableViewCell: UITableViewCell { var detailImage : UIImageView? var detailName : UILabel? var cellModel : DetailTeacherListModel? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupTeacherCellM() } func setUpCellDataM(_ model:DetailTeacherListModel) { self.cellModel = model let imageUrl : String = imageUrlString + (model.picPath)! let url = NSURL.init(string: imageUrl) self.detailImage?.af_setImage(withURL: url! as URL, placeholderImage:UIImage.init(named: "加载中")) do{ var name = String() if Int(model.isStar!)! == 0 { name = " 高级讲师 " + (model.name)! }else if Int(model.isStar!)! == 1 { name = " 首席讲师 " + (model.name)! } let attribut = NSMutableAttributedString.init(string: name) attribut.addAttribute(NSAttributedStringKey.foregroundColor, value: navColor, range: NSRange.init(location: 0, length: 5)) attribut.addAttribute(NSAttributedStringKey.font, value: FONT(15), range: NSRange.init(location: 0, length: (model.name?.characters.count)!)) self.detailName?.attributedText = attribut } } func setupTeacherCellM() { do{ detailImage = UIImageView() self.contentView.addSubview(detailImage!) detailName = UILabel() detailName?.font = FONT(15) self.contentView.addSubview(detailName!) } do{ let line = UIView() line.backgroundColor = lineColor self.contentView.addSubview(line) detailImage?.snp.makeConstraints({ (make) in make.left.top.equalTo(self).offset(12) make.width.equalTo(60 * Ratio_height) make.height.equalTo(45 * Ratio_height) }) detailName?.snp.makeConstraints({ (make) in make.left.equalTo(detailImage!.snp.right).offset(5) make.top.equalTo(detailImage!.snp.top).offset(10) make.height.equalTo(21) make.width.equalTo(self.contentView).multipliedBy(0.5) }) line.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.contentView) make.height.equalTo(0.5) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
c4ec701f00a5b0ce9a8274e58da2dcef
32.444444
153
0.581728
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/People/PeopleCell.swift
gpl-2.0
2
import UIKit import WordPressShared class PeopleCell: WPTableViewCell { @IBOutlet var avatarImageView: CircularImageView! @IBOutlet var displayNameLabel: UILabel! @IBOutlet var usernameLabel: UILabel! @IBOutlet var roleBadge: PeopleRoleBadgeLabel! @IBOutlet var superAdminRoleBadge: PeopleRoleBadgeLabel! override func awakeFromNib() { WPStyleGuide.configureLabel(displayNameLabel, textStyle: .callout) } func bindViewModel(_ viewModel: PeopleCellViewModel) { setAvatarURL(viewModel.avatarURL as URL?) displayNameLabel.text = viewModel.displayName usernameLabel.text = viewModel.usernameText roleBadge.borderColor = viewModel.roleBorderColor roleBadge.backgroundColor = viewModel.roleBackgroundColor roleBadge.textColor = viewModel.roleTextColor roleBadge.text = viewModel.roleText roleBadge.isHidden = viewModel.roleHidden superAdminRoleBadge.text = viewModel.superAdminText superAdminRoleBadge.isHidden = viewModel.superAdminHidden superAdminRoleBadge.borderColor = viewModel.superAdminBorderColor superAdminRoleBadge.backgroundColor = viewModel.superAdminBackgroundColor } func setAvatarURL(_ avatarURL: URL?) { let gravatar = avatarURL.flatMap { Gravatar($0) } let placeholder = UIImage(named: "gravatar")! avatarImageView.downloadGravatar(gravatar, placeholder: placeholder, animate: false) } /* It seems UIKit clears the background of all the cells' subviews when highlighted/selected, so he have to set our wanted color again. Otherwise we get this: https://cldup.com/NT3pbaeIc1.png */ override func setHighlighted(_ highlighted: Bool, animated: Bool) { let roleBackgroundColor = roleBadge.backgroundColor let superAdminBackgroundColor = superAdminRoleBadge.backgroundColor super.setHighlighted(highlighted, animated: animated) if highlighted { roleBadge.backgroundColor = roleBackgroundColor superAdminRoleBadge.backgroundColor = superAdminBackgroundColor } } override func setSelected(_ selected: Bool, animated: Bool) { let roleBackgroundColor = roleBadge.backgroundColor let superAdminBackgroundColor = superAdminRoleBadge.backgroundColor super.setSelected(selected, animated: animated) if selected { roleBadge.backgroundColor = roleBackgroundColor superAdminRoleBadge.backgroundColor = superAdminBackgroundColor } } }
ad81a49cbb2a244b73daf7e193dc4c72
38.646154
92
0.729142
false
false
false
false
Sajjon/Zeus
refs/heads/master
Zeus/Models/JSON.swift
apache-2.0
1
// // JSON.swift // Zeus // // Created by Cyon Alexander (Ext. Netlight) on 29/08/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation internal typealias RawJSON = Dictionary<String, NSObject> internal typealias ValuesForPropertiesNamed = Dictionary<String, NSObject> internal protocol JSONProtocol: Sequence { var map: RawJSON { get set } func valueFor(nestedKey: String) -> NSObject? } internal extension JSONProtocol { func makeIterator() -> DictionaryIterator<String, NSObject> { return map.makeIterator() } subscript(key: String) -> NSObject? { get { return map[key] } set(newValue) { map[key] = newValue } } func valueFor(nestedKey: String) -> NSObject? { return valueFor(nestedKey: nestedKey, inJson: map) } } private extension JSONProtocol { func valueFor(nestedKey: String, inJson rawJson: RawJSON?) -> NSObject? { let json = rawJson ?? map guard nestedKey.contains(".") else { let finalValue = json[nestedKey] return finalValue } let keys = nestedKey.components(separatedBy: ".") let slice: ArraySlice<String> = keys.dropFirst() let keysWithFirstDropped: [String] = Array(slice) let nestedKeyWithoutFirst: String if keysWithFirstDropped.count > 1 { nestedKeyWithoutFirst = keysWithFirstDropped.reduce("") { return $0 + "." + $1 } } else { nestedKeyWithoutFirst = keysWithFirstDropped[0] } let firstKey = keys[0] guard let subJson = json[firstKey] as? RawJSON else { return nil } return valueFor(nestedKey: nestedKeyWithoutFirst, inJson: subJson) } } internal struct JSON: JSONProtocol { internal var map: RawJSON internal init(_ map: RawJSON = [:]) { self.map = map } } internal struct FlattnedJSON: JSONProtocol { internal var map: RawJSON internal init(_ json: JSON? = nil) { self.map = json?.map ?? [:] } } internal struct MappedJSON: JSONProtocol { internal var map: RawJSON internal init(_ json: FlattnedJSON? = nil) { self.map = json?.map ?? [:] } } internal struct CherryPickedJSON: JSONProtocol { internal var map: RawJSON internal init(_ mappedJson: MappedJSON? = nil) { self.map = mappedJson?.map ?? [:] } }
681cc198b5d2312cadd01b0d5e575ca1
25.271739
92
0.625155
false
false
false
false
pawan007/SmartZip
refs/heads/master
SmartZip/Library/Controls/DesignableTextField.swift
mit
1
// // DesignableTextField.swift // SmartZip // // Created by Pawan Kumar on 02/06/16. // Copyright © 2016 Modi. All rights reserved. // import UIKit @IBDesignable class DesignableTextField: UITextField { var topBorder: UIView? var bottomBorder: UIView? var leftBorder: UIView? var rightBorder: UIView? @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var placeHolderColor : UIColor = UIColor.lightGrayColor(){ didSet { setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor") } } @IBInspectable var bottomLineWidth : CGFloat = 1 { didSet{ let border: CALayer = CALayer() border.borderColor = UIColor.darkGrayColor().CGColor self.frame = CGRectMake(0, self.frame.size.height - bottomLineWidth, self.frame.size.width, self.frame.size.height) border.borderWidth = borderWidth self.layer.addSublayer(border) self.layer.masksToBounds = true } } @IBInspectable var bottomLineColor : UIColor = UIColor.lightGrayColor(){ didSet { let border: CALayer = CALayer() border.borderColor = bottomLineColor.CGColor } } @IBInspectable var leftImage : String = "" { didSet { leftViewMode = UITextFieldViewMode.Always let imageView = UIImageView(); imageView.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+5, 30,self.frame.size.height-4) let image = UIImage(named:leftImage); imageView.image = image; leftView = imageView; } } @IBInspectable var paddingLeft: CGFloat = 0 @IBInspectable var paddingRight: CGFloat = 0 override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y, bounds.size.width - paddingLeft - paddingRight, bounds.size.height); } override func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } @IBInspectable var topBorderColor : UIColor = UIColor.clearColor() @IBInspectable var topBorderHeight : CGFloat = 0 { didSet{ if topBorder == nil{ topBorder = UIView() topBorder?.backgroundColor=topBorderColor; topBorder?.frame = CGRectMake(0, 0, self.frame.size.width, topBorderHeight) addSubview(topBorder!) } } } @IBInspectable var bottomBorderColor : UIColor = UIColor.clearColor() @IBInspectable var bottomBorderHeight : CGFloat = 0 { didSet{ if bottomBorder == nil{ bottomBorder = UIView() bottomBorder?.backgroundColor=bottomBorderColor; bottomBorder?.frame = CGRectMake(0, self.frame.size.height - bottomBorderHeight, self.frame.size.width, bottomBorderHeight) addSubview(bottomBorder!) } } } @IBInspectable var leftBorderColor : UIColor = UIColor.clearColor() @IBInspectable var leftBorderHeight : CGFloat = 0 { didSet{ if leftBorder == nil{ leftBorder = UIView() leftBorder?.backgroundColor=leftBorderColor; leftBorder?.frame = CGRectMake(0, 0, leftBorderHeight, self.frame.size.height) addSubview(leftBorder!) } } } @IBInspectable var rightBorderColor : UIColor = UIColor.clearColor() @IBInspectable var rightBorderHeight : CGFloat = 0 { didSet{ if rightBorder == nil{ rightBorder = UIView() rightBorder?.backgroundColor=topBorderColor; rightBorder?.frame = CGRectMake(self.frame.size.width - rightBorderHeight, 0, rightBorderHeight, self.frame.size.height) addSubview(rightBorder!) } } } }
5de3ed0eecf743977e23148f03c895d2
32.59542
139
0.6
false
false
false
false
tamershahin/iOS8Challenges
refs/heads/master
Postcard/Postcard/Postcard/ViewController.swift
apache-2.0
1
// // ViewController.swift // Postcard // // Created by Tamer Shahin on 09/11/2014. // Copyright (c) 2014 Tasin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var enterNameTextField: UITextField! @IBOutlet weak var enterMessageTextField: UITextField! @IBOutlet weak var mailButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendMailButtonPressed(sender: UIButton){ messageLabel.hidden = false messageLabel.text = enterMessageTextField.text messageLabel.textColor = UIColor.redColor() enterMessageTextField.text = "" enterMessageTextField.resignFirstResponder() mailButton.setTitle("Mail Sent", forState: UIControlState.Normal) nameLabel.hidden = false nameLabel.text = enterNameTextField.text nameLabel.textColor = UIColor.blueColor() enterNameTextField.text = "" enterNameTextField.resignFirstResponder() } }
ae66fc7d914238a34a4e6b0105950989
26.607843
80
0.668324
false
false
false
false
everald/JetPack
refs/heads/master
Sources/UI/Window.swift
mit
1
import UIKit @objc(JetPack_Window) open class Window: _Window { public override convenience init() { self.init(workaroundForSubclassing: ()) } public init(workaroundForSubclassing: Void) { super.init() if bounds.isEmpty { frame = UIScreen.main.bounds } } @available(*, unavailable, message: "You must use init() since init(frame:) does no longer set-up the window properly in multitasking environments. In any case you can still set the frame manually after creating the window.") public dynamic override init(frame: CGRect) { // not supposed to be called super.init(frame: frame) } public required init?(coder: NSCoder) { super.init(coder: coder) } open override var rootViewController: UIViewController? { get { return super.rootViewController } set { guard newValue !== rootViewController else { return } // Due to a bug in iOS 8 changing the rootViewController doesn't remove modally presented view controllers. super.rootViewController = nil removeAllSubviews() super.rootViewController = newValue } } } extension Window: _NonSystemWindow {} // fix to make init() the designated initializers of Window @objc(_JetPack_Window) open class _Window: UIWindow { fileprivate dynamic init() { // not supposed to be called super.init(frame: UIScreen.main.bounds) } fileprivate dynamic override init(frame: CGRect) { // not supposed to be called super.init(frame: frame) } public required init?(coder: NSCoder) { super.init(coder: coder) } } @objc(_JetPack_UI_Window_Initialization) private class StaticInitialization: NSObject, StaticInitializable { static func staticInitialize() { redirectMethod(in: Window.self, from: #selector(UIView.init(frame:)), to: #selector(UIView.init(frame:)), in: UIWindow.self) redirectMethod(in: _Window.self, from: #selector(NSObject.init), to: #selector(NSObject.init), in: UIWindow.self) redirectMethod(in: _Window.self, from: #selector(UIView.init(frame:)), to: #selector(UIView.init(frame:)), in: UIWindow.self) } }
203134b7a8d0c8865c54ee878a2cf0c5
23.329412
226
0.720986
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/WrappedModels/PictureNote.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_sciencejournal_ios_ScienceJournalProtos /// A wrapper for a GSJLabel that contains a picture. public class PictureNote: Note { /// The file path of the image. public var filePath: String? { get { do { let value = try GSJPictureLabelValue(data: proto.protoData) return value.filePath } catch { print("[PictureNote] Error when parsing protoData: \(error.localizedDescription)") return nil } } set { let value = GSJPictureLabelValue() value.filePath = newValue proto.protoData = value.data() } } /// Initializes a picture note with an empty proto. convenience init() { let proto = GSJLabel() proto.type = .picture self.init(proto: proto) ID = UUID().uuidString timestamp = Date().millisecondsSince1970 } }
e0e55066204b38b5d1d43995802093d0
28.078431
90
0.681726
false
false
false
false
stefanrenne/ConstraintLib
refs/heads/master
ConstraintLibTests/ConstraintLibTests.swift
apache-2.0
1
// // ConstraintLibTests.swift // ConstraintLibTests // // Created by [email protected] on 30/03/2017. // Copyright © 2017. All rights reserved. // import XCTest @testable import ConstraintLib class ConstraintLibTests: XCTestCase { func testItCanGetTheHashValue() { XCTAssertEqual(PinEdge.left.hashValue, 1) XCTAssertEqual(PinEdge.right.hashValue, 2) XCTAssertEqual(PinEdge.bottom.hashValue, 3) XCTAssertEqual(PinEdge.top.hashValue, 4) XCTAssertEqual(PinEdge.centerX.hashValue, 5) XCTAssertEqual(PinEdge.centerY.hashValue, 6) XCTAssertEqual(PinEdge.width.hashValue, 7) XCTAssertEqual(PinEdge.height.hashValue, 8) XCTAssertEqual(PinEdge.leftTo(UIView()).hashValue, 9) XCTAssertEqual(PinEdge.rightTo(UIView()).hashValue, 10) XCTAssertEqual(PinEdge.bottomTo(UIView()).hashValue, 11) XCTAssertEqual(PinEdge.topTo(UIView()).hashValue, 12) XCTAssertEqual(PinEdge.equalWidth(UIView()).hashValue, 13) XCTAssertEqual(PinEdge.equalHeight(UIView()).hashValue, 14) XCTAssertEqual(PinEdge.topLayoutGuide.hashValue, 15) XCTAssertEqual(PinEdge.bottomLayoutGuide.hashValue, 16) XCTAssertEqual(PinEdge.left, PinEdge.left) XCTAssertNotEqual(PinEdge.left, PinEdge.right) } func testItCanCreateEdgeConstraintsFromRect() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView) let topConstraint = newView.pin(.top) let leftConstraint = newView.pin(.left) let bottomConstraint = newView.pin(.bottom) let rightConstraint = newView.pin(.right) /* Validated created constraints */ XCTAssertEqual(topConstraint.constant, 50.0) XCTAssertEqual(leftConstraint.constant, 50.0) XCTAssertEqual(bottomConstraint.constant, 330.0) XCTAssertEqual(rightConstraint.constant, 170.0) /* Find Constraints in tree */ XCTAssertEqual(topConstraint, newView.constraint(.top)) XCTAssertEqual(leftConstraint, newView.constraint(.left)) XCTAssertEqual(bottomConstraint, newView.constraint(.bottom)) XCTAssertEqual(rightConstraint, newView.constraint(.right)) } func testItCanCreatePositionConstraintsFromRect() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView(frame: CGRect(x: 110.0, y: 140.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView) let widthConstraint = newView.pin(.width) let heightConstraint = newView.pin(.height) let centerXConstraint = newView.pin(.centerX) let centerYConstraint = newView.pin(.centerY) /* Validated created constraints */ XCTAssertEqual(widthConstraint.constant, 100.0) XCTAssertEqual(heightConstraint.constant, 100.0) XCTAssertEqual(centerXConstraint.constant, 0.0) XCTAssertEqual(centerYConstraint.constant, 0.0) /* Find Constraints in tree */ XCTAssertEqual(widthConstraint, newView.constraint(.width)) XCTAssertEqual(heightConstraint, newView.constraint(.height)) XCTAssertEqual(centerXConstraint, newView.constraint(.centerX)) XCTAssertEqual(centerYConstraint, newView.constraint(.centerY)) } func testItCanStickViewsToOtherViews() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView1 = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 200.0, height: 200.0)) viewcontroller.view.addSubview(newView1) newView1.pin([.left, .top, .width, .height]) XCTAssertEqual(newView1.constraint(.left)?.constant, 50.0) XCTAssertEqual(newView1.constraint(.top)?.constant, 50.0) XCTAssertEqual(newView1.constraint(.width)?.constant, 200.0) XCTAssertEqual(newView1.constraint(.height)?.constant, 200.0) let newView2 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView2) let leftConstraint1 = newView2.pin(.leftTo(newView1)) let topConstraint1 = newView2.pin(.topTo(newView1)) let rightConstraint1 = newView2.pin(.rightTo(newView1)) let bottomConstraint1 = newView2.pin(.bottomTo(newView1)) /* Validated created constraints */ XCTAssertEqual(leftConstraint1.constant, 0.0) XCTAssertEqual(topConstraint1.constant, 0.0) XCTAssertEqual(rightConstraint1.constant, 0.0) XCTAssertEqual(bottomConstraint1.constant, 0.0) /* Find Constraints in tree */ XCTAssertEqual(leftConstraint1, newView2.constraint(.leftTo(newView1))) XCTAssertEqual(topConstraint1, newView2.constraint(.topTo(newView1))) XCTAssertEqual(rightConstraint1, newView2.constraint(.rightTo(newView1))) XCTAssertEqual(bottomConstraint1, newView2.constraint(.bottomTo(newView1))) } func testItCanFindConstraintsFromTheOtherView() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView1 = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 200.0, height: 200.0)) viewcontroller.view.addSubview(newView1) newView1.pin([.left, .top, .width, .height]) let newView2 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView2) let leftConstraint1 = newView2.pin(.leftTo(newView1)) let topConstraint1 = newView2.pin(.topTo(newView1)) let rightConstraint1 = newView2.pin(.rightTo(newView1)) let bottomConstraint1 = newView2.pin(.bottomTo(newView1)) let newView3 = UIView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView3) let leftConstraint2 = newView3.pin(.leftTo(newView1)) let topConstraint2 = newView3.pin(.topTo(newView1)) let rightConstraint2 = newView3.pin(.rightTo(newView1)) let bottomConstraint2 = newView3.pin(.bottomTo(newView1)) /* Find Constraints in tree */ XCTAssertEqual(leftConstraint1, newView1.constraint(.rightTo(newView2))) XCTAssertEqual(topConstraint1, newView1.constraint(.bottomTo(newView2))) XCTAssertEqual(rightConstraint1, newView1.constraint(.leftTo(newView2))) XCTAssertEqual(bottomConstraint1, newView1.constraint(.topTo(newView2))) XCTAssertEqual(leftConstraint2, newView1.constraint(.rightTo(newView3))) XCTAssertEqual(topConstraint2, newView1.constraint(.bottomTo(newView3))) XCTAssertEqual(rightConstraint2, newView1.constraint(.leftTo(newView3))) XCTAssertEqual(bottomConstraint2, newView1.constraint(.topTo(newView3))) } func testItCanPinWidthAndHightToOtherViews() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView1 = UIView() viewcontroller.view.addSubview(newView1) newView1.pin([.left:50.0, .top:50.0, .width:100.0, .height:100.0]) let newView2 = UIView() viewcontroller.view.addSubview(newView2) let leftConstraint = newView2.pin(.left, constant: 50.0) let topConstraint = newView2.pin(.top, constant: 50.0) let equalWidthConstraint = newView2.pin(.equalWidth(newView1)) let equalHeightConstraint = newView2.pin(.equalHeight(newView1)) /* Validated created constraints */ XCTAssertEqual(leftConstraint.constant, 50.0) XCTAssertEqual(topConstraint.constant, 50.0) XCTAssertEqual(equalWidthConstraint.constant, 0.0) XCTAssertEqual(equalHeightConstraint.constant, 0.0) /* Find Constraints in tree */ XCTAssertEqual(leftConstraint, newView2.constraint(.left)) XCTAssertEqual(topConstraint, newView2.constraint(.top)) XCTAssertEqual(equalWidthConstraint, newView2.constraint(.equalWidth(newView1))) XCTAssertEqual(equalHeightConstraint, newView2.constraint(.equalHeight(newView1))) } func testItCanRemoveConstraints() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView) let topConstraint = newView.pin(.top) let leftConstraint = newView.pin(.left) let bottomConstraint = newView.pin(.bottom) let rightConstraint = newView.pin(.right) /* Find Constraints in tree */ XCTAssertEqual(topConstraint, newView.constraint(.top)) XCTAssertEqual(leftConstraint, newView.constraint(.left)) XCTAssertEqual(bottomConstraint, newView.constraint(.bottom)) XCTAssertEqual(rightConstraint, newView.constraint(.right)) leftConstraint.remove() /* Find Constraints in tree */ XCTAssertEqual(topConstraint, newView.constraint(.top)) XCTAssertNil(newView.constraint(.left)) XCTAssertEqual(bottomConstraint, newView.constraint(.bottom)) XCTAssertEqual(rightConstraint, newView.constraint(.right)) } func testItCantFindTheParentViewControllerFromAnUnassignedView() { let newView = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0)) XCTAssertNil(newView.parentViewController) } func testItCanFindTheParentViewController() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView) XCTAssertEqual(newView.parentViewController, viewcontroller) } func testItCanPinAViewToTheLayoutGuides() { if #available(iOS 9.0, *) { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView() viewcontroller.view.addSubview(newView) let topConstraint = newView.pin(.topLayoutGuide, constant: 2.0) let _ = newView.pin(.left, constant: 0.0) let bottomConstraint = newView.pin(.bottomLayoutGuide, constant: 4.0) let _ = newView.pin(.right, constant: 0.0) /* Validated created constraints */ XCTAssertEqual(topConstraint.constant, 2.0) XCTAssertEqual(bottomConstraint.constant, 4.0) XCTAssertEqual(topConstraint.firstItem as? UIView, newView) XCTAssertEqual((topConstraint.secondItem as! UILayoutGuide).owningView, viewcontroller.view) XCTAssertEqual((bottomConstraint.firstItem as! UILayoutGuide).owningView, viewcontroller.view) XCTAssertEqual(bottomConstraint.secondItem as? UIView, newView) } } func testItCanCreateAMulitplierConstraint() { let viewcontroller = UIViewController() viewcontroller.view.frame = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 480.0) let newView = UIView(frame: CGRect(x: 50.0, y: 50.0, width: 100.0, height: 100.0)) viewcontroller.view.addSubview(newView) let topConstraint = newView.pin(.top) let leftConstraint = newView.pin(.left, multiplier: 1.0) let bottomConstraint = newView.pin(.bottom, multiplier: 2.0) let rightConstraint = newView.pin(.right, multiplier: 3.0) /* Find Constraints in tree */ XCTAssertEqual(topConstraint.multiplier, 1.0) XCTAssertEqual(topConstraint.multiplier, newView.constraint(.top)?.multiplier) XCTAssertEqual(leftConstraint.multiplier, 1.0) XCTAssertEqual(leftConstraint.multiplier, newView.constraint(.left)?.multiplier) XCTAssertEqual(bottomConstraint.multiplier, 2.0) XCTAssertEqual(bottomConstraint.multiplier, newView.constraint(.bottom)?.multiplier) XCTAssertEqual(rightConstraint.multiplier, 3.0) XCTAssertEqual(rightConstraint.multiplier, newView.constraint(.right)?.multiplier) } }
3d59cfaa85c927bab3ae55d63c836288
45.04947
106
0.663521
false
true
false
false
box/box-ios-sdk
refs/heads/main
Sources/Responses/SearchResult.swift
apache-2.0
1
// // SearchResult.swift // BoxSDK-iOS // // Created by Skye Free on 2/9/21. // Copyright © 2021 box. All rights reserved. // import Foundation /// Files, folders and web links that matched the search query, including the additional information about any shared links through which the item has been shared with the user. public class SearchResult: BoxModel { // MARK: - BoxModel private static var resourceType: String = "search_result" /// Box item type public var type: String public private(set) var rawData: [String: Any] // MARK: - Properties /// The optional shared link through which the user has access to this item. /// This value is only returned for items for which the user has recently accessed the file through a shared link. For all other items this value will return nil. public let accessibleViaSharedLink: URL? /// The file, folder or web link that matched the search query. public let item: FolderItem /// Initializer. /// /// - Parameter json: JSON dictionary /// - Throws: Decoding error. public required init(json: [String: Any]) throws { guard let itemType = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } guard itemType == SearchResult.resourceType else { throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [SearchResult.resourceType])) } rawData = json type = itemType accessibleViaSharedLink = try BoxJSONDecoder.optionalDecodeURL(json: json, forKey: "accessible_via_shared_link") item = try BoxJSONDecoder.decode(json: json, forKey: "item") } }
90dfdfbe57e6b9549e7a62f4c3544d94
34.979167
177
0.68095
false
false
false
false
Jamnitzer/MBJ_Mipmapping
refs/heads/master
MBJ_Mipmapping/MBJ_Mipmapping/MBJTypes.swift
mit
1
// // MBETypes.h // Mipmapping // // Created by Warren Moore on 11/10/14. // Copyright (c) 2014 Metal By Example. All rights reserved. //------------------------------------------------------------------------ // converted to Swift by Jamnitzer (Jim Wrenholt) //------------------------------------------------------------------------ import UIKit import Metal import simd import Accelerate //------------------------------------------------------------------------------ struct MBJUniforms { var modelMatrix = float4x4(1.0) var modelViewProjectionMatrix = float4x4(1.0) var normalMatrix = float3x3(1.0) } //------------------------------------------------------------------------------ struct MBJVertex { var position = float4(0.0) var normal = float4(0.0) var texCoords = float2(0.0) } //------------------------------------------------------------------------------ typealias MBJIndexType = UInt16 //------------------------------------------------------------------------------
9325254f29a5fd60759a40d71b4605b5
31.645161
80
0.375494
false
false
false
false
EZ-NET/ESGists
refs/heads/swift-2.2
ESGistsTestApp/ESGistsTestApp/UsersViewController.swift
mit
1
// // UsersViewController.swift // ESGists // // Created by Tomohiro Kumagai on H27/08/12. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import UIKit import ESGists import APIKit class UsersViewController: UIViewController { @IBOutlet weak var usernameTextField:UITextField! @IBOutlet weak var idLabel:UILabel! @IBOutlet weak var loginLabel:UILabel! @IBOutlet weak var nameLabel:UILabel! @IBOutlet weak var urlLabel:UILabel! @IBOutlet weak var typeLabel:UILabel! @IBOutlet weak var createdAtLabel:UILabel! @IBAction func pushGetButton(sender:UIButton?) { let username = self.usernameTextField.text! let request = GitHubAPI.Users.GetSingleUser(username: username) NSLog("Try to send request: base url = \(request.baseURL), path = \(request.path).") GitHubAPI.sendRequest(request) { response in switch response { case .Success(let user): self.user = user case .Failure(let error): self.user = nil self.showErrorAlert("Failed to get user", error: error) } } } var user:GistUser? { didSet { self.idLabel.text = self.user?.id.description self.loginLabel.text = self.user?.login self.nameLabel.text = self.user?.name self.urlLabel.text = self.user?.urls.htmlUrl.description self.typeLabel.text = self.user?.type.rawValue } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bd66d4092b23cc6165602133d9db76bc
23.864198
106
0.692651
false
false
false
false
maisa/iConv
refs/heads/master
App_iOS/iConv/ConfController.swift
gpl-2.0
1
// // ConfController.swift // iConv // // Created by Leandro Paiva Andrade on 4/6/16. // Copyright © 2016 Leandro Paiva Andrade. All rights reserved. // import Foundation import UIKit //import SwiftyJSON class ConfController: UITableViewController{ var selectedMunicipio: Municipio! @IBOutlet weak var cidadeText: UITextField! @IBOutlet weak var estadoText: UITextField! @IBOutlet weak var estadoPicker: UIPickerView! @IBOutlet weak var cidadePicker: UIPickerView! var buttonGoverno = false var selectedEstado = "AC" var test = [Municipio]() var allMunicipios = [Municipio]() var i = 0 var data = [[String: [Municipio]]]() override func viewDidLoad() { super.viewDidLoad() // if let path = NSBundle.mainBundle().pathForResource("estados-cidades", ofType: "json") { // if let data = NSData(contentsOfFile: path){ // let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil) // //print("jsonData:\(json)") // } // } // runAPI() // gradePicker.dataSource = self // gradePicker.delegate = self cidade() estadoPicker.showsSelectionIndicator = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) tableView.reloadData() } @IBAction func estadualButton(sender: CheckboxButton) { let state = sender.on ? "ON" : "OFF" if state == "ON"{ buttonGoverno = true tableView.reloadData() } if state == "OFF"{ buttonGoverno = false tableView.reloadData() } // print("CheckboxButton: did turn \(state)") } @IBAction func prefeituraButton(sender: CheckboxButton) { let state = sender.on ? "ON" : "OFF" if state == "ON"{ buttonGoverno = false tableView.reloadData() } if state == "OFF"{ buttonGoverno = true tableView.reloadData() } // print("CheckboxButton: did turn \(state)") } func cidade(){ // print(data) // for item in data{ // if let test = item[estados[i]] { // print(estados[i]) // print(test.count) // print("") // // } // i = i + 1 // } } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if textField.placeholder == "Estado"{ toggleDatepicker(0) } if textField.placeholder == "Cidade"{ toggleDatepicker(1) } return false } @IBAction func closePicker(sender: UIButton) { toggleDatepicker(0) } @IBAction func closeCidade(sender: UIButton) { toggleDatepicker(1) } ///let test = ["lala", "elel"] func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { if pickerView.tag == 1 { estadoText.text = estadosNome[row][1] selectedEstado = estadosNome[row][0] print(selectedEstado) cidadeText.text = "Cidade" cidadePicker.reloadAllComponents() } if pickerView.tag == 2 { cidadeText.text = test[row].nome selectedMunicipio = test[row] } //estadoPicker.hidden = true; } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView.tag == 1{ return estados.count } else { var countMuni = 0; for item in data{ if let test = item[selectedEstado] { //print(selectedEstado) countMuni = test.count // print("") } i = i + 1 } return countMuni } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { if pickerView.tag == 1{ return estadosNome[row][1] } else { if selectedEstado.isEmpty { print(selectedEstado) } else { for item in data{ if let test2 = item[selectedEstado] { test = test2 //print(selectedEstado) // print("") } } } return test[row].nome } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 && indexPath.row == 0 { toggleDatepicker(0) } if( indexPath.section == 2){ toggleDatepicker(1) } } var estadoPickerHide = true var cidadePickerHide = true override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if estadoPickerHide && indexPath.section == 1 && indexPath.row == 1 { return 0 } else if cidadePickerHide && indexPath.section == 2 && indexPath.row == 1{ return 0 } else if buttonGoverno && indexPath.section == 2 && indexPath.row == 0{ return 0 } else{ return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } // override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // if buttonGoverno && indexPath.section == 2 && indexPath.row == 0{ // return 0 // } // return UITableViewAutomaticDimension // } func toggleDatepicker(toggleHide: Int){ if(toggleHide == 0){ estadoPickerHide = !estadoPickerHide if(cidadePickerHide == false){ cidadePickerHide = true } } if(toggleHide == 1){ cidadePickerHide = !cidadePickerHide if(estadoPickerHide == false){ estadoPickerHide = true } } tableView.beginUpdates() tableView.endUpdates() } // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // if segue.identifier == "segueToMuni"{ // let DestView : HomeScreen = segue.destinationViewController as! HomeScreen // //print(dict) // DestView.data = self.selectedMunicipio // } // // // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
b4d81cf9f7bd446fa3c0c5d333f6442f
27.886179
123
0.529768
false
false
false
false
safx/TypetalkKit
refs/heads/master
IDL/Auth.swift
mit
1
// // Auth.swift // IDL // // Created by Safx Developer on 2015/08/10. // Copyright © 2015年 Safx Developers. All rights reserved. // import Foundation import APIKit class Authorize: ClassInit, APIKitHelper, AuthRequest { // router:",authorize" typealias APIKitResponse = OAuth2Credential let client_id: String let redirect_uri: String let scope: String let response_type: String = "code" } class AccessToken: ClassInit, APIKitHelper, AuthRequest { // router:"POST, access_token" typealias APIKitResponse = OAuth2Credential let grant_type: GrantType let client_id: String let client_secret: String let redirect_uri: String? = nil // AuthorizationCode let code: String? = nil // AuthorizationCode let refresh_token: String? = nil // RefreshToken let scope: String? = nil // ClientCredentials } class OAuth2Credential: NSObject, ClassInit, Decodable, Encodable { open let accessToken: String // json:"access_token" open let tokenType: String // json:"token_type" open let refreshToken: String // json:"refresh_token" open let expiryIn: Int // json:"expires_in" //public let scope: Scope } enum GrantType: String, Encodable { case authorizationCode = "authorization_code" case clientCredentials = "client_credentials" case refreshToken = "refresh_token" }
8bf5982bc427a189e472dbb462615e49
30.636364
88
0.686782
false
false
false
false
mrdepth/EVEOnlineAPI
refs/heads/master
EVEAPI/EVEAPI/codegen/Contacts.swift
mit
1
import Foundation import Alamofire import Futures public extension ESI { var contacts: Contacts { return Contacts(esi: self) } struct Contacts { let esi: ESI @discardableResult public func editContacts(characterID: Int, contactIds: [Int], labelIds: [Int64]? = nil, standing: Float, watched: Bool? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<String>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-characters.write_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body = try? JSONEncoder().encode(contactIds) var headers = HTTPHeaders() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = labelIds?.httpQuery { query.append(URLQueryItem(name: "label_ids", value: v)) } if let v = standing.httpQuery { query.append(URLQueryItem(name: "standing", value: v)) } if let v = watched?.httpQuery { query.append(URLQueryItem(name: "watched", value: v)) } let url = esi.baseURL + "/characters/\(characterID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<String>>() esi.request(components.url!, method: .put, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<String>) in promise.set(response: response, cached: nil) } return promise.future } @discardableResult public func getContacts(characterID: Int, ifNoneMatch: String? = nil, page: Int? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.Contact]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-characters.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = page?.httpQuery { query.append(URLQueryItem(name: "page", value: v)) } let url = esi.baseURL + "/characters/\(characterID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.Contact]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.Contact]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func addContacts(characterID: Int, contactIds: [Int], labelIds: [Int64]? = nil, standing: Float, watched: Bool? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Int]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-characters.write_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body = try? JSONEncoder().encode(contactIds) var headers = HTTPHeaders() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = labelIds?.httpQuery { query.append(URLQueryItem(name: "label_ids", value: v)) } if let v = standing.httpQuery { query.append(URLQueryItem(name: "standing", value: v)) } if let v = watched?.httpQuery { query.append(URLQueryItem(name: "watched", value: v)) } let url = esi.baseURL + "/characters/\(characterID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Int]>>() esi.request(components.url!, method: .post, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Int]>) in promise.set(response: response, cached: nil) } return promise.future } @discardableResult public func deleteContacts(characterID: Int, contactIds: [Int], cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<String>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-characters.write_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = contactIds.httpQuery { query.append(URLQueryItem(name: "contact_ids", value: v)) } let url = esi.baseURL + "/characters/\(characterID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<String>>() esi.request(components.url!, method: .delete, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<String>) in promise.set(response: response, cached: nil) } return promise.future } @discardableResult public func getContactLabels(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.Label]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-characters.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/characters/\(characterID)/contacts/labels/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.Label]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.Label]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func getCorporationContactLabels(corporationID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.GetCorporationsCorporationIDContactsLabelsOk]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-corporations.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/corporations/\(corporationID)/contacts/labels/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.GetCorporationsCorporationIDContactsLabelsOk]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.GetCorporationsCorporationIDContactsLabelsOk]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func getAllianceContacts(allianceID: Int, ifNoneMatch: String? = nil, page: Int? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.GetAlliancesAllianceIDContactsOk]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-alliances.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = page?.httpQuery { query.append(URLQueryItem(name: "page", value: v)) } let url = esi.baseURL + "/alliances/\(allianceID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.GetAlliancesAllianceIDContactsOk]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.GetAlliancesAllianceIDContactsOk]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func getCorporationContacts(corporationID: Int, ifNoneMatch: String? = nil, page: Int? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.GetCorporationsCorporationIDContactsOk]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-corporations.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) if let v = page?.httpQuery { query.append(URLQueryItem(name: "page", value: v)) } let url = esi.baseURL + "/corporations/\(corporationID)/contacts/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.GetCorporationsCorporationIDContactsOk]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.GetCorporationsCorporationIDContactsOk]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func getAllianceContactLabels(allianceID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Contacts.GetAlliancesAllianceIDContactsLabelsOk]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-alliances.read_contacts.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/alliances/\(allianceID)/contacts/labels/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Contacts.GetAlliancesAllianceIDContactsLabelsOk]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Contacts.GetAlliancesAllianceIDContactsLabelsOk]>) in promise.set(response: response, cached: 300.0) } return promise.future } public struct GetCorporationsCorporationIDContactsOk: Codable, Hashable { public enum GetCorporationsCorporationIDContactsContactType: String, Codable, HTTPQueryable { case alliance = "alliance" case character = "character" case corporation = "corporation" case faction = "faction" public var httpQuery: String? { return rawValue } } public var contactID: Int public var contactType: Contacts.GetCorporationsCorporationIDContactsOk.GetCorporationsCorporationIDContactsContactType public var isWatched: Bool? public var labelIds: [Int64]? public var standing: Float public init(contactID: Int, contactType: Contacts.GetCorporationsCorporationIDContactsOk.GetCorporationsCorporationIDContactsContactType, isWatched: Bool?, labelIds: [Int64]?, standing: Float) { self.contactID = contactID self.contactType = contactType self.isWatched = isWatched self.labelIds = labelIds self.standing = standing } enum CodingKeys: String, CodingKey, DateFormatted { case contactID = "contact_id" case contactType = "contact_type" case isWatched = "is_watched" case labelIds = "label_ids" case standing var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct GetAlliancesAllianceIDContactsOk: Codable, Hashable { public enum GetAlliancesAllianceIDContactsContactType: String, Codable, HTTPQueryable { case alliance = "alliance" case character = "character" case corporation = "corporation" case faction = "faction" public var httpQuery: String? { return rawValue } } public var contactID: Int public var contactType: Contacts.GetAlliancesAllianceIDContactsOk.GetAlliancesAllianceIDContactsContactType public var labelIds: [Int64]? public var standing: Float public init(contactID: Int, contactType: Contacts.GetAlliancesAllianceIDContactsOk.GetAlliancesAllianceIDContactsContactType, labelIds: [Int64]?, standing: Float) { self.contactID = contactID self.contactType = contactType self.labelIds = labelIds self.standing = standing } enum CodingKeys: String, CodingKey, DateFormatted { case contactID = "contact_id" case contactType = "contact_type" case labelIds = "label_ids" case standing var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct PostCharactersCharacterIDContactsError520: Codable, Hashable { public var error: String? public init(error: String?) { self.error = error } enum CodingKeys: String, CodingKey, DateFormatted { case error var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct Label: Codable, Hashable { public var labelID: Int64 public var labelName: String public init(labelID: Int64, labelName: String) { self.labelID = labelID self.labelName = labelName } enum CodingKeys: String, CodingKey, DateFormatted { case labelID = "label_id" case labelName = "label_name" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct Contact: Codable, Hashable { public enum GetCharactersCharacterIDContactsContactType: String, Codable, HTTPQueryable { case alliance = "alliance" case character = "character" case corporation = "corporation" case faction = "faction" public var httpQuery: String? { return rawValue } } public var contactID: Int public var contactType: Contacts.Contact.GetCharactersCharacterIDContactsContactType public var isBlocked: Bool? public var isWatched: Bool? public var labelIds: [Int64]? public var standing: Float public init(contactID: Int, contactType: Contacts.Contact.GetCharactersCharacterIDContactsContactType, isBlocked: Bool?, isWatched: Bool?, labelIds: [Int64]?, standing: Float) { self.contactID = contactID self.contactType = contactType self.isBlocked = isBlocked self.isWatched = isWatched self.labelIds = labelIds self.standing = standing } enum CodingKeys: String, CodingKey, DateFormatted { case contactID = "contact_id" case contactType = "contact_type" case isBlocked = "is_blocked" case isWatched = "is_watched" case labelIds = "label_ids" case standing var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct GetAlliancesAllianceIDContactsLabelsOk: Codable, Hashable { public var labelID: Int64 public var labelName: String public init(labelID: Int64, labelName: String) { self.labelID = labelID self.labelName = labelName } enum CodingKeys: String, CodingKey, DateFormatted { case labelID = "label_id" case labelName = "label_name" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct GetCorporationsCorporationIDContactsLabelsOk: Codable, Hashable { public var labelID: Int64 public var labelName: String public init(labelID: Int64, labelName: String) { self.labelID = labelID self.labelName = labelName } enum CodingKeys: String, CodingKey, DateFormatted { case labelID = "label_id" case labelName = "label_name" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } } }
8496e51285d3d4d676c858ba35ddb25a
33.294798
241
0.694983
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/SILGen/optional-cast.swift
apache-2.0
4
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class A {} class B : A {} // CHECK-LABEL: sil hidden @_T04main3fooyAA1ACSgF : $@convention(thin) (@owned Optional<A>) -> () { // CHECK: bb0([[ARG:%.*]] : $Optional<A>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // Check whether the temporary holds a value. // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]] // CHECK-NEXT: cond_br [[T1]], [[IS_PRESENT:bb.*]], [[NOT_PRESENT:bb[0-9]+]] // // CHECK: [[NOT_PRESENT]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[NOT_PRESENT_FINISH:bb[0-9]+]] // // If so, pull the value out and check whether it's a B. // CHECK: [[IS_PRESENT]]: // CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data [[ARG_COPY]] : $Optional<A>, #Optional.some!enumelt.1 // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, materialize that and inject it into x. // CHECK: [[IS_B]]([[T0:%.*]] : $B): // CHECK-NEXT: store [[T0]] to [init] [[X_VALUE]] : $*B // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: br [[CONT:bb[0-9]+]] // // If not, destroy_value the A and inject nothing into x. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none // CHECK-NEXT: br [[CONT]] // // Finish the present path. // CHECK: [[CONT]]: // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: br [[RETURN_BB:bb[0-9]+]] // // Finish. // CHECK: [[RETURN_BB]]: // CHECK-NEXT: destroy_value [[X]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return // // Finish the not-present path. // CHECK: [[NOT_PRESENT_FINISH]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[RETURN_BB]] func foo(_ y : A?) { var x = (y as? B) } // CHECK-LABEL: sil hidden @_T04main3baryAA1ACSgSgSgSgF : $@convention(thin) (@owned Optional<Optional<Optional<Optional<A>>>>) -> () { // CHECK: bb0([[ARG:%.*]] : $Optional<Optional<Optional<Optional<A>>>>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // -- Check for some(...) // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]] // CHECK-NEXT: cond_br [[T1]], [[P:bb.*]], [[NIL_DEPTH_1:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_1]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[FINISH_NIL_0:bb[0-9]+]] // // If so, drill down another level and check for some(some(...)). // CHECK: [[P]]: // CHECK-NEXT: [[VALUE_OOOA:%.*]] = unchecked_enum_data [[ARG_COPY]] // CHECK: [[T1:%.*]] = select_enum [[VALUE_OOOA]] // CHECK-NEXT: cond_br [[T1]], [[PP:bb.*]], [[NIL_DEPTH_2:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_2]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[FINISH_NIL_0]] // // If so, drill down another level and check for some(some(some(...))). // CHECK: [[PP]]: // CHECK-NEXT: [[VALUE_OOA:%.*]] = unchecked_enum_data [[VALUE_OOOA]] // CHECK: [[T1:%.*]] = select_enum [[VALUE_OOA]] // CHECK-NEXT: cond_br [[T1]], [[PPP:bb.*]], [[NIL_DEPTH_3:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_3]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[FINISH_NIL_1:bb[0-9]+]] // // If so, drill down another level and check for some(some(some(some(...)))). // CHECK: [[PPP]]: // CHECK-NEXT: [[VALUE_OA:%.*]] = unchecked_enum_data [[VALUE_OOA]] // CHECK: [[T1:%.*]] = select_enum [[VALUE_OA]] // CHECK-NEXT: cond_br [[T1]], [[PPPP:bb.*]], [[NIL_DEPTH_4:bb[0-9]+]] // // CHECK: [[NIL_DEPTH_4]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[FINISH_NIL_2:bb[0-9]+]] // // If so, pull out the A and check whether it's a B. // CHECK: [[PPPP]]: // CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data [[VALUE_OA]] // CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // // If so, inject it back into an optional. // TODO: We're going to switch back out of this; we really should peephole it. // CHECK: [[IS_B]]([[T0:%.*]] : $B): // CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt.1, [[T0]] // CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]]( // // If not, inject nothing into an optional. // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $A): // CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]] // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[SWITCH_OB2]]( // // Switch out on the value in [[OB2]]. // CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : $Optional<B>): // CHECK: [[T0:%.*]] = select_enum [[VAL]] // CHECK: cond_br [[T0]], [[HAVE_B:bb[0-9]+]], [[FINISH_NIL_4:bb[0-9]+]] // // CHECK: [[FINISH_NIL_4]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[FINISH_NIL_0]] // // CHECK: [[HAVE_B]]: // CHECK: [[UNWRAPPED_VAL:%.*]] = unchecked_enum_data [[VAL]] // CHECK: [[REWRAPPED_VAL:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[UNWRAPPED_VAL]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br [[DONE_DEPTH0:bb[0-9]+]] // // CHECK: [[DONE_DEPTH0]]( // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt.1, // CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]] // // Set X := some(OOB). // CHECK: [[DONE_DEPTH1]] // CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt.1, // CHECK: br [[DONE_DEPTH2:bb[0-9]+]] // CHECK: [[DONE_DEPTH2]] // CHECK-NEXT: destroy_value [[X]] // CHECK-NEXT: destroy_value %0 // CHECK: return // // On various failure paths, set OOB := nil. // CHECK: [[FINISH_NIL_2]]: // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH0]] // // CHECK: [[FINISH_NIL_1]]: // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH1]] // // On various failure paths, set X := nil. // CHECK: [[FINISH_NIL_0]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[DONE_DEPTH2]] // Done. func bar(_ y : A????) { var x = (y as? B??) } // CHECK-LABEL: sil hidden @_T04main3bazys9AnyObject_pSgF : $@convention(thin) (@owned Optional<AnyObject>) -> () { // CHECK: bb0([[ARG:%.*]] : $Optional<AnyObject>): // CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[T1:%.*]] = select_enum [[ARG_COPY]] // CHECK: bb1: // CHECK: [[VAL:%.*]] = unchecked_enum_data [[ARG_COPY]] // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // CHECK: [[IS_B]]([[CASTED_VALUE:%.*]] : $B): // CHECK: store [[CASTED_VALUE]] to [init] [[X_VALUE]] // CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : $AnyObject): // CHECK: destroy_value [[ORIGINAL_VALUE]] // CHECK: } // end sil function '_T04main3bazys9AnyObject_pSgF' func baz(_ y : AnyObject?) { var x = (y as? B) } // <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond // CHECK-LABEL: sil hidden @_T04main07opt_to_B8_trivialSQySiGSiSgF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x" // CHECK-NEXT: return %0 : $Optional<Int> // CHECK-NEXT:} func opt_to_opt_trivial(_ x: Int?) -> Int! { return x } // CHECK-LABEL: sil hidden @_T04main07opt_to_B10_referenceAA1CCSgSQyADGF : // CHECK: bb0([[ARG:%.*]] : $Optional<C>): // CHECK: debug_value [[ARG]] : $Optional<C>, let, name "x" // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[RESULT:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] : $Optional<C> // CHECK: } // end sil function '_T04main07opt_to_B10_referenceAA1CCSgSQyADGF' func opt_to_opt_reference(_ x : C!) -> C? { return x } // CHECK-LABEL: sil hidden @_T04main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $*Optional<T>): // CHECK-NEXT: debug_value_addr %1 : $*Optional<T>, let, name "x" // CHECK-NEXT: copy_addr %1 to [initialization] %0 // CHECK-NEXT: destroy_addr %1 func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x } class C {} public struct TestAddressOnlyStruct<T> { func f(_ a : T?) {} // CHECK-LABEL: sil hidden @_T04main21TestAddressOnlyStructV8testCall{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<T>, %1 : $TestAddressOnlyStruct<T>): // CHECK: [[TMPBUF:%.*]] = alloc_stack $Optional<T> // CHECK-NEXT: copy_addr %0 to [initialization] [[TMPBUF]] // CHECK-NEXT: apply {{.*}}<T>([[TMPBUF]], %1) func testCall(_ a : T!) { f(a) } } // CHECK-LABEL: sil hidden @_T04main35testContextualInitOfNonAddrOnlyTypeySiSgF // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: store %0 to [trivial] [[PB]] : $*Optional<Int> // CHECK-NEXT: destroy_value [[X]] : ${ var Optional<Int> } func testContextualInitOfNonAddrOnlyType(_ a : Int?) { var x: Int! = a }
c92f12ab8055dbfcb4bf07f15196b59b
40.104603
135
0.569829
false
false
false
false
johndpope/Cerberus
refs/heads/master
Cerberus/Classes/Models/Calendar.swift
mit
1
import Foundation import EventKit import Timepiece enum CalendarAuthorizationStatus { case Success case Error } final class Calendar { var date: NSDate private let eventStore: EKEventStore! private let calendar: NSCalendar! private var selectedCalendars: [EKCalendar]? var events: [Event] private var timer: NSTimer? private let timerTickIntervalSec = 60.0 init() { self.events = [] self.eventStore = EKEventStore() self.calendar = NSCalendar.currentCalendar() self.selectedCalendars = nil self.date = NSDate() self.timer = NSTimer.scheduledTimerWithTimeInterval(timerTickIntervalSec, target: self, selector: "onTimerTick:", userInfo: nil, repeats: true) registerNotificationObservers() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) self.timer?.invalidate() } private func registerNotificationObservers() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "didChooseCalendarNotification:", name: NotifictionNames.CalendarModelDidChooseCalendarNotification.rawValue, object: nil ) notificationCenter.addObserver(self, selector: "didChangeEventNotification:", name: EKEventStoreChangedNotification, object: nil ) } @objc func didChooseCalendarNotification(notification: NSNotification) { self.selectedCalendars = notification.object as? [EKCalendar] self.update() } @objc func didChangeEventNotification(notification: NSNotification) { NSNotificationCenter.defaultCenter().postNotificationName(NotifictionNames.CalendarModelDidChangeEventNotification.rawValue, object: nil) } @objc func onTimerTick(timer: NSTimer) { self.eventStore.refreshSourcesIfNecessary() self.date = NSDate() self.update() } func isAuthorized() -> Bool { let status: EKAuthorizationStatus = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent) return status == .Authorized } func authorize(completion: ((status: CalendarAuthorizationStatus) -> Void)?) { if isAuthorized() { fetchEvents() completion?(status: .Success) return } self.eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { [weak self] (granted, error) -> Void in if granted { self?.fetchEvents() completion?(status: .Success) return } else { completion?(status: .Error) } }) } func update() { if isAuthorized() { fetchEvents() } } private func fetchEvents() { self.events.removeAll(keepCapacity: true) let calStartDate = self.date.beginningOfDay let calEndDate = calStartDate + 1.day if let calendars = self.selectedCalendars { let predicate = self.eventStore.predicateForEventsWithStartDate(calStartDate, endDate: calEndDate, calendars: calendars) var currentDateOffset = calStartDate if let matchingEvents = self.eventStore.eventsMatchingPredicate(predicate) as? [EKEvent] { for event in matchingEvents { if let startDate = event.startDate, endDate = event.endDate { if startDate < currentDateOffset { continue } else if startDate >= calEndDate { break } if currentDateOffset < startDate { self.events.append(Event(startDate: currentDateOffset, endDate: startDate)) } let event = Event(fromEKEvent: event) if endDate > calEndDate { event.endDate = calEndDate } self.events.append(event) currentDateOffset = endDate } } } if currentDateOffset < calEndDate { self.events.append(Event(startDate: currentDateOffset, endDate: calEndDate)) } } NSNotificationCenter.defaultCenter().postNotificationName(NotifictionNames.CalendarModelDidChangeEventNotification.rawValue, object: nil) } }
df5f45b529b78890fac88ac16ade1073
29.576159
151
0.599653
false
false
false
false
zwaldowski/URLGrey
refs/heads/swift-2_0
URLGrey/NSURL+Ancestors.swift
mit
1
// // NSURL+Parents.swift // URLGrey // // Created by Zachary Waldowski on 3/30/15. // Copyright © 2014-2015. Some rights reserved. // import Foundation // MARK: Result Types public enum URLAncestorResult { case Next(NSURL) case VolumeRoot(NSURL) case Failure(ErrorType) } // MARK: Generator private struct URLAncestorsGenerator: GeneratorType { var nextURL: NSURL? init(URL: NSURL) { self.nextURL = URL } private mutating func next() -> URLAncestorResult? { guard let current = nextURL else { return nil } do { guard try !current.valueForResource(URLResource.IsVolume) else { nextURL = nil return .VolumeRoot(current) } nextURL = try current.valueForResource(URLResource.ParentDirectoryURL) return .Next(current) } catch { nextURL = nil return .Failure(error) } } } // MARK: Ancestors extension extension NSURL { public var ancestors: AnySequence<URLAncestorResult> { return AnySequence { URLAncestorsGenerator(URL: self) } } }
d83bb33aa87067ca3fc5848d50ed000f
19.754386
82
0.595943
false
false
false
false
cuappdev/tempo
refs/heads/master
Tempo/Controllers/StyleController.swift
mit
1
// // StyleController.swift // Tempo // // Created by Lucas Derraugh on 8/8/15. // Copyright © 2015 CUAppDev. All rights reserved. // import UIKit class StyleController { class func applyStyles() { // UIKit appearances UINavigationBar.appearance().barTintColor = .tempoRed UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().barStyle = .black UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "AvenirNext-Medium", size: 18.0)!, NSForegroundColorAttributeName: UIColor.white] UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext-Regular", size: 17.0)!], for: .normal) UISearchBar.appearance().backgroundImage = UIImage() UISearchBar.appearance().backgroundColor = .tempoRed UISearchBar.appearance().barTintColor = .tempoRed UISearchBar.appearance().tintColor = .white UISearchBar.appearance().isTranslucent = true UISearchBar.appearance().placeholder = "Search" UISearchBar.appearance().searchBarStyle = .prominent UITableView.appearance().backgroundColor = .backgroundDarkGrey UITableView.appearance().separatorColor = .clear UITableView.appearance().separatorStyle = .none UITableView.appearance().sectionHeaderHeight = 0 UITableView.appearance().sectionFooterHeight = 0 UITableView.appearance().rowHeight = 96 UITableViewCell.appearance().backgroundColor = .readCellColor // User defined appearances SearchPostView.appearance().backgroundColor = .searchBackgroundRed } }
ce9690fd30f2cd0261a3e17a6a90a51c
39.477273
189
0.775407
false
false
false
false
gvzq/iOS-Instagram-Lab
refs/heads/master
Instagram/ViewController.swift
apache-2.0
1
// // ViewController.swift // Instagram // // Created by Gerardo Vazquez on 1/27/16. // Copyright © 2016 Gerardo Vazquez. All rights reserved. // import UIKit import AFNetworking class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate { @IBOutlet weak var headerView: UIView! @IBOutlet weak var tableView: UITableView! var pictures: [NSDictionary]! var isMoreDataLoading = false func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("InstagramCell", forIndexPath: indexPath) as! InstagramViewCell let photo = pictures![indexPath.row] let poster = (photo["images"])!["low_resolution"]!!["url"]! as! String let title = (photo["user"])!["username"]! as! String let profile = (photo["user"])!["profile_picture"]! as! String let imageURL = NSURL(string: poster) cell.posterView.setImageWithURL(imageURL!) cell.InstagramLabel.text = title let profileURL = NSURL(string: profile) cell.profileView.setImageWithURL(profileURL!) let backgroundView = UIView() backgroundView.backgroundColor = UIColor.clearColor() cell.selectedBackgroundView = backgroundView return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let pictures = pictures{ return pictures.count } else { return 0 } } //this is not working! func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated:true) } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self let clientId = "e05c462ebd86446ea48a5af73769b602" let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)") let request = NSURLRequest(URL: url!) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { NSLog("response: \(responseDictionary)") self.pictures = responseDictionary["data"] as? [NSDictionary] self.tableView.reloadData() } } }); task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. let cell = sender as! UITableViewCell let indexPath = tableView.indexPathForCell(cell) let picture = pictures![indexPath!.row] // var vc = segue.destinationViewController as! ViewController // var indexPath = tableView.indexPathForCell(sender as! UITableViewCell) let photoDetailsViewController = segue.destinationViewController as! PhotoDetailsViewController photoDetailsViewController.vc = picture // PhotoDetailsViewController.vc = vc // PhotoDetailsViewController.indexPath = indexPath // Pass the selected object to the new view controller. } func scrollViewDidScroll(scrollView: UIScrollView) { // Handle scroll behavior here if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = tableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.dragging) { isMoreDataLoading = true // ... Code to load more results ... loadMoreData() } } } // func loadMoreData() { // // // ... Create the NSURLRequest (myRequest) ... // // // Configure session so that completion handler is executed on main UI thread // let session = NSURLSession( // configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), // delegate:nil, // delegateQueue:NSOperationQueue.mainQueue() // ) // // let task : NSURLSessionDataTask = session.dataTaskWithRequest(myRequest, // completionHandler: { (data, response, error) in // // // Update flag // self.isMoreDataLoading = false // // // ... Use the new data to update the data source ... // // // Reload the tableView now that there is new data // self.myTableView.reloadData() // }); // task.resume() // } func loadMoreData() { let clientId = "e05c462ebd86446ea48a5af73769b602" let url = NSURL(string:"https://api.instagram.com/v1/media/popular?client_id=\(clientId)") let request = NSURLRequest(URL: url!) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:nil, delegateQueue:NSOperationQueue.mainQueue() ) //Show HUD before the request is made //let HUDindicator = MBProgressHUD.showHUDAddedTo(self.view, animated: true) //HUDindicator.labelText = "Loading" //HUDindicator.detailsLabelText = "Please wait" let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in // Update flag self.isMoreDataLoading = false if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { NSLog("response: \(responseDictionary)") self.pictures = responseDictionary["data"] as? [NSDictionary] self.tableView.reloadData() } } }); task.resume() } }
ac383b0395412d6b5f2d68f8c3d1878e
34.970443
126
0.590249
false
false
false
false
Estimote/iOS-Mirror-SDK
refs/heads/master
Sources/DisplayRequest.swift
apache-2.0
1
import Foundation struct DisplayRequest { let id:UUID let mirrorIdentifier:String let dictionary:[String:Any] let completionBlock:((Error?) -> Void)? init(mirrorIdentifier:String, dictionary:[String:Any], completion:((_ error:Error?) -> Void)? = nil) { self.id = UUID() self.mirrorIdentifier = mirrorIdentifier self.dictionary = dictionary self.completionBlock = completion } init(mirrorIdentifier:String, view:View, completion:((_ error:Error?) -> Void)? = nil) { self.id = UUID() self.mirrorIdentifier = mirrorIdentifier self.dictionary = [ "template": "estimote/__built-in_views", "actions": [[ "showView": [ "id": self.id.uuidString, "type": view.typeName, "data": view.dataDict ]] ] ] self.completionBlock = completion } }
e66acd4560ae1acde3be7646f90babb7
30.322581
106
0.548919
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/Settings/Menu/NotificationsAndSounds/NotificationsTableViewController.swift
gpl-3.0
1
// // NotificationsTableViewController.swift // FalconMessenger // // Created by Roman Mizin on 8/17/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit class NotificationsTableViewController: MenuControlsTableViewController { var notificationElements = [SwitchObject]() override func viewDidLoad() { super.viewDidLoad() createDataSource() navigationItem.title = "Notifications" } fileprivate func createDataSource() { let inAppNotificationsState = userDefaults.currentBoolObjectState(for: userDefaults.inAppNotifications) let inAppSoundsState = userDefaults.currentBoolObjectState(for: userDefaults.inAppSounds) let inAppVibrationState = userDefaults.currentBoolObjectState(for: userDefaults.inAppVibration) let inAppNotifications = SwitchObject("In-App Preview", subtitle: nil, state: inAppNotificationsState, defaultsKey: userDefaults.inAppNotifications) let inAppSounds = SwitchObject("In-App Sounds", subtitle: nil, state: inAppSoundsState, defaultsKey: userDefaults.inAppSounds) let inAppVibration = SwitchObject("In-App Vibrate", subtitle: nil, state: inAppVibrationState, defaultsKey: userDefaults.inAppVibration) notificationElements.append(inAppNotifications) notificationElements.append(inAppSounds) notificationElements.append(inAppVibration) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notificationElements.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: switchCellID, for: indexPath) as? SwitchTableViewCell ?? SwitchTableViewCell() cell.currentViewController = self cell.setupCell(object: notificationElements[indexPath.row], index: indexPath.row) return cell } }
c7827efe9363baedc2876bc6bec8d91b
39.244898
152
0.78144
false
false
false
false
SquidKit/SquidKit
refs/heads/master
SquidKit/JSONEntity.swift
mit
1
// // JSONEntity.swift // SquidKit // // Created by Mike Leavy on 9/3/14. // Copyright © 2014-2019 Squid Store, LLC. All rights reserved. // import Foundation open class JSONEntity: Sequence { enum JSONEntityError: Error { case invalidKey case invalidValue case invalidFormat case invalidJSON } fileprivate struct Entity { var key: String var value: AnyObject init(_ key: String, _ value: AnyObject) { self.key = key self.value = value } } fileprivate var entity: Entity fileprivate class NilValue { } open var count: Int { if let array = self.array() { return array.count } else if let dictionary = self.dictionary() { return dictionary.count } return 0 } open var isValid: Bool { if let _ = self.entity.value as? NilValue { return false } return true } open var key: String { return self.entity.key } open var realValue: AnyObject? { if let _ = self.entity.value as? NilValue { return nil } return self.entity.value } public init () { self.entity = Entity("", NilValue()) } public init(_ key: String, _ value: AnyObject) { self.entity = Entity(key, value) } public init(resourceFilename: String) { let jsonEntity = JSONEntity.entityFromResourceFile(resourceFilename) self.entity = jsonEntity.entity; } public init(jsonDictionary: NSDictionary) { self.entity = Entity("", jsonDictionary) } public init(jsonArray: NSArray) { self.entity = Entity("", jsonArray) } open func string() -> String? { return self.stringWithDefault(nil) } open func array() -> NSArray? { return self.arrayWithDefault(nil) } open func dictionary() -> NSDictionary? { return self.dictionaryWithDefault(nil) } open func int() -> Int? { return self.intWithDefault(nil) } open func double() -> Double? { return self.doubleWithDefault(nil) } open func bool() -> Bool? { return self.boolWithDefault(nil) } open func stringWithDefault(_ defaultValue: String?) -> String? { return EntityConverter<String>().get(entity.value, defaultValue) } open func arrayWithDefault(_ defaultValue: NSArray?) -> NSArray? { return EntityConverter<NSArray>().get(entity.value, defaultValue) } open func dictionaryWithDefault(_ defaultValue: NSDictionary?) -> NSDictionary? { return EntityConverter<NSDictionary>().get(entity.value, defaultValue) } open func intWithDefault(_ defaultValue: Int?) -> Int? { if let int = EntityConverter<Int>().get(entity.value, nil) { return int } else if let intString = EntityConverter<String>().get(entity.value, nil) { return (intString as NSString).integerValue } return defaultValue } open func doubleWithDefault(_ defaultValue: Double?) -> Double? { if let double = EntityConverter<Double>().get(entity.value, nil) { return double } else if let doubleString = EntityConverter<String>().get(entity.value, nil) { return (doubleString as NSString).doubleValue } return defaultValue } open func boolWithDefault(_ defaultValue: Bool?) -> Bool? { if let bool = EntityConverter<Bool>().get(entity.value, nil) { return bool } else if let boolString = EntityConverter<String>().get(entity.value, nil) { return (boolString as NSString).boolValue } return defaultValue } open subscript(key: String) -> JSONEntity { if let e: NSDictionary = entity.value as? NSDictionary { if let object: AnyObject = e.object(forKey: key) as AnyObject? { return JSONEntity(key, object) } } return JSONEntity(key, NilValue()) } open subscript(index: Int) -> JSONEntity? { if let array: NSArray = entity.value as? NSArray { return JSONEntity(self.entity.key, array[index] as AnyObject) } return nil } public typealias GeneratorType = JSONEntityGenerator open func makeIterator() -> GeneratorType { let generator = JSONEntityGenerator(self) return generator } } public extension JSONEntity { class func entityFromResourceFile(_ fileName: String) -> JSONEntity { var result: JSONEntity? if let inputStream = InputStream(fileAtPath: String.stringWithPathToResourceFile(fileName)) { inputStream.open() do { let serialized = try JSONSerialization.jsonObject(with: inputStream, options: JSONSerialization.ReadingOptions(rawValue: 0)) if let serializedASDictionary = serialized as? NSDictionary { result = JSONEntity(jsonDictionary: serializedASDictionary) } else if let serializedAsArray = serialized as? NSArray { result = JSONEntity(jsonArray: serializedAsArray) } else { result = JSONEntity() } } catch { result = JSONEntity() } inputStream.close() } else { result = JSONEntity() } return result! } } public extension JSONEntity { // this can be useful when deserializing elements directly into something like // Realm, which dies if it encounters null values func entityWithoutNullValues() throws -> JSONEntity { if let array = self.array() { let mutableArray = NSMutableArray(array: array) return JSONEntity(jsonArray: mutableArray) } else if let dictionary = self.dictionary() { let mutableDictionary = NSMutableDictionary(dictionary: dictionary) return JSONEntity(jsonDictionary: mutableDictionary) } throw JSONEntityError.invalidJSON } func removeNull(_ dictionary: NSMutableDictionary) { for key in dictionary.allKeys { let key = key as! String if let _ = dictionary[key] as? NSNull { dictionary.removeObject(forKey: key) } else if let arrayElement = dictionary[key] as? NSArray { let mutableArray = NSMutableArray(array: arrayElement) dictionary.setObject(mutableArray, forKey: key as NSCopying) self.removeNull(mutableArray) } else if let dictionaryElement = dictionary[key] as? NSDictionary { let mutableDictionary = NSMutableDictionary(dictionary: dictionaryElement) dictionary.setObject(mutableDictionary, forKey: key as NSCopying) self.removeNull(mutableDictionary) } } } func removeNull(_ array: NSMutableArray) { for element in array { if let dictionary = element as? NSDictionary { let mutableDictionary = NSMutableDictionary(dictionary: dictionary) array.replaceObject(at: array.index(of: dictionary), with: mutableDictionary) self.removeNull(mutableDictionary) } } } } public extension JSONEntity { func convertIfDate(_ datekeys: [String], formatter: DateFormatter) throws -> JSONEntity { if datekeys.contains(self.entity.key) { guard let value = self.entity.value as? String else {throw JSONEntityError.invalidValue} guard let date = formatter.date(from: value) else {throw JSONEntityError.invalidFormat} return JSONEntity(self.entity.key, date as AnyObject) } return self } } public struct JSONEntityGenerator: IteratorProtocol { public typealias Element = JSONEntity let entity: JSONEntity var sequenceIndex = 0 public init(_ entity: JSONEntity) { self.entity = entity } public mutating func next() -> Element? { if let array = self.entity.array() { if sequenceIndex < array.count { let result = JSONEntity(self.entity.entity.key, array[sequenceIndex] as AnyObject) sequenceIndex += 1 return result } else { sequenceIndex = 0 } } else if let dictionary = self.entity.dictionary() { if sequenceIndex < dictionary.count { let result = JSONEntity(dictionary.allKeys[sequenceIndex] as! String, dictionary.object(forKey: dictionary.allKeys[sequenceIndex])! as AnyObject) sequenceIndex += 1 return result } else { sequenceIndex = 0 } } return .none } } private class EntityConverter<T> { init() { } func get(_ entity: AnyObject, _ defaultValue: T? = nil) -> T? { if let someEntity: T = entity as? T { return someEntity } return defaultValue } }
b9e1e116cfff9452b2152f91b4fcbedb
29.21519
161
0.576979
false
false
false
false
narner/AudioKit
refs/heads/master
Examples/macOS/MIDIUtility/MIDIUtility/ViewController.swift
mit
1
// // ViewController.swift // MIDIUtility // // Created by Aurelius Prochazka and Jeff Cooper on 4/29/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import Cocoa class ViewController: NSViewController, AKMIDIListener { @IBOutlet private var outputTextView: NSTextView! @IBOutlet private var sourcePopUpButton: NSPopUpButton! var midi = AKMIDI() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. midi.openInput("Session 1") midi.addListener(self) sourcePopUpButton.removeAllItems() sourcePopUpButton.addItems(withTitles: midi.inputNames) } @IBAction func sourceChanged(_ sender: NSPopUpButton) { midi.closeAllInputs() midi.openInput(midi.inputNames[sender.indexOfSelectedItem]) } func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { updateText("Channel: \(channel + 1) noteOn: \(noteNumber) velocity: \(velocity) ") } func receivedMIDINoteOff(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { updateText("Channel: \(channel + 1) noteOff: \(noteNumber) velocity: \(velocity) ") } func receivedMIDIController(_ controller: MIDIByte, value: MIDIByte, channel: MIDIChannel) { updateText("Channel: \(channel + 1) controller: \(controller) value: \(value) ") } func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIWord, channel: MIDIChannel) { updateText("Pitch Wheel on Channel: \(channel + 1) value: \(pitchWheelValue) ") } func receivedMIDIAftertouch(noteNumber: MIDINoteNumber, pressure: MIDIByte, channel: MIDIChannel) { updateText("Channel: \(channel + 1) midiAftertouchOnNote: \(noteNumber) pressure: \(pressure) ") } func receivedMIDIAfterTouch(_ pressure: MIDIByte, channel: MIDIChannel) { updateText("Channel: \(channel + 1) midiAfterTouch pressure: \(pressure) ") } func receivedMIDIPitchWheel(_ pitchWheelValue: MIDIByte, channel: MIDIChannel) { updateText("Channel: \(channel + 1) midiPitchWheel: \(pitchWheelValue)") } func receivedMIDIProgramChange(_ program: MIDIByte, channel: MIDIChannel) { updateText("Channel: \(channel + 1) programChange: \(program)") } func receivedMIDISystemCommand(_ data: [MIDIByte]) { if let command = AKMIDISystemCommand(rawValue: data[0]) { var newString = "MIDI System Command: \(command) \n" for i in 0 ..< data.count { newString.append("\(data[i]) ") } updateText(newString) } } func updateText(_ input: String) { DispatchQueue.main.async(execute: { self.outputTextView.string = "\(input)\n\(self.outputTextView.string)" }) } @IBAction func clearText(_ sender: Any) { DispatchQueue.main.async(execute: { self.outputTextView.string = "" }) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
cdb10b1c104664b3bd73b419fd8f75e7
33.924731
104
0.643165
false
false
false
false
LYM-mg/MGDS_Swift
refs/heads/master
MGDS_Swift/MGDS_Swift/Class/Main/Controller/WKWebViewController.swift
mit
1
// // WKWebViewController.swift // ProductionReport // // Created by i-Techsys.com on 17/2/16. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import WebKit class WKWebViewController: UIViewController { // MARK: - lazy fileprivate lazy var webView: WKWebView = { [unowned self] in // 创建webveiew let webView = WKWebView(frame: self.view.bounds) webView.navigationDelegate = self webView.uiDelegate = self return webView }() fileprivate lazy var progressView: UIProgressView = { let progressView = UIProgressView(progressViewStyle: .bar) progressView.frame.size.width = self.view.frame.size.width // 这里可以改进度条颜色 progressView.tintColor = UIColor.green return progressView }() // MARK: - 生命周期 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) view.addSubview(webView) view.insertSubview(progressView, aboveSubview: webView) } convenience init(navigationTitle: String, urlStr: String) { self.init(nibName: nil, bundle: nil) navigationItem.title = navigationTitle webView.load(URLRequest(url: URL(string: urlStr)!)) } convenience init(navigationTitle: String, url: URL) { self.init(nibName: nil, bundle: nil) navigationItem.title = navigationTitle webView.load(URLRequest(url: url)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge() webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) } // MARK: - 导航栏 fileprivate func buildRightItemBarButton() { let backItem = UIBarButtonItem(image: #imageLiteral(resourceName: "goback"), title: "", target: self, action: #selector(backClick)) let closeItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(closeClick)) self.navigationItem.leftBarButtonItems = [backItem,closeItem] self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "v2_refresh"), style: .plain, target: self, action: #selector(self.refreshClick)) } // MARK: - Action @objc fileprivate func backClick() { if webView.canGoBack { webView.goBack() }else { self.navigationController?.popViewController(animated: true) } } @objc fileprivate func closeClick() { self.navigationController?.popViewController(animated: true) } // MARK: - Action @objc fileprivate func refreshClick() { if webView.url != nil && webView.url!.absoluteString.count > 1 { webView.reload() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "loading" { // print("loading") } else if keyPath == "title" { // title = self.webView.title } else if keyPath == "estimatedProgress" { print(webView.estimatedProgress) progressView.setProgress(Float(webView.estimatedProgress), animated: false) } self.progressView.isHidden = (self.progressView.progress == 1) if webView.isLoading == true { // 手动调用JS代码 let js = "callJsAlert()" webView.evaluateJavaScript(js, completionHandler: { (any, err) in debugPrint(any) }) } } // 移除观察者 deinit { webView.removeObserver(self, forKeyPath: "loading") webView.removeObserver(self, forKeyPath: "title") webView.removeObserver(self, forKeyPath: "estimatedProgress") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - WKScriptMessageHandler extension WKWebViewController: WKScriptMessageHandler { // WKScriptMessageHandler:必须实现的函数,是APP与js交互,提供从网页中收消息的回调方法 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.body) print(message.webView) } } // MARK: - WKNavigationDelegate extension WKWebViewController: WKNavigationDelegate { // 决定导航的动作,通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制,不允许跨域,因此我们要对不能跨域的链接 // 单独处理。但是,对于Safari是允许跨域的,不用这么处理。 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let hostname = (navigationAction.request as NSURLRequest).url?.host?.lowercased() print(hostname) print(navigationAction.navigationType) // 处理跨域问题 if navigationAction.navigationType == .linkActivated && hostname!.contains(".baidu.com") { // 手动跳转 UIApplication.shared.openURL(navigationAction.request.url!) // 不允许导航 decisionHandler(.cancel) } else { decisionHandler(.allow) } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print(#function) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { print(#function) decisionHandler(.allow) } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { print(#function) completionHandler(.performDefaultHandling, nil) } } // MARK: - WKUIDelegate extension WKWebViewController: WKUIDelegate { func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: "tip", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (_) -> Void in // We must call back js completionHandler() })) self.present(alert, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { completionHandler(true) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { completionHandler("woqu") } func webViewDidClose(_ webView: WKWebView) { print("close") } }
1e23b209a6c2bdb7c619df5d63392d0e
36.86911
201
0.661966
false
false
false
false
fanyu/EDCCharla
refs/heads/master
EDCChat/EDCChat/EDCChatMessageCell+Text.swift
mit
1
// // EDCChatMessageCellText.swift // EDCChat // // Created by FanYu on 15/12/2015. // Copyright © 2015 FanYu. All rights reserved. // import UIKit class EDCChatMessageCellText: EDCChatMessageCellBubble { private(set) lazy var emojiViews = [Int: EDCChatEmojiView]() private(set) lazy var contentLabel = EDCChatLabel(frame: CGRectZero) override var style: EDCChatMessageCellStyle { willSet { guard newValue != style else { return } switch newValue { case .Left: contentLabel.textColor = UIColor.blackColor() case .Right: contentLabel.textColor = UIColor.whiteColor() case .Unknow : break } } } override var message: EDCChatMessageProtocol? { didSet { guard let content = message?.content as? EDCChatMessageContentText else { return } self.contentLabel.text = content.text self.contentLabel.preferredMaxLayoutWidth = 0 } } override func systemLayoutSizeFittingSize(targetSize: CGSize) -> CGSize { self.contentLabel.preferredMaxLayoutWidth = 0 self.layoutIfNeeded() self.contentLabel.preferredMaxLayoutWidth = contentLabel.bounds.width return super.systemLayoutSizeFittingSize(targetSize) } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "chatCellCopy:" { return true } return super.canPerformAction(action, withSender: sender) } override func setup() { super.setup() let vs = ["c" : contentLabel] // config contentLabel.font = UIFont.systemFontOfSize(16) contentLabel.numberOfLines = 0 contentLabel.textColor = UIColor.blackColor() contentLabel.translatesAutoresizingMaskIntoConstraints = false // sub bubbleView.contentView.addSubview(contentLabel) // constraint contentView.addConstraints(NSLayoutConstraintMake("H:|-(8)-[c]-(8)-|", views: vs)) contentView.addConstraints(NSLayoutConstraintMake("V:|-(8)-[c]-(8)-|", views: vs)) // kvo EDCChatNotificationCenter.addObserver(self, selector: "textAttachmentChanged:", name: EDCChatTextAttachmentChangedNotification) } } // emoji extension EDCChatMessageCellText { private func makeEmojiViews() { guard let text = self.contentLabel.attributedText where self.enabled else { self.emojiViews.forEach { $0.1.removeFromSuperview() } self.emojiViews.removeAll() return } EDCLog.trace() // var temp = self.emojiViews.values.reverse() self.emojiViews.removeAll() text.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, text.length), options: .LongestEffectiveRangeNotRequired) { (at, r, s) -> Void in guard let at = at as? EDCChatEmojiView else { return } let v = temp.first ?? EDCChatEmojiView() if !temp.isEmpty { temp.removeFirst() } // config v.emoji = at.emoji v.backgroundColor = UIColor.orangeColor() v.hidden = true self.emojiViews[r.location] = v } // 删除 temp.forEach { $0.removeFromSuperview() } // 添加 self.emojiViews.forEach { self.contentLabel.addSubview($0.1) } } } extension EDCChatMessageCellText { private dynamic func textAttachmentChanged(sender: NSNotification) { guard let at = sender.object as? EDCChatEmojiView where self.enabled else { return } guard let text = self.contentLabel.attributedText where text.length != 0 else { return } guard let index = sender.userInfo?[EDCChatTextAttachmentCharIndexUserInfoKey] as? Int else { return } guard let frame = sender.userInfo?[EDCChatTextAttachmentFrameUserInfoKey]?.CGRectValue else { return } guard text.attribute(NSAttachmentAttributeName, atIndex: index, effectiveRange: nil) === at else { return } // 调整emoji的内容 if let v = self.emojiViews[index] { v.frame = CGRectMake(frame.origin.x, frame.origin.y - frame.size.height, frame.size.width, frame.size.height) v.hidden = false } EDCLog.debug(at) } // copy dynamic func chatCellCopy(sender: AnyObject) { EDCLog.trace() if let ctx = message?.content as? EDCChatMessageContentText { // 复制进去:) UIPasteboard.generalPasteboard().string = ctx.text // 完成 self.delegate?.chatCellDidCpoy?(self) } } }
44bff83908e2bd6e683632f412540481
29.60241
164
0.585236
false
false
false
false
mrchenhao/ViewFaster
refs/heads/master
ViewFaster/ViewFaster.swift
mit
1
// // ViewFaster.swift // ViewFaster // // Created by ChenHao on 5/23/16. // Copyright © 2016 HarriesChen. All rights reserved. // import Foundation import SpriteKit open class ViewFaster: NSObject { open static var shareInstance: ViewFaster = ViewFaster() static let kFPSLabelWidth = 60 static let kHardwareFramesPerSecond = 60 var lastSecondOfFrameTimes = [CFTimeInterval]() var frameNumber = 0 open var isEnabled: Bool = false { didSet { if isEnabled { enableFPS() } else { disableFPS() } } } var isRunning: Bool = false { didSet { if isRunning { start() } else { stop() } } } override init() { for _ in 0...ViewFaster.kHardwareFramesPerSecond { lastSecondOfFrameTimes.append(CACurrentMediaTime()) } } lazy var window: UIWindow = { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = UIViewController() window.windowLevel = UIWindowLevelStatusBar + 10.0 window.isUserInteractionEnabled = false return window }() lazy var FPSLabel: UILabel = { let label = UILabel(frame: CGRect(x: 0, y: 0, width: kFPSLabelWidth, height: 20)) label.backgroundColor = UIColor.red label.textAlignment = .center return label }() func enableFPS() { window.addSubview(FPSLabel) window.isHidden = false isRunning = true } func disableFPS() { FPSLabel.removeFromSuperview() window.isHidden = true isRunning = false } lazy var displayLink: CADisplayLink = { let displayLink = CADisplayLink(target: self, selector: #selector(displayLinkWillDraw)) return displayLink }() lazy var sceneView: SKView = { let sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 10, height: 1)) return sceneView }() func displayLinkWillDraw() { let currentFrameTime = displayLink.timestamp recordFrameTime(currentFrameTime) updateFPSLabel() } func lastFrameTime() -> CFTimeInterval { if frameNumber <= ViewFaster.kHardwareFramesPerSecond { return lastSecondOfFrameTimes[self.frameNumber] } else { return CACurrentMediaTime() } } func recordFrameTime(_ timeInterval: CFTimeInterval) { frameNumber += 1 lastSecondOfFrameTimes[frameNumber % ViewFaster.kHardwareFramesPerSecond] = timeInterval } func updateFPSLabel() { let fps = ViewFaster.kHardwareFramesPerSecond - droppedFrameCountInLastSecond() if fps >= 56 { FPSLabel.backgroundColor = UIColor.green } else if fps >= 45 { FPSLabel.backgroundColor = UIColor.orange } else { FPSLabel.backgroundColor = UIColor.red } FPSLabel.text = "\(fps)" } func start() { self.displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) clearLastSecondOfFrameTimes() let scene = SKScene() sceneView.presentScene(scene) UIApplication.shared.keyWindow?.addSubview(sceneView) } func stop() { sceneView.removeFromSuperview() self.displayLink.invalidate() } func clearLastSecondOfFrameTimes() { } func droppedFrameCountInLastSecond() -> Int { var droppedFrameCount = 0 let kNormalFrameDuration = 1.0 / Double(ViewFaster.kHardwareFramesPerSecond) let lastFrameTime = CACurrentMediaTime() - kNormalFrameDuration for i in 0..<ViewFaster.kHardwareFramesPerSecond { if 1.0 <= lastFrameTime - lastSecondOfFrameTimes[i] { droppedFrameCount += 1 } } return droppedFrameCount } }
db4069a93ad931c4df06bf40d80a81ad
25.635135
96
0.60756
false
false
false
false
MBKwon/TestAppStore
refs/heads/master
TestAppStore/TestAppStore/AppScreanImages.swift
mit
1
// // AppScreanImages.swift // TestAppStore // // Created by Moonbeom KWON on 2017. 4. 17.. // Copyright © 2017년 Kyle. All rights reserved. // import Foundation import UIKit import ImageSlideshow import AlamofireImage class AppScreanImages: UITableViewCell { var imageSlide: ImageSlideshow? var superViewController: UIViewController? func setInfo(_ itemInfo: AppDetailModel?) { guard let imageArray = itemInfo?.screenshotUrls?.map({ (imageUrl) -> AlamofireSource in return AlamofireSource(urlString: imageUrl)! }) else { return } imageSlide?.setImageInputs(imageArray) } } extension AppScreanImages { override func layoutSubviews() { super.layoutSubviews() if imageSlide == nil { imageSlide = ImageSlideshow(frame: self.bounds) self.contentView.addSubview(imageSlide!) let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didTap)) imageSlide?.addGestureRecognizer(gestureRecognizer) } } func didTap() { imageSlide?.presentFullScreenController(from: superViewController!) } }
6b4bbf5b46a2e32f49b8a8b6c307d707
24.854167
104
0.64303
false
false
false
false
NobodyNada/SwiftChatSE
refs/heads/master
Sources/SwiftChatSE/Row.swift
mit
1
// // Row.swift // SwiftChatSE // // Created by NobodyNada on 5/8/17. // // import Foundation #if os(Linux) import CSQLite #else import SQLite3 #endif open class Row { ///The columns of this row. public let columns: [DatabaseNativeType?] ///A Dictionary mapping the names of this row's columns to their indices in `columns`. public let columnNames: [String:Int] ///Initializes a Row with the results of a prepared statement. public init(statement: OpaquePointer) { var columns = [DatabaseNativeType?]() var columnNames = [String:Int]() for i in 0..<sqlite3_column_count(statement) { let value: DatabaseNativeType? let type = sqlite3_column_type(statement, i) switch type { case SQLITE_INTEGER: value = sqlite3_column_int64(statement, i) case SQLITE_FLOAT: value = sqlite3_column_double(statement, i) case SQLITE_TEXT: value = String(cString: sqlite3_column_text(statement, i)) case SQLITE_BLOB: let bytes = sqlite3_column_bytes(statement, i) if bytes == 0 { value = Data() } else { value = Data(bytes: sqlite3_column_blob(statement, i), count: Int(bytes)) } case SQLITE_NULL: value = nil default: fatalError("unrecognized SQLite type \(type)") } columns.append(value) columnNames[String(cString: sqlite3_column_name(statement, i))] = Int(i) } self.columns = columns self.columnNames = columnNames } ///Initializes a Row with the specified columns. public init(columns: [DatabaseNativeType?], columnNames: [String:Int]) { self.columns = columns self.columnNames = columnNames } //MARK: - Convenience functions for accessing columns ///Returns the contents of the column at the specified index. /// ///- parameter index: The index of the column to return. ///- parameter type: The type of the column to return. Will be inferred by the compiler /// if not specified. Must conform to `DatabaseType`. /// ///- returns: The contents of the column, or `nil` if the contents are `NULL`. /// ///- warning: Will crash if the index is out of range or the column has an incompatible type. open func column<T: DatabaseType>(at index: Int, type: T.Type = T.self) -> T? { guard let value = columns[index] else { return nil } guard let converted = T.from(native: value) else { fatalError("column \(index) has an incompatible type ('\(Swift.type(of: value))' could not be converted to '\(type)')") } return converted } ///Returns the contents of the column with the specified name. /// ///- parameter name: The name of the column to return. ///- parameter type: The type of the column to return. Will be inferred by the compiler /// if not specified. Must conform to `DatabaseType`. /// ///- returns: The contents of the column. /// ///- warning: Will crash if the name does not exist or the column has an incompatible type. open func column<T: DatabaseType>(named name: String, type: T.Type = T.self) -> T? { guard let index = columnNames[name] else { fatalError("column '\(name)' not found in \(Array(columnNames.keys))") } return column(at: index) } }
11542f1d27176b1b96beea71da1f70c2
30.284314
122
0.669696
false
false
false
false
SeaHub/ImgTagging
refs/heads/master
ImgMaster/ImgMaster/PhotoGalleryViewController.swift
gpl-3.0
1
// // PhotoGalleryViewController.swift // ImgMaster // // Created by SeaHub on 2017/6/27. // Copyright © 2017年 SeaCluster. All rights reserved. // import UIKit import Kingfisher import PopupDialog import NVActivityIndicatorView class PhotoGalleryViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var maskView: UIView! fileprivate var photos: [Image] = [] fileprivate var imageList: ImageList? = nil fileprivate var style: PhotoTagsViewControllerStyle = .tags private let indicator = NVActivityIndicatorView(frame: CGRect(x: 100, y: 100, width: 200, height: 100), type: .orbit, color: .white, padding: 0) lazy var sizes: [CGSize] = { return (0 ..< self.photos.count).map { _ in return CGSize(width: floor((UIScreen.main.bounds.width - (4 * 10)) / 3), height: floor((UIScreen.main.bounds.width - (4 * 10)) / 3)) } }() override func viewDidLoad() { super.viewDidLoad() self.configureIndicator() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.fetchData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func fetchData() { self.indicatorStartAnimating() APIManager.getImageList(token: ImgMasterUtil.userToken!, currentPage: "1", perPage: "99999", success: { (imageList) in self.indicatorStopAnimating() self.imageList = imageList self.photos = imageList.images self.collectionView.reloadData() }) { (error) in debugPrint(error) self.indicatorStopAnimating() self.showErrorAlert() } } fileprivate func showErrorAlert() { let alert = PopupDialog(title: "Tips", message: "An error occured, please retry later!", image: nil) let cancelButton = CancelButton(title: "OK") { } alert.addButtons([cancelButton]) self.present(alert, animated: true, completion: nil) } fileprivate func indicatorStartAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0.5 } } fileprivate func indicatorStopAnimating() { UIView.animate(withDuration: 0.5) { self.maskView.alpha = 0 self.indicator.stopAnimating() } } fileprivate func configureIndicator() { self.indicator.center = CGPoint(x: self.view.bounds.width / 2, y: self.view.bounds.height / 2) self.maskView.addSubview(self.indicator) self.indicator.startAnimating() } @IBAction func refreshButtonClicked(_ sender: Any) { self.fetchData() self.collectionView.scrollToItem(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == ConstantStoryboardSegue.kShowPhotoTagControllerSegue { let dvc = segue.destination as! PhotoTagsViewController dvc.photo = sender! as! Image dvc.style = self.style } } } extension PhotoGalleryViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ConstantUICollectionCellIdentifier.kCollectionImageViewCellIdentifier, for: indexPath) as! CollectionImageViewCell if let imageURLString = self.photos[indexPath.row].url { let httpURL = "http://\(imageURLString)?imageView2/1/w/50/h/50" let url = URL(string: httpURL) _ = cell.imageView.kf.setImage(with: url, placeholder: nil, options: [.transition(ImageTransition.fade(1))], progressBlock: nil, completionHandler: nil) } return cell } } extension PhotoGalleryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { debugPrint(indexPath) APIManager.doStatistics(token: ImgMasterUtil.userToken!, imageID: self.photos[indexPath.row].imageID, success: { let alert = PopupDialog(title: "Tips", message: "What do you want to do?", image: nil) let seeCurrentTagsButton = DefaultButton(title: "See current tags") { self.style = .tags self.performSegue(withIdentifier: ConstantStoryboardSegue.kShowPhotoTagControllerSegue, sender: self.photos[indexPath.row]) } let seeResultButton = DefaultButton(title: "See result") { self.style = .result self.performSegue(withIdentifier: ConstantStoryboardSegue.kShowPhotoTagControllerSegue, sender: self.photos[indexPath.row]) } let cancelButton = CancelButton(title: "CANCEL") { } alert.addButtons([seeCurrentTagsButton, seeResultButton, cancelButton]) self.present(alert, animated: true, completion: nil) }) { (error) in debugPrint(error) self.indicatorStopAnimating() self.showErrorAlert() } } } extension PhotoGalleryViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return sizes[indexPath.row] } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } }
b6fe3a476b90fa435e607de5883f8b26
39.158537
189
0.623444
false
false
false
false
bgerstle/HomeFries
refs/heads/master
Pods/Nimble/Nimble/Expectation.swift
mit
1
import Foundation public struct Expectation<T> { let expression: Expression<T> public func verify(pass: Bool, _ message: String) { NimbleAssertionHandler.assert(pass, message: message, location: expression.location) } public func to<U where U: Matcher, U.ValueType == T>(matcher: U) { var msg = FailureMessage() let pass = matcher.matches(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(expression.evaluate()))>" } verify(pass, msg.stringValue()) } public func toNot<U where U: Matcher, U.ValueType == T>(matcher: U) { var msg = FailureMessage() let pass = matcher.doesNotMatch(expression, failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(expression.evaluate()))>" } verify(pass, msg.stringValue()) } public func notTo<U where U: Matcher, U.ValueType == T>(matcher: U) { toNot(matcher) } // see: // - BasicMatcherWrapper for extension // - AsyncMatcherWrapper for extension // - NonNilMatcherWrapper for extension // // - NMBExpectation for Objective-C interface }
7a649a8d9f793284d9033b144e7b260b
31.263158
92
0.621533
false
false
false
false
blinksh/blink
refs/heads/raw
Blink/SmarterKeys/KBKeyShape.swift
gpl-3.0
1
//////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation enum KBKeyShape: Hashable { // Compact sized button case icon(value: KBKeyValue) // Standart sized button case key(value: KBKeyValue) case wideKey(value: KBKeyValue) case flexKey(value: KBKeyValue) // Standart sized button with two values case vertical2(a: KBKeyValue, b: KBKeyValue) case arrows init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let value: KBKeyValue = try container.decodeIfPresent(KBKeyValue.self, forKey: .icon) { self = .icon(value: value) return } if let value: KBKeyValue = try container.decodeIfPresent(KBKeyValue.self, forKey: .key) { self = .key(value: value) return } if let value: KBKeyValue = try container.decodeIfPresent(KBKeyValue.self, forKey: .wideKey) { self = .wideKey(value: value) return } if container.contains(.arrows) { self = .arrows return } if let values = try container.decodeIfPresent([KBKeyValue].self, forKey: .vertical2), values.count == 2 { self = .vertical2(a: values[0], b: values[1]) return } throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "Hmm")) } } extension KBKeyShape: Identifiable { var id: String { switch self { case .icon(let value): return "icon.\(value.id)" case .key(let value): return "key.\(value.id)" case .wideKey(let value): return "wideKey.\(value.id)" case .flexKey(let value): return "flexKey.\(value.id)" case .vertical2(let a, let b): return "vertical2.\(a.id),\(b.id)" case .arrows: return "arrows" } } } extension KBKeyShape { var primaryValue: KBKeyValue { switch self { case .icon(let value): return value case .key(let value): return value case .wideKey(let value): return value case .flexKey(let value): return value case .vertical2(let a, _): return a case .arrows: return .up } } var secondaryValue: KBKeyValue? { switch self { case .vertical2(_, let b): return b default: return nil } } var primaryText: String { primaryValue.text } var secondaryText: String? { switch self { case .vertical2(_, let b): return b.text default: return nil } } } extension KBKeyShape { enum CodingKeys: CodingKey { case icon case key case wideKey case flexKey case vertical2 case triangle case arrows } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .icon(let value): try container.encode(value, forKey: .icon) case .key(let value): try container.encode(value, forKey: .key) case .wideKey(let value): try container.encode(value, forKey: .wideKey) case .flexKey(let value): try container.encode(value, forKey: .flexKey) case .vertical2(let a, let b): try container.encode([a, b], forKey: .vertical2) case .arrows: try container.encode(true, forKey: .arrows) } } }
26ac42176b178348377af3e55b7c7b5c
27.185897
101
0.641574
false
false
false
false
yonat/MultiSlider
refs/heads/master
Sources/MultiSlider+Internal.swift
mit
1
// // MultiSlider+Internal.swift // MultiSlider // // Created by Yonat Sharon on 21/06/2019. // import UIKit extension MultiSlider { func setup() { trackView.backgroundColor = actualTintColor updateTrackViewCornerRounding() slideView.layoutMargins = .zero setupOrientation() setupPanGesture() isAccessibilityElement = true accessibilityIdentifier = "multi_slider" accessibilityLabel = "slider" accessibilityTraits = [.adjustable] minimumView.isHidden = true maximumView.isHidden = true if #available(iOS 11.0, *) { valueLabelFormatter.addObserverForAllProperties(observer: self) } } private func setupPanGesture() { addConstrainedSubview(panGestureView) for edge: NSLayoutConstraint.Attribute in [.top, .bottom, .left, .right] { constrain(panGestureView, at: edge, diff: -edge.inwardSign * margin) } let panGesture = UIPanGestureRecognizer(target: self, action: #selector(didDrag(_:))) panGesture.delegate = self panGestureView.addGestureRecognizer(panGesture) } func setupOrientation() { trackView.removeFromSuperview() trackView.removeConstraints(trackView.constraints) slideView.removeFromSuperview() minimumView.removeFromSuperview() maximumView.removeFromSuperview() switch orientation { case .vertical: let centerAttribute: NSLayoutConstraint.Attribute if #available(iOS 12, *) { centerAttribute = .centerX // iOS 12 doesn't like .topMargin, .rightMargin } else { centerAttribute = .centerXWithinMargins } addConstrainedSubview(trackView, constrain: .top, .bottom, centerAttribute) trackView.constrain(.width, to: trackWidth) trackView.addConstrainedSubview(slideView, constrain: .left, .right) constrainVerticalTrackViewToLayoutMargins() addConstrainedSubview(minimumView, constrain: .bottomMargin, centerAttribute) addConstrainedSubview(maximumView, constrain: .topMargin, centerAttribute) default: let centerAttribute: NSLayoutConstraint.Attribute if #available(iOS 12, *) { centerAttribute = .centerY // iOS 12 doesn't like .leftMargin, .rightMargin } else { centerAttribute = .centerYWithinMargins } addConstrainedSubview(trackView, constrain: .left, .right, centerAttribute) trackView.constrain(.height, to: trackWidth) trackView.addConstrainedSubview(slideView, constrain: .top, .bottom) constrainHorizontalTrackViewToLayoutMargins() addConstrainedSubview(minimumView, constrain: .leftMargin, centerAttribute) addConstrainedSubview(maximumView, constrain: .rightMargin, centerAttribute) } setupTrackLayoutMargins() } func setupTrackLayoutMargins() { let thumbSize = (thumbImage ?? defaultThumbImage)?.size ?? CGSize(width: 2, height: 2) let thumbDiameter = orientation == .vertical ? thumbSize.height : thumbSize.width let halfThumb = thumbDiameter / 2 - 1 // 1 pixel for semi-transparent boundary if orientation == .vertical { trackView.layoutMargins = UIEdgeInsets(top: halfThumb, left: 0, bottom: halfThumb, right: 0) constrain(.width, to: max(thumbSize.width, trackWidth), relation: .greaterThanOrEqual) } else { trackView.layoutMargins = UIEdgeInsets(top: 0, left: halfThumb, bottom: 0, right: halfThumb) constrainHorizontalTrackViewToLayoutMargins() constrain(.height, to: max(thumbSize.height, trackWidth), relation: .greaterThanOrEqual) } } /// workaround to a problem in iOS 12-13, of constraining to `leftMargin` and `rightMargin`. func constrainHorizontalTrackViewToLayoutMargins() { trackView.constrain(slideView, at: .left, diff: trackView.layoutMargins.left) trackView.constrain(slideView, at: .right, diff: -trackView.layoutMargins.right) } /// workaround to a problem in iOS 12-13, of constraining to `topMargin` and `bottomMargin`. func constrainVerticalTrackViewToLayoutMargins() { trackView.constrain(slideView, at: .top, diff: trackView.layoutMargins.top) trackView.constrain(slideView, at: .bottom, diff: -trackView.layoutMargins.bottom) } func repositionThumbViews() { thumbViews.forEach { $0.removeFromSuperview() } thumbViews = [] valueLabels.forEach { $0.removeFromSuperview() } valueLabels = [] adjustThumbCountToValueCount() } func adjustThumbCountToValueCount() { if value.count == thumbViews.count { return } else if value.count < thumbViews.count { thumbViews.removeViewsStartingAt(value.count) valueLabels.removeViewsStartingAt(value.count) } else { // add thumbViews for _ in thumbViews.count ..< value.count { addThumbView() } } updateOuterTrackViews() } func updateOuterTrackViews() { outerTrackViews.removeViewsStartingAt(0) outerTrackViews.removeAll() guard nil != outerTrackColor else { return } guard let lastThumb = thumbViews.last else { return } outerTrackViews = [outerTrackView(constraining: .bottom(in: orientation), to: lastThumb)] guard let firstThumb = thumbViews.first, firstThumb != lastThumb else { return } outerTrackViews += [outerTrackView(constraining: .top(in: orientation), to: firstThumb)] } private func outerTrackView(constraining: NSLayoutConstraint.Attribute, to thumbView: UIView) -> UIView { let view = UIView() view.backgroundColor = outerTrackColor trackView.addConstrainedSubview(view, constrain: .top, .bottom, .left, .right) trackView.removeFirstConstraint { $0.firstItem === view && $0.firstAttribute == constraining } trackView.constrain(view, at: constraining, to: thumbView, at: .center(in: orientation)) trackView.sendSubviewToBack(view) view.layer.cornerRadius = trackView.layer.cornerRadius if #available(iOS 11.0, *) { view.layer.maskedCorners = .direction(constraining.opposite) } return view } private func addThumbView() { let i = thumbViews.count let thumbView = UIImageView(image: thumbImage ?? defaultThumbImage) thumbView.applyTint(color: thumbTintColor) thumbView.addShadow() thumbViews.append(thumbView) slideView.addConstrainedSubview(thumbView, constrain: NSLayoutConstraint.Attribute.center(in: orientation).perpendicularCenter) positionThumbView(i) thumbView.blur(disabledThumbIndices.contains(i)) addValueLabel(i) updateThumbViewShadowVisibility() } func updateThumbViewShadowVisibility() { thumbViews.forEach { $0.layer.shadowOpacity = showsThumbImageShadow ? 0.25 : 0 } } func addValueLabel(_ i: Int) { guard valueLabelPosition != .notAnAttribute else { return } let valueLabel = UITextField() valueLabel.borderStyle = .none slideView.addConstrainedSubview(valueLabel) valueLabel.textColor = valueLabelColor ?? valueLabel.textColor valueLabel.font = valueLabelFont ?? UIFont.preferredFont(forTextStyle: .footnote) if #available(iOS 10.0, *) { valueLabel.adjustsFontForContentSizeCategory = true } let thumbView = thumbViews[i] slideView.constrain(valueLabel, at: valueLabelPosition.perpendicularCenter, to: thumbView) slideView.constrain( valueLabel, at: valueLabelPosition.opposite, to: thumbView, at: valueLabelPosition, diff: -valueLabelPosition.inwardSign * thumbView.diagonalSize / 4 ) valueLabels.append(valueLabel) updateValueLabel(i) } func updateValueLabel(_ i: Int) { let labelValue: CGFloat if isValueLabelRelative { labelValue = i > 0 ? value[i] - value[i - 1] : value[i] - minimumValue } else { labelValue = value[i] } valueLabels[i].text = valueLabelTextForThumb?(i, labelValue) ?? valueLabelFormatter.string(from: NSNumber(value: Double(labelValue))) } func updateAllValueLabels() { for i in 0 ..< valueLabels.count { updateValueLabel(i) } } func updateValueCount(_ count: Int) { guard count != value.count else { return } isSettingValue = true if value.count < count { let appendCount = count - value.count var startValue = value.last ?? minimumValue let length = maximumValue - startValue let relativeStepSize = snapStepSize / (maximumValue - minimumValue) var step: CGFloat = 0 if value.isEmpty && 1 < appendCount { step = (length / CGFloat(appendCount - 1)).truncated(relativeStepSize) } else { step = (length / CGFloat(appendCount)).truncated(relativeStepSize) if !value.isEmpty { startValue += step } } if 0 == step { step = relativeStepSize } value += stride(from: startValue, through: maximumValue, by: step) } if value.count > count { // don't add "else", since prev calc may add too many values in some cases value.removeLast(value.count - count) } isSettingValue = false } func adjustValuesToStepAndLimits() { var adjusted = value.sorted() for i in 0 ..< adjusted.count { let snapped = adjusted[i].rounded(snapStepSize) adjusted[i] = min(maximumValue, max(minimumValue, snapped)) } isSettingValue = true value = adjusted isSettingValue = false for i in 0 ..< value.count { positionThumbView(i) } } func positionThumbView(_ i: Int) { let thumbView = thumbViews[i] let thumbValue = value[i] slideView.removeFirstConstraint { $0.firstItem === thumbView && $0.firstAttribute == .center(in: orientation) } let thumbRelativeDistanceToMax = (maximumValue - thumbValue) / (maximumValue - minimumValue) if orientation == .horizontal { if thumbRelativeDistanceToMax < 1 { slideView.constrain(thumbView, at: .centerX, to: slideView, at: .right, ratio: CGFloat(1 - thumbRelativeDistanceToMax)) } else { slideView.constrain(thumbView, at: .centerX, to: slideView, at: .left) } } else { // vertical orientation if thumbRelativeDistanceToMax.isNormal { slideView.constrain(thumbView, at: .centerY, to: slideView, at: .bottom, ratio: CGFloat(thumbRelativeDistanceToMax)) } else { slideView.constrain(thumbView, at: .centerY, to: slideView, at: .top) } } UIView.animate(withDuration: 0.1) { self.slideView.updateConstraintsIfNeeded() } } func layoutTrackEdge(toView: UIImageView, edge: NSLayoutConstraint.Attribute, superviewEdge: NSLayoutConstraint.Attribute) { removeFirstConstraint { $0.firstItem === self.trackView && ($0.firstAttribute == edge || $0.firstAttribute == superviewEdge) } if nil != toView.image { constrain(trackView, at: edge, to: toView, at: edge.opposite, diff: edge.inwardSign * 8) } else { constrain(trackView, at: edge, to: self, at: superviewEdge) } } func updateTrackViewCornerRounding() { trackView.layer.cornerRadius = hasRoundTrackEnds ? trackWidth / 2 : 1 outerTrackViews.forEach { $0.layer.cornerRadius = trackView.layer.cornerRadius } } }
6d2ec57936458434a215fc5e0cf07c35
41.100694
135
0.639175
false
false
false
false
phimage/SLF4Swift
refs/heads/master
Backend/XCGLogger/XCGLogger.swift
mit
1
// // XCGLogger.swift // SLF4Swift /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation #if EXTERNAL import SLF4Swift #endif import XCGLogger open class XCGLoggerSLF: LoggerType { open class var instance = XCGLoggerSLF(logger: XCGLogger.defaultInstance()) open var level: SLFLogLevel { get { return XCGLoggerSLF.toLevel(self.logger.outputLogLevel) } set { self.logger.outputLogLevel = XCGLoggerSLF.fromLevel(newValue) } } open var name: LoggerKeyType { return self.logger.identifier } open var logger: XCGLogger public init(logger: XCGLogger) { self.logger = logger } open func info(_ message: LogMessageType) { self.logger.info(message) } open func error(_ message: LogMessageType) { self.logger.error(message) } open func severe(_ message: LogMessageType) { self.logger.severe(message) } open func warn(_ message: LogMessageType) { self.logger.warning(message) } open func debug(_ message: LogMessageType) { self.logger.debug(message) } open func verbose(_ message: LogMessageType) { self.logger.verbose(message) } open func log(_ level: SLFLogLevel,_ message: LogMessageType) { self.logger.logln(XCGLoggerSLF.fromLevel(level), closure: {message}) } open func isLoggable(_ level: SLFLogLevel) -> Bool { return level <= self.level } open static func toLevel(_ level:XCGLogger.LogLevel) -> SLFLogLevel { switch(level){ case .None: return SLFLogLevel.Off case .Severe: return SLFLogLevel.Severe case .Error: return SLFLogLevel.Error case .Warning: return SLFLogLevel.Warn case .Info: return SLFLogLevel.Info case .Debug: return SLFLogLevel.Debug case .Verbose: return SLFLogLevel.Verbose } } open static func fromLevel(_ level:SLFLogLevel) -> XCGLogger.LogLevel { switch(level){ case .Off: return XCGLogger.LogLevel.None case .Severe: return XCGLogger.LogLevel.Severe case .Error: return XCGLogger.LogLevel.Error case .Warn: return XCGLogger.LogLevel.Warning case .Info: return XCGLogger.LogLevel.Info case .Debug: return XCGLogger.LogLevel.Debug case .Verbose: return XCGLogger.LogLevel.Verbose case .All: return XCGLogger.LogLevel.Verbose } } } open class XCGLoggerSLFFactory: SLFLoggerFactory { open class var instance = XCGLoggerSLFFactory() public override init(){ super.init() } open override func doCreateLogger(_ name: LoggerKeyType) -> LoggerType { let logger = XCGLogger() logger.identifier = name return XCGLoggerSLF(logger: logger) } }
294c0a26acee69be1764605b772250a5
30.491935
79
0.686812
false
false
false
false
noahprince22/bardar
refs/heads/master
Bardar/AppDelegate.swift
mit
1
// // AppDelegate.swift // Bardar // // Created by Noah Prince on 6/1/16. // Copyright © 2016 Noah Prince. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.Bardar" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Bardar", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
bc21dc895c717b18a549d79acf618131
53.72973
291
0.718848
false
false
false
false
ifeherva/HSTracker
refs/heads/master
HSTracker/UIs/Trackers/OverWindowController.swift
mit
2
// // OverWindowController.swift // HSTracker // // Created by Benjamin Michotte on 19/10/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import Cocoa class OverWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() self.window!.backgroundColor = NSColor.clear self.window!.isOpaque = false self.window!.hasShadow = false self.window!.acceptsMouseMovedEvents = true if let panel = self.window as? NSPanel { panel.isFloatingPanel = true } } func setWindowSizes() { var width: Double switch Settings.cardSize { case .tiny: width = kTinyFrameWidth case .small: width = kSmallFrameWidth case .medium: width = kMediumFrameWidth case .huge: width = kHighRowFrameWidth case .big: width = kFrameWidth } guard let window = self.window else { return } window.contentMinSize = NSSize(width: CGFloat(width), height: 400) window.contentMaxSize = NSSize(width: CGFloat(width), height: NSScreen.main!.frame.height) } /** Updates the UI based on stored data. This method should only be called from the main thread */ func updateFrames() { // update gui elements based on internal data } }
a004f8ec56b33a9822cf66b01f469851
27.857143
99
0.623762
false
false
false
false
congncif/SiFUtilities
refs/heads/master
Example/SiFUtilities/AppDelegate.swift
mit
1
// // AppDelegate.swift // SiFUtilities // // Created by NGUYEN CHI CONG on 05/29/2016. // Copyright (c) 2016 NGUYEN CHI CONG. All rights reserved. // import SiFUtilities import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let debouncer: Debouncer? = Debouncer(delay: .seconds(2)) { print("XX") } private var timerDebouncer: TimerDebouncer? = TimerDebouncer(delay: .seconds(2)) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { DispatchQueue.global().asyncAfter(deadline: .now() + 1) { self.debouncer?.perform() } DispatchQueue.global().asyncAfter(deadline: .now() + 2) { self.debouncer?.perform() } DispatchQueue.global().asyncAfter(deadline: .now() + 4.1) { self.debouncer?.perform() } timerDebouncer?.performNow() DispatchQueue.global().asyncAfter(deadline: .now() + 7) { self.timerDebouncer = nil } let dict = ["abc": "abc", "def": "def"] let newDict = dict.mapping(key: "abc", to: "ABC") print(newDict) return true } func applicationDidBecomeActive(_ application: UIApplication) {} func applicationDidEnterBackground(_ application: UIApplication) {} }
826e8c26152f884fd1dd150c1e1ef695
28.6875
151
0.639298
false
false
false
false
mohssenfathi/MTLImage
refs/heads/master
Example-iOS/Example-iOS/ViewControllers/Filters/FiltersViewController.swift
mit
1
// // FiltersViewController.swift // MTLImage // // Created by Mohssen Fathi on 4/2/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import MTLImage protocol FiltersViewControllerDelegate { func filtersViewControllerDidSelectFilter(_ sender: FiltersViewController, filter: MTLObject) func filtersViewControllerDidSelectFilterGroup(_ sender: FiltersViewController, filterGroup: MTLObject) func filtersViewControllerBackButtonPressed(_ sender: FiltersViewController) } class FiltersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var editButton: UIBarButtonItem! var settingsViewController: SettingsViewController? var filterGroupViewController: FilterGroupViewController? var selectedFilter: MTLObject! var delegate: FiltersViewControllerDelegate? var filterNames = MTLImage.filters.sorted() var savedFilterGroups: [FilterGroup]! var filterGroup: FilterGroup! var newFilterSeleced: Bool! override func viewDidLoad() { super.viewDidLoad() navigationController?.delegate = self navigationController?.interactivePopGestureRecognizer?.isEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadSavedFilters() editButton.isEnabled = savedFilterGroups.count > 0 tableView.reloadData() } func loadSavedFilters() { savedFilterGroups = MTLImage.savedFilterGroups() // let path = NSBundle.mainBundle().pathForResource("Retro", ofType: "") // let data = NSData(contentsOfFile: path!) // let filterGroup = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! FilterGroup // savedFilterGroups.append(filterGroup) } func handleTouchAtLocation(_ location: CGPoint) { settingsViewController?.handleTouchAtLocation(location) filterGroupViewController?.handleTouchAtLocation(location) } @IBAction func editButtonPressed(_ sender: UIBarButtonItem) { let edit = !tableView.isEditing sender.title = edit ? "Done" : "Edit" tableView.setEditing(edit, animated: true) } // MARK: - UINavigationController Delegate func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController == navigationController.viewControllers.first { delegate?.filtersViewControllerBackButtonPressed(self) } } // MARK: - UITableView // MARK: DataSource func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return savedFilterGroups.count + 1 } return filterNames.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Saved Filters" : "Single Filters" } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell if (indexPath as NSIndexPath).section == 0 { if indexPath.row == savedFilterGroups.count { cell = tableView.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) } else { cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = savedFilterGroups[indexPath.row].title } } else { cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = filterNames[indexPath.row] } return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if (indexPath as NSIndexPath).section == 0 && indexPath.row != savedFilterGroups.count { return true } return false } // MARK: Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if (indexPath as NSIndexPath).section == 0 { if indexPath.row == savedFilterGroups.count { filterGroup = FilterGroup() newFilterSeleced = true } else { filterGroup = savedFilterGroups[indexPath.row] filterGroup.needsUpdate = true newFilterSeleced = false } delegate?.filtersViewControllerDidSelectFilterGroup(self, filterGroup: filterGroup) performSegue(withIdentifier: "filterGroup", sender: self) } else { let title = filterNames[indexPath.row] let object = try! MTLImage.filter(title) if object is Filter { selectedFilter = object as! Filter delegate?.filtersViewControllerDidSelectFilter(self, filter: selectedFilter) self.performSegue(withIdentifier: "settings", sender: self) } else if object is FilterGroup { selectedFilter = object as! FilterGroup delegate?.filtersViewControllerDidSelectFilterGroup(self, filterGroup: selectedFilter) performSegue(withIdentifier: "filterGroup", sender: self) } else { selectedFilter = object delegate?.filtersViewControllerDidSelectFilter(self, filter: selectedFilter) performSegue(withIdentifier: "settings", sender: self) } } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let filterGroup = savedFilterGroups[indexPath.row] MTLImage.remove(filterGroup, completion: { (success) in if success == true { self.savedFilterGroups.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } }) } } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let alert = UIAlertController(title: "Rename", message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: { (textField) in textField.placeholder = self.savedFilterGroups[indexPath.row].title }) let doneAction = UIAlertAction(title: "Done", style: .default) { (action) in let textField = alert.textFields?.first! if textField!.text == nil || textField!.text == "" { return } let filterGroup = self.savedFilterGroups[indexPath.row] filterGroup.title = textField!.text! self.tableView.reloadData() self.dismiss(animated: true, completion: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (action) in self.dismiss(animated: true, completion: nil) } alert.addAction(cancelAction) alert.addAction(doneAction) present(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "settings" { settingsViewController = segue.destination as? SettingsViewController settingsViewController?.filter = selectedFilter as! Filter! } else if segue.identifier == "filterGroup" { filterGroupViewController = segue.destination as? FilterGroupViewController if selectedFilter is FilterGroup { filterGroupViewController?.filterGroup = selectedFilter as! FilterGroup } else { filterGroupViewController?.filterGroup = filterGroup filterGroupViewController?.isNewFilter = newFilterSeleced } } } }
571355f36a0bc64754c9f886cf54c3c9
37.343891
138
0.639603
false
false
false
false
NickAger/NACommonUtils
refs/heads/master
NACommonUtils/Extensions/UIView+Autolayout.swift
mit
1
// // UIView+Autolayout.swift // Autolayout helpers - somewhat obsoleted by layout anchors - https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html // // NACommonUtils // // Created by Nick Ager on 05/02/2016. // Copyright © 2016 RocketBox Ltd. All rights reserved. // import UIKit extension UIView { /** Declare that a `UIView` based component is using auto-layout. - Returns: `Self` - designed as a fluid API eg: `let label = UILabel().useAutolayout()` */ @discardableResult public func useAutolayout() -> Self { self.translatesAutoresizingMaskIntoConstraints = false return self } } extension UIView { /** Adds the `NSLayoutConstraint`s for centering a view in a superview. The constraints are added to the specified superview. - Parameter superview: the view to be centered within. - Returns: The array of associated `NSLayoutConstraint` */ @discardableResult public func centerIn(superview: UIView) -> [NSLayoutConstraint] { let horizontalCenterConstraint = centerHorizontallyIn(superview: superview) let verticallyCenterConstraint = centerVerticallyIn(superview: superview) return [horizontalCenterConstraint, verticallyCenterConstraint] } /** Adds the `NSLayoutConstraint` for centering horizontally a view in a superview. The constraints are added to the specified superview. - Parameter superview: the view to be centered within. - Returns: The array of associated `NSLayoutConstraint` */ @discardableResult public func centerHorizontallyIn(superview: UIView) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute:.centerX, relatedBy:.equal, toItem:superview, attribute:.centerX, multiplier:1.0, constant:0) superview.addConstraint(constraint) return constraint } /** Adds the `NSLayoutConstraint` for centering vertically a view in a superview. The constraints are added to the specified superview. - Parameter superview: the view to be centered within. - Returns: The array of associated `NSLayoutConstraint` */ @discardableResult public func centerVerticallyIn(superview: UIView) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute:.centerY, relatedBy:.equal, toItem:superview, attribute:.centerY, multiplier:1.0, constant:0) superview.addConstraint(constraint) return constraint } /** Adds the `NSLayoutConstraint` for constraining a view to a specified width. The constraints are added directly to the view. - Parameter width: width - Returns: The associated `NSLayoutConstraint` */ @discardableResult public func constrainTo(width: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy:.equal, toItem:nil, attribute:.notAnAttribute, multiplier:0, constant:width) self.addConstraint(constraint) return constraint } /** Adds the `NSLayoutConstraint` for constraining a view to a specified height. The constraints are added directly to the view. - Parameter height: height - Returns: The associated `NSLayoutConstraint` */ @discardableResult public func constrainTo(height: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy:.equal, toItem:nil, attribute:.notAnAttribute, multiplier:0, constant:height) self.addConstraint(constraint) return constraint } /** Adds `NSLayoutConstraint`s for constraining a view to a specified size. The constraints are added directly to the view. - Parameter size: size - Returns: The associated `NSLayoutConstraint`s */ @discardableResult public func constrainTo(size: CGSize) -> [NSLayoutConstraint] { let heightConstraint = constrainTo(height: size.height) let widthConstraint = constrainTo(width: size.width) return [heightConstraint,widthConstraint] } }
7564965770ddc402c0296df949bcc484
36.842105
201
0.696338
false
false
false
false
lukevanin/OCRAI
refs/heads/master
CardScanner/Vertex.swift
mit
1
// // FragmentAnnotationVertex.swift // CardScanner // // Created by Luke Van In on 2017/02/28. // Copyright © 2017 Luke Van In. All rights reserved. // import Foundation import UIKit import CoreData private let entityName = "Vertex" extension Vertex { var point: CGPoint { get { return CGPoint(x: self.x, y: self.y) } set { self.x = Double(newValue.x) self.y = Double(newValue.y) } } convenience init(x: Double, y: Double, context: NSManagedObjectContext) { guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else { fatalError("Cannot initialize entity \(entityName)") } self.init(entity: entity, insertInto: context) self.x = x self.y = y } }
c59b5c6f9863d2ac1da4414038bc14ed
22.8
100
0.59904
false
false
false
false
codefellows/sea-d34-iOS
refs/heads/master
Sample Code/Week 3/GithubToGo/GithubToGo/GithubService.swift
mit
1
// // GithubService.swift // GithubToGo // // Created by Bradley Johnson on 4/13/15. // Copyright (c) 2015 BPJ. All rights reserved. // import Foundation class GithubService : NSObject, NSURLSessionDataDelegate { static let sharedInstance : GithubService = GithubService() let githubSearchRepoURL = "https://api.github.com/search/repositories" let localURL = "http://127.0.0.1:3000" func fetchReposForSearch(searchTerm : String, completionHandler : ( [Repository]?, String?) ->(Void)) { let queryString = "?q=\(searchTerm)" let requestURL = githubSearchRepoURL + queryString let url = NSURL(string: requestURL) let request = NSMutableURLRequest(URL: url!) if let token = NSUserDefaults.standardUserDefaults().objectForKey("githubToken") as? String { request.setValue("token \(token)", forHTTPHeaderField: "Authorization") } let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if let httpResponse = response as? NSHTTPURLResponse { println(httpResponse.statusCode) if httpResponse.statusCode == 200 { let repos = RepoJSONParser.reposFromJSONData(data) NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in completionHandler(repos,nil) }) } } //this is our callback }) dataTask.resume() } func fetchUsersForSearch(search : String, completionHandler : ([User]?, String?) -> (Void)) { let searchURL = "https://api.github.com/search/users?q=" let url = searchURL + search let request = NSMutableURLRequest(URL: NSURL(string: url)!) if let token = NSUserDefaults.standardUserDefaults().objectForKey("githubToken") as? String { request.setValue("token \(token)", forHTTPHeaderField: "Authorization") } let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in let users = UserJSONParser.usersFromJSONData(data) NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in println("hi") completionHandler(users,nil) }) // NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in // // completionHandler(users, nil) // }) }) dataTask.resume() } }
eb64d8c300f36e060abaedd8d27d8df8
31.693333
132
0.654976
false
false
false
false
quillford/OctoControl-iOS
refs/heads/master
OctoControl/SettingsViewController.swift
gpl-2.0
1
// // SettingsViewController.swift // OctoControl // // Created by quillford on 2/6/15. // Copyright (c) 2015 quillford. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var ipField: UITextField! @IBOutlet weak var apikeyField: UITextField! var userDefaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() //get previous stored values self.ipField.text = userDefaults.stringForKey("ip") self.apikeyField.text = userDefaults.stringForKey("apikey") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func setIP(sender: AnyObject) { //save the ip address userDefaults.setObject(self.ipField.text, forKey: "ip") //dismiss keyboard self.view.endEditing(true) } @IBAction func setApikey(sender: AnyObject) { //save the api key userDefaults.setObject(self.apikeyField.text, forKey: "apikey") //dismiss the keyboard self.view.endEditing(true) } @IBAction func testConnection(sender: AnyObject) { userDefaults.setObject(self.ipField.text, forKey: "ip") userDefaults.setObject(self.apikeyField.text, forKey: "apikey") let ip = userDefaults.stringForKey("ip") let apikey = userDefaults.stringForKey("apikey") let alert = UIAlertView() alert.addButtonWithTitle("OK") if (OctoPrint.testConnection(ip!, apikey: apikey!)){ alert.title = "Connected!" alert.message = "You have successfully connected to your OctoPrint server" }else { alert.title = "Not Connected" alert.message = "OctoControl cannot connect to your OctoPrint server. Please check your settings." } alert.show() self.view.endEditing(true) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { self.view.endEditing(true) } }
055b1b0ed90b9721367563a26b6902dd
29.378378
110
0.633452
false
false
false
false
Seanalair/GreenAR
refs/heads/master
GreenAR/Classes/Controllers/MappingManager.swift
mit
1
// // MappingManager.swift // GreenAR // // Created by Daniel Grenier on 10/20/17. // import Foundation import SceneKit /** A helper class which enables serializing a `RoomMapping` into a json file and deserializing a `RoomMapping` such a json file by using a reference point for necessary translation */ public class MappingManager { /** Writes a representation of a `RoomMapping` object to a json file. - Parameter roomMapping: The `RoomMapping` object to convert to json. - Parameter fileName: The name of the file to write the json representation to. */ public static func saveRoomMapping(_ roomMapping: RoomMapping, fileName:String) { guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let fileUrl = documentDirectoryUrl.appendingPathComponent("\(fileName).json") if let roomData = roomMapping.serialize() { do { let data = try JSONSerialization.data(withJSONObject: roomData, options: []) try data.write(to: fileUrl, options: []) } catch { print(error) } } } /** Initializes a `RoomMapping` from a representation stored in a json file. - Parameter fileName: The name of the file containing the json representation. - Parameter referencePosition: The current reference position to compare to the stored reference position for translations during deserialization. - Returns: An initialized `RoomMapping`, or `nil` if the file could not be read or did not contain a valid json representation of a `RoomMapping`. */ public static func loadRoomMapping(fileName:String, referencePosition:SCNVector3) -> RoomMapping? { guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } let fileUrl = documentsDirectoryUrl.appendingPathComponent("\(fileName).json") do { let data = try Data(contentsOf: fileUrl, options: []) if let roomObject = try JSONSerialization.jsonObject(with: data,options: []) as? [String : Any], let roomMapping = RoomMapping.init(jsonObject:roomObject, newReferencePosition:referencePosition) { return roomMapping } } catch { print(error) } return nil } }
acd67f8415df49291877bea8b2ca07b7
39.33871
151
0.659336
false
false
false
false
kay-kim/stitch-examples
refs/heads/master
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/ExtendedJson/Decimal+ExtendedJson.swift
apache-2.0
1
// // Decimal+ExtendedJson.swift // ExtendedJson // // Created by Jason Flax on 10/3/17. // Copyright © 2017 MongoDB. All rights reserved. // import Foundation extension Decimal: ExtendedJsonRepresentable { public static func fromExtendedJson(xjson: Any) throws -> ExtendedJsonRepresentable { guard let json = xjson as? [String: Any], let decimalString = json[ExtendedJsonKeys.numberDecimal.rawValue] as? String, let decimal = Decimal(string: decimalString), json.count == 1 else { throw BsonError.parseValueFailure(value: xjson, attemptedType: Decimal.self) } return decimal } public var toExtendedJson: Any { return [ExtendedJsonKeys.numberDecimal.rawValue: String(describing: self)] } public func isEqual(toOther other: ExtendedJsonRepresentable) -> Bool { if let other = other as? Decimal { return self == other } return false } }
13afa3452d23d03931ae11b96891edb9
28.939394
92
0.651822
false
false
false
false
whiteshadow-gr/HatForIOS
refs/heads/master
HAT/Objects/Phatav2/HATProfileAbout.swift
mpl-2.0
1
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATProfileAbout: HATObject, HatApiType { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `body` in JSON is `body` * `title` in JSON is `title` */ private enum CodingKeys: String, CodingKey { case body case title } // MARK: - Variables /// Body part of about public var body: String = "" /// Main part of about public var title: String = "" // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(dict: Dictionary<String, JSON>) { self.init() self.initialize(dict: dict) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public mutating func initialize(dict: Dictionary<String, JSON>) { if let tempBody: String = (dict[CodingKeys.body.rawValue]?.stringValue) { body = tempBody } if let tempTitle: String = (dict[CodingKeys.title.rawValue]?.stringValue) { title = tempTitle } } // MARK: HatApiType protocol /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.body.rawValue: self.body, CodingKeys.title.rawValue: self.title ] } /** It initialises everything from the received Dictionary file from the cache - fromCache: The dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let json: JSON = JSON(fromCache) self.initialize(dict: json.dictionaryValue) } }
4d345cd98dbb751f6cad7fad5784b35e
23.423077
83
0.582283
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/GameCreationViewController.swift
mit
1
// // GameCreationViewController.swift // Stats // // Created by Parker Rushton on 4/17/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import BetterSegmentedControl import Firebase import TextFieldEffects class GameCreationViewController: Component, AutoStoryboardInitializable { // MARK: - IBOutlets @IBOutlet weak var opponentTextField: HoshiTextField! @IBOutlet weak var locationTextField: HoshiTextField! @IBOutlet weak var homeAwaySegControl: BetterSegmentedControl! @IBOutlet weak var regSeasonSegControl: BetterSegmentedControl! @IBOutlet weak var dateTextField: MadokaTextField! @IBOutlet weak var lineupView: UIView! @IBOutlet weak var lineupLabel: UILabel! @IBOutlet weak var startButton: CustomButton! @IBOutlet var keyboardAccessoryView: UIView! // MARK: - Public var editingGame: Game? var showLineup = false fileprivate var date = Date() { didSet { dateTextField.text = date.gameDayString } } fileprivate let datePicker = UIDatePicker() fileprivate lazy var newGameRef: DatabaseReference = { return StatsRefs.gamesRef(teamId: App.core.state.teamState.currentTeam!.id).childByAutoId() }() // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() updateUI(with: editingGame) if let editingGame = editingGame { let lineupPlayers = editingGame.lineupIds.compactMap { core.state.playerState.player(withId: $0) } core.fire(event: LineupUpdated(players: lineupPlayers)) } if showLineup { pushLineup(animated: false) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = .mainAppColor updateSaveButton() view.endEditing(false) } // MARK: - IBActions @IBAction func dismissButtonPressed(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func lineupViewPressed(_ sender: Any) { pushLineup() } @IBAction func startButtonPressed(_ sender: UIButton) { guard let game = construtedGame() else { return } if let _ = editingGame { core.fire(command: SetObject(game)) } else { core.fire(command: CreateGame(game: game)) } dismiss(animated: true, completion: nil) } @IBAction func downButtonPressed(_ sender: UIButton) { if opponentTextField.isFirstResponder { locationTextField.becomeFirstResponder() } else if locationTextField.isFirstResponder { dateTextField.becomeFirstResponder() } else { view.endEditing(false) } } @IBAction func upButtonPressed(_ sender: UIButton) { if dateTextField.isFirstResponder { locationTextField.becomeFirstResponder() } else if locationTextField.isFirstResponder { opponentTextField.becomeFirstResponder() } else { view.endEditing(false) } } @IBAction func keyboardPressed(_ sender: UIButton) { view.endEditing(false) } @IBAction func textFieldChanged(_ sender: UITextField) { updateSaveButton() } @IBAction func homeAwayChanged(_ sender: BetterSegmentedControl) { updateSaveButton() } @IBAction func seasonTypeChanged(_ sender: BetterSegmentedControl) { updateSaveButton() } @objc func dateChanged(_ sender: UIDatePicker) { date = sender.date } // MARK: - Subscriber override func update(with state: AppState) { updateSaveButton() } } // MARK: - Private extension GameCreationViewController { fileprivate func setUpSegmentedControls() { let homeAwayTitles = ["Home", "Away"] homeAwaySegControl.setUp(with: homeAwayTitles) let regSeasonTitles = ["Regular Season", "Post Season"] regSeasonSegControl.setUp(with: regSeasonTitles) } fileprivate func setUpDatePicker() { datePicker.datePickerMode = .dateAndTime datePicker.minuteInterval = 15 datePicker.addTarget(self, action: #selector(dateChanged), for: .valueChanged) dateTextField.inputAccessoryView = keyboardAccessoryView dateTextField.inputView = datePicker } fileprivate func updateUI(with game: Game?) { opponentTextField.inputAccessoryView = keyboardAccessoryView locationTextField.inputAccessoryView = keyboardAccessoryView setUpSegmentedControls() setUpDatePicker() date = Date().nearestHalfHour guard let game = game else { return } title = "Edit Game" opponentTextField.text = game.opponent try? homeAwaySegControl.setIndex(game.isHome ? 0 : 1) try? regSeasonSegControl.setIndex(game.isRegularSeason ? 0 : 1) date = game.date if !game.lineupIds.isEmpty { } } fileprivate func pushLineup(animated: Bool = true) { let rosterVC = RosterViewController.initializeFromStoryboard() rosterVC.isLineup = true navigationController?.pushViewController(rosterVC, animated: animated) } fileprivate func updateSaveButton() { let newGame = construtedGame() if let editingGame = editingGame { startButton.isEnabled = newGame != nil && !newGame!.isSame(as: editingGame) } else { startButton.isEnabled = newGame != nil } guard let currentLineup = core.state.newGameState.lineup else { return } lineupLabel.text = currentLineup.isEmpty ? "Set Lineup" : "Edit Lineup (\(currentLineup.count))" } fileprivate func construtedGame() -> Game? { guard let opponentText = opponentTextField.text, !opponentText.isEmpty else { print("Opponent can't be empty"); return nil } guard let currentTeam = core.state.teamState.currentTeam else { print("current team can't be nil"); return nil } guard let currentSeasonId = currentTeam.currentSeasonId else { print("curent season can't be nil"); return nil } var locationString = locationTextField.text if let locationText = locationTextField.text, locationText.isEmpty { locationString = nil } let isHome = homeAwaySegControl.index == 0 let isRegularSeason = regSeasonSegControl.index == 0 let lineupIds = core.state.newGameState.lineup?.map { $0.id } ?? [] if var editingGame = editingGame { editingGame.opponent = opponentText editingGame.location = locationString editingGame.isHome = isHome editingGame.isRegularSeason = isRegularSeason editingGame.lineupIds = lineupIds return editingGame } else { return Game(id: newGameRef.key, date: date, inning: 1, isCompleted: false, isHome: isHome, isRegularSeason: isRegularSeason, lineupIds: lineupIds, location: locationString, opponent: opponentText, seasonId: currentSeasonId, teamId: currentTeam.id) } } } // MARK: - TextField extension GameCreationViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { guard textField == dateTextField else { return } datePicker.setDate(date, animated: true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == opponentTextField { dateTextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } }
1f67f8d0fd95b39f8c6fb6eb6ee3a9e8
31.784232
259
0.647513
false
false
false
false
neonichu/Wunderschnell
refs/heads/master
Phone App/AppDelegate.swift
mit
1
// // AppDelegate.swift // WatchButton // // Created by Boris Bügling on 09/05/15. // Copyright (c) 2015 Boris Bügling. All rights reserved. // import Keys import MMWormhole import UIKit // Change the used sphere.io project here let SphereIOProject = "ecomhack-demo-67" private extension Array { func randomItem() -> T { let index = Int(arc4random_uniform(UInt32(self.count))) return self[index] } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private let beaconController = BeaconController() private let keys = WatchButtonKeys() private var sphereClient: SphereIOClient! private let wormhole = MMWormhole(applicationGroupIdentifier: AppGroupIdentifier, optionalDirectory: DirectoryIdentifier) var selectedProduct: [String:AnyObject]? var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { PayPalMobile.initializeWithClientIdsForEnvironments([ PayPalEnvironmentSandbox: WatchButtonKeys().payPalSandboxClientId()]) sphereClient = SphereIOClient(clientId: keys.sphereIOClientId(), clientSecret: keys.sphereIOClientSecret(), project: SphereIOProject) beaconController.beaconCallback = { (beacon, _) in self.wormhole.passMessageObject(true, identifier: Reply.BeaconRanged.rawValue) } beaconController.outOfRangeCallback = { self.wormhole.passMessageObject(false, identifier: Reply.BeaconRanged.rawValue) } beaconController.refresh() return true } func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) { if let reply = reply, userInfo = userInfo, command = userInfo[CommandIdentifier] as? String { handleCommand(command, reply) } else { fatalError("Invalid WatchKit extension request :(") } // Keep the phone app running a bit for demonstration purposes UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler() {} } // MARK: - Helpers func fetchSelectedProduct(completion: () -> ()) { if selectedProduct != nil { completion() return } sphereClient.fetchProductData() { (result) in if let value = result.value, results = value["results"] as? [[String:AnyObject]] { self.selectedProduct = results.randomItem() completion() } else { fatalError("Failed to retrieve products from Sphere.IO") } } } private func handleCommand(command: String, _ reply: (([NSObject : AnyObject]!) -> Void)) { switch(Command(rawValue: command)!) { case .GetProduct: fetchSelectedProduct() { if let product = self.selectedProduct { reply([Reply.Product.rawValue: product]) } return } break case .MakeOrder: fetchSelectedProduct() { self.sphereClient.quickOrder(product: self.selectedProduct!, to:retrieveShippingAddress()) { (result) in if let order = result.value { let pp = Product(self.selectedProduct!) let amount = pp.price["amount"]! let currency = pp.price["currency"]! let client = PayPalClient(clientId: self.keys.payPalSandboxClientId(), clientSecret: self.keys.payPalSandboxClientSecret(), code: retrieveRefreshToken()) client.pay(retrievePaymentId(), currency, amount) { (paid) in reply([Reply.Paid.rawValue: paid]) self.wormhole.passMessageObject(paid, identifier: Reply.Paid.rawValue) self.sphereClient.setPaymentState(paid ? .Paid : .Failed, forOrder: order) { (result) in //println("Payment state result: \(result)") if let order = result.value { self.sphereClient.setState(.Complete, forOrder: order) { (result) in println("Ordered successfully.") } } else { fatalError("Failed to set order to complete state.") } } } } } } break default: break } } }
82e51299d183d0cb2fc08daa292812fd
37.845528
177
0.580996
false
false
false
false
Constantine-Fry/das-quadrat
refs/heads/develop
Source/Shared/Request.swift
apache-2.0
2
// // Request.swift // Quadrat // // Created by Constantine Fry on 17/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation class Request { let parameters: Parameters? /** Endpoint path. */ let path: String /** Can be POST or GET. */ let HTTPMethod: String /** Session wise parameters from configuration. */ let sessionParameters: Parameters /** Should be like this "https://api.foursquare.com/v2". Specified in `Configuration` */ let baseURL: URL /** The timeout interval in seconds. */ var timeoutInterval: TimeInterval = 60 /** Optionally pass in a preformatted query string to append after all other params are added **/ var preformattedQueryString: String? init(baseURL: URL, path: String, parameters: Parameters?, sessionParameters: Parameters, HTTPMethod: String, preformattedQueryString: String? = nil) { self.baseURL = baseURL self.parameters = parameters self.sessionParameters = sessionParameters self.HTTPMethod = HTTPMethod self.path = path self.preformattedQueryString = preformattedQueryString } func URLRequest() -> Foundation.URLRequest { // if multi, var allParameters = self.sessionParameters if let parameters = self.parameters { allParameters += parameters } let URL = self.baseURL.appendingPathComponent(self.path) let requestURL = Parameter.buildURL(URL, parameters: allParameters, preformattedQueryString: preformattedQueryString) let request = NSMutableURLRequest(url: requestURL) request.httpMethod = HTTPMethod return request as URLRequest } }
b73832096bbe84ad898ce8859412b751
30.807018
101
0.646442
false
false
false
false
vgorloff/AUHost
refs/heads/master
Vendor/mc/mcxUIExtensions/Sources/AppKit/NSWindow.swift
mit
1
// // NSWindow.swift // MCA-OSS-AUH // // Created by Vlad Gorlov on 06.06.2020. // Copyright © 2020 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import mcxUI extension NSWindow { public enum Style { case welcome case `default` } public convenience init(contentRect: NSRect, styleMask style: NSWindow.StyleMask) { self.init(contentRect: contentRect, styleMask: style, backing: .buffered, defer: true) if #available(macOS 11.0, *) { titlebarSeparatorStyle = .shadow } } public convenience init(contentRect: CGRect, style: Style) { switch style { case .welcome: let styleMask: NSWindow.StyleMask = [.closable, .titled, .fullSizeContentView] self.init(contentRect: contentRect, styleMask: styleMask, backing: .buffered, defer: true) titlebarAppearsTransparent = true titleVisibility = .hidden standardWindowButton(.zoomButton)?.isHidden = true standardWindowButton(.miniaturizeButton)?.isHidden = true case .default: let styleMask: NSWindow.StyleMask = [.closable, .titled, .miniaturizable, .resizable] self.init(contentRect: contentRect, styleMask: styleMask) } } public func removeTitlebarAccessoryViewController(_ vc: NSTitlebarAccessoryViewController) { for (idx, controller) in titlebarAccessoryViewControllers.enumerated() { if controller == vc { removeTitlebarAccessoryViewController(at: idx) return } } } public var anchor: LayoutConstraint { return LayoutConstraint() } } #endif
8574fcfaf007a28cd80056f9b6f07eca
29.6
99
0.67142
false
false
false
false
DivineDominion/mac-appdev-code
refs/heads/master
DDDViewDataExample/Box.swift
mit
1
import Cocoa public protocol BoxRepository { func nextId() -> BoxId func nextItemId() -> ItemId func addBox(_ box: Box) func removeBox(boxId: BoxId) func boxes() -> [Box] func box(boxId: BoxId) -> Box? func count() -> Int } open class Box: NSObject { open let boxId: BoxId open dynamic var title: String dynamic var items: [Item] = [] public init(boxId: BoxId, title: String) { self.boxId = boxId self.title = title } open func addItem(_ item: Item) { precondition(!hasValue(item.box), "item should not have a parent box already") items.append(item) } open func item(itemId: ItemId) -> Item? { guard let index = indexOfItem(itemId: itemId) else { return nil } return items[index] } open func removeItem(itemId: ItemId) { guard let index = indexOfItem(itemId: itemId) else { return } items.remove(at: index) } func indexOfItem(itemId: ItemId) -> Int? { for (index, item) in items.enumerated() { if item.itemId == itemId { return index } } return nil } }
e48770a352be3eef22ac5bb6e96615e1
22.407407
86
0.537184
false
false
false
false
NingPeiChao/DouYu
refs/heads/master
DouYuTV/DouYuTV/Classes/Main/Controller/MianTabbarController.swift
mit
1
// // MianTabbarController.swift // DouYuTV // // Created by lulutrip on 2017/5/25. // Copyright © 2017年 宁培超. All rights reserved. // import UIKit class MianTabbarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildViewControllers() } private func addChildViewControllers() { //添加子控制器 addChildViewController(childControllerNamed: "HomeController", title: "首页", imageNamed: "btn_home") addChildViewController(childControllerNamed: "LiveController", title: "直播", imageNamed: "btn_column") addChildViewController(childControllerNamed: "FollowController", title: "关注", imageNamed: "btn_live") addChildViewController(childControllerNamed: "UserController", title: "我的", imageNamed: "btn_user") } internal func addChildViewController(childControllerNamed: String , title :String , imageNamed : String) { //-1.动态获取命名空间 let nsMessage = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String //0.将字符串转化为类 //因为swift的类名是 (命名空间+类名)组成的 //命名空间 默认是项目名称 let cls : AnyClass? = NSClassFromString(nsMessage + "." + childControllerNamed) //0.1将AnyClass转化成为指定的类型 let vcCls = cls as! UIViewController.Type //0.1.1通过类创建一个对象并且实例化 let vc = vcCls.init() //1 设置首页tabbar对应的图片 vc.tabBarItem.image = UIImage(named: imageNamed) vc.tabBarItem.selectedImage = UIImage(named: imageNamed + "_selected") vc.title = title //2.给首页一个导航视图控制器 let nav = UINavigationController(rootViewController : vc) // 3.添加控制器到tabbarVC addChildViewController(nav) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
5c50f3ac0783048f47537db15d1ceda4
29.296875
110
0.638989
false
false
false
false
larryhou/swift
refs/heads/master
SpriteKit/SpriteKit/NinjaPresenter.swift
mit
1
// // NinjaPresenter.swift // SpriteKit // // Created by larryhou on 25/5/15. // Copyright (c) 2015 larryhou. All rights reserved. // import Foundation import UIKit import SpriteKit class NinjaPresenter: SKSpriteNode { var atlas: SKTextureAtlas! var actionInfos: [NinjaActionInfo]! var data: NinjaActionInfo! var frameIndex: Int = 0 var frameCount: Int = 0 var layers: [SKSpriteNode]! convenience init(atlas: SKTextureAtlas, actionInfos: [NinjaActionInfo]) { self.init(color: UIColor.clearColor(), size: CGSize(width: 1, height: 1)) self.actionInfos = actionInfos self.atlas = atlas } func playNextAction() { let index = (data.index + 1) % actionInfos.count play(actionInfos[index].name) } func play(name: String) -> Bool { removeAllChildren() data = nil for i in 0 ..< actionInfos.count { if name == actionInfos[i].name { data = actionInfos[i] break } } if data == nil { return false } layers = [] for i in 0..<data.layers.count { var list: [SKAction] = [] var sprite = SKSpriteNode() addChild(sprite) var index: Int = 0 let layerInfo = data.layers[i] for j in 0 ..< layerInfo.length { if j >= layerInfo.frames[index].position { index++ } let frame = layerInfo.frames[index] if frame.texture != "" { list.append(SKAction.setTexture(atlas.textureNamed(frame.texture), resize: true)) list.append(SKAction.runBlock({ sprite.position.x = CGFloat(frame.x) sprite.position.y = CGFloat(frame.y) })) } else { list.append(SKAction.waitForDuration(1/30)) } } list.append(SKAction.removeFromParent()) sprite.runAction(SKAction.sequence(list)) } return true } }
0ba3895d18ea5ab68cbd7a8930cc073d
25.9625
101
0.52573
false
false
false
false
thisfin/HostsManager
refs/heads/develop
HostsManager/Constants.swift
mit
1
// // Constants.swift // HostsManager // // Created by wenyou on 2016/12/28. // Copyright © 2016年 wenyou. All rights reserved. // import AppKit typealias SimpleBlockNoneParameter = () -> Void typealias SimpleBlock = (_ data: AnyObject) -> Void class Constants { static let colorBianchi = NSColor.colorWithHexValue(0x8bddd1) static let colorTableBackground = NSColor.colorWithHexValue(0xf6f6f6) static let colorTableBackgroundLight = NSColor.white static let colorTableBorder = NSColor.colorWithHexValue(0xc8c8c8) static let colorSelected = NSColor.colorWithHexValue(0x00cc00) static let colorFont = NSColor.colorWithHexValue(0x333333) static let iconfontScan = "\u{f029}" static let iconfontHistory = "\u{f03a}" static let iconfontlight = "\u{f0e7}" static let iconfontImage = "\u{f03e}" static let iconfontDelete = "\u{f014}" static let iconfontCog = "\u{f013}" static let iconfontEdit = "\u{f044}" static let iconfontText = "\u{f0f6}" static let iconfontRandom = "\u{f074}" static let marginWidth: CGFloat = 20 static let hostsFileURL = URL.init(fileURLWithPath: NSOpenStepRootDirectory() + "private/etc/hosts") static let hostsFileGroupPrefix = "# ``` " static let hostsFileBookmarkKey = "bookmark_key_hosts" static let hostInfoFontSize: CGFloat = 14 static let hostFont = NSFont(name: "PT Mono", size: Constants.hostInfoFontSize)! static let hostFontColor = Constants.colorFont static let hostNoteFontColor = NSColor.brown }
795274dbb4865af723615e021262721a
33.863636
104
0.722947
false
false
false
false
alblue/swift
refs/heads/master
test/SILGen/partial_apply_init.swift
apache-2.0
2
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s class C { init(x: Int) {} required init(required: Double) {} } class D { required init(required: Double) {} } protocol P { init(proto: String) } extension P { init(protoExt: Float) { self.init(proto: "") } } // CHECK-LABEL: sil hidden @$s18partial_apply_init06class_c1_a1_B0{{[_0-9a-zA-Z]*}}F func class_init_partial_apply(c: C.Type) { // Partial applications at the static metatype use the direct (_TTd) thunk. // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd let xC: (Int) -> C = C.init // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd let requiredC: (Double) -> C = C.init // Partial applications to a dynamic metatype must be dynamically dispatched and use // the normal thunk. // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredM: (Double) -> C = c.init } // CHECK-LABEL: sil shared [thunk] @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK-LABEL: sil shared [thunk] @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fCTcTd // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK-LABEL: sil shared [thunk] @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC // CHECK: class_method %0 : $@thick C.Type, #C.init!allocator.1 // CHECK-LABEL: sil hidden @$s18partial_apply_init010archetype_c1_a1_B0{{[_0-9a-zA-Z]*}}F func archetype_init_partial_apply<T: C>(t: T.Type) where T: P { // Archetype initializations are always dynamic, whether applied to the type or a metatype. // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredT: (Double) -> T = T.init // CHECK: function_ref @$s18partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC let protoT: (String) -> T = T.init // CHECK: function_ref @$s18partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC let protoExtT: (Float) -> T = T.init // CHECK: function_ref @$s18partial_apply_init1CC{{[_0-9a-zA-Z]*}}fC let requiredM: (Double) -> T = t.init // CHECK: function_ref @$s18partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC let protoM: (String) -> T = t.init // CHECK: function_ref @$s18partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC let protoExtM: (Float) -> T = t.init } // CHECK-LABEL: sil shared [thunk] @$s18partial_apply_init1PP{{[_0-9a-zA-Z]*}}fC // CHECK: witness_method $Self, #P.init!allocator.1 // CHECK-LABEL: sil shared [thunk] @$s18partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC // CHECK: function_ref @$s18partial_apply_init1PPAAE{{[_0-9a-zA-Z]*}}fC
7956652ac108f8fb27ab12b5134273f3
39.242424
93
0.650602
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/VisualRecognitionV3/VisualRecognition.swift
mit
1
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The IBM Watson Visual Recognition service uses deep learning algorithms to identify scenes, objects, and faces in images you upload to the service. You can create and train a custom classifier to identify subjects that suit your needs. */ public class VisualRecognition { /// The base URL to use when contacting the service. public var serviceURL = "https://gateway-a.watsonplatform.net/visual-recognition/api" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() internal let credentials: Credentials internal let domain = "com.ibm.watson.developer-cloud.VisualRecognitionV3" internal let version: String /** Create a `VisualRecognition` object. - parameter apiKey: The API key used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ public init(apiKey: String, version: String) { self.credentials = .apiKey(name: "api_key", key: apiKey, in: .query) self.version = version } /** If the response or data represents an error returned by the Visual Recognition service, then return NSError with information about the error that occured. Otherwise, return nil. - parameter response: the URL response returned from the service. - parameter data: Raw data returned from the service that may represent an error. */ private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? { // First check http status code in response if let response = response { if (200..<300).contains(response.statusCode) { return nil } } // ensure data is not nil guard let data = data else { if let code = response?.statusCode { return NSError(domain: domain, code: code, userInfo: nil) } return nil // RestKit will generate error for this case } let code = response?.statusCode ?? 400 do { let json = try JSONWrapper(data: data) let errorID = (try? json.getString(at: "error_id")) ?? (try? json.getString(at: "error", "error_id")) let error = try? json.getString(at: "error") let status = try? json.getString(at: "status") let html = try? json.getString(at: "Error") let message = errorID ?? error ?? status ?? html ?? "Unknown error." let description = (try? json.getString(at: "description")) ?? (try? json.getString(at: "error", "description")) let statusInfo = try? json.getString(at: "statusInfo") let reason = description ?? statusInfo ?? "Please use the status code to refer to the documentation." let userInfo = [ NSLocalizedDescriptionKey: message, NSLocalizedFailureReasonErrorKey: reason, ] return NSError(domain: domain, code: code, userInfo: userInfo) } catch { return NSError(domain: domain, code: code, userInfo: nil) } } /** Classify images. Classify images with built-in or custom classifiers. - parameter imagesFile: An image file (.jpg, .png) or .zip file with images. Maximum image size is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. - parameter acceptLanguage: The language of the output class names. The full set of languages is supported only for the built-in `default` classifier ID. The class names of custom classifiers are not translated. The response might not be in the specified language when the requested language is not supported or when there is no translation for the class name. - parameter url: The URL of an image to analyze. Must be in .jpg, or .png format. The minimum recommended pixel density is 32X32 pixels per inch, and the maximum image size is 10 MB. You can also include images with the **images_file** parameter. - parameter threshold: The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to ignore the classification score and return all values. - parameter owners: The categories of classifiers to apply. Use `IBM` to classify against the `default` general classifier, and use `me` to classify against your custom classifiers. To analyze the image against both classifier categories, set the value to both `IBM` and `me`. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - parameter classifierIDs: Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. The following built-in classifier IDs require no training: - `default`: Returns classes from thousands of general tags. - `food`: (Beta) Enhances specificity and accuracy for images of food items. - `explicit`: (Beta) Evaluates whether the image might be pornographic. - parameter imagesFileContentType: The content type of imagesFile. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func classify( imagesFile: URL? = nil, url: String? = nil, threshold: Double? = nil, owners: [String]? = nil, classifierIDs: [String]? = nil, acceptLanguage: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ClassifiedImages) -> Void) { // construct body let multipartFormData = MultipartFormData() if let imagesFile = imagesFile { multipartFormData.append(imagesFile, withName: "images_file") } if let url = url { guard let urlData = url.data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(urlData, withName: "url") } if let threshold = threshold { guard let thresholdData = "\(threshold)".data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(thresholdData, withName: "threshold") } if let owners = owners { guard let ownersData = owners.joined(separator: ",").data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(ownersData, withName: "owners") } if let classifierIDs = classifierIDs { guard let classifierIDsData = classifierIDs.joined(separator: ",").data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(classifierIDsData, withName: "classifier_ids") } guard let body = try? multipartFormData.toData() else { failure?(RestError.encodingError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType if let acceptLanguage = acceptLanguage { headerParameters["Accept-Language"] = acceptLanguage } // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v3/classify", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ClassifiedImages>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Detect faces in images. **Important:** On April 2, 2018, the identity information in the response to calls to the Face model was removed. The identity information refers to the `name` of the person, `score`, and `type_hierarchy` knowledge graph. For details about the enhanced Face model, see the [Release notes](https://console.bluemix.net/docs/services/visual-recognition/release-notes.html#2april2018). Analyze and get data about faces in images. Responses can include estimated age and gender. This feature uses a built-in model, so no training is necessary. The Detect faces method does not support general biometric facial recognition. Supported image formats include .gif, .jpg, .png, and .tif. The maximum image size is 10 MB. The minimum recommended pixel density is 32X32 pixels per inch. - parameter imagesFile: An image file (gif, .jpg, .png, .tif.) or .zip file with images. Limit the .zip file to 100 MB. You can include a maximum of 15 images in a request. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. - parameter url: The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. The minimum recommended pixel density is 32X32 pixels per inch, and the maximum image size is 10 MB. Redirects are followed, so you can use a shortened URL. You can also include images with the **images_file** parameter. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func detectFaces( imagesFile: URL? = nil, url: String? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (DetectedFaces) -> Void) { // construct body let multipartFormData = MultipartFormData() if let imagesFile = imagesFile { multipartFormData.append(imagesFile, withName: "images_file", mimeType: "application/octet-stream") } if let url = url { guard let urlData = url.data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(urlData, withName: "url") } guard let body = try? multipartFormData.toData() else { failure?(RestError.encodingError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v3/detect_faces", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<DetectedFaces>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create a classifier. Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive or negative examples. Include at least two sets of examples, either two positive example files or one positive and one negative file. You can upload a maximum of 256 MB per call. Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. - parameter name: The name of the new classifier. Encode special characters in UTF-8. - parameter positiveExamples: An array of positive examples, each with a name and a compressed (.zip) file of images that depict the visual subject for a class within the new classifier. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. - parameter negativeExamples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createClassifier( name: String, positiveExamples: [PositiveExample], negativeExamples: URL? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifier) -> Void) { // construct body let multipartFormData = MultipartFormData() guard let nameData = name.data(using: .utf8) else { failure?(RestError.serializationError) return } multipartFormData.append(nameData, withName: "name") positiveExamples.forEach { example in multipartFormData.append(example.examples, withName: example.name + "_positive_examples") } if let negativeExamples = negativeExamples { multipartFormData.append(negativeExamples, withName: "negative_examples") } guard let body = try? multipartFormData.toData() else { failure?(RestError.encodingError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v3/classifiers", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifier>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Retrieve a list of classifiers. - parameter owners: Unused. This parameter will be removed in a future release. - parameter verbose: Specify `true` to return details about the classifiers. Omit this parameter to return a brief list of classifiers. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listClassifiers( owners: [String]? = nil, verbose: Bool? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifiers) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) if let verbose = verbose { let queryParameter = URLQueryItem(name: "verbose", value: "\(verbose)") queryParameters.append(queryParameter) } // construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v3/classifiers", credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifiers>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Retrieve classifier details. Retrieve information about a custom classifier. - parameter classifierID: The ID of the classifier. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getClassifier( classifierID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifier) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v3/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifier>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Update a classifier. Update a custom classifier by adding new positive or negative classes (examples) or by adding new images to existing classes. You must supply at least one set of positive or negative examples. For details, see [Updating custom classifiers](https://console.bluemix.net/docs/services/visual-recognition/customizing.html#updating-custom-classifiers). Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. **Tip:** Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests in parallel, the last request overwrites the previous requests. The retrained property shows the last time the classifier retraining finished. - parameter classifierID: The ID of the classifier. - parameter positiveExamples: An array of positive examples, each with a name and a compressed (.zip) file of images that depict the visual subject for a class within the new classifier. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. - parameter negativeExamples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func updateClassifier( classifierID: String, positiveExamples: [PositiveExample]? = nil, negativeExamples: URL? = nil, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifier) -> Void) { // construct body let multipartFormData = MultipartFormData() if let positiveExamples = positiveExamples { positiveExamples.forEach { example in multipartFormData.append(example.examples, withName: example.name + "_positive_examples") } } if let negativeExamples = negativeExamples { multipartFormData.append(negativeExamples, withName: "negative_examples") } guard let body = try? multipartFormData.toData() else { failure?(RestError.encodingError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v3/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifier>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete a classifier. - parameter classifierID: The ID of the classifier. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteClassifier( classifierID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v3/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } /** Retrieve a Core ML model of a classifier. Download a Core ML model file (.mlmodel) of a custom classifier that returns <tt>\"core_ml_enabled\": true</tt> in the classifier details. - parameter classifierID: The ID of the classifier. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getCoreMlModel( classifierID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (URL) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/octet-stream" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) // construct REST request let path = "/v3/classifiers/\(classifierID)/core_ml_model" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, queryItems: queryParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<URL>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } }
e07ce0bd73e181f441a4ba56d33361ee
43.010736
147
0.643353
false
false
false
false
pascaljette/GearKit
refs/heads/master
Example/GearKit/Samples/Graphs/GKRadarGraph/GKRadarGraphModel.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 pascaljette // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import GearKit /// Model containing the data necessary to display the radar graph view controller. struct GKRadarGraphModel { // // MARK: Stored properties // /// Array of parameters for the plot. var parameters: [GKRadarGraphView.Parameter] = [] /// Series representing the data in the plot. var series: [GKRadarGraphView.Serie] = [] // // MARK: Initialisation // /// Initialize with default values. init() { let hpParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "HP") let mpParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "MP") let strengthParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "STR") let defenseParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "DF") let magicParameter: GKRadarGraphView.Parameter = GKRadarGraphView.Parameter(name: "MGC") parameters = [hpParameter, mpParameter, strengthParameter, defenseParameter, magicParameter] // We only support gradients for a single serie radar graph var firstSerie = GKRadarGraphView.Serie() firstSerie.strokeColor = UIColor.blueColor() firstSerie.strokeWidth = 4.0 firstSerie.name = "blue" let firstFillColor: UIColor = UIColor(red: 0.1, green: 0.1, blue: 0.7, alpha: 0.7) firstSerie.fillMode = .SOLID(firstFillColor) firstSerie.percentageValues = [0.9, 0.5, 0.6, 0.2, 0.9] firstSerie.decoration = .SQUARE(8.0) var secondSerie = GKRadarGraphView.Serie() secondSerie.strokeColor = UIColor.greenColor() secondSerie.strokeWidth = 4.0 secondSerie.name = "green" let secondFillColor: UIColor = UIColor(red: 0.1, green: 0.7, blue: 0.1, alpha: 0.7) secondSerie.fillMode = .SOLID(secondFillColor) secondSerie.percentageValues = [0.9, 0.1, 0.2, 0.9, 0.3] secondSerie.decoration = .CIRCLE(6.0) var thirdSerie = GKRadarGraphView.Serie() thirdSerie.strokeColor = UIColor.redColor() thirdSerie.strokeWidth = 4.0 thirdSerie.name = "red" let thirdSerieFillColor: UIColor = UIColor(red: 0.7, green: 0.1, blue: 0.1, alpha: 0.7) thirdSerie.fillMode = .SOLID(thirdSerieFillColor) thirdSerie.percentageValues = [0.5, 0.9, 0.5, 0.5, 0.6] thirdSerie.decoration = .DIAMOND(8.0) series = [firstSerie, secondSerie, thirdSerie] } }
2b4503058cf5ec240ee338e088cc4a46
41.793103
100
0.680902
false
false
false
false
ngageoint/fog-machine
refs/heads/master
Demo/FogViewshed/FogViewshed/Models/Elevation/ElevationScene.swift
mit
1
// // ElevationScene.swift // FogViewshed // import Foundation import SceneKit import MapKit class ElevationScene: SCNNode { // MARK: Variables var elevation:[[Int]] var vertexSource:SCNGeometrySource var maxScaledElevation:Float var image:UIImage? let cellSize:Float = 1.0 // MARK: Initializer init(elevation: [[Int]], viewshedImage: UIImage?) { self.elevation = elevation self.vertexSource = SCNGeometrySource() self.maxScaledElevation = 1.0 self.image = viewshedImage super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Process Functions func generateScene() { self.addChildNode(SCNNode(geometry: createGeometry())) } func drawVertices() { self.addChildNode(generateLineNode(vertexSource, vertexCount: vertexSource.vectorCount)) } func addObserver(location: (Int, Int), altitude: Double) { self.addChildNode(generateObserverNode(location, altitude: altitude)) } func addCamera() { self.addChildNode(generateCameraNode()) } // MARK: Private Functions private func createGeometry() -> SCNGeometry { let geometry:SCNGeometry = calculateGeometry() addImageToGeometry(geometry) return geometry } private func calculateGeometry() -> SCNGeometry { let maxRows = elevation.count let maxColumns = elevation[0].count var vertices:[SCNVector3] = [] var textures:[(x:Float, y:Float)] = [] for row in 0..<(maxRows - 1) { for column in 0..<(maxColumns - 1) { let topLeftZ = getElevationAtLocation(row, column: column) let topRightZ = getElevationAtLocation(row, column: column + 1) let bottomLeftZ = getElevationAtLocation(row + 1, column: column) let bottomRightZ = getElevationAtLocation(row + 1, column: column + 1) let coordX = Float(column) let coordY = Float(row) let topLeft = SCNVector3Make(Float(coordX), Float(-coordY), Float(topLeftZ)) let topRight = SCNVector3Make(Float(coordX) + cellSize, Float(-coordY), Float(topRightZ)) let bottomLeft = SCNVector3Make(Float(coordX), Float(-coordY) - cellSize, Float(bottomLeftZ)) let bottomRight = SCNVector3Make(Float(coordX) + cellSize, Float(-coordY) - cellSize, Float(bottomRightZ)) vertices.append(topLeft) vertices.append(topRight) vertices.append(bottomRight) vertices.append(bottomLeft) let columnScale = Float(maxColumns) - 1 let rowScale = Float(maxRows) - 1 let topLeftTexture = (x:Float(coordX / columnScale), y:Float(coordY / rowScale)) let bottomLeftTexture = (x:Float((coordX + 1) / columnScale), y:Float(coordY / rowScale)) let topRightTexture = (x:Float(coordX / columnScale), y:Float((coordY + 1) / rowScale)) let bottomRightTexture = (x:Float((coordX + 1) / columnScale), y:Float((coordY + 1) / rowScale)) textures.append(topLeftTexture) textures.append(bottomLeftTexture) textures.append(bottomRightTexture) textures.append(topRightTexture) } } var geometrySources:[SCNGeometrySource] = [] //Add vertex vertexSource = SCNGeometrySource(vertices: vertices, count: vertices.count) geometrySources.append(vertexSource) //Add normal let normal = SCNVector3(0, 0, 1) var normals:[SCNVector3] = [] for _ in 0..<vertexSource.vectorCount { normals.append(normal) } let normalSource:SCNGeometrySource = SCNGeometrySource(vertices: normals, count: normals.count) geometrySources.append(normalSource) //Add textures let textureData = NSData(bytes: textures, length: (sizeof((x:Float, y:Float)) * textures.count)) let textureSource = SCNGeometrySource(data: textureData, semantic: SCNGeometrySourceSemanticTexcoord, vectorCount: textures.count, floatComponents: true, componentsPerVector: 2, bytesPerComponent: sizeof(Float), dataOffset: 0, dataStride: sizeof((x:Float, y:Float))) geometrySources.append(textureSource) //Create Indices var geometryData:[CInt] = [] var geometryCount: CInt = 0 while (geometryCount < CInt(vertexSource.vectorCount)) { geometryData.append(geometryCount) geometryData.append(geometryCount + 2) geometryData.append(geometryCount + 1) geometryData.append(geometryCount) geometryData.append(geometryCount + 3) geometryData.append(geometryCount + 2) geometryCount += 4 } let element:SCNGeometryElement = SCNGeometryElement(indices: geometryData, primitiveType: .Triangles) //Create SCNGeometry let geometry:SCNGeometry = SCNGeometry(sources: geometrySources, elements: [element]) return geometry } private func addImageToGeometry(geometry: SCNGeometry) -> SCNGeometry { let imageMaterial = SCNMaterial() if let viewshedImage = self.image { imageMaterial.diffuse.contents = viewshedImage } else { imageMaterial.diffuse.contents = UIColor.darkGrayColor() } imageMaterial.doubleSided = true geometry.materials = [imageMaterial] return geometry } private func generateObserverNode(location: (Int, Int), altitude: Double) -> SCNNode { let observerCapsule = SCNCapsule(capRadius: 0.125, height: 0.5) let capsuleSizeFactor:Float = 0.25 let observerNode = SCNNode(geometry: observerCapsule) let row: Int = location.1 let column: Int = location.0 let observerY:Float = -Float(row) let observerX:Float = Float(column) let boundedElevation:Float = getElevationAtLocation(row - 1, column: column - 1, additionalAltitude: Float(altitude)) let observerZ: Float = Float(boundedElevation) + capsuleSizeFactor observerNode.position = SCNVector3Make(observerX, observerY, observerZ) observerNode.eulerAngles = SCNVector3Make(Float(M_PI_2), 0, 0) return observerNode } private func generateLineNode(vertexSource: SCNGeometrySource, vertexCount: Int) -> SCNNode { var lineData:[CInt] = [] var lineCount: CInt = 0 while (lineCount < CInt(vertexCount)) { lineData.append(lineCount) lineData.append(lineCount + 1) lineData.append(lineCount + 1) lineData.append(lineCount + 2) lineData.append(lineCount + 2) lineData.append(lineCount + 3) lineData.append(lineCount + 3) lineData.append(lineCount) lineData.append(lineCount + 0) lineData.append(lineCount + 2) lineCount = lineCount + 4 } let lineEle = SCNGeometryElement(indices: lineData, primitiveType: .Line) let lineGeo = SCNGeometry(sources: [vertexSource], elements: [lineEle]) let whiteMaterial = SCNMaterial() if self.image != nil { whiteMaterial.diffuse.contents = UIColor.darkGrayColor() } else { whiteMaterial.diffuse.contents = UIColor.whiteColor() } lineGeo.materials = [whiteMaterial] return SCNNode(geometry: lineGeo) } private func generateCameraNode() -> SCNNode { let cameraNode = SCNNode() cameraNode.camera = SCNCamera() // Add an additional 20 cellSize units to set the camera above the scene let cameraFactor:Float = self.cellSize * 20 let cameraZ = maxScaledElevation + cameraFactor let cameraX:Float = Float(elevation[0].count / 2) let cameraY:Float = -Float(elevation.count / 2) cameraNode.position = SCNVector3Make(cameraX, cameraY, cameraZ) return cameraNode } private func getElevationAtLocation(row: Int, column: Int, additionalAltitude:Float = 0.0) -> Float { let maxRows:Int = elevation.count - 1 let actualRow:Int = maxRows - row let elevationValue: Float = boundElevation(elevation[actualRow][column]) return elevationValue } // Bound elevation to remove data voids and unknown values private func boundElevation(unboundElevation:Int, altitude:Float = 0.0) -> Float { var boundedElevation:Float = Float(unboundElevation) // Remove data voids and invalid elevations if (unboundElevation < Elevation.MIN_BOUND) { boundedElevation = Float(Elevation.MIN_BOUND) } else if (unboundElevation > Elevation.MAX_BOUND) { boundedElevation = Float(Elevation.MAX_BOUND) } // Scale elevation by 99.7% to render in the Scene let scaleFactor:Float = 0.997 let elevationRange:Float = Float(Elevation.MAX_BOUND - Elevation.MIN_BOUND) let sizeFactor:Float = elevationRange - elevationRange * scaleFactor boundedElevation = (boundedElevation + altitude) / sizeFactor //While checking each elevation, record the maxScaledElevation if (maxScaledElevation < boundedElevation) { maxScaledElevation = boundedElevation } return boundedElevation } }
7fe4b9d856f81a601a24868f5b1c5583
38.529851
125
0.577929
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Bit Crush Operation.xcplaygroundpage/Contents.swift
mit
1
//: ## Bit Crush Operation //: import AudioKitPlaygrounds import AudioKit import AudioKitUI let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let effect = AKOperationEffect(player) { input, parameters in let baseSampleRate = parameters[0] let sampleRateVariation = parameters[1] let baseBitDepth = parameters[2] let bitDepthVariation = parameters[3] let frequency = parameters[4] let sinusoid = AKOperation.sineWave(frequency: frequency) let sampleRate = baseSampleRate + sinusoid * sampleRateVariation let bitDepth = baseBitDepth + sinusoid * bitDepthVariation return input.bitCrush(bitDepth: bitDepth, sampleRate: sampleRate) } effect.parameters = [22_050, 0, 16, 0, 1] AudioKit.output = effect AudioKit.start() player.play() class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Bit Crush Operation") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Base Sample Rate", value: effect.parameters[0], range: 300 ... 22_050, format: "%0.1f Hz" ) { sliderValue in effect.parameters[0] = sliderValue }) addView(AKSlider(property: "Sample Rate Variation", value: effect.parameters[1], range: 0 ... 8_000, format: "%0.1f Hz" ) { sliderValue in effect.parameters[1] = sliderValue }) addView(AKSlider(property: "Base Bit Depth", value: effect.parameters[2], range: 1 ... 24 ) { sliderValue in effect.parameters[2] = sliderValue }) addView(AKSlider(property: "Bit Depth Variation", value: effect.parameters[3], range: 0 ... 12, format: "%0.3f Hz" ) { sliderValue in effect.parameters[3] = sliderValue }) addView(AKSlider(property: "Frequency", value: effect.parameters[4], range: 0 ... 5, format: "%0.3f Hz" ) { sliderValue in effect.parameters[4] = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
1787694131940b2d9207a72fcf4e1327
32.25974
96
0.585318
false
false
false
false
Mclarenyang/medicine_aid
refs/heads/master
medicine aid/selectTableViewController.swift
apache-2.0
1
// // selectTableViewController.swift // medicine aid // // Created by nexuslink mac 2 on 2017/5/16. // Copyright © 2017年 NMID. All rights reserved. // import UIKit import RealmSwift class selectTableViewController: UITableViewController { // 屏幕信息 let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height // 测试预设参数 var titles :[(String,String)] = [("昵称",""),("姓名",""),("性别",""),("年龄",""),("电话号码",""),("密码","点击修改")] var indexI = 0 override func viewDidLoad() { super.viewDidLoad() /// 设置导航栏 self.navigationItem.title = "个人信息" self.navigationController?.navigationBar.barTintColor = UIColor(red:255/255,green:60/255,blue:40/255 ,alpha:1) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] //数据库读取数据 getInfo() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(_ animated: Bool) { getInfo() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } // tableview 加载cell override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { /// 定义cell let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cellId") // 读取数据 let title = titles[indexPath.row].0 let value = titles[indexPath.row].1 cell.textLabel?.text = title cell.detailTextLabel?.text = value return cell } // 点击跳转事件 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 点击行 NSLog(String(indexPath.row)) let rowIndex = indexPath.row switch rowIndex { case 0...5: let infochange = changeInfoViewController() infochange.key = rowIndex self.navigationController?.pushViewController(infochange, animated: true) default: print("无效操作") } } // 读取数据 func getInfo() { let defaults = UserDefaults.standard let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] titles[0].1 = User.UserNickname titles[1].1 = User.UserName titles[2].1 = User.UserSex titles[3].1 = User.UserAge titles[4].1 = User.UserPhoneNum } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc947d9a673e8a58935d79a0d8c88c13
29.69375
136
0.620851
false
false
false
false
lelandjansen/fatigue
refs/heads/master
Carthage/Checkouts/PhoneNumberKit/PhoneNumberKit/NSRegularExpression+Swift.swift
apache-2.0
4
// // NSRegularExpression+Swift.swift // PhoneNumberKit // // Created by David Beck on 8/15/16. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation extension String { func nsRange(from range: Range<String.Index>) -> NSRange { let utf16view = self.utf16 let from = range.lowerBound.samePosition(in: utf16view) let to = range.upperBound.samePosition(in: utf16view) return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to)) } func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } } extension NSRegularExpression { func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, using block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) self.enumerateMatches(in: string, options: options, range: nsRange, using: block) } func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> [NSTextCheckingResult] { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.matches(in: string, options: options, range: nsRange) } func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Int { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.numberOfMatches(in: string, options: options, range: nsRange) } func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> NSTextCheckingResult? { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.firstMatch(in: string, options: options, range: nsRange) } func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil) -> Range<String.Index>? { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) let match = self.rangeOfFirstMatch(in: string, options: options, range: nsRange) return string.range(from: match) } func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: Range<String.Index>? = nil, withTemplate templ: String) -> String { let range = range ?? string.startIndex..<string.endIndex let nsRange = string.nsRange(from: range) return self.stringByReplacingMatches(in: string, options: options, range: nsRange, withTemplate: templ) } }
15639ba3dd9edd055f2360500200884b
40.960526
248
0.728442
false
false
false
false
CodaFi/swift
refs/heads/master
stdlib/public/core/SIMDVector.swift
apache-2.0
14
//===--- SIMDVector.swift -------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// infix operator .==: ComparisonPrecedence infix operator .!=: ComparisonPrecedence infix operator .<: ComparisonPrecedence infix operator .<=: ComparisonPrecedence infix operator .>: ComparisonPrecedence infix operator .>=: ComparisonPrecedence infix operator .&: LogicalConjunctionPrecedence infix operator .^: LogicalDisjunctionPrecedence infix operator .|: LogicalDisjunctionPrecedence infix operator .&=: AssignmentPrecedence infix operator .^=: AssignmentPrecedence infix operator .|=: AssignmentPrecedence prefix operator .! /// A type that can function as storage for a SIMD vector type. /// /// The `SIMDStorage` protocol defines a storage layout and provides /// elementwise accesses. Computational operations are defined on the `SIMD` /// protocol, which refines this protocol, and on the concrete types that /// conform to `SIMD`. public protocol SIMDStorage { /// The type of scalars in the vector space. associatedtype Scalar: Codable, Hashable /// The number of scalars, or elements, in the vector. var scalarCount: Int { get } /// Creates a vector with zero in all lanes. init() /// Accesses the element at the specified index. /// /// - Parameter index: The index of the element to access. `index` must be in /// the range `0..<scalarCount`. subscript(index: Int) -> Scalar { get set } } extension SIMDStorage { /// The number of scalars, or elements, in a vector of this type. @_alwaysEmitIntoClient public static var scalarCount: Int { // Wouldn't it make more sense to define the instance var in terms of the // static var? Yes, probably, but by doing it this way we make the static // var backdeployable. return Self().scalarCount } } /// A type that can be used as an element in a SIMD vector. public protocol SIMDScalar { associatedtype SIMDMaskScalar: SIMDScalar & FixedWidthInteger & SignedInteger associatedtype SIMD2Storage: SIMDStorage where SIMD2Storage.Scalar == Self associatedtype SIMD4Storage: SIMDStorage where SIMD4Storage.Scalar == Self associatedtype SIMD8Storage: SIMDStorage where SIMD8Storage.Scalar == Self associatedtype SIMD16Storage: SIMDStorage where SIMD16Storage.Scalar == Self associatedtype SIMD32Storage: SIMDStorage where SIMD32Storage.Scalar == Self associatedtype SIMD64Storage: SIMDStorage where SIMD64Storage.Scalar == Self } /// A SIMD vector of a fixed number of elements. public protocol SIMD: SIMDStorage, Codable, Hashable, CustomStringConvertible, ExpressibleByArrayLiteral { /// The mask type resulting from pointwise comparisons of this vector type. associatedtype MaskStorage: SIMD where MaskStorage.Scalar: FixedWidthInteger & SignedInteger } extension SIMD { /// The valid indices for subscripting the vector. @_transparent public var indices: Range<Int> { return 0 ..< scalarCount } /// A vector with the specified value in all lanes. @_transparent public init(repeating value: Scalar) { self.init() for i in indices { self[i] = value } } /// Returns a Boolean value indicating whether two vectors are equal. @_transparent public static func ==(lhs: Self, rhs: Self) -> Bool { var result = true for i in lhs.indices { result = result && lhs[i] == rhs[i] } return result } /// Hashes the elements of the vector using the given hasher. @inlinable public func hash(into hasher: inout Hasher) { for i in indices { hasher.combine(self[i]) } } /// Encodes the scalars of this vector into the given encoder in an unkeyed /// container. /// /// This function throws an error if any values are invalid for the given /// encoder's format. /// /// - Parameter encoder: The encoder to write data to. public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for i in indices { try container.encode(self[i]) } } /// Creates a new vector by decoding scalars from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. public init(from decoder: Decoder) throws { self.init() var container = try decoder.unkeyedContainer() guard container.count == scalarCount else { throw DecodingError.dataCorrupted( DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Expected vector with exactly \(scalarCount) elements." ) ) } for i in indices { self[i] = try container.decode(Scalar.self) } } /// A textual description of the vector. public var description: String { get { return "\(Self.self)(" + indices.map({"\(self[$0])"}).joined(separator: ", ") + ")" } } /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent public static func .==(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] == rhs[i] } return result } /// Returns a vector mask with the result of a pointwise inequality /// comparison. @_transparent public static func .!=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] != rhs[i] } return result } /// Replaces elements of this vector with elements of `other` in the lanes /// where `mask` is `true`. @_transparent public mutating func replace(with other: Self, where mask: SIMDMask<MaskStorage>) { for i in indices { self[i] = mask[i] ? other[i] : self[i] } } /// Creates a vector from the specified elements. /// /// - Parameter scalars: The elements to use in the vector. `scalars` must /// have the same number of elements as the vector type. @inlinable public init(arrayLiteral scalars: Scalar...) { self.init(scalars) } /// Creates a vector from the given sequence. /// /// - Precondition: `scalars` must have the same number of elements as the /// vector type. /// /// - Parameter scalars: The elements to use in the vector. @inlinable public init<S: Sequence>(_ scalars: S) where S.Element == Scalar { self.init() var index = 0 for scalar in scalars { if index == scalarCount { _preconditionFailure("Too many elements in sequence.") } self[index] = scalar index += 1 } if index < scalarCount { _preconditionFailure("Not enough elements in sequence.") } } /// Extracts the scalars at specified indices to form a SIMD2. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD2<Index>) -> SIMD2<Scalar> where Index: FixedWidthInteger { var result = SIMD2<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD3. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD3<Index>) -> SIMD3<Scalar> where Index: FixedWidthInteger { var result = SIMD3<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD4. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD4<Index>) -> SIMD4<Scalar> where Index: FixedWidthInteger { var result = SIMD4<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD8. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD8<Index>) -> SIMD8<Scalar> where Index: FixedWidthInteger { var result = SIMD8<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD16. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD16<Index>) -> SIMD16<Scalar> where Index: FixedWidthInteger { var result = SIMD16<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD32. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD32<Index>) -> SIMD32<Scalar> where Index: FixedWidthInteger { var result = SIMD32<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } /// Extracts the scalars at specified indices to form a SIMD64. /// /// The elements of the index vector are wrapped modulo the count of elements /// in this vector. Because of this, the index is always in-range and no trap /// can occur. @_alwaysEmitIntoClient public subscript<Index>(index: SIMD64<Index>) -> SIMD64<Scalar> where Index: FixedWidthInteger { var result = SIMD64<Scalar>() for i in result.indices { result[i] = self[Int(index[i]) % scalarCount] } return result } } // Implementations of comparison operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. extension SIMD where Scalar: Comparable { /// Returns a vector mask with the result of a pointwise less than /// comparison. @_transparent public static func .<(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] < rhs[i] } return result } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent public static func .<=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { var result = SIMDMask<MaskStorage>() for i in result.indices { result[i] = lhs[i] <= rhs[i] } return result } /// The least element in the vector. @_alwaysEmitIntoClient public func min() -> Scalar { return indices.reduce(into: self[0]) { $0 = Swift.min($0, self[$1]) } } /// The greatest element in the vector. @_alwaysEmitIntoClient public func max() -> Scalar { return indices.reduce(into: self[0]) { $0 = Swift.max($0, self[$1]) } } } // These operations should never need @_semantics; they should be trivial // wrappers around the core operations defined above. extension SIMD { /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent public static func .==(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .== rhs } /// Returns a vector mask with the result of a pointwise inequality comparison. @_transparent public static func .!=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .!= rhs } /// Returns a vector mask with the result of a pointwise equality comparison. @_transparent public static func .==(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .== Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise inequality comparison. @_transparent public static func .!=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .!= Self(repeating: rhs) } /// Replaces elements of this vector with `other` in the lanes where `mask` /// is `true`. @_transparent public mutating func replace(with other: Scalar, where mask: SIMDMask<MaskStorage>) { replace(with: Self(repeating: other), where: mask) } /// Returns a copy of this vector, with elements replaced by elements of /// `other` in the lanes where `mask` is `true`. @_transparent public func replacing(with other: Self, where mask: SIMDMask<MaskStorage>) -> Self { var result = self result.replace(with: other, where: mask) return result } /// Returns a copy of this vector, with elements `other` in the lanes where /// `mask` is `true`. @_transparent public func replacing(with other: Scalar, where mask: SIMDMask<MaskStorage>) -> Self { return replacing(with: Self(repeating: other), where: mask) } } extension SIMD where Scalar: Comparable { /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent public static func .>=(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { return rhs .<= lhs } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent public static func .>(lhs: Self, rhs: Self) -> SIMDMask<MaskStorage> { return rhs .< lhs } /// Returns a vector mask with the result of a pointwise less than comparison. @_transparent public static func .<(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .< rhs } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent public static func .<=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .<= rhs } /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent public static func .>=(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .>= rhs } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent public static func .>(lhs: Scalar, rhs: Self) -> SIMDMask<MaskStorage> { return Self(repeating: lhs) .> rhs } /// Returns a vector mask with the result of a pointwise less than comparison. @_transparent public static func .<(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .< Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise less than or equal /// comparison. @_transparent public static func .<=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .<= Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise greater than or /// equal comparison. @_transparent public static func .>=(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .>= Self(repeating: rhs) } /// Returns a vector mask with the result of a pointwise greater than /// comparison. @_transparent public static func .>(lhs: Self, rhs: Scalar) -> SIMDMask<MaskStorage> { return lhs .> Self(repeating: rhs) } @_alwaysEmitIntoClient public mutating func clamp(lowerBound: Self, upperBound: Self) { self = self.clamped(lowerBound: lowerBound, upperBound: upperBound) } @_alwaysEmitIntoClient public func clamped(lowerBound: Self, upperBound: Self) -> Self { return pointwiseMin(upperBound, pointwiseMax(lowerBound, self)) } } extension SIMD where Scalar: FixedWidthInteger { /// A vector with zero in all lanes. @_transparent public static var zero: Self { return Self() } /// A vector with one in all lanes. @_alwaysEmitIntoClient public static var one: Self { return Self(repeating: 1) } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable public static func random<T: RandomNumberGenerator>( in range: Range<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable public static func random(in range: Range<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable public static func random<T: RandomNumberGenerator>( in range: ClosedRange<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable public static func random(in range: ClosedRange<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } } extension SIMD where Scalar: FloatingPoint { /// A vector with zero in all lanes. @_transparent public static var zero: Self { return Self() } /// A vector with one in all lanes. @_alwaysEmitIntoClient public static var one: Self { return Self(repeating: 1) } @_alwaysEmitIntoClient public mutating func clamp(lowerBound: Self, upperBound: Self) { self = self.clamped(lowerBound: lowerBound, upperBound: upperBound) } @_alwaysEmitIntoClient public func clamped(lowerBound: Self, upperBound: Self) -> Self { return pointwiseMin(upperBound, pointwiseMax(lowerBound, self)) } } extension SIMD where Scalar: BinaryFloatingPoint, Scalar.RawSignificand: FixedWidthInteger { /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable public static func random<T: RandomNumberGenerator>( in range: Range<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable public static func random(in range: Range<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a vector with random values from within the specified range in /// all lanes, using the given generator as a source for randomness. @inlinable public static func random<T: RandomNumberGenerator>( in range: ClosedRange<Scalar>, using generator: inout T ) -> Self { var result = Self() for i in result.indices { result[i] = Scalar.random(in: range, using: &generator) } return result } /// Returns a vector with random values from within the specified range in /// all lanes. @inlinable public static func random(in range: ClosedRange<Scalar>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } } @frozen public struct SIMDMask<Storage>: SIMD where Storage: SIMD, Storage.Scalar: FixedWidthInteger & SignedInteger { public var _storage: Storage public typealias MaskStorage = Storage public typealias Scalar = Bool @_transparent public var scalarCount: Int { return _storage.scalarCount } @_transparent public init() { _storage = Storage() } @_transparent public init(_ _storage: Storage) { self._storage = _storage } public subscript(index: Int) -> Bool { @_transparent get { _precondition(indices.contains(index)) return _storage[index] < 0 } @_transparent set { _precondition(indices.contains(index)) _storage[index] = newValue ? -1 : 0 } } } extension SIMDMask { /// Returns a vector mask with `true` or `false` randomly assigned in each /// lane, using the given generator as a source for randomness. @inlinable public static func random<T: RandomNumberGenerator>(using generator: inout T) -> SIMDMask { var result = SIMDMask() for i in result.indices { result[i] = Bool.random(using: &generator) } return result } /// Returns a vector mask with `true` or `false` randomly assigned in each /// lane. @inlinable public static func random() -> SIMDMask { var g = SystemRandomNumberGenerator() return SIMDMask.random(using: &g) } } // Implementations of integer operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. extension SIMD where Scalar: FixedWidthInteger { @_transparent public var leadingZeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].leadingZeroBitCount) } return result } @_transparent public var trailingZeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].trailingZeroBitCount) } return result } @_transparent public var nonzeroBitCount: Self { var result = Self() for i in indices { result[i] = Scalar(self[i].nonzeroBitCount) } return result } @_transparent public static prefix func ~(rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = ~rhs[i] } return result } @_transparent public static func &(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] & rhs[i] } return result } @_transparent public static func ^(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] ^ rhs[i] } return result } @_transparent public static func |(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] | rhs[i] } return result } @_transparent public static func &<<(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &<< rhs[i] } return result } @_transparent public static func &>>(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &>> rhs[i] } return result } @_transparent public static func &+(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &+ rhs[i] } return result } @_transparent public static func &-(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &- rhs[i] } return result } @_transparent public static func &*(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] &* rhs[i] } return result } @_transparent public static func /(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] / rhs[i] } return result } @_transparent public static func %(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] % rhs[i] } return result } /// Returns the sum of the scalars in the vector, computed with wrapping /// addition. /// /// Equivalent to indices.reduce(into: 0) { $0 &+= self[$1] }. @_alwaysEmitIntoClient public func wrappedSum() -> Scalar { return indices.reduce(into: 0) { $0 &+= self[$1] } } } // Implementations of floating-point operations. These should eventually all // be replaced with @_semantics to lower directly to vector IR nodes. extension SIMD where Scalar: FloatingPoint { @_transparent public static func +(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] + rhs[i] } return result } @_transparent public static func -(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] - rhs[i] } return result } @_transparent public static func *(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] * rhs[i] } return result } @_transparent public static func /(lhs: Self, rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = lhs[i] / rhs[i] } return result } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var result = Self() for i in result.indices { result[i] = self[i].addingProduct(lhs[i], rhs[i]) } return result } @_transparent public func squareRoot( ) -> Self { var result = Self() for i in result.indices { result[i] = self[i].squareRoot() } return result } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var result = Self() for i in result.indices { result[i] = self[i].rounded(rule) } return result } /// Returns the least scalar in the vector. @_alwaysEmitIntoClient public func min() -> Scalar { return indices.reduce(into: self[0]) { $0 = Scalar.minimum($0, self[$1]) } } /// Returns the greatest scalar in the vector. @_alwaysEmitIntoClient public func max() -> Scalar { return indices.reduce(into: self[0]) { $0 = Scalar.maximum($0, self[$1]) } } /// Returns the sum of the scalars in the vector. @_alwaysEmitIntoClient public func sum() -> Scalar { // Implementation note: this eventually be defined to lower to either // llvm.experimental.vector.reduce.fadd or an explicit tree-sum. Open- // coding the tree sum is problematic, we probably need to define a // Swift Builtin to support it. return indices.reduce(into: 0) { $0 += self[$1] } } } extension SIMDMask { @_transparent public static prefix func .!(rhs: SIMDMask) -> SIMDMask { return SIMDMask(~rhs._storage) } @_transparent public static func .&(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage & rhs._storage) } @_transparent public static func .^(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage ^ rhs._storage) } @_transparent public static func .|(lhs: SIMDMask, rhs: SIMDMask) -> SIMDMask { return SIMDMask(lhs._storage | rhs._storage) } } // These operations should never need @_semantics; they should be trivial // wrappers around the core operations defined above. extension SIMD where Scalar: FixedWidthInteger { @_transparent public static func &(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) & rhs } @_transparent public static func ^(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) ^ rhs } @_transparent public static func |(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) | rhs } @_transparent public static func &<<(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &<< rhs } @_transparent public static func &>>(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &>> rhs } @_transparent public static func &+(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &+ rhs } @_transparent public static func &-(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &- rhs } @_transparent public static func &*(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) &* rhs } @_transparent public static func /(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) / rhs } @_transparent public static func %(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) % rhs } @_transparent public static func &(lhs: Self, rhs: Scalar) -> Self { return lhs & Self(repeating: rhs) } @_transparent public static func ^(lhs: Self, rhs: Scalar) -> Self { return lhs ^ Self(repeating: rhs) } @_transparent public static func |(lhs: Self, rhs: Scalar) -> Self { return lhs | Self(repeating: rhs) } @_transparent public static func &<<(lhs: Self, rhs: Scalar) -> Self { return lhs &<< Self(repeating: rhs) } @_transparent public static func &>>(lhs: Self, rhs: Scalar) -> Self { return lhs &>> Self(repeating: rhs) } @_transparent public static func &+(lhs: Self, rhs: Scalar) -> Self { return lhs &+ Self(repeating: rhs) } @_transparent public static func &-(lhs: Self, rhs: Scalar) -> Self { return lhs &- Self(repeating: rhs) } @_transparent public static func &*(lhs: Self, rhs: Scalar) -> Self { return lhs &* Self(repeating: rhs) } @_transparent public static func /(lhs: Self, rhs: Scalar) -> Self { return lhs / Self(repeating: rhs) } @_transparent public static func %(lhs: Self, rhs: Scalar) -> Self { return lhs % Self(repeating: rhs) } @_transparent public static func &=(lhs: inout Self, rhs: Self) { lhs = lhs & rhs } @_transparent public static func ^=(lhs: inout Self, rhs: Self) { lhs = lhs ^ rhs } @_transparent public static func |=(lhs: inout Self, rhs: Self) { lhs = lhs | rhs } @_transparent public static func &<<=(lhs: inout Self, rhs: Self) { lhs = lhs &<< rhs } @_transparent public static func &>>=(lhs: inout Self, rhs: Self) { lhs = lhs &>> rhs } @_transparent public static func &+=(lhs: inout Self, rhs: Self) { lhs = lhs &+ rhs } @_transparent public static func &-=(lhs: inout Self, rhs: Self) { lhs = lhs &- rhs } @_transparent public static func &*=(lhs: inout Self, rhs: Self) { lhs = lhs &* rhs } @_transparent public static func /=(lhs: inout Self, rhs: Self) { lhs = lhs / rhs } @_transparent public static func %=(lhs: inout Self, rhs: Self) { lhs = lhs % rhs } @_transparent public static func &=(lhs: inout Self, rhs: Scalar) { lhs = lhs & rhs } @_transparent public static func ^=(lhs: inout Self, rhs: Scalar) { lhs = lhs ^ rhs } @_transparent public static func |=(lhs: inout Self, rhs: Scalar) { lhs = lhs | rhs } @_transparent public static func &<<=(lhs: inout Self, rhs: Scalar) { lhs = lhs &<< rhs } @_transparent public static func &>>=(lhs: inout Self, rhs: Scalar) { lhs = lhs &>> rhs } @_transparent public static func &+=(lhs: inout Self, rhs: Scalar) { lhs = lhs &+ rhs } @_transparent public static func &-=(lhs: inout Self, rhs: Scalar) { lhs = lhs &- rhs } @_transparent public static func &*=(lhs: inout Self, rhs: Scalar) { lhs = lhs &* rhs } @_transparent public static func /=(lhs: inout Self, rhs: Scalar) { lhs = lhs / rhs } @_transparent public static func %=(lhs: inout Self, rhs: Scalar) { lhs = lhs % rhs } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") public static func +(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") public static func -(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") public static func *(lhs: Self, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") public static func +(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") public static func -(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") public static func *(lhs: Self, rhs: Scalar) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead") public static func +(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead") public static func -(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead") public static func *(lhs: Scalar, rhs: Self) -> Self { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead") public static func +=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead") public static func -=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead") public static func *=(lhs: inout Self, rhs: Self) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead") public static func +=(lhs: inout Self, rhs: Scalar) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead") public static func -=(lhs: inout Self, rhs: Scalar) { fatalError() } @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead") public static func *=(lhs: inout Self, rhs: Scalar) { fatalError() } } extension SIMD where Scalar: FloatingPoint { @_transparent public static prefix func -(rhs: Self) -> Self { return 0 - rhs } @_transparent public static func +(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) + rhs } @_transparent public static func -(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) - rhs } @_transparent public static func *(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) * rhs } @_transparent public static func /(lhs: Scalar, rhs: Self) -> Self { return Self(repeating: lhs) / rhs } @_transparent public static func +(lhs: Self, rhs: Scalar) -> Self { return lhs + Self(repeating: rhs) } @_transparent public static func -(lhs: Self, rhs: Scalar) -> Self { return lhs - Self(repeating: rhs) } @_transparent public static func *(lhs: Self, rhs: Scalar) -> Self { return lhs * Self(repeating: rhs) } @_transparent public static func /(lhs: Self, rhs: Scalar) -> Self { return lhs / Self(repeating: rhs) } @_transparent public static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs } @_transparent public static func -=(lhs: inout Self, rhs: Self) { lhs = lhs - rhs } @_transparent public static func *=(lhs: inout Self, rhs: Self) { lhs = lhs * rhs } @_transparent public static func /=(lhs: inout Self, rhs: Self) { lhs = lhs / rhs } @_transparent public static func +=(lhs: inout Self, rhs: Scalar) { lhs = lhs + rhs } @_transparent public static func -=(lhs: inout Self, rhs: Scalar) { lhs = lhs - rhs } @_transparent public static func *=(lhs: inout Self, rhs: Scalar) { lhs = lhs * rhs } @_transparent public static func /=(lhs: inout Self, rhs: Scalar) { lhs = lhs / rhs } @_transparent public func addingProduct(_ lhs: Scalar, _ rhs: Self) -> Self { return self.addingProduct(Self(repeating: lhs), rhs) } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Scalar) -> Self { return self.addingProduct(lhs, Self(repeating: rhs)) } @_transparent public mutating func addProduct(_ lhs: Self, _ rhs: Self) { self = self.addingProduct(lhs, rhs) } @_transparent public mutating func addProduct(_ lhs: Scalar, _ rhs: Self) { self = self.addingProduct(lhs, rhs) } @_transparent public mutating func addProduct(_ lhs: Self, _ rhs: Scalar) { self = self.addingProduct(lhs, rhs) } @_transparent public mutating func formSquareRoot( ) { self = self.squareRoot() } @_transparent public mutating func round(_ rule: FloatingPointRoundingRule) { self = self.rounded(rule) } } extension SIMDMask { @_transparent public static func .&(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .& rhs } @_transparent public static func .^(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .^ rhs } @_transparent public static func .|(lhs: Bool, rhs: SIMDMask) -> SIMDMask { return SIMDMask(repeating: lhs) .| rhs } @_transparent public static func .&(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .& SIMDMask(repeating: rhs) } @_transparent public static func .^(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .^ SIMDMask(repeating: rhs) } @_transparent public static func .|(lhs: SIMDMask, rhs: Bool) -> SIMDMask { return lhs .| SIMDMask(repeating: rhs) } @_transparent public static func .&=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .& rhs } @_transparent public static func .^=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .^ rhs } @_transparent public static func .|=(lhs: inout SIMDMask, rhs: SIMDMask) { lhs = lhs .| rhs } @_transparent public static func .&=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .& rhs } @_transparent public static func .^=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .^ rhs } @_transparent public static func .|=(lhs: inout SIMDMask, rhs: Bool) { lhs = lhs .| rhs } } /// True if any lane of mask is true. @_alwaysEmitIntoClient public func any<Storage>(_ mask: SIMDMask<Storage>) -> Bool { return mask._storage.min() < 0 } /// True if every lane of mask is true. @_alwaysEmitIntoClient public func all<Storage>(_ mask: SIMDMask<Storage>) -> Bool { return mask._storage.max() < 0 } /// The lanewise minimum of two vectors. /// /// Each element of the result is the minimum of the corresponding elements /// of the inputs. @_alwaysEmitIntoClient public func pointwiseMin<T>(_ a: T, _ b: T) -> T where T: SIMD, T.Scalar: Comparable { var result = T() for i in result.indices { result[i] = min(a[i], b[i]) } return result } /// The lanewise maximum of two vectors. /// /// Each element of the result is the minimum of the corresponding elements /// of the inputs. @_alwaysEmitIntoClient public func pointwiseMax<T>(_ a: T, _ b: T) -> T where T: SIMD, T.Scalar: Comparable { var result = T() for i in result.indices { result[i] = max(a[i], b[i]) } return result } /// The lanewise minimum of two vectors. /// /// Each element of the result is the minimum of the corresponding elements /// of the inputs. @_alwaysEmitIntoClient public func pointwiseMin<T>(_ a: T, _ b: T) -> T where T: SIMD, T.Scalar: FloatingPoint { var result = T() for i in result.indices { result[i] = T.Scalar.minimum(a[i], b[i]) } return result } /// The lanewise maximum of two vectors. /// /// Each element of the result is the maximum of the corresponding elements /// of the inputs. @_alwaysEmitIntoClient public func pointwiseMax<T>(_ a: T, _ b: T) -> T where T: SIMD, T.Scalar: FloatingPoint { var result = T() for i in result.indices { result[i] = T.Scalar.maximum(a[i], b[i]) } return result } // Break the ambiguity between AdditiveArithmetic and SIMD for += and -= extension SIMD where Self: AdditiveArithmetic, Self.Scalar: FloatingPoint { @_alwaysEmitIntoClient public static func +=(lhs: inout Self, rhs: Self) { lhs = lhs + rhs } @_alwaysEmitIntoClient public static func -=(lhs: inout Self, rhs: Self) { lhs = lhs - rhs } }
95d2c49888913d0fd5cf878f781a6d7a
28.360759
136
0.652918
false
false
false
false
RoverPlatform/rover-ios
refs/heads/master
Sources/Data/EventQueue/EventInfo.swift
apache-2.0
1
// // EventInfo.swift // RoverData // // Created by Sean Rucker on 2017-11-30. // Copyright © 2017 Rover Labs Inc. All rights reserved. // import Foundation #if !COCOAPODS import RoverFoundation #endif public struct EventInfo { public let name: String public let namespace: String? public let attributes: Attributes? public let timestamp: Date? public init(name: String, namespace: String? = nil, attributes: Attributes? = nil, timestamp: Date? = nil) { self.name = name self.namespace = namespace self.attributes = attributes self.timestamp = timestamp } } public extension EventInfo { /// Create an EventInfo that tracks a Screen Viewed event for Analytics use. Use it for tracking screens & content in your app belonging to components other than Rover. init( screenViewedWithName screenName: String, contentID: String? = nil, contentName: String? = nil ) { let eventAttributes: Attributes = [:] eventAttributes["screenName"] = screenName if let contentID = contentID { eventAttributes["contentID"] = contentID } if let contentName = contentName { eventAttributes["contentName"] = contentName } // using a nil namespace to represent events for screens owned by the app vendor. self.init(name: "Screen Viewed", attributes: eventAttributes) } }
89707c09be2664d49dfbf6b9992b4219
28.4
173
0.646939
false
false
false
false
Rahulclaritaz/rahul
refs/heads/master
ixprez/ixprez/XPNotificationViewController.swift
mit
1
// // XPNotificationViewController.swift // ixprez // // Created by Claritaz Techlabs on 08/05/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit class XPNotificationViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,sectionData { var userEmail = String() var getEmotionUrl = URLDirectory.MyUpload() var getEmotionWebService = MyUploadWebServices() var commomWebService = XPWebService() var commonWebUrl = URLDirectory.notificationData() var getPrivateWebData = PrivateWebService() var getPrivateURL = URLDirectory.PrivateData() var recordPrivateData = [[String : Any]]() var recordMessageStatus = String() var checkAcceptUser : Bool! var showAddContact : Bool! @IBOutlet weak var myImage = UIImageView() var notificationCount = NSArray() var privateType : String! var privateIdValue : String! var privatefromEmail : String! var privateIndexPathLength : Int! var customAlertController : DOAlertController! @IBOutlet weak var notificationTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.checkAcceptUser = false self.showAddContact = false self.title = "Notification" userEmail = UserDefaults.standard.string(forKey: "emailAddress")! self.navigationController?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]; getBackGroundView() self.getValueFromService() self.notificationTableView.backgroundColor = UIColor.clear // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { } @IBAction func backButton (_sender : Any) { self.navigationController?.popViewController(animated: true) } func getBackGroundView () { self.myImage?.frame = CGRect(x: 0, y: 0, width: notificationTableView.frame.size.width, height: notificationTableView.frame.size.height) self.myImage?.image = UIImage(named: "SearchCaughtUPBGImage") self.myImage?.contentMode = .scaleAspectFit } func getValueFromService() { let parameter : NSDictionary = ["user_email" :userEmail,"limit" : "30","index":"0","notificationCount":"1"] commomWebService.getNotificationData(urlString: commonWebUrl.getNotificationData(), dicData: parameter, callBack: { (dicc,dic,erro) in print("check private web service data",dicc) let messageCode : String = dic.value(forKey: "code") as! String if (messageCode == "200") { self.recordPrivateData = dicc.value(forKey: "Records") as! [[String : Any]] } else { self.recordMessageStatus = dicc.value(forKey: "msg") as! String } DispatchQueue.main.async{ // self.refershController.beginRefreshing() // self.notificationTableView.reloadData() // // self.refershController.endRefreshing() } // self.recordPrivateData = dicc as [[String : Any]] // self.recordPrivateData = [myData as! [String : Any]] }) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 6 } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = UIColor.getXprezBlueColor() } func numberOfSections(in tableView: UITableView) -> Int { return recordPrivateData.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let privateData = recordPrivateData[indexPath.section] let privatecell = tableView.dequeueReusableCell(withIdentifier: "privatecell", for: indexPath) as! PrivateAudioVideoTableViewCell /* guard let getData = self.recordMessageStatus as? String else { privatecell.isHidden = false privatecell.lblPrivateTitle.text = privateData["title"] as? String privatecell.lblPrivateTitle.textColor = UIColor.getLightBlueColor() privatecell.lblPrivateTitleDescription.text = privateData["from_email"] as? String if (privatecell.lblPrivateTitleDescription.text == nil) { print("There is no data in the notification") } else { let checkIsContact = privateData["from_email"] as! String let username = privateData["title"] as? String let string1 : String = privateData["updatedAt"] as! String let dataStringFormatter = DateFormatter() dataStringFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let date1 = dataStringFormatter.date(from: string1) print("first formate date1",date1!) let dataStringFormatterTime = DateFormatter() dataStringFormatterTime.dateFormat = "hh:mm" let time1 : String = dataStringFormatterTime.string(from: date1!) print("time data",time1) let dataStringFormatterDay = DateFormatter() dataStringFormatterDay.dateFormat = "MMM d, YYYY" let day1 : String = dataStringFormatterDay.string(from: date1!) print("day data",day1) privatecell.lblPrivateTime.text = time1 privatecell.lblPrivateDate.text = day1 privatecell.layer.cornerRadius = 5.0 privatecell.layer.masksToBounds = true privatecell.imgPrivateVideoAudio.layer.cornerRadius = 5.0 privatecell.backgroundColor = UIColor.getPrivateCellColor() let privatefilemimeType = privateData["filemimeType"] as? String if privatefilemimeType == "video/mp4" { let btnplayVideo = UIImage(named: "privateplay") //privatecell.btnPrivatePlay.setImage(btnplayVideo, for: .normal) privatecell.imgAV.image = btnplayVideo var privatethumbnailPath = privateData["thumbnailPath"] as? String privatethumbnailPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/") print("privatethumbnailPath",privatethumbnailPath!) privatecell.imgPrivateVideoAudio.getImageFromUrl(privatethumbnailPath!) } else { let btnplayaudio = UIImage(named: "privateAudio" ) // privatecell.btnPrivatePlay.setImage( btnplayaudio , for:UIControlState.normal) privatecell.imgAV.image = btnplayaudio privatecell.imgPrivateVideoAudio.backgroundColor = UIColor.getLightBlueColor() } privatecell.btnPrivatePlay.tag = indexPath.section privatecell.btnPrivatePlay.addTarget(self, action: #selector(playVideoAudio(passUrl:)), for: .touchUpInside) if deviceEmailID.contains(checkIsContact) { privatecell.contentView.backgroundColor = UIColor.clear } else { // if checkAcceptUser == false // { // privatecell.contentView.backgroundColor = UIColor.red // // } // else // // { // // if !deviceEmailID.contains(checkIsContact) // { // createAddressBookContactWithFirstName(username!, lastName: "", email: checkIsContact , phone: "", image: UIImage(named: "bg_reg.png" )) // // privatecell.contentView.backgroundColor = UIColor.clear // // getContact() // // } // else // { // // privatecell.contentView.backgroundColor = UIColor.clear // // } // // // // } } } return privatecell } */ if ( self.recordMessageStatus == "No Records") { privatecell.isHidden = true self.myImage?.isHidden = false // let noDataLabel: UILabel = UILabel(frame:CGRect(x: 0, y: 0, width: privateTableView.bounds.size.width, height: privateTableView.bounds.size.height)) //noDataLabel.text = "No data available" // noDataLabel.textColor = UIColor.black // noDataLabel.textAlignment = .center // noDataLabel.textColor = UIColor.white // noDataLabel.font = UIFont(name: "Mosk", size: 20) notificationTableView.backgroundView = self.myImage notificationTableView.separatorStyle = .none } else { self.myImage?.isHidden = true privatecell.isHidden = false privatecell.lblPrivateName.text = privateData["from_name"] as? String privatecell.lblPrivateName.textColor = UIColor.getLightBlueColor() privatecell.lblPrivateTitle.text = privateData["title"] as? String if (privatecell.lblPrivateTitle.text == nil) { print("There is no data in the notification") } else { let checkIsContact = privateData["from_email"] as! String let username = privateData["title"] as? String let string1 : String = privateData["createdAt"] as! String let dataStringFormatter = DateFormatter() dataStringFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let date1 = dataStringFormatter.date(from: string1) print("first formate date1",date1!) let dataStringFormatterTime = DateFormatter() dataStringFormatterTime.dateFormat = "hh:mm" let time1 : String = dataStringFormatterTime.string(from: date1!) print("time data",time1) let dataStringFormatterDay = DateFormatter() dataStringFormatterDay.dateFormat = "MMM d, YYYY" let day1 : String = dataStringFormatterDay.string(from: date1!) print("day data",day1) privatecell.lblPrivateTime.text = time1 privatecell.lblPrivateDate.text = day1 privatecell.layer.cornerRadius = 5.0 privatecell.layer.masksToBounds = true privatecell.imgPrivateVideoAudio.layer.cornerRadius = 5.0 privatecell.backgroundColor = UIColor.getPrivateCellColor() let privatefilemimeType = privateData["filemimeType"] as? String if privatefilemimeType == "video/mp4" { let btnplayVideo = UIImage(named: "privateplay") //privatecell.btnPrivatePlay.setImage(btnplayVideo, for: .normal) privatecell.imgAV.image = btnplayVideo var privatethumbnailPath = privateData["thumbnailPath"] as? String privatethumbnailPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/") print("privatethumbnailPath",privatethumbnailPath!) privatecell.imgPrivateVideoAudio.getImageFromUrl(privatethumbnailPath!) } else { let btnplayaudio = UIImage(named: "privateAudio" ) // privatecell.btnPrivatePlay.setImage( btnplayaudio , for:UIControlState.normal) privatecell.imgAV.image = btnplayaudio privatecell.imgPrivateVideoAudio.backgroundColor = UIColor.getLightBlueColor() } privatecell.btnPrivatePlay.tag = indexPath.section privatecell.btnPrivatePlay.addTarget(self, action: #selector(playVideoAudio(passUrl:)), for: .touchUpInside) if deviceEmailID.contains(checkIsContact) { privatecell.contentView.backgroundColor = UIColor.clear } else { // if checkAcceptUser == false // { // privatecell.contentView.backgroundColor = UIColor.red // // } // else // // { // // if !deviceEmailID.contains(checkIsContact) // { // createAddressBookContactWithFirstName(username!, lastName: "", email: checkIsContact , phone: "", image: UIImage(named: "bg_reg.png" )) // // privatecell.contentView.backgroundColor = UIColor.clear // // getContact() // // } // else // { // // privatecell.contentView.backgroundColor = UIColor.clear // // } // // // // } } } return privatecell } return privatecell } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { var privateDataDic = self.recordPrivateData[indexPath.section] let privacyType : String = privateDataDic["privacy"] as! String if (privacyType == "Private") { self.privateType = privateDataDic["filemimeType"] as? String self.privateIdValue = privateDataDic["_id"] as? String self.privatefromEmail = privateDataDic["from_email"] as? String privateIndexPathLength = indexPath.section print("check mathan email_id",self.privatefromEmail) print(privateIndexPathLength) if self.privateType == "video/mp4" { self.privateType = "video" } else { self.privateType = "audio" } let blockAction = UITableViewRowAction(style: .normal, title: " ", handler: { (action,index) in if deviceEmailID.contains(self.privatefromEmail) { self.showAddContact = true } else { self.showAddContact = false } print("block") self.getBlockAction() }) blockAction.backgroundColor = UIColor(patternImage: UIImage(named: "privateBlock")!) // blockAction.backgroundColor = UIColor.red let rejectAction = UITableViewRowAction(style: .normal, title: " ", handler: { (action,index) in print("reject") self.getRejectAction() }) rejectAction.backgroundColor = UIColor(patternImage: UIImage(named: "privateReject")!) // rejectAction.backgroundColor = UIColor.green let acceptAction = UITableViewRowAction(style: .normal, title: " ", handler: { (action,index) in print("accept") self.getAcceptAction() }) acceptAction.backgroundColor = UIColor(patternImage: UIImage(named: "privateAccept")!) // acceptAction.backgroundColor = UIColor.blue return [blockAction ,rejectAction ,acceptAction] } else { self.privateType = privateDataDic["filemimeType"] as? String self.privateIdValue = privateDataDic["_id"] as? String self.privatefromEmail = privateDataDic["from_email"] as? String privateIndexPathLength = indexPath.section print("check mathan email_id",self.privatefromEmail) print(privateIndexPathLength) if self.privateType == "video/mp4" { self.privateType = "video" } else { self.privateType = "audio" } // let blockAction = UITableViewRowAction(style: .normal, title: " ", handler: // { // (action,index) in // // // if deviceEmailID.contains(self.privatefromEmail) // { // self.showAddContact = true // } // else // { // self.showAddContact = false // } // print("block") // // self.getBlockAction() // // // // }) // // blockAction.backgroundColor = UIColor(patternImage: UIImage(named: "privateBlock")!) // blockAction.backgroundColor = UIColor.red // let rejectAction = UITableViewRowAction(style: .normal, title: " ", handler: { // (action,index) in // print("reject") // // self.getRejectAction() // // }) // // rejectAction.backgroundColor = UIColor(patternImage: UIImage(named: "privateReject")!) // rejectAction.backgroundColor = UIColor.green let followUser = UITableViewRowAction(style: .normal, title: " ", handler: { (action,index) in print("follow user") // self.getAcceptAction() }) followUser.backgroundColor = UIColor(patternImage: UIImage(named: "NotificationUnfollowImage")!) // followUser.backgroundColor = UIColor.blue return [followUser] } } func playVideoAudio(passUrl : UIButton) { // let indexPath = Int(passUrl.tag) // let currentCell = privateTableView.cellForRow(at: indexPath) as! PrivateAudioVideoTableViewCell //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:[Sender tag]]; let indexPathValue = NSIndexPath(row: 0, section: passUrl.tag) var playPrivateData = recordPrivateData[indexPathValue.section] var playVideoPath = playPrivateData["tokenizedUrl"] as? String let playVideoTitle = playPrivateData["title"] as? String let playVideoFromEmail = playPrivateData["from_email"] as? String let playId = playPrivateData["_id"] as? String let playType = playPrivateData["filemimeType"] as? String let playTypeValue : String? if playType == "video/mp4" { playTypeValue = "video" } else { playTypeValue = "audio" } //http://192.168.1.20:3000 // playVideoPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/") // playVideoPath?.replace("/var/www/html/xpresslive/Xpress/", with: "http://192.168.1.20:3000/") print(playVideoPath!) let playViewController = self.storyboard?.instantiateViewController(withIdentifier: "XPPriavtePlayVideoAudioViewController") as! XPPriavtePlayVideoAudioViewController playViewController.privateUrlString = playVideoPath! playViewController.privateTitle = playVideoTitle! playViewController.idValue = playId! playViewController.typeVideo = playTypeValue! playViewController.fromEmail = playVideoFromEmail! playViewController.sectionNo = passUrl.tag playViewController.delegate = self self.navigationController?.pushViewController(playViewController, animated: true) } func sectionnumber( no : Int ) { // remove the data from array recordPrivateData.remove(at: no) // remove the section from tableview self.notificationTableView.beginUpdates() notificationTableView.deleteSections([no], with: .automatic) self.notificationTableView.endUpdates() } func getBlockAction() { if showAddContact == false { let title = self.privatefromEmail let message = "can’t Express themselves to you anymore. Sure you want ro proceed?" let cancelButtonTitle = "Cancel" let otherButtonTitle = "Reject & Block" let otherButtonTitle1 = "Add Contact" let otherBottonTitle2 = "Report SPAM" print(self.privatefromEmail) print(self.privateIdValue) print(self.privateType) customAlertController = DOAlertController(title: title, message: message, preferredStyle: .alert) self.changecustomAlertController() // customAlertController.overlayColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.1) let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in print("hi") }) let otherAction = DOAlertAction(title: otherButtonTitle, style: .default, handler:{ action in let dicValue = [ "user_email" : self.userEmail , "blocked_email": self.privatefromEmail ] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateBlockAudioVideo(), dicData: dicValue as NSDictionary, callback: { (dicc, erro) in DispatchQueue.main.async { self.notificationTableView.beginUpdates() // Remove item from the array self.recordPrivateData.remove(at: self.privateIndexPathLength) // Delete the row from the table view self.notificationTableView.deleteSections([self.privateIndexPathLength], with: .fade) self.notificationTableView.endUpdates() } if ((dicc["status"] as! String).isEqual("OK")) { let dicValue = [ "id" : self.privateIdValue , "video_type" : self.privateType , "feedback" : "0"] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateAcceptRejectAudioVideo(), dicData: dicValue as NSDictionary, callback:{ (dicc,err) in }) } }) }) let otherAction1 = DOAlertAction(title: otherButtonTitle1, style: .default, handler: { action in self.checkAcceptUser = true DispatchQueue.main.async { /* for i in 0...self.recordPrivateData.count { let indexPath = IndexPath(row: 0, section: i) self.privateTableView.rectForRow(at: indexPath) }*/ self.notificationTableView.reloadData() } print("add") }) let otherAction2 = DOAlertAction(title: otherBottonTitle2, style: .default, handler: { action in self.dismiss(animated:true, completion: { () -> Void in let title = "Report Abuse" //let message = "A message should be a short, complete sentence." let cancelButtonTitle = "DISCARD" let otherButtonTitle = "POST" self.customAlertController = DOAlertController(title: title, message: nil, preferredStyle: .alert) self.changecustomAlertController() // Add the text field for text entry. // alert.addTextField(configurationHandler: textFieldHandler) self.customAlertController.addTextFieldWithConfigurationHandler { textField in textField?.frame.size = CGSize(width: 240.0, height: 30.0) textField?.font = UIFont(name: "Mosk", size: 15.0) textField?.textColor = UIColor.blue textField?.keyboardAppearance = UIKeyboardAppearance.dark textField?.returnKeyType = UIReturnKeyType.send // textfield1 = textField! // textField?.delegate = self as! UITextFieldDelegate // If you need to customize the text field, you can do so here. } // Create the actions. let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel) { action in NSLog("The \"Text Entry\" alert's cancel action occured.") } let otherAction = DOAlertAction(title: otherButtonTitle, style: .default) { action in NSLog("The \"Text Entry\" alert's other action occured.") let textFields = self.customAlertController.textFields as? Array<UITextField> if textFields != nil { for textField: UITextField in textFields! { print("mathan Check",textField.text!) let dicData = [ "user_email" :self.privatefromEmail , "description" : textField.text! , "file_id" : self.privateIdValue , "file_type" : self.privateType] as [String : Any] self.getEmotionWebService.getReportMyUploadWebService(urlString: self.getEmotionUrl.uploadReportAbuse(), dicData: dicData as NSDictionary, callback: { (dicc,erro) in print(dicc) }) } } } // Add the actions. self.customAlertController.addAction(cancelAction) self.customAlertController.addAction(otherAction) self.present(self.customAlertController , animated: true, completion: nil) }) }) customAlertController.addAction(otherAction1) customAlertController.addAction(otherAction2) customAlertController.addAction(cancelAction) customAlertController.addAction(otherAction) self.present(customAlertController, animated: true, completion: nil) } else { let title = self.privatefromEmail let message = "can’t Express themselves to you anymore. Sure you want ro proceed?" let cancelButtonTitle = "Cancel" let otherButtonTitle = "Reject & Block" print(self.privatefromEmail) print(self.privateIdValue) print(self.privateType) customAlertController = DOAlertController(title: title, message: message, preferredStyle: .alert) self.changecustomAlertController() // customAlertController.overlayColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.1) let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in print("hi") }) let otherAction = DOAlertAction(title: otherButtonTitle, style: .default, handler:{ action in let dicValue = [ "user_email" : self.userEmail , "blocked_email": self.privatefromEmail ] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateBlockAudioVideo(), dicData: dicValue as NSDictionary, callback: { (dicc, erro) in DispatchQueue.main.async { self.notificationTableView.beginUpdates() // Remove item from the array self.recordPrivateData.remove(at: self.privateIndexPathLength) // Delete the row from the table view self.notificationTableView.deleteSections([self.privateIndexPathLength], with: .fade) self.notificationTableView.endUpdates() } if ((dicc["status"] as! String).isEqual("OK")) { let dicValue = [ "id" : self.privateIdValue , "video_type" : self.privateType , "feedback" : "0"] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateAcceptRejectAudioVideo(), dicData: dicValue as NSDictionary, callback:{ (dicc,err) in }) } }) }) customAlertController.addAction(cancelAction) customAlertController.addAction(otherAction) self.present(customAlertController, animated: true, completion: nil) } } func getRejectAction() { let title = self.privatefromEmail let message = "wanted to Xpress this to you badly . Are you sure you want to reject it?" let cancelButtonTitle = "Cancel" let otherButtonTitle = "Confirm Rejection" print(self.privatefromEmail) print(self.privateIdValue) print(self.privateType) customAlertController = DOAlertController(title: title, message: message, preferredStyle: .alert) self.changecustomAlertController() // customAlertController.overlayColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.1) let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in print("hi") }) let otherAction = DOAlertAction(title: otherButtonTitle, style: .default, handler:{ action in let dicValue = [ "id" : self.privateIdValue , "video_type" : self.privateType , "feedback" : "0"] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateAcceptRejectAudioVideo(), dicData: dicValue as NSDictionary, callback:{ (dicc,err) in if ((dicc["status"] as! String).isEqual("OK")) { let dicData = [ "description" : "Accept","file_id" :self.privateIdValue ,"file_type" : self.privateType ,"user_email" :self.privatefromEmail ] as [String : Any] self.getPrivateWebData.getPrivateData(urlString: self.getPrivateURL.audioVideoReportAbuse(), dicData: dicData, callback: { (dic, err) in print("check Private Data report Abuse",dic) }) DispatchQueue.main.async { self.notificationTableView.beginUpdates() // Remove item from the array self.recordPrivateData.remove(at: self.privateIndexPathLength) // Delete the row from the table view self.notificationTableView.deleteSections([self.privateIndexPathLength], with: .fade) self.notificationTableView.endUpdates() } } }) }) customAlertController.addAction(cancelAction) customAlertController.addAction(otherAction) self.present(customAlertController, animated: true, completion: nil) } func getAcceptAction() { let title = self.privatefromEmail let message = "It's your turn to xpress! Want to reply right now and xpress yourself back to them? Do it" let cancelButtonTitle = "Cancel" let otherButtonTitle = "Xpress it" print(self.privatefromEmail) print(self.privateIdValue) print(self.privateType) customAlertController = DOAlertController(title: title, message: message, preferredStyle: .alert) self.changecustomAlertController() // customAlertController.overlayColor = UIColor(red:255/255, green:255/255, blue:255/255, alpha:0.1) let cancelAction = DOAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in print("hi") }) let otherAction = DOAlertAction(title: otherButtonTitle, style: .default, handler:{ action in let dicValue = [ "id" : self.privateIdValue , "video_type" : self.privateType , "feedback" : "1"] self.getPrivateWebData.getPrivateAcceptRejectWebService(urlString: self.getPrivateURL.privateAcceptRejectAudioVideo(), dicData: dicValue as NSDictionary, callback:{ (dicc,err) in if ((dicc["status"] as! String).isEqual("OK")) { let dicData = [ "description" : "Accept","file_id" :self.privateIdValue ,"file_type" : self.privateType ,"user_email" :self.privatefromEmail ] as [String : Any] self.getPrivateWebData.getPrivateData(urlString: self.getPrivateURL.audioVideoReportAbuse(), dicData: dicData, callback: { (dic, err) in print("check Private Data report Abuse",dic) }) //http://103.235.104.118:3000/commandService/audioVideoReportAbuse /* "{ ""description"": ""ggahhajajajakakq"", ""file_id"": ""5923ec0cbf18f87f42727888"", ""file_type"": ""video/mp4"", ""user_email"": ""[email protected]""}" */ DispatchQueue.main.async { self.notificationTableView.beginUpdates() // Remove item from the array self.recordPrivateData.remove(at: self.privateIndexPathLength) // Delete the row from the table view self.notificationTableView.deleteSections([self.privateIndexPathLength], with: .automatic) self.notificationTableView.endUpdates() } } }) }) customAlertController.addAction(cancelAction) customAlertController.addAction(otherAction) self.present(customAlertController, animated: true, completion: nil) } func changecustomAlertController() { customAlertController.alertView.layer.cornerRadius = 6.0 customAlertController.alertViewBgColor = UIColor(red:255-255, green:255-255, blue:255-255, alpha:0.7) customAlertController.titleFont = UIFont(name: "Mosk", size: 17.0) customAlertController.titleTextColor = UIColor.green customAlertController.messageFont = UIFont(name: "Mosk", size: 12.0) customAlertController.messageTextColor = UIColor.white customAlertController.buttonFont[.cancel] = UIFont(name: "Mosk", size: 15.0) customAlertController.buttonBgColor[.cancel] = UIColor.getLightBlueColor() customAlertController.buttonFont[.default] = UIFont(name: "Mosk", size: 15.0) customAlertController.buttonBgColor[.default] = UIColor.getOrangeColor() customAlertController.buttonBgColor[.destructive] = UIColor.red customAlertController.buttonFont[.destructive] = UIFont.xprezMediumFontOfsize(size: 15.0) //customAlertController.buttons } /* // 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. } */ }
4e79846bd1934602fa3d4f9ce8ca77ad
31.13087
182
0.505774
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureApp/Sources/FeatureAppUI/VerifyDevice/AuthorizeDeviceViewController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import ComposableArchitecture import FeatureAuthenticationDomain import FeatureAuthenticationUI import PlatformUIKit import SwiftUI import UIKit public final class AuthorizeDeviceViewController: UINavigationController { // MARK: - Properties private let store: Store<AuthorizeDeviceState, AuthorizeDeviceAction> private let viewStore: ViewStore<AuthorizeDeviceState, AuthorizeDeviceAction> private let viewDismissed: () -> Void private var detailsScreenViewController: DetailsScreenViewController? private var cancellables = Set<AnyCancellable>() // MARK: - Setup public init( store: Store<AuthorizeDeviceState, AuthorizeDeviceAction>, viewDismissed: @escaping () -> Void ) { self.store = store self.viewDismissed = viewDismissed viewStore = ViewStore(store) super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle override public func viewDidLoad() { super.viewDidLoad() setup() viewStore .publisher .authorizationResult .compactMap { $0 } .sink { [weak self] result in guard let self = self else { return } self.showAuthorizationResult(result) } .store(in: &cancellables) } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) viewDismissed() } override public func viewDidLayoutSubviews() { detailsScreenViewController?.view.frame = view.bounds } // MARK: Methods private func setup() { setNavigationBarHidden(true, animated: true) navigationItem.setHidesBackButton(true, animated: true) let presenter = VerifyDeviceDetailsScreenPresenter( details: viewStore.loginRequestInfo.details, requestTime: viewStore.loginRequestInfo.timestamp, didAuthorizeDevice: { [weak self] authorized in guard let self = self else { return } self.viewStore.send(.handleAuthorization(authorized)) } ) let vc = DetailsScreenViewController(presenter: presenter) detailsScreenViewController = vc add(child: vc) } private func showAuthorizationResult(_ result: AuthorizationResult) { var viewController: UIHostingController<AuthorizationResultView> var view: AuthorizationResultView switch result { case .success: view = .success case .linkExpired: view = .linkExpired case .requestDenied: view = .rejected case .unknown: view = .unknown } view.okButtonPressed = { self.dismiss(animated: true, completion: nil) } viewController = UIHostingController(rootView: view) pushViewController(viewController, animated: true) detailsScreenViewController = nil } }
9fb5c645a856e3abf388d189d0459d03
29.990291
81
0.648496
false
false
false
false
Desgard/Calendouer-iOS
refs/heads/master
Calendouer/Calendouer/App/Model/AirObject.swift
mit
1
// // AirObject.swift // Calendouer // // Created by 段昊宇 on 2017/4/21. // Copyright © 2017年 Desgard_Duan. All rights reserved. // import UIKit class AirObject: NSObject { var aqi = "" var co = "" var no2 = "" var o3 = "" var pm10 = "" var pm25 = "" var qlty = "" var so2 = "" var txt = "" }
714b94f92801ad11db7d0cdcee47b219
14.857143
56
0.525526
false
false
false
false
Brightify/ReactantUI
refs/heads/master
Sources/Tokenizer/Layout/Layout.swift
mit
1
// // Layout.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation /** * Layout information deserialized from XML element. Contains constraints, compression and hugging priorities as well as the layout ID * which is exclusive to ReactantUI. * - NOTE: Conditions inside constraints in the layout are evaluated independently on each other. */ public struct Layout: XMLElementDeserializable { static let nonConstraintables = ["layout:id", "layout:compressionPriority.vertical", "layout:compressionPriority.horizontal", "layout:compressionPriority", "layout:huggingPriority.vertical", "layout:huggingPriority.horizontal", "layout:huggingPriority"] public var id: String? public var contentCompressionPriorityHorizontal: ConstraintPriority? public var contentCompressionPriorityVertical: ConstraintPriority? public var contentHuggingPriorityHorizontal: ConstraintPriority? public var contentHuggingPriorityVertical: ConstraintPriority? public var constraints: [Constraint] public var hasConditions: Bool init(id: String? = nil, contentCompressionPriorityHorizontal: ConstraintPriority?, contentCompressionPriorityVertical: ConstraintPriority?, contentHuggingPriorityHorizontal: ConstraintPriority?, contentHuggingPriorityVertical: ConstraintPriority?, constraints: [Constraint] = []) { self.id = id self.constraints = constraints self.contentCompressionPriorityHorizontal = contentCompressionPriorityHorizontal self.contentCompressionPriorityVertical = contentCompressionPriorityVertical self.contentHuggingPriorityHorizontal = contentHuggingPriorityHorizontal self.contentHuggingPriorityVertical = contentHuggingPriorityVertical self.hasConditions = constraints.firstIndex(where: { $0.condition != nil }) != nil } /** * Get all layout information from the passed XML element. * - parameter node: XML element to parse * - returns: constructed layout information in form of `Layout` */ public static func deserialize(_ node: XMLElement) throws -> Layout { let layoutAttributes = node.allAttributes .filter { $0.key.hasPrefix("layout:") && !nonConstraintables.contains($0.key) } .map { ($0.replacingOccurrences(of: "layout:", with: ""), $1) } var contentCompressionPriorityHorizontal: ConstraintPriority? var contentCompressionPriorityVertical: ConstraintPriority? var contentHuggingPriorityHorizontal: ConstraintPriority? var contentHuggingPriorityVertical: ConstraintPriority? if let compressionPriority = node.value(ofAttribute: "layout:compressionPriority") as String? { let priority = try ConstraintPriority(compressionPriority) contentCompressionPriorityHorizontal = priority contentCompressionPriorityVertical = priority } if let verticalCompressionPriority = node.value(ofAttribute: "layout:compressionPriority.vertical") as String? { contentCompressionPriorityVertical = try ConstraintPriority(verticalCompressionPriority) } if let horizontalCompressionPriority = node.value(ofAttribute: "layout:compressionPriority.horizontal") as String? { contentCompressionPriorityHorizontal = try ConstraintPriority(horizontalCompressionPriority) } if let huggingPriority = node.value(ofAttribute: "layout:huggingPriority") as String? { let priority = try ConstraintPriority(huggingPriority) contentHuggingPriorityHorizontal = priority contentHuggingPriorityVertical = priority } if let verticalHuggingPriority = node.value(ofAttribute: "layout:huggingPriority.vertical") as String? { contentHuggingPriorityVertical = try ConstraintPriority(verticalHuggingPriority) } if let horizontalHuggingPriority = node.value(ofAttribute: "layout:huggingPriority.horizontal") as String? { contentHuggingPriorityHorizontal = try ConstraintPriority(horizontalHuggingPriority) } return try Layout( id: node.value(ofAttribute: "layout:id"), contentCompressionPriorityHorizontal: contentCompressionPriorityHorizontal, contentCompressionPriorityVertical: contentCompressionPriorityVertical, contentHuggingPriorityHorizontal: contentHuggingPriorityHorizontal, contentHuggingPriorityVertical: contentHuggingPriorityVertical, constraints: layoutAttributes.flatMap(Constraint.constraints(name:attribute:))) } }
9c30819a915d115485ae0d6d2f9d6b65
48.29
134
0.706228
false
false
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Classes/Reusable/Clients/StudentSchedule/StudentScheduleClient.swift
apache-2.0
1
// // StudentScheduleClient.swift // byuSuite // // Created by Erik Brady on 1/23/18. // Copyright © 2018 Brigham Young University. All rights reserved. // private let BASE_URL = "https://api.byu.edu/domains/legacy/academic/registration/studentschedule/v1" class StudentScheduleClient: ByuClient2 { static func getStudentSchedule(yearTerm: String, callback: @escaping (StudentSchedule?, ByuError?) -> Void) { ByuCredentialManager.getPersonSummary { (personSummary, error) in if let personSummary = personSummary { let request = ByuRequest2(url: super.url(base: BASE_URL, pathParams: [personSummary.personId, yearTerm])) makeRequest(request, callback: { (response) in if let dict = response.getDataJson() as? [String: Any], let data = dict[keyPath: "WeeklySchedService.response"] as? [String: Any] { callback(StudentSchedule(dict: data), nil) } else { callback(nil, response.error) } }) } else { callback(nil, PERSON_SUMMARY_ERROR) } } } }
7baccf65cfa86900d500b6e241766f72
30.84375
110
0.693817
false
false
false
false
itechline/bonodom_new
refs/heads/master
SlideMenuControllerSwift/EstateModel.swift
mit
1
// // EstateModel.swift // Bonodom // // Created by Attila Dán on 2016. 06. 08.. // Copyright © 2016. Itechline. All rights reserved. // import SwiftyJSON class EstateModel { var id: Int! var adress: String! var street: String! var description: String! var price: String! var size: String! var pictures: [String]! = [] var ingatlan_szsz_id: String! var ingatlan_szsz: String! var ingatlan_parkolas_id: String! var mobil: String! var ingatlan_lift: Int! var ingatlan_emelet_id: String! var ingatlan_parkolas: String! var ingatlan_title: String! var ingatlan_kilatas: String! var ingatlan_allapot_id: String! var ingatlan_varos: String! var ingatlan_energiatan_id: String! var ingatlan_butorozott: Int! var ingatlan_tipus_id: String! var ingatlan_tipus: String! var ingatlan_kilatas_id: String! var vezeteknev: String! var keresztnev: String! var ingatlan_allapot: String! var ingatlan_ar: String! var kedvenc: Bool! var ing_e_type: String! var ingatlan_utca: String! var ingatlan_lat: Double! var ingatlan_lng: Double! var ingatlan_id: String! var ing_e_type_id: Int! var ingatlan_rovidleiras: String! var ingatlan_futestipus: String! var ingatlan_emelet: String! var face: String! var ingatlan_erkely: Int! var felh_tipus: String! var ingatlan_energiatan: String! var ingatlan_futestipus_id: String! var finish: String! var start: String! var hetfo: Int! var kedd: Int! var szerda: Int! var csutortok: Int! var pentek: Int! var szombat: Int! var vasarnap: Int! /* { "ingatlan_szsz_id" : "0", "ingatlan_szsz" : "", "ingatlan_parkolas_id" : "0", "mobil" : "06203232", "ingatlan_lift" : "0", "ingatlan_emelet_id" : "0", "ingatlan_parkolas" : "", "ingatlan_title" : "hsh", "ingatlan_kilatas" : "", "ingatlan_allapot_id" : "0", "ingatlan_varos" : "Debrecen", "ingatlan_energiatan_id" : "0", "ingatlan_butorozott" : "3", "ingatlan_tipus_id" : "0", "ingatlan_tipus" : "", "ingatlan_kilatas_id" : "0", "vezeteknev" : "Dan", "ingatlan_allapot" : "", "ingatlan_picture_url" : "", "ingatlan_ar" : "652", "kedvenc" : "false", "keresztnev" : "Attila", "ing_e_type" : "Eladó", "ingatlan_utca" : "Piac", "ingatlan_lng" : "", "ingatlan_id" : "259", "kepek" : [ { "kepek_url" : "https:\/\/bonodom.com\/ing\/img\/1920_1080\/b33ea9ed248368cc1efd756e90f2bca2.png" }, { "kepek_url" : "https:\/\/bonodom.com\/ing\/img\/1920_1080\/3c6eb37b34eef2ee71af45b7f3fef657.png" }, { "kepek_url" : "https:\/\/bonodom.com\/ing\/img\/1920_1080\/89547ff2bd6e87ef8dde0b69d0111e33.png" } ], "ing_e_type_id" : "1", "ingatlan_rovidleiras" : "hshs", "ingatlan_futestipus" : "", "ingatlan_emelet" : "", "ingatlan_meret" : "88", "ingatlan_lat" : "", "face" : "", "ingatlan_erkely" : "0", "tipus" : "", "ingatlan_energiatan" : "", "ingatlan_futestipus_id" : "0" } */ required init(json: JSON) { id = json["ingatlan_id"].intValue ingatlan_title = json["ingatlan_title"].stringValue adress = json["ingatlan_varos"].stringValue street = json["ingatlan_utca"].stringValue description = json["ingatlan_rovidleiras"].stringValue price = json["ingatlan_ar"].stringValue size = json["ingatlan_meret"].stringValue keresztnev = json["keresztnev"].stringValue vezeteknev = json["vezeteknev"].stringValue ing_e_type = json["ing_e_type"].stringValue ing_e_type_id = json["ing_e_type_id"].intValue ingatlan_futestipus = json["ingatlan_futestipus"].stringValue ingatlan_szsz = json["ingatlan_szsz"].stringValue ingatlan_parkolas = json["ingatlan_parkolas"].stringValue mobil = json["mobil"].stringValue ingatlan_lift = json["ingatlan_lift"].intValue ingatlan_emelet = json["ingatlan_emelet"].stringValue ingatlan_allapot = json["ingatlan_allapot"].stringValue ingatlan_energiatan = json["ingatlan_energiatan"].stringValue ingatlan_butorozott = json["ingatlan_butorozott"].intValue ingatlan_tipus = json["ingatlan_tipus"].stringValue ingatlan_kilatas = json["ingatlan_kilatas"].stringValue kedvenc = json["kedvenc"].boolValue ingatlan_erkely = json["ingatlan_erkely"].intValue ingatlan_lat = json["ingatlan_lat"].doubleValue ingatlan_lng = json["ingatlan_lng"].doubleValue face = json["face"].stringValue felh_tipus = json["tipus"].stringValue for picArray in json["kepek"] { print ("PICTURE") print(picArray.1["kepek_url"].stringValue) pictures.append(picArray.1["kepek_url"].stringValue) //pic = picArray.1["kepek_url"].stringValue //pic.append(picArray.1["kepek_url"].stringValue) } for timeArray in json["showtime"] { start = timeArray.1["start"].stringValue finish = timeArray.1["finish"].stringValue hetfo = timeArray.1["mon"].intValue kedd = timeArray.1["tue"].intValue szerda = timeArray.1["wed"].intValue csutortok = timeArray.1["thu"].intValue pentek = timeArray.1["fri"].intValue szombat = timeArray.1["sat"].intValue vasarnap = timeArray.1["sun"].intValue } /*if (pictures.isEmpty) { pictures.append("") }*/ } }
bc9e6ecc4bdd96f5c38a6e7c00cdbe58
31.885714
101
0.59583
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/UserProfile/ProfileViewControllerViewModel.swift
gpl-3.0
1
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel import WireSystem import WireSyncEngine private let zmLog = ZMSLog(tag: "ProfileViewControllerViewModel") enum ProfileViewControllerContext { case search case groupConversation case oneToOneConversation case deviceList /// when opening from a URL scheme, not linked to a specific conversation case profileViewer } final class ProfileViewControllerViewModel: NSObject { let user: UserType let conversation: ZMConversation? let viewer: UserType let context: ProfileViewControllerContext let classificationProvider: ClassificationProviding? weak var delegate: ProfileViewControllerDelegate? { didSet { backButtonTitleDelegate = delegate as? BackButtonTitleDelegate } } weak var backButtonTitleDelegate: BackButtonTitleDelegate? private var observerToken: Any? weak var viewModelDelegate: ProfileViewControllerViewModelDelegate? init(user: UserType, conversation: ZMConversation?, viewer: UserType, context: ProfileViewControllerContext, classificationProvider: ClassificationProviding? = ZMUserSession.shared() ) { self.user = user self.conversation = conversation self.viewer = viewer self.context = context self.classificationProvider = classificationProvider super.init() if let userSession = ZMUserSession.shared() { observerToken = UserChangeInfo.add(observer: self, for: user, in: userSession) } } var classification: SecurityClassification { classificationProvider?.classification(with: [user]) ?? .none } var hasLegalHoldItem: Bool { return user.isUnderLegalHold || conversation?.isUnderLegalHold == true } var shouldShowVerifiedShield: Bool { return user.isVerified && context != .deviceList } var hasUserClientListTab: Bool { return context != .search && context != .profileViewer } var userSet: UserSet { return UserSet(arrayLiteral: user) } var incomingRequestFooterHidden: Bool { return !user.isPendingApprovalBySelfUser } var blockTitle: String? { return BlockResult.title(for: user) } var allBlockResult: [BlockResult] { return BlockResult.all(isBlocked: user.isBlocked) } func cancelConnectionRequest(completion: @escaping Completion) { self.user.cancelConnectionRequest { [weak self] error in if let error = error as? ConnectToUserError { self?.viewModelDelegate?.presentError(error) } else { completion() } } } func toggleBlocked() { if user.isBlocked { user.accept { [weak self] error in if let error = error as? LocalizedError { self?.viewModelDelegate?.presentError(error) } } } else { user.block { [weak self] error in if let error = error as? LocalizedError { self?.viewModelDelegate?.presentError(error) } } } } func openOneToOneConversation() { var conversation: ZMConversation? ZMUserSession.shared()?.enqueue({ conversation = self.user.oneToOneConversation }, completionHandler: { guard let conversation = conversation else { return } self.delegate?.profileViewController(self.viewModelDelegate as? ProfileViewController, wantsToNavigateTo: conversation) }) } // MARK: - Action Handlers func archiveConversation() { transitionToListAndEnqueue { self.conversation?.isArchived.toggle() } } func handleBlockAndUnblock() { switch context { case .search: /// stay on this VC and let user to decise what to do next enqueueChanges(toggleBlocked) default: transitionToListAndEnqueue { self.toggleBlocked() } } } // MARK: - Notifications func updateMute(enableNotifications: Bool) { ZMUserSession.shared()?.enqueue { self.conversation?.mutedMessageTypes = enableNotifications ? .none : .all // update the footer view to display the correct mute/unmute button self.viewModelDelegate?.updateFooterViews() } } func handleNotificationResult(_ result: NotificationResult) { if let mutedMessageTypes = result.mutedMessageTypes { ZMUserSession.shared()?.perform { self.conversation?.mutedMessageTypes = mutedMessageTypes } } } // MARK: Delete Contents func handleDeleteResult(_ result: ClearContentResult) { guard case .delete(leave: let leave) = result else { return } transitionToListAndEnqueue { self.conversation?.clearMessageHistory() if leave { self.conversation?.removeOrShowError(participant: SelfUser.current) } } } // MARK: - Helpers func transitionToListAndEnqueue(leftViewControllerRevealed: Bool = true, _ block: @escaping () -> Void) { ZClientViewController.shared?.transitionToList(animated: true, leftViewControllerRevealed: leftViewControllerRevealed) { self.enqueueChanges(block) } } func enqueueChanges(_ block: @escaping () -> Void) { ZMUserSession.shared()?.enqueue(block) } // MARK: - Factories func makeUserNameDetailViewModel() -> UserNameDetailViewModel { // TODO: add addressBookEntry to ZMUser return UserNameDetailViewModel(user: user, fallbackName: user.name ?? "", addressBookName: (user as? ZMUser)?.addressBookEntry?.cachedName) } var profileActionsFactory: ProfileActionsFactory { return ProfileActionsFactory(user: user, viewer: viewer, conversation: conversation, context: context) } // MARK: Connect func sendConnectionRequest() { user.connect { [weak self] error in if let error = error as? ConnectToUserError { self?.viewModelDelegate?.presentError(error) } self?.viewModelDelegate?.updateFooterViews() } } func acceptConnectionRequest() { user.accept { [weak self] error in if let error = error as? ConnectToUserError { self?.viewModelDelegate?.presentError(error) } else { self?.user.refreshData() self?.viewModelDelegate?.updateFooterViews() } } } func ignoreConnectionRequest() { user.ignore { [weak self] error in if let error = error as? ConnectToUserError { self?.viewModelDelegate?.presentError(error) } else { self?.viewModelDelegate?.returnToPreviousScreen() } } } } extension ProfileViewControllerViewModel: ZMUserObserver { func userDidChange(_ note: UserChangeInfo) { if note.trustLevelChanged { viewModelDelegate?.updateShowVerifiedShield() } if note.legalHoldStatusChanged { viewModelDelegate?.setupNavigationItems() } if note.nameChanged { viewModelDelegate?.updateTitleView() } if note.user.isAccountDeleted || note.connectionStateChanged { viewModelDelegate?.updateFooterViews() } } } extension ProfileViewControllerViewModel: BackButtonTitleDelegate { func suggestedBackButtonTitle(for controller: ProfileViewController?) -> String? { return user.name?.uppercasedWithCurrentLocale } } protocol ProfileViewControllerViewModelDelegate: AnyObject { func updateShowVerifiedShield() func setupNavigationItems() func updateFooterViews() func updateTitleView() func returnToPreviousScreen() func presentError(_ error: LocalizedError) }
8583824d6893f016259db439285f3518
30.469965
147
0.636762
false
false
false
false
ZoranPandovski/al-go-rithms
refs/heads/master
math/euclids_gcd/Swift/euclidGCF.swift
cc0-1.0
1
//===----------------------------------------------------------------------===// // Function //===----------------------------------------------------------------------===// func euclidGCF(_ a: Int, _ b: Int) -> Int { let answer: Int if a%b == 0 { answer = b } else { answer = euclidGCF(b, a%b) } return answer } //===----------------------------------------------------------------------===// // Demo //===----------------------------------------------------------------------===// let pairs: [(Int, Int)] = [ (1, 2), (10, 5), (7657, 663), (5789, 492), (112, 2296), ] for (a, b) in pairs { let gcf = euclidGCF(a, b) print("GCF(\(a), \(b)) = \(gcf)") }
88ab35b426143eb078063ddab53fe1dd
22.290323
80
0.243767
false
false
false
false
AishPratap/APSGroupedTableView
refs/heads/master
Example/APSGroupedTableView/APSGroupedTableView/APSGroupedTableView.swift
apache-2.0
1
// // APSGroupedTableView.swift // APSGroupedTableView // // Created by Aishwarya Pratap Singh on 9/29/16. // Copyright © 2016 Aishwarya Pratap Singh. All rights reserved. // import Foundation import UIKit protocol APSGroupedTableDataSource:class { func apstableview(tableView:APSGroupedTableView , cellForRowAt indexPath:IndexPath) -> UITableViewCell func apstableview(_ tableView: APSGroupedTableView, numberOfRowsIn section:Int) -> Int func apstableview(_ tableView: APSGroupedTableView, heightForRowAt indexPath: IndexPath) -> CGFloat } protocol APSGroupedTableViewOptionalDatasources:class { func numberOfSections(tableView:APSGroupedTableView) -> Int } protocol APSGroupedTableDelegte:class { func apsTableView(tableView:APSGroupedTableView, didTap index:[Int]) } class APSGroupedTableView : UITableView,UITableViewDelegate,UITableViewDataSource,APSGroupedCellDelegate{ var rowsCount = 5; weak var apsDataSource:APSGroupedTableDataSource? weak var apsDelegate:APSGroupedTableDelegte? weak var apsOptionalDelegate:APSGroupedTableViewOptionalDatasources? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style); self.separatorStyle = .none self.setDelegatesAndDataSource() } func setDelegatesAndDataSource() { self.delegate = self self.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let numRows = apsDataSource?.apstableview(self, numberOfRowsIn: section) else{ return 1 } return numRows } func numberOfSections(in tableView: UITableView) -> Int { guard let numSections = apsOptionalDelegate?.numberOfSections(tableView: self) else{ return 1 } return numSections } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell:APSGroupedTableViewCell = apsDataSource?.apstableview(tableView: self, cellForRowAt: indexPath) as? APSGroupedTableViewCell else { return UITableViewCell(style: .default, reuseIdentifier: "DefaultCellIndentifier") } cell.tag = indexPath.section*100 + indexPath.row*10 cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let height = apsDataSource?.apstableview(self, heightForRowAt: indexPath) else { return self.rowHeight } return height } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } //MARK: - Cell Delegate func apsGroupedCellDidTapButton(buttonIndex: [Int]) { apsDelegate?.apsTableView(tableView: self, didTap: buttonIndex) } }
e2b7618e3f2501ccdd2a6ef6b1f11c25
33.359551
153
0.700458
false
false
false
false