repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gizmosachin/VolumeBar | Sources/VolumeBar.swift | 1 | 4034 | //
// VolumeBar.swift
//
// Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import AudioToolbox
import MediaPlayer
public final class VolumeBar {
/// The shared VolumeBar singleton.
public static let shared = VolumeBar()
/// The stack view that displays the volume bar.
public var view: UIStackView?
// MARK: Animation
/// The minimum visible duration that VolumeBar will appear on screen after a volume button is pressed.
/// If VolumeBar is already showing and a volume button is pressed, VolumeBar will continue to show
/// and the duration it's displayed on screen will be extended by this number of seconds.
public var minimumVisibleDuration: TimeInterval = 1.5
/// The animation used to show VolumeBar.
public var showAnimation: VolumeBarAnimation = .fadeIn
/// The animation used to hide VolumeBar.
public var hideAnimation: VolumeBarAnimation = .fadeOut
// MARK: Style
/// The current style of VolumeBar.
public var style: VolumeBarStyle = VolumeBarStyle() {
didSet {
window?.apply(style: style)
if let stackView = view as? VolumeBarStackView {
stackView.apply(style: style)
}
}
}
// MARK: Internal
internal var window: VolumeBarWindow?
internal var timer: Timer?
internal var systemVolumeManager: SystemVolumeManager?
}
public extension VolumeBar {
// MARK: Lifecycle
/// Start VolumeBar and automatically show when the volume changes.
func start() {
// If we have a systemVolumeManager, we're already started.
guard systemVolumeManager == nil else { return }
let stackView = VolumeBarStackView()
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let viewController = UIViewController()
viewController.view.addSubview(stackView)
self.view = stackView
self.window = VolumeBarWindow(viewController: viewController)
// Initial style
stackView.apply(style: style)
window?.apply(style: style)
// Start observing changes in system volume
systemVolumeManager = SystemVolumeManager()
systemVolumeManager?.addObserver(self)
systemVolumeManager?.addObserver(stackView)
}
/// Stop VolumeBar from automatically showing when the volume changes.
func stop() {
hide()
window = nil
systemVolumeManager = nil
}
}
public extension VolumeBar {
// MARK: Presentation
/// Show VolumeBar immediately using the current `showAnimation`.
func show() {
// Invalidate the timer and extend the on-screen duration
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: minimumVisibleDuration, target: self, selector: #selector(VolumeBar.hide), userInfo: nil, repeats: false)
window?.show(withAnimation: showAnimation)
}
/// Show VolumeBar immediately using the current `hideAnimation`.
@objc func hide() {
window?.hide(withAnimation: hideAnimation)
}
}
extension VolumeBar: SystemVolumeObserver {
internal func volumeChanged(to volume: Float) {
show()
}
}
| mit | 96964a2283513af67544a45000ce03b3 | 31.015873 | 150 | 0.745414 | 4.30064 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/StateMachine/StateMachine.swift | 1 | 1717 | //
// StateMachine.swift
// Redstone
//
// Created by nixzhu on 2017/1/6.
// Copyright © 2017年 nixWork. All rights reserved.
//
public class StateMachine<State: Hashable, Transition: Hashable> {
public typealias Operation = () -> Void
private var body = [State: Operation?]()
public private(set) var previousState: State?
public private(set) var lastTransition: Transition?
public private(set) var currentState: State? {
willSet {
previousState = currentState
}
didSet {
if let state = currentState {
body[state]??()
}
}
}
public var initialState: State? {
didSet {
if oldValue == nil, initialState != nil {
currentState = initialState
}
}
}
private var stateTransitionTable: [State: [Transition: State]] = [:]
public init() {
}
public func add(state: State, entryOperation: Operation?) {
body[state] = entryOperation
}
public func add(transition: Transition, fromState: State, toState: State) {
var bag = stateTransitionTable[fromState] ?? [:]
bag[transition] = toState
stateTransitionTable[fromState] = bag
}
public func add(transition: Transition, fromStates: Set<State>, toState: State) {
fromStates.forEach {
add(transition: transition, fromState: $0, toState: toState)
}
}
public func fire(transition: Transition) {
guard let state = currentState else { return }
guard let toState = stateTransitionTable[state]?[transition] else { return }
lastTransition = transition
currentState = toState
}
}
| mit | 58d5ee873b0bb360448a69a4d1bacf4d | 31.339623 | 85 | 0.606184 | 4.721763 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/Model/DealModel/DealModel.swift | 1 | 2346 |
//
// DealModel.swift
// iOSStar
//
// Created by J-bb on 17/6/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
import RealmSwift
class EntrustSuccessModel: Object {
dynamic var amount = 0
dynamic var buySell = 2
dynamic var id = 132
dynamic var openPrice = 13.0
dynamic var positionId:Int64 = 0
dynamic var positionTime:Int64 = 1496920841
dynamic var symbol = ""
}
class ReceiveMacthingModel: Object {
dynamic var buyUid = 0
dynamic var sellUid = 0
dynamic var openPositionTime:Int64 = 0
dynamic var openPrice:Double = 1.00
dynamic var orderId:Int64 = 2371231398736937636
dynamic var symbol = "1001"
dynamic var amount = 0
override static func primaryKey() -> String?{
return "orderId"
}
func cacheSelf() {
let realm = try! Realm()
try! realm.write {
realm.add(self, update: true)
}
}
class func getData() -> ReceiveMacthingModel? {
let realm = try! Realm()
let results = realm.objects(ReceiveMacthingModel.self)
return results.first
}
}
class SureOrderResultModel: Object {
dynamic var orderId:Int64 = 0
dynamic var status:Int32 = 0
}
class OrderResultModel: Object {
dynamic var orderId:Int64 = 0
dynamic var result:Int32 = 0
}
class EntrustListModel: Object {
dynamic var rtAmount = 0
dynamic var amount:Int64 = 0
dynamic var buySell = AppConst.DealType.buy.rawValue
dynamic var handle:Int32 = AppConst.OrderStatus.pending.rawValue
dynamic var id:Int64 = 142
dynamic var openCharge:Double = 0.0
dynamic var openPrice:Double = 0.0
dynamic var positionId:Int64 = 0
dynamic var positionTime:Int64 = 0
dynamic var symbol = ""
}
class OrderListModel: Object {
dynamic var amount:Int64 = 0
dynamic var buyUid:Int64 = 0
dynamic var sellUid:Int64 = 0
dynamic var closeTime:Int64 = 0
dynamic var grossProfit:Double = 0.0
dynamic var openCharge:Double = 0.0
dynamic var openTime:Int64 = 0
dynamic var orderId:Int64 = 0
dynamic var positionId:Int64 = 0
dynamic var result = false
dynamic var symbol = ""
dynamic var handle:Int32 = 0
dynamic var buyHandle:Int32 = 0
dynamic var sellHandle:Int32 = 0
dynamic var openPrice = 0.0
}
| gpl-3.0 | 15ea31ad3d95db7c8bf611105ed8f08e | 23.925532 | 68 | 0.665386 | 3.815961 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Controllers/ActionsCollectionViewController.swift | 1 | 10367 | //
// ActionsCollectionViewController.swift
// URLRemote
//
// Created by Svacha, Michal on 30/05/16.
// Copyright © 2016 Svacha, Michal. All rights reserved.
//
import UIKit
import Material
import Bond
import ReactiveKit
///
class ActionsCollectionViewController: UICollectionViewController, PersistenceStackController {
var stack: PersistenceStack! {
didSet {
viewModel = ActionsViewModel()
}
}
var viewModel: ActionsViewModel!
var menu: FABMenu?
var pageControl: UIPageControl?
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.isPagingEnabled = true
collectionView?.backgroundColor = UIColor(named: .gray)
collectionView?.register(CategoryViewCell.self, forSupplementaryViewOfKind: "header", withReuseIdentifier: Constants.CollectionViewCell.header)
self.setupNavigationController()
self.setupMenu()
self.setLoginNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - View setup
///
func setupNavigationController() {
let navigationController = self.navigationController as? ApplicationNavigationController
navigationController?.prepare()
navigationController?.statusBarStyle = .lightContent
navigationController?.navigationBar.barTintColor = UIColor(named: .yellow)
let logout = FlatButton(title: NSLocalizedString("LOGOUT", comment: ""))
logout.apply(Stylesheet.General.flatButton)
logout.reactive.tap.bind(to: self) { me, _ in
me.stack.authentication.logOut()
}.dispose(in: bag)
self.navigationItem.leftViews = [logout]
let settingsButton = MaterialFactory.genericIconButton(image: Icon.cm.settings)
settingsButton.reactive.tap.bind(to: self) { _, _ in
print("Settings coming soon!")
}.dispose(in: bag)
let editButton = MaterialFactory.genericIconButton(image: Icon.cm.edit)
editButton.reactive.tap.bind(to: self) { me, _ in
me.displayEditCategory()
}.dispose(in: bag)
self.navigationItem.rightViews = [editButton, settingsButton]
self.navigationItem.titleLabel.textColor = .white
self.navigationItem.detailLabel.textColor = .white
self.navigationItem.titleLabel.text = "URLRemote"
self.navigationItem.detailLabel.text = "Making your IoT awesome!"
}
///
func setLoginNotifications() {
stack.authentication
.dataSource()
.observeNext {
if let src = $0 {
self.viewModel.dataSource.value = src
self.setupCollectionDataSource()
} else {
self.viewModel.dataSource.value = nil
self.resetCollectionDataSource()
self.displayLogin()
}
}
.dispose(in: bag)
}
///
func setupCollectionDataSource() {
pageControl = UIPageControl()
pageControl?.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.4)
pageControl?.currentPageIndicatorTintColor = UIColor.lightGray
self.view.layout(pageControl!).bottom(30.0).centerHorizontally()
viewModel.data.bind(to: self) { me, data in
me.pageControl?.numberOfPages = data.dataSource.numberOfSections
me.collectionView?.reloadData()
me.collectionView?.collectionViewLayout.invalidateLayout()
}.dispose(in: bag)
}
///
func resetCollectionDataSource() {
pageControl?.removeFromSuperview()
collectionView?.contentOffset = CGPoint(x: 0, y: 0)
collectionView?.collectionViewLayout.invalidateLayout()
}
/// MARK: - ViewController presentation
///
func displayLogin() {
let loginController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.login) as! LoginTableViewController
loginController.stack = stack
self.presentEmbedded(viewController: loginController, barTintColor: UIColor(named: .green))
}
///
func displayEntrySetup() {
let entryController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.entrySetup) as! EntrySetupViewController
entryController.stack = stack
self.presentEmbedded(viewController: entryController, barTintColor: UIColor(named: .green))
}
///
func displayCategorySetup() {
let categoryDialog = AlertDialogBuilder
.dialog(title: "NEW_CATEGORY", text: "NEW_CATEGORY_DESC")
.cancelAction()
let okAction = UIAlertAction(
title: NSLocalizedString("OK", comment: ""),
style: .default,
handler: { _ in
if let textFields = categoryDialog.textFields, let textField = textFields[safe: 0], let text = textField.text, text != "" {
self.viewModel.createCategory(named: text)
}
})
categoryDialog.addAction(okAction)
categoryDialog.addTextField { textField in
textField.placeholder = NSLocalizedString("NEW_CATEGORY_PLACEHOLDER", comment: "")
textField.reactive
.isEmpty
.bind(to: okAction.reactive.enabled)
.dispose(in: categoryDialog.bag)
}
self.present(categoryDialog, animated: true, completion: nil)
}
///
func displayEditCategory() {
let visibleSection = collectionView?.indexPathsForVisibleSupplementaryElements(ofKind: "header")[safe: 0]?.section ?? 0
let editCategoryController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.categoryEdit) as! CategoryEditTableViewController
editCategoryController.stack = stack
let category = viewModel.data[visibleSection].metadata
editCategoryController.viewModel.category = category
self.presentEmbedded(viewController: editCategoryController, barTintColor: UIColor(named: .green))
}
// MARK: - Collection view data source methods
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
let currentPage = Int(floor((scrollView.contentOffset.x - pageWidth / 2.0) / pageWidth) + 1.0)
pageControl?.currentPage = currentPage
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
collectionView.collectionViewLayout.invalidateLayout()
return viewModel.data.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.data[section].items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: Constants.CollectionViewCell.entry,
for: indexPath) as! ActionViewCell
cell.setUpView()
// Dispose all bindings because the cell objects are reused.
cell.bag.dispose()
cell.bind(with: viewModel.data[indexPath.section].items[indexPath.row])
return cell
}
@objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: "header", withReuseIdentifier: Constants.CollectionViewCell.header, for: indexPath) as! CategoryViewCell
header.setUpView()
header.bind(with: viewModel.data[indexPath.section].metadata)
return header
}
}
//
extension ActionsCollectionViewController: FABMenuDelegate {
///
private func genericMenuItem(image: String, title: String) -> FABMenuItem {
let item = FABMenuItem()
item.fabButton.image = UIImage(named: image)
item.fabButton.apply(Stylesheet.Actions.fabButton)
item.title = NSLocalizedString(title, comment: "")
return item
}
///
private func menuEntryItem() -> FABMenuItem {
let entryItem = genericMenuItem(image: "new_entry", title: "NEW_ENTRY")
entryItem.fabButton.depthPreset = .depth1
entryItem.fabButton.reactive.tap.observeNext { [weak self] in
self?.menu?.toggle()
self?.displayEntrySetup()
}.dispose(in: bag)
return entryItem
}
///
private func menuCategoryItem() -> FABMenuItem {
let categoryItem = genericMenuItem(image: "new_category", title: "NEW_CATEGORY")
categoryItem.fabButton.reactive.tap.observeNext { [weak self] in
self?.menu?.toggle()
self?.displayCategorySetup()
}.dispose(in: bag)
return categoryItem
}
///
func setupMenu() {
self.menu = FABMenu()
let addButton = FABButton(image: Icon.cm.add, tintColor: .white)
addButton.frame = CGRect(x: 0.0, y: 0.0, width: 48.0, height: 48.0)
addButton.pulseColor = .white
addButton.backgroundColor = UIColor(named: .green).darker()
addButton.reactive.tap
.observeNext { [weak self] in self?.menu?.toggle() }
.dispose(in: bag)
menu?.delegate = self
menu?.fabButton = addButton
menu?.fabMenuItems = [menuEntryItem(), menuCategoryItem()]
menu?.fabMenuItemSize = CGSize(width: 40.0, height: 40.0)
view.layout(menu!).size(addButton.frame.size).bottom(30).right(30)
}
/// MARK: - Menu delegate method
///
public func fabMenu(fabMenu menu: FABMenu, tappedAt point: CGPoint, isOutside: Bool) {
if isOutside {
menu.toggle()
}
}
}
| apache-2.0 | 0f25b263fd4bd82cace8145b8d0cbe0a | 36.557971 | 181 | 0.643353 | 5.305015 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Managers/AutoScrollableShotsDataSource.swift | 1 | 3668 | //
// AutoScrollableShotsDataSource.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 28/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class AutoScrollableShotsDataSource: NSObject {
fileprivate typealias AutoScrollableImageContent = (image: UIImage,
isDuplicateForExtendedContent: Bool)
fileprivate var content: [AutoScrollableImageContent]!
fileprivate(set) var extendedScrollableItemsCount = 0
var itemSize: CGSize {
return CGSize(width: collectionView.bounds.width,
height: collectionView.bounds.width)
}
let collectionView: UICollectionView
init(collectionView: UICollectionView, content: [UIImage]) {
self.collectionView = collectionView
self.content = content.map { ($0, false) }
super.init()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(AutoScrollableCollectionViewCell.self, type: .cell)
prepareExtendedContentToDisplayWithOffset(0)
}
@available(*, unavailable, message: "Use init(collectionView:content:) instead")
override init() {
fatalError("init() has not been implemented")
}
/// Prepares itself for animation and reloads collectionView.
func prepareForAnimation() {
extendedScrollableItemsCount = Int(ceil(collectionView.bounds.height /
itemSize.height))
prepareExtendedContentToDisplayWithOffset(extendedScrollableItemsCount)
collectionView.reloadData()
}
}
// MARK: UICollectionViewDataSource
extension AutoScrollableShotsDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableClass(AutoScrollableCollectionViewCell.self,
forIndexPath: indexPath,
type: .cell)
cell.imageView.image = content[indexPath.row].image
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return content.count
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension AutoScrollableShotsDataSource: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return itemSize
}
}
// MARK: Private
private extension AutoScrollableShotsDataSource {
func prepareExtendedContentToDisplayWithOffset(_ offset: Int) {
let images = content.filter { !$0.isDuplicateForExtendedContent }
var extendedContent = [AutoScrollableImageContent]()
for index in 0..<(images.count + 2 * offset) {
let indexSubscript: Int
var isDuplicateForExtendedContent = true
if index < offset {
indexSubscript = images.count - offset + index
} else if index > images.count + offset - 1 {
indexSubscript = index - images.count - offset
} else {
isDuplicateForExtendedContent = false
indexSubscript = index - offset
}
extendedContent.append((images[indexSubscript].image, isDuplicateForExtendedContent))
}
content = extendedContent
}
}
| gpl-3.0 | 22525ba7dcc27a4ad3cc3429093b68c7 | 30.34188 | 97 | 0.666485 | 5.783912 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/User/RealmOwnedGear.swift | 1 | 802 | //
// RealmOwnedGear.swift
// Habitica Database
//
// Created by Phillip Thelen on 12.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import RealmSwift
import Habitica_Models
@objc
class RealmOwnedGear: Object, OwnedGearProtocol {
@objc dynamic var combinedKey: String?
@objc dynamic var key: String?
@objc dynamic var userID: String?
@objc dynamic var isOwned: Bool = false
override static func primaryKey() -> String {
return "combinedKey"
}
convenience init(userID: String?, gearProtocol: OwnedGearProtocol) {
self.init()
combinedKey = (userID ?? "") + (gearProtocol.key ?? "")
self.userID = userID
key = gearProtocol.key
isOwned = gearProtocol.isOwned
}
}
| gpl-3.0 | d14d6a294efa19a0f20387422ea2a14a | 23.272727 | 72 | 0.650437 | 4.150259 | false | false | false | false |
TelerikAcademy/Mobile-Applications-with-iOS | demos/StoryboardsAndViewControllers/StoryboardsAndViewControllers/DetailsViewController.swift | 1 | 1809 | //
// DetailsViewController.swift
// StoryboardsAndViewControllers
//
// Created by Doncho Minkov on 3/17/17.
// Copyright © 2017 Doncho Minkov. All rights reserved.
//
import UIKit
class DetailsViewController: UIViewController {
var name: String = ""
var labelName: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
let topOffeset = self.navigationController?.navigationBar.bounds.size.height
let origin = CGPoint(x: self.view.bounds.origin.x, y: self.view.bounds.origin.y + topOffeset!)
self.labelName = UILabel(frame: CGRect(origin: origin,
size: CGSize(width: 100, height: 50)))
self.labelName?.text = self.name
self.labelName?.backgroundColor = .purple
self.labelName?.textColor = .yellow
self.view.addSubview(self.labelName!)
print(self.name)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func unwindToMainTableViewController(segue: UIStoryboardSegue) {
print("fired!");
}
@IBAction func goBacl(_ sender: UIButton) {
print("Tapped")
self.performSegue(withIdentifier: "unwind", sender: self)
}
/*
// 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.
}
*/
}
| mit | fbd02a892805af817403345777037cf8 | 29.133333 | 106 | 0.631084 | 4.770449 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Views/TintColorChangingButton.swift | 1 | 3015 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
/// A button which automatically updates its tint color based on the button's current state.
final class TintColorChangingButton: UIButton {
private let normalTintColor: UIColor
private let disabledTintColor: UIColor
private let selectedTintColor: UIColor
private let highlightedTintColor: UIColor
/// Designated initializer.
///
/// - Parameters:
/// - normalTintColor: The color the button should be when enabled. Defaults to the theme color.
/// - disabledTintColor: The color the button should be when disabled. Defaults to a gray color.
/// - selectedTintColor: [Optional] The color the button should be when selected.
/// If nil, the `normalTintColor` will be used. Defaults to nil.
/// - highlightedTintColor: [Optional] The color the button should be when highlighted.
/// If nil, the `normalTintColor` will be use. Defaults to nil.
init(normalTintColor: UIColor = Theme.tintColor,
disabledTintColor: UIColor = Theme.greyTextColor,
selectedTintColor: UIColor? = nil,
highlightedTintColor: UIColor? = nil) {
self.normalTintColor = normalTintColor
self.disabledTintColor = disabledTintColor
self.selectedTintColor = selectedTintColor ?? normalTintColor
self.highlightedTintColor = highlightedTintColor ?? normalTintColor
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isEnabled: Bool {
didSet {
updateTintColor()
}
}
override var isHighlighted: Bool {
didSet {
updateTintColor()
}
}
override var isSelected: Bool {
didSet {
updateTintColor()
}
}
private func updateTintColor() {
switch state {
case .normal:
tintColor = normalTintColor
case .disabled:
tintColor = disabledTintColor
case .selected:
tintColor = selectedTintColor
case .highlighted:
tintColor = highlightedTintColor
default:
// some state combo is happening, leave things where they are
break
}
}
}
| gpl-3.0 | afecbd39178545444eb3c5c215df6bf7 | 34.892857 | 102 | 0.657048 | 5.252613 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/PDFReader/Sources/Classes/PDFPageView.swift | 1 | 8908 | //
// PDFPageView.swift
// PDFReader
//
// Created by ALUA KINZHEBAYEVA on 4/23/15.
// Copyright (c) 2015 AK. All rights reserved.
//
import UIKit
/// Delegate that is informed of important interaction events with the current `PDFPageView`
protocol PDFPageViewDelegate: class {
/// User has tapped on the page view
func handleSingleTap(_ pdfPageView: PDFPageView)
}
/// An interactable page of a document
internal final class PDFPageView: UIScrollView {
/// The TiledPDFView that is currently front most.
private var tiledPDFView: TiledView
/// Current scale of the scrolling view
private var scale: CGFloat
/// Number of zoom levels possible when double tapping
private let zoomLevels: CGFloat = 2
/// View which contains all of our content
private var contentView: UIView
/// A low resolution image of the PDF page that is displayed until the TiledPDFView renders its content.
private let backgroundImageView: UIImageView
/// Page reference being displayed
private let pdfPage: CGPDFPage
/// Current amount being zoomed
private var zoomAmount: CGFloat?
/// Delegate that is informed of important interaction events
private weak var pageViewDelegate: PDFPageViewDelegate?
/// Instantiates a scrollable page view
///
/// - parameter frame: frame of the view
/// - parameter document: document to be displayed
/// - parameter pageNumber: specific page number of the document to display
/// - parameter backgroundImage: background image of the page to display while rendering
/// - parameter pageViewDelegate: delegate notified of any important interaction events
///
/// - returns: a freshly initialized page view
init(frame: CGRect, document: PDFDocument, pageNumber: Int, backgroundImage: UIImage?, pageViewDelegate: PDFPageViewDelegate?) {
guard let pageRef = document.coreDocument.page(at: pageNumber + 1) else { fatalError() }
pdfPage = pageRef
self.pageViewDelegate = pageViewDelegate
let originalPageRect = pageRef.originalPageRect
scale = min(frame.width/originalPageRect.width, frame.height/originalPageRect.height)
let scaledPageRectSize = CGSize(width: originalPageRect.width * scale, height: originalPageRect.height * scale)
let scaledPageRect = CGRect(origin: originalPageRect.origin, size: scaledPageRectSize)
guard !scaledPageRect.isEmpty else { fatalError() }
// Create our content view based on the size of the PDF page
contentView = UIView(frame: scaledPageRect)
backgroundImageView = UIImageView(image: backgroundImage)
backgroundImageView.frame = contentView.bounds
// Create the TiledPDFView and scale it to fit the content view.
tiledPDFView = TiledView(frame: contentView.bounds, scale: scale, newPage: pdfPage)
super.init(frame: frame)
let targetRect = bounds.insetBy(dx: 0, dy: 0)
var zoomScale = zoomScaleThatFits(targetRect.size, source: bounds.size)
minimumZoomScale = zoomScale // Set the minimum and maximum zoom scales
maximumZoomScale = zoomScale * (zoomLevels * zoomLevels) // Max number of zoom levels
zoomAmount = (maximumZoomScale - minimumZoomScale) / zoomLevels
scale = 1
if zoomScale > minimumZoomScale {
zoomScale = minimumZoomScale
}
contentView.addSubview(backgroundImageView)
contentView.sendSubview(toBack: backgroundImageView)
contentView.addSubview(tiledPDFView)
addSubview(contentView)
let doubleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleDoubleTap))
doubleTapOne.numberOfTapsRequired = 2
doubleTapOne.cancelsTouchesInView = false
addGestureRecognizer(doubleTapOne)
let singleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleSingleTap))
singleTapOne.numberOfTapsRequired = 1
singleTapOne.cancelsTouchesInView = false
addGestureRecognizer(singleTapOne)
singleTapOne.require(toFail: doubleTapOne)
bouncesZoom = false
decelerationRate = UIScrollViewDecelerationRateFast
delegate = self
autoresizesSubviews = true
autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Use layoutSubviews to center the PDF page in the view.
override func layoutSubviews() {
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen.
let contentViewSize = contentView.frame.size
// Center horizontally.
let xOffset: CGFloat
if contentViewSize.width < bounds.width {
xOffset = (bounds.width - contentViewSize.width) / 2
} else {
xOffset = 0
}
// Center vertically.
let yOffset: CGFloat
if contentViewSize.height < bounds.height {
yOffset = (bounds.height - contentViewSize.height) / 2
} else {
yOffset = 0
}
contentView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: contentViewSize)
// To handle the interaction between CATiledLayer and high resolution screens, set the
// tiling view's contentScaleFactor to 1.0. If this step were omitted, the content scale factor
// would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale.
tiledPDFView.contentScaleFactor = 1
}
/// Notifies the delegate that a single tap was performed
@objc func handleSingleTap(_ tapRecognizer: UITapGestureRecognizer) {
pageViewDelegate?.handleSingleTap(self)
}
/// Zooms in and out accordingly, based on the current zoom level
@objc func handleDoubleTap(_ tapRecognizer: UITapGestureRecognizer) {
var newScale = zoomScale * zoomLevels
if newScale >= maximumZoomScale {
newScale = minimumZoomScale
}
let zoomRect = zoomRectForScale(newScale, zoomPoint: tapRecognizer.location(in: tapRecognizer.view))
zoom(to: zoomRect, animated: true)
}
/// Calculates the zoom scale given a target size and a source size
///
/// - parameter target: size of the target rect
/// - parameter source: size of the source rect
///
/// - returns: the zoom scale of the target in relation to the source
private func zoomScaleThatFits(_ target: CGSize, source: CGSize) -> CGFloat {
let widthScale = target.width / source.width
let heightScale = target.height / source.height
return (widthScale < heightScale) ? widthScale : heightScale
}
/// Calculates the new zoom rect given a desired scale and a point to zoom on
///
/// - parameter scale: desired scale to zoom to
/// - parameter zoomPoint: the reference point to zoom on
///
/// - returns: a new zoom rect
private func zoomRectForScale(_ scale: CGFloat, zoomPoint: CGPoint) -> CGRect {
// Normalize current content size back to content scale of 1.0f
let updatedContentSize = CGSize(width: contentSize.width/zoomScale, height: contentSize.height/zoomScale)
let translatedZoomPoint = CGPoint(x: (zoomPoint.x / bounds.width) * updatedContentSize.width,
y: (zoomPoint.y / bounds.height) * updatedContentSize.height)
// derive the size of the region to zoom to
let zoomSize = CGSize(width: bounds.width / scale, height: bounds.height / scale)
// offset the zoom rect so the actual zoom point is in the middle of the rectangle
return CGRect(x: translatedZoomPoint.x - zoomSize.width / 2.0,
y: translatedZoomPoint.y - zoomSize.height / 2.0,
width: zoomSize.width,
height: zoomSize.height)
}
}
extension PDFPageView: UIScrollViewDelegate {
/// A UIScrollView delegate callback, called when the user starts zooming.
/// Return the content view
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return contentView
}
/// A UIScrollView delegate callback, called when the user stops zooming.
/// When the user stops zooming, create a new Tiled
/// PDFView based on the new zoom level and draw it on top of the old TiledPDFView.
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.scale = scale
}
}
| mit | 1fb94817376c7be2c02471d66dff66a3 | 40.821596 | 132 | 0.664122 | 5.478475 | false | false | false | false |
danielsaidi/iExtra | iExtra/Files/FilteredDirectoryFileManager.swift | 1 | 1222 | //
// FilteredDirectoryFileManager.swift
// iExtra
//
// Created by Daniel Saidi on 2016-12-19.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import UIKit
open class FilteredDirectoryFileManager: DirectoryFileManagerDefault {
// MARK: - Initialization
public init?(directory: FileManager.SearchPathDirectory, fileExtensions: [String], fileManager: AppFileManager) {
self.fileExtensions = fileExtensions
super.init(directory: directory, fileManager: fileManager)
}
public init(directoryUrl: URL, fileExtensions: [String], fileManager: AppFileManager) {
self.fileExtensions = fileExtensions
super.init(directoryUrl: directoryUrl, fileManager: fileManager)
}
// MARK: - Properties
fileprivate let fileExtensions: [String]
// MARK: - Public Functions
open override func getFileNames() -> [String] {
let fileNames = super.getFileNames()
let fileExtensions = self.fileExtensions.map { $0.lowercased() }
return fileNames.filter {
let fileName = $0.lowercased()
return fileExtensions.filter { fileName.hasSuffix($0) }.first != nil
}
}
}
| mit | 92abed848fb60f50bfc27b55232e12b8 | 28.071429 | 117 | 0.662572 | 4.903614 | false | false | false | false |
kaizeiyimi/XLYIDTracker-swift | XLYIDTracker.swift | 1 | 8109 | //
// XLYIDTracker
//
// Created by 王凯 on 14-9-24.
// Copyright (c) 2014年 kaizei. All rights reserved.
//
import Foundation
/*
//create a tracker with a given queue and store it somewhere
var tracker: XLYIDTracker = XLYIDTracker(trackerQueue: dispatch_queue_create("tracker", DISPATCH_QUEUE_SERIAL))
// make a common handler for response
var handler: XLYTrackingHandler = { (trackingInfo, response) -> () in
if let value = response {
println("get response : \(value)")
} else {
println("no response get")
}
}
// must add trackingInfos in tracker's queue
dispatch_async(tracker.trackerQueue) {
//default queue uses tracker's queue
tracker.addTrackingInfo("a", timeOut: 2, queue: nil, handler)
//track in the main queue
tracker.addTrackingInfo("b", timeOut: 2, queue: dispatch_get_main_queue(), handler)
var queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
//track in a custom queue
tracker.addTrackingInfo("c", timeOut: 2, queue: queue, handler)
//or you can create a trackingInfo and then add it
var trackingInfo = XLYBasicTrackingInfo(trackID: "d", timeOut: 2, queue: queue, handler)
trackingInfo.autoRemoveFromTracker = true
tracker.addTrackingInfo(trackingInfo)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
dispatch_async(self.tracker?.trackerQueue) {
let _ = self.tracker?.responseTrackingForID("d", response: "d hello")
}
}
}
*/
/// trackingInfo 的回调方法,传递trackinginfo和回应的数据,如果没有数据则为nil
public typealias XLYTrackingHandler = (trackingInfo: XLYTrackingInfo, response:Any?) -> ()
//MARK: XLYIDTracker
public class XLYIDTracker {
public let trackerQueue: dispatch_queue_t
private var trackingInfos = [String : XLYTrackingInfo]()
private let queueTag = UnsafeMutablePointer<Void>(malloc(1))
public init(trackerQueue:dispatch_queue_t) {
self.trackerQueue = trackerQueue
dispatch_queue_set_specific(trackerQueue, queueTag, queueTag, nil)
}
private let lock = NSLock()
private subscript(trackID: String) -> XLYTrackingInfo? {
get {
assert(queueTag == dispatch_get_specific(queueTag), "must invoke tracker methods in tracker queue")
lock.lock()
let trackingInfo = trackingInfos[trackID]
lock.unlock()
return trackingInfo
}
set {
assert(queueTag == dispatch_get_specific(queueTag), "must invoke tracker methods in tracker queue")
assert(newValue?.tracker == nil, "can not add a trackingInfo which already has a tracker associated")
lock.lock()
if let trackingInfo = trackingInfos.removeValueForKey(trackID) {
trackingInfo.cancelTimer()
}
if var trackingInfo = newValue {
trackingInfos[trackID] = trackingInfo
trackingInfo.tracker = self
trackingInfo.startTimer()
}
lock.unlock()
}
}
///通过trackID和回调方法来创建trackingInfo,会使用默认的trackingInfo实现
public func addTrackingInfo(trackID: String, timeOut: NSTimeInterval, queue: dispatch_queue_t?, handler: XLYTrackingHandler) {
let trackingInfo = XLYBasicTrackingInfo(trackID: trackID, timeOut: timeOut, queue: queue ?? self.trackerQueue, handler: handler)
addTrackingInfo(trackingInfo)
}
///添加一个配置好的trackingInfo,会覆盖已有的trackingInfo
public func addTrackingInfo(var trackingInfo: XLYTrackingInfo) {
self[trackingInfo.trackID] = trackingInfo
}
///响应一个tracking, 如果响应成功返回true,否则返回NO
public func responseTrackingForID(trackID: String, response: Any?) -> Bool {
if let trackingInfo = self[trackID] {
self[trackID] = nil
dispatch_async(trackingInfo.trackQueue, {trackingInfo.response(response)})
return true
}
return false
}
///停止track
public func stopTrackingForID(trackID: String) {
self[trackID] = nil
}
///停止所有的tracking
public func stopAllTracking() {
for trackID in trackingInfos.keys {
self[trackID] = nil
}
}
}
//MARK: - XLYTrackingInfo protocol
/// all properties and functions should not be called directly.
public protocol XLYTrackingInfo {
///标识唯一的track id.
var trackID: String {get}
///track所使用的queue,计时应该在这个queue里面进行
var trackQueue: dispatch_queue_t {get}
///所从属的tracker
weak var tracker: XLYIDTracker! {get set}
init(trackID: String, timeOut: NSTimeInterval, queue :dispatch_queue_t, handler: XLYTrackingHandler)
///开始计时,应该在trackQueue里面进行,超时后需要调用tracker的response方法并传递自定义的错误信息比如nil
func startTimer()
///停止计时,取消掉timer
func cancelTimer()
///响应一个track,可以是任何对象,由tracker在trackQueue中进行调用
func response(response: Any?)
}
//MARK: - XLYBasicTrackingInfo
public class XLYBasicTrackingInfo: XLYTrackingInfo {
public let trackID: String
public let trackQueue: dispatch_queue_t
public var autoRemoveFromTracker = false
public weak var tracker: XLYIDTracker!
private let trackTimeOut: NSTimeInterval = 15
private let trackHandler: XLYTrackingHandler
private var trackTimer: dispatch_source_t?
private let queueTag = UnsafeMutablePointer<Void>(malloc(1))
required public init(trackID: String, timeOut: NSTimeInterval, queue :dispatch_queue_t, handler: XLYTrackingHandler) {
self.trackID = trackID
trackHandler = handler
trackQueue = queue
if timeOut > 0 {
trackTimeOut = timeOut
}
dispatch_queue_set_specific(queue, queueTag, queueTag, nil)
}
deinit {
cancelTimer()
}
///超时后response为nil,意味着没有规定时间内没有得到响应数据
public func startTimer() {
assert(trackTimer == nil, "XLYBasicTrackingInfo class can start counting down only when timer is stoped.")
assert(tracker != nil, "XLYBasicTrackingInfo class must have tracker set to perform response")
trackTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, trackQueue);
dispatch_source_set_event_handler(trackTimer) {
[weak self] in
autoreleasepool(){
if let strongSelf = self {
if let tracker = strongSelf.tracker {
dispatch_async(tracker.trackerQueue) {
if strongSelf.autoRemoveFromTracker {
let _ = tracker.responseTrackingForID(strongSelf.trackID, response: nil)
} else {
dispatch_async(strongSelf.trackQueue) {
strongSelf.response(nil)
}
}
}
}
}
}
}
let tt = dispatch_time(DISPATCH_TIME_NOW, Int64(trackTimeOut * NSTimeInterval(NSEC_PER_SEC)));
dispatch_source_set_timer(trackTimer!, tt, DISPATCH_TIME_FOREVER, 0)
dispatch_resume(trackTimer!);
}
public func cancelTimer() {
if let timer = trackTimer {
dispatch_source_cancel(timer)
trackTimer = nil
}
}
public func response(response: Any?) {
assert(queueTag == dispatch_get_specific(queueTag), "should response in XLYBasicTrackingInfo.trackQueue.")
autoreleasepool() {
self.trackHandler(trackingInfo: self, response: response)
}
}
}
| mit | cded5cf700494b1b64146c0eca8415ee | 37.20297 | 136 | 0.630038 | 4.76358 | false | false | false | false |
aiwalle/LiveProject | macSocket/LJSocket/LJClientManager.swift | 1 | 2925 | //
// LJClientManager.swift
// LiveProject
//
// Created by liang on 2017/8/28.
// Copyright © 2017年 liang. All rights reserved.
//
import Cocoa
protocol LJClientManagerDelegate : class {
func sendMsgToClient(_ data : Data)
func removeClient(client : LJClientManager)
}
class LJClientManager : NSObject {
weak var delegate : LJClientManagerDelegate?
var client : TCPClient
fileprivate var isClientConnecting : Bool = false
fileprivate var heartTimeCount : Int = 0
init(client : TCPClient) {
self.client = client
}
}
extension LJClientManager {
func readMessage() {
isClientConnecting = true
while isClientConnecting {
if let headMsg = client.read(4) {
let timer = Timer(fireAt: Date(), interval: 1, target: self, selector: #selector(checkHeartBeat), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
timer.fire()
let headData = Data(bytes: headMsg, count: 4)
var actualLength = 0
// 给actualLength赋值,获取消息内容长度
(headData as NSData).getBytes(&actualLength, length: 4)
guard let typeMsg = client.read(2) else {
return
}
let typeData = Data(bytes: typeMsg, count: 2)
var type = 0
(typeData as NSData).getBytes(&type, length: 2)
guard let actualMsg = client.read(actualLength) else {
return
}
let actualData = Data(bytes: actualMsg, count: actualLength)
let actualMsgStr = String(data: actualData, encoding: .utf8)
if type == 1 {
removeClient()
} else if type == 100 {
// 客户端在线才会给服务器发送❤️包,所以如果收到了❤️,就一直连接服务器,除非客户端退出或下线
heartTimeCount = 0
// 不读❤️包的消息
continue
}
print(actualMsgStr ?? "解析消息出错")
let totalData = headData + typeData + actualData
delegate?.sendMsgToClient(totalData)
} else {
removeClient()
}
}
}
@objc fileprivate func checkHeartBeat() {
heartTimeCount += 1
if heartTimeCount >= 10 {
removeClient()
}
print("收到了心跳包")
}
private func removeClient() {
delegate?.removeClient(client: self)
isClientConnecting = false
print("客户端断开了连接")
_ = client.close()
}
}
| mit | 519c6c08bb2a833b34eb466b90d3cdb5 | 29.21978 | 143 | 0.517455 | 4.867257 | false | false | false | false |
corey-lin/PlayMarvelAPI | NameSHero/QuizViewController.swift | 1 | 2922 | //
// QuizViewController.swift
// NameSHero
//
// Created by coreylin on 3/2/16.
// Copyright © 2016 coreylin. All rights reserved.
//
import UIKit
//import ReactiveCocoa
import Kingfisher
import SwiftSpinner
import TAOverlay
class QuizViewController: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var pictureImageView: UIImageView!
@IBOutlet var choiceButtons: [UIButton]!
@IBOutlet weak var quizPlayView: UIView!
var viewModel = QuizViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.pictureURL.producer.startWithNext {
print("\($0)")
if let imageURL = $0 {
self.pictureImageView.kf_setImageWithURL(imageURL)
}
}
viewModel.choices.producer.startWithNext {
if let choices = $0 {
for index in 0..<choices.count {
self.choiceButtons[index].setTitle(choices[index], forState: UIControlState.Normal)
}
}
}
viewModel.numberOfQuests.producer.startWithNext {
if $0 > 0 {
let score = ($0 - 1) * 10
self.scoreLabel.text = "Score:\(score)"
if score == 100 {
self.performSegueWithIdentifier("toResult", sender: nil)
}
}
}
viewModel.quizViewStateInfo.producer.startWithNext {
if $0.curState == QuizViewState.GameOver {
self.performSegueWithIdentifier("toResult", sender: nil)
} else if $0.curState == QuizViewState.Loading {
SwiftSpinner.show("Loading Data From Server...")
self.quizPlayView.hidden = true
} else if $0.curState == QuizViewState.UserPlay {
SwiftSpinner.hide()
self.quizPlayView.hidden = false
}
}
viewModel.notifyAnswerCorrect.producer.startWithNext {
if $0 && self.viewModel.numberOfQuests.value > 0 {
TAOverlay.showOverlayWithLabel(nil, options:[
TAOverlayOptions.OverlayTypeSuccess,
TAOverlayOptions.AutoHide,
TAOverlayOptions.OverlaySizeFullScreen])
}
}
viewModel.notifyAnswerWrong.producer.startWithNext {
if $0 && self.viewModel.numberOfQuests.value > 0 {
TAOverlay.showOverlayWithLabel(nil, options:[
TAOverlayOptions.OverlayTypeError,
TAOverlayOptions.AutoHide,
TAOverlayOptions.OverlaySizeFullScreen
])
}
}
}
override func viewWillAppear(animated: Bool) {
viewModel.resetQuiz()
viewModel.fetchCharacterPicture()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toResult" {
let resultVC = segue.destinationViewController as! ResultViewController
let vm = ResultViewModel((viewModel.numberOfQuests.value - 1) * 10)
resultVC.bindViewModel(vm)
}
}
@IBAction func selectButtonPressed(sender: AnyObject) {
let button = sender as! UIButton
viewModel.checkAnswer(button.titleLabel?.text)
}
} | mit | fe46b50c730d0c49f7414477b75a877b | 30.419355 | 93 | 0.6734 | 4.585557 | false | false | false | false |
nalexn/ViewInspector | Sources/ViewInspector/SwiftUI/TextField.swift | 1 | 3543 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct TextField: KnownViewType {
public static var typePrefix: String = "TextField"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: SingleViewContent {
func textField() throws -> InspectableView<ViewType.TextField> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: MultipleViewContent {
func textField(_ index: Int) throws -> InspectableView<ViewType.TextField> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.TextField: SupplementaryChildrenLabelView { }
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.TextField {
func labelView() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func callOnEditingChanged() throws {
try guardIsResponsive()
typealias Callback = (Bool) -> Void
let callback: Callback = try {
if let value = try? Inspector
.attribute(label: "onEditingChanged", value: content.view, type: Callback.self) {
return value
}
return try Inspector
.attribute(path: deprecatedActionsPath("editingChanged"), value: content.view, type: Callback.self)
}()
callback(false)
}
func callOnCommit() throws {
try guardIsResponsive()
typealias Callback = () -> Void
let callback: Callback = try {
if let value = try? Inspector
.attribute(label: "onCommit", value: content.view, type: Callback.self) {
return value
}
return try Inspector
.attribute(path: deprecatedActionsPath("commit"), value: content.view, type: Callback.self)
}()
callback()
}
private func deprecatedActionsPath(_ action: String) -> String {
return "_state|state|_value|deprecatedActions|some|\(action)"
}
func input() throws -> String {
return try inputBinding().wrappedValue
}
func setInput(_ value: String) throws {
try guardIsResponsive()
try inputBinding().wrappedValue = value
}
private func inputBinding() throws -> Binding<String> {
let label: String
if #available(iOS 13.2, macOS 10.17, tvOS 13.2, *) {
label = "_text"
} else {
label = "text"
}
return try Inspector.attribute(label: label, value: content.view, type: Binding<String>.self)
}
}
// MARK: - Global View Modifiers
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func textFieldStyle() throws -> Any {
let modifier = try self.modifier({ modifier -> Bool in
return modifier.modifierType.hasPrefix("TextFieldStyleModifier")
}, call: "textFieldStyle")
return try Inspector.attribute(path: "modifier|style", value: modifier)
}
}
| mit | b26836ac647b08cc9567082fdbb9e489 | 31.504587 | 115 | 0.628846 | 4.467844 | false | false | false | false |
asurinsaka/swift_examples_2.1 | MemLeak/MemLeak/ViewController.swift | 1 | 792 | //
// ViewController.swift
// MemLeak
//
// Created by doudou on 10/3/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
class Client
{
var name:String
var account:Account!
init(name:String)
{
self.name = name
self.account = Account(client: self)
}
deinit
{
println("Client::deinit")
}
}
class Account
{
var client:Client
var balance:Int
init(client:Client)
{
self.client = client
self.balance = 0
}
deinit
{
println("Account::deinit")
}
}
override func viewDidLoad()
{
super.viewDidLoad()
var client:Client! = Client(name: "larryhou")
client = nil
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
| mit | 8efefd4a6d643f4fc18ca8d497864330 | 11.571429 | 53 | 0.640152 | 3.069767 | false | false | false | false |
shajrawi/swift | test/stdlib/StringCompatibility.swift | 1 | 8336 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4
// Requires swift-version 4
// UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic
// REQUIRES: executable_test
import StdlibUnittest
//===--- MyString ---------------------------------------------------------===//
/// A simple StringProtocol with a wacky .description that proves
/// LosslessStringConvertible is not infecting ordinary constructions by using
/// .description as the content of a copied string.
struct MyString {
var base: String
}
extension MyString : BidirectionalCollection {
typealias Iterator = String.Iterator
typealias Index = String.Index
typealias SubSequence = MyString
func makeIterator() -> Iterator { return base.makeIterator() }
var startIndex: String.Index { return base.startIndex }
var endIndex: String.Index { return base.startIndex }
subscript(i: Index) -> Character { return base[i] }
subscript(indices: Range<Index>) -> MyString {
return MyString(base: String(self.base[indices]))
}
func index(after i: Index) -> Index { return base.index(after: i) }
func index(before i: Index) -> Index { return base.index(before: i) }
func index(_ i: Index, offsetBy n: Int) -> Index {
return base.index(i, offsetBy: n)
}
func distance(from i: Index, to j: Index) -> Int {
return base.distance(from: i, to: j)
}
}
extension MyString : RangeReplaceableCollection {
init() { base = "" }
mutating func append<S: Sequence>(contentsOf s: S)
where S.Element == Character {
base.append(contentsOf: s)
}
mutating func replaceSubrange<C: Collection>(_ r: Range<Index>, with c: C)
where C.Element == Character {
base.replaceSubrange(r, with: c)
}
}
extension MyString : CustomStringConvertible {
var description: String { return "***MyString***" }
}
extension MyString : TextOutputStream {
public mutating func write(_ other: String) {
append(contentsOf: other)
}
}
extension MyString : TextOutputStreamable {
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(base)
}
}
extension MyString : ExpressibleByUnicodeScalarLiteral {
public init(unicodeScalarLiteral value: String) {
base = .init(unicodeScalarLiteral: value)
}
}
extension MyString : ExpressibleByExtendedGraphemeClusterLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
base = .init(extendedGraphemeClusterLiteral: value)
}
}
extension MyString : ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
base = .init(stringLiteral: value)
}
}
extension MyString : CustomReflectable {
public var customMirror: Mirror {
return base.customMirror
}
}
extension MyString : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return base.customPlaygroundQuickLook
}
}
extension MyString : CustomDebugStringConvertible {
public var debugDescription: String {
return "(***MyString***)"
}
}
extension MyString : Equatable {
public static func ==(lhs: MyString, rhs: MyString) -> Bool {
return lhs.base == rhs.base
}
}
extension MyString : Comparable {
public static func <(lhs: MyString, rhs: MyString) -> Bool {
return lhs.base < rhs.base
}
}
extension MyString : Hashable {
public var hashValue : Int {
return base.hashValue
}
}
extension MyString {
public func hasPrefix(_ prefix: String) -> Bool {
return self.base.hasPrefix(prefix)
}
public func hasSuffix(_ suffix: String) -> Bool {
return self.base.hasSuffix(suffix)
}
}
extension MyString : StringProtocol {
var utf8: String.UTF8View { return base.utf8 }
var utf16: String.UTF16View { return base.utf16 }
var unicodeScalars: String.UnicodeScalarView { return base.unicodeScalars }
var characters: String.CharacterView { return base.characters }
func lowercased() -> String {
return base.lowercased()
}
func uppercased() -> String {
return base.uppercased()
}
init<C: Collection, Encoding: Unicode.Encoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
)
where C.Iterator.Element == Encoding.CodeUnit {
base = .init(decoding: codeUnits, as: sourceEncoding)
}
init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
base = .init(cString: nullTerminatedUTF8)
}
init<Encoding: Unicode.Encoding>(
decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type) {
base = .init(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding)
}
func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result {
return try base.withCString(body)
}
func withCString<Result, Encoding: Unicode.Encoding>(
encodedAs targetEncoding: Encoding.Type,
_ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result
) rethrows -> Result {
return try base.withCString(encodedAs: targetEncoding, body)
}
}
//===----------------------------------------------------------------------===//
public typealias ExpectedConcreteSlice = Substring
public typealias ExpectedStringFromString = String
let swift = 4
var Tests = TestSuite("StringCompatibility")
Tests.test("String/Range/Slice/ExpectedType/\(swift)") {
var s = "hello world"
var sub = s[s.startIndex ..< s.endIndex]
var subsub = sub[s.startIndex ..< s.endIndex]
expectType(String.self, &s)
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("String/ClosedRange/Slice/ExpectedType/\(swift)") {
var s = "hello world"
let lastIndex = s.index(before:s.endIndex)
var sub = s[s.startIndex ... lastIndex]
var subsub = sub[s.startIndex ... lastIndex]
expectType(String.self, &s)
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("Substring/Range/Slice/ExpectedType/\(swift)") {
let s = "hello world" as Substring
var sub = s[s.startIndex ..< s.endIndex]
var subsub = sub[s.startIndex ..< s.endIndex]
// slicing a String in Swift 3 produces a String
// but slicing a Substring should still produce a Substring
expectType(Substring.self, &sub)
expectType(Substring.self, &subsub)
}
Tests.test("Substring/ClosedRange/Slice/ExpectedType/\(swift)") {
let s = "hello world" as Substring
let lastIndex = s.index(before:s.endIndex)
var sub = s[s.startIndex ... lastIndex]
var subsub = sub[s.startIndex ... lastIndex]
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("RangeReplaceable.init/generic/\(swift)") {
func check<
T: RangeReplaceableCollection, S: Collection
>(_: T.Type, from source: S)
where T.Element : Equatable, T.Element == S.Element
{
var r = T(source)
expectType(T.self, &r)
expectEqualSequence(Array(source), Array(r))
}
check(String.self, from: "a" as String)
check(Substring.self, from: "b" as String)
// FIXME: Why isn't this working?
// check(MyString.self, from: "c" as String)
check(String.self, from: "d" as Substring)
check(Substring.self, from: "e" as Substring)
// FIXME: Why isn't this working?
// check(MyString.self, from: "f" as Substring)
// FIXME: Why isn't this working?
// check(String.self, from: "g" as MyString)
// check(Substring.self, from: "h" as MyString)
check(MyString.self, from: "i" as MyString)
}
Tests.test("String.init(someString)/default type/\(swift)") {
var s = String("" as String)
expectType(ExpectedStringFromString.self, &s)
}
Tests.test("Substring.init(someString)/default type/\(swift)") {
var s = Substring("" as Substring)
expectType(Substring.self, &s)
}
Tests.test("LosslessStringConvertible/generic/\(swift)") {
func f<T : LosslessStringConvertible>(_ x: T.Type) {
_ = T("")! // unwrapping optional should work in generic context
}
f(String.self)
}
public typealias ExpectedUTF8ViewSlice = String.UTF8View.SubSequence
Tests.test("UTF8ViewSlicing") {
let s = "Hello, String.UTF8View slicing world!".utf8
var slice = s[s.startIndex..<s.endIndex]
expectType(ExpectedUTF8ViewSlice.self, &slice)
_ = s[s.startIndex..<s.endIndex] as String.UTF8View.SubSequence
}
runAllTests()
| apache-2.0 | 21bdd2e4cd92385ec6c19b225e9b27a2 | 29.312727 | 115 | 0.699856 | 4.03485 | false | true | false | false |
MattMcEachern/CustomLoadingIndicator | CustomLoadingIndicatorDemo/ViewController.swift | 1 | 1076 | //
// ViewController.swift
// CustomLoadingIndicatorDemo
//
// Created by Matt McEachern on 8/16/15.
// Copyright (c) 2015 Matt McEachern. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let loadingLabel = UILabel(frame: CGRect(x: 0,y: 0,width: self.view.bounds.width, height: 100.0))
loadingLabel.text = "LOADING"
loadingLabel.textColor = UIColor.blackColor()
loadingLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(loadingLabel)
loadingLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 55.0);
let customLoadingIndicator = CustomLoadingIndicator()
self.view.addSubview(customLoadingIndicator)
customLoadingIndicator.center = self.view.center
customLoadingIndicator.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | d70a4735018c7ea19a56addbd1a98826 | 30.647059 | 105 | 0.686803 | 4.578723 | false | false | false | false |
Motsai/neblina-swift | NebCtrlMultiSync/iOS/NebCtrlMultiSync/ViewController.swift | 2 | 59274 | //
// ViewController.swift
// BauerPanel
//
// Created by Hoan Hoang on 2017-02-23.
// Copyright © 2017 Hoan Hoang. All rights reserved.
//
import UIKit
import CoreBluetooth
import QuartzCore
import SceneKit
let CmdMotionDataStream = Int32(1)
let CmdHeading = Int32(2)
let NebCmdList = [NebCmdItem] (arrayLiteral:
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_BLE.rawValue),
Name: "BLE Data Port", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_UART.rawValue),
Name: "UART Data Port", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, ActiveStatus: 0,
Name: "Calibrate Forward Pos", Actuator : 2, Text: "Calib Fwrd"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, ActiveStatus: 0,
Name: "Calibrate Down Pos", Actuator : 2, Text: "Calib Dwn"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_FUSION_TYPE, ActiveStatus: 0,
Name: "Fusion 9 axis", Actuator : 1, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, ActiveStatus: 0,
Name: "Reset timestamp", Actuator : 2, Text: "Reset"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_QUATERNION.rawValue),
Name: "Quaternion Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER.rawValue),
Name: "Accelerometer Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_GYROSCOPE.rawValue),
Name: "Gyroscope Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_MAGNETOMETER.rawValue),
Name: "Magnetometer Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.rawValue),
Name: "Accel & Gyro Stream", Actuator : 1, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_PRESSURE.rawValue),
Name: "Pressure Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_TEMPERATURE.rawValue),
Name: "Temperature Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_HUMIDITY.rawValue),
Name: "Humidity Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, ActiveStatus: 0,
Name: "Lock Heading Ref.", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: UInt32(NEBLINA_RECORDER_STATUS_RECORD.rawValue),
Name: "Flash Record", Actuator : 2, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: 0,
Name: "Flash Record", Actuator : 2, Text: "Stop"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK, ActiveStatus: 0,
Name: "Flash Playback", Actuator : 4, Text: "Play"),
// NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, ActiveStatus: 0,
// Name: "Flash Download", Actuator : 2, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED0 level", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED1 level", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED2", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_EEPROM, CmdId: NEBLINA_COMMAND_EEPROM_READ, ActiveStatus: 0,
Name: "EEPROM Read", Actuator : 2, Text: "Read"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_POWER, CmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, ActiveStatus: 0,
Name: "Charge Current in mA", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: CmdMotionDataStream, ActiveStatus: 0,
Name: "Motion data stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: CmdHeading, ActiveStatus: 0,
Name: "Heading", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_ERASE_ALL, ActiveStatus: 0,
Name: "Flash Erase All", Actuator : 2, Text: "Erase"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, ActiveStatus: 0,
Name: "Firmware Update", Actuator : 2, Text: "DFU")
// Baromter, pressure
)
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, SCNSceneRendererDelegate, CBCentralManagerDelegate, NeblinaDelegate {
//, CBPeripheralDelegate {
let scene = SCNScene(named: "art.scnassets/ship.scn")!
let scene2 = SCNScene(named: "art.scnassets/ship.scn")!
var ship = [SCNNode]() //= scene.rootNode.childNodeWithName("ship", recursively: true)!
let max_count = Int16(15)
var prevTimeStamp : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var cnt = Int16(15)
var xf = Int16(0)
var yf = Int16(0)
var zf = Int16(0)
var heading = Bool(false)
//var flashEraseProgress = Bool(false)
var PaketCnt : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var dropCnt : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var bleCentralManager : CBCentralManager!
var foundDevices = [Neblina]()
var connectedDevices = [Neblina]()
//var nebdev = Neblina(devid: 0, peripheral: nil)
var selectedDevices = [Neblina]()
var curSessionId = UInt16(0)
var curSessionOffset = UInt32(0)
var sessionCount = UInt8(0)
var startDownload = Bool(false)
var filepath = String()
var file : FileHandle?
var downloadRecovering = Bool(false)
var playback = Bool(false)
var packetCnt = Int(0)
var graphDisplay = Bool(false)
@IBOutlet weak var cmdView: UITableView!
@IBOutlet weak var devscanView : UITableView!
@IBOutlet weak var selectedView : UITableView!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var flashLabel: UILabel!
//@IBOutlet weak var dumpLabel: UILabel!
@IBOutlet weak var logView: UITextView!
@IBOutlet weak var sceneView : SCNView!
@IBOutlet weak var sceneView2 : SCNView!
@IBAction func doubleTap(_ sender: UITapGestureRecognizer) {
let idx = selectedView.indexPathForSelectedRow! as IndexPath
if idx.row > 0 {
let dev = connectedDevices.remove(at: idx.row - 1)
if connectedDevices.count > 0 {
if selectedDevices.count > 2 {
selectedDevices.remove(at: 0)
}
selectedDevices.append(connectedDevices[0])
}
else {
selectedDevices.removeAll()
// nebdev = Neblina(devid: 0, peripheral: nil)
}
bleCentralManager.cancelPeripheralConnection(dev.device)
//foundDevices.append(dev)
foundDevices.removeAll()
devscanView.reloadData()
selectedView.reloadData()
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
}
}
func getCmdIdx(_ subsysId : Int32, cmdId : Int32) -> Int {
for (idx, item) in NebCmdList.enumerated() {
if (item.SubSysId == subsysId && item.CmdId == cmdId) {
return idx
}
}
return -1
}
override func viewDidLoad() {
super.viewDidLoad()
devscanView.dataSource = self
selectedView.dataSource = self
cmdView.dataSource = self
bleCentralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
// Do any additional setup after loading the view, typically from a nib.
cnt = max_count
//textview = self.view.viewWithTag(3) as! UITextView
// create a new scene
//scene = SCNScene(named: "art.scnassets/ship.scn")!
//scene = SCNScene(named: "art.scnassets/Arc-170_ship/Obj_Shaded/Arc170.obj")
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
let cameraNode2 = SCNNode()
cameraNode2.camera = SCNCamera()
scene2.rootNode.addChildNode(cameraNode2)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
cameraNode2.position = SCNVector3(x: 0, y: 0, z: 15)
//cameraNode.position = SCNVector3(x: 0, y: 15, z: 0)
//cameraNode.rotation = SCNVector4(0, 0, 1, GLKMathDegreesToRadians(-180))
//cameraNode.rotation = SCNVector3(x:
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLight.LightType.omni
lightNode.position = SCNVector3(x: 0, y: 10, z: 50)
scene.rootNode.addChildNode(lightNode)
let lightNode2 = SCNNode()
lightNode2.light = SCNLight()
lightNode2.light!.type = SCNLight.LightType.omni
lightNode2.position = SCNVector3(x: 0, y: 10, z: 50)
scene2.rootNode.addChildNode(lightNode2)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLight.LightType.ambient
ambientLightNode.light!.color = UIColor.darkGray
scene.rootNode.addChildNode(ambientLightNode)
let ambientLightNode2 = SCNNode()
ambientLightNode2.light = SCNLight()
ambientLightNode2.light!.type = SCNLight.LightType.ambient
ambientLightNode2.light!.color = UIColor.darkGray
scene2.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
// ship = scene.rootNode.childNodeWithName("MillenniumFalconTop", recursively: true)!
// ship = scene.rootNode.childNodeWithName("ARC_170_LEE_RAY_polySurface1394376_2_2", recursively: true)!
var sh = scene.rootNode.childNode(withName: "ship", recursively: true)!
ship.append(sh)
// ship = scene.rootNode.childNodeWithName("MDL Obj", recursively: true)!
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180))
//ship.rotation = SCNVector4(1, 0, 0, GLKMathDegreesToRadians(90))
//print("1 - \(ship)")
// animate the 3d object
//ship.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1)))
//ship.runAction(SCNAction.rotateToX(CGFloat(eulerAngles.x), y: CGFloat(eulerAngles.y), z: CGFloat(eulerAngles.z), duration:1 ))// 10, y: 0.0, z: 0.0, duration: 1))
let sh1 = scene2.rootNode.childNode(withName: "ship", recursively: true)!
ship.append(sh1)
// ship = scene.rootNode.childNodeWithName("MDL Obj", recursively: true)!
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180))
// retrieve the SCNView
let scnView = self.view.subviews[0] as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.black
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:)))
scnView.addGestureRecognizer(tapGesture)
//scnView.preferredFramesPerSecond = 60
// let scnView2 = self.view.subviews[1] as! SCNView
// set the scene to the view
sceneView2.scene = scene2
// allows the user to manipulate the camera
sceneView2.allowsCameraControl = true
// show statistics such as fps and timing information
sceneView2.showsStatistics = true
// configure the view
sceneView2.backgroundColor = UIColor.black
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func handleTap(_ gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view.subviews[0] as! SCNView
// check what nodes are tapped
let p = gestureRecognize.location(in: scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
// on completion - unhighlight
/*SCNTransaction.completionBlock {
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
material.emission.contents = UIColor.black
SCNTransaction.commit()
}
*/
material.emission.contents = UIColor.red
SCNTransaction.commit()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
var value = UInt16(textField.text!)
let idx = cmdView.indexPath(for: textField.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if (value == nil) {
value = 0
}
switch (NebCmdList[row].SubSysId) {
case NEBLINA_SUBSYSTEM_LED:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE)
for item in connectedDevices {
item.setLed(UInt8(row - i), Value: UInt8(value!))
}
break
case NEBLINA_SUBSYSTEM_POWER:
for item in connectedDevices {
item.setBatteryChargeCurrent(value!)
}
break
default:
break
}
return true;
}
@IBAction func didSelectDevice(sender : UITableViewCell) {
}
@IBAction func buttonAction(_ sender:UIButton)
{
let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if connectedDevices.count <= 0 {
return
}
if (row < NebCmdList.count) {
switch (NebCmdList[row].SubSysId)
{
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE:
for item in connectedDevices {
item.firmwareUpdate()
}
//nebdev.firmwareUpdate()
print("DFU Command")
break
case NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP:
for item in connectedDevices {
item.resetTimeStamp(Delayed: true)
}
// nebdev.resetTimeStamp(Delayed: true)
print("Reset timestamp")
default:
break
}
break
case NEBLINA_SUBSYSTEM_EEPROM:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_EEPROM_READ:
selectedDevices[0].eepromRead(0)
break
case NEBLINA_COMMAND_EEPROM_WRITE:
//UInt8_t eepdata[8]
//nebdev.SendCmdEepromWrite(0, eepdata)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch (NebCmdList[row].CmdId) {
case NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION:
for item in connectedDevices {
item.calibrateForwardPosition()
}
break
case NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION:
for item in connectedDevices {
item.calibrateDownPosition()
}
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
//if flashEraseProgress == false {
// flashEraseProgress = true;
for item in connectedDevices {
item.eraseStorage(false)
logView.text = logView.text + String(format: "%@ - Erase command sent\n", item.device.name!)
}
//}
case NEBLINA_COMMAND_RECORDER_RECORD:
if NebCmdList[row].ActiveStatus == 0 {
for item in connectedDevices {
item.sessionRecord(false, info: "")
}
//nebdev.sessionRecord(false)
}
else {
for item in connectedDevices {
item.sessionRecord(true, info: "")
}
//nebdev.sessionRecord(true)
}
break
case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD:
/* let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if (cell != nil) {
//let control = cell!.viewWithTag(4) as! UITextField
//let but = cell!.viewWithTag(2) as! UIButton
//but.isEnabled = false
curSessionId = 0//UInt16(control.text!)!
startDownload = true
curSessionOffset = 0
//let filename = String(format:"NeblinaRecord_%d.dat", curSessionId)
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)
if dirPaths != nil {
filepath = dirPaths[0]// as! String
filepath.append(String(format:"/%@/", (nebdev?.device.name!)!))
do {
try FileManager.default.createDirectory(atPath: filepath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
filepath.append(String(format:"%@_%d.dat", (nebdev?.device.name!)!, curSessionId))
FileManager.default.createFile(atPath: filepath, contents: nil, attributes: nil)
do {
try file = FileHandle(forWritingAtPath: filepath)
} catch { print("file failed \(filepath)")}
nebdev?.sessionDownload(true, SessionId : curSessionId, Len: 16, Offset: 0)
}
}*/
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if cell != nil {
let tf = cell?.viewWithTag(4) as! UITextField
let bt = cell?.viewWithTag(2) as! UIButton
if playback == true {
bt.setTitle("Play", for: .normal)
playback = false
}
else {
bt.setTitle("Stop", for: .normal)
var n = UInt16(0)
if UInt16(tf.text!)! != nil {
n = UInt16(tf.text!)!
}
for item in connectedDevices {
item.sessionPlayback(true, sessionId : n)
}
//selectedDevices[1].sessionPlayback(true, sessionId : n)
//nebdev.sessionPlayback(true, sessionId : n)
packetCnt = 0
playback = true
}
}
break
default:
break
}
default:
break
}
}
}
@IBAction func switchAction(_ sender:UISegmentedControl)
{
//let tableView = sender.superview?.superview?.superview?.superview as! UITableView
let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if (selectedDevices.count <= 0) {
return
}
if (row < NebCmdList.count) {
switch (NebCmdList[row].SubSysId)
{
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS:
//nebdev!.setInterface(sender.selectedSegmentIndex)
break
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE:
for item in connectedDevices {
item.setDataPort(row, Ctrl:UInt8(sender.selectedSegmentIndex))
}
break;
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM:
for item in connectedDevices {
item.streamMotionState(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_FUSION_TYPE:
for item in connectedDevices {
item.setFusionType(UInt8(sender.selectedSegmentIndex))
}
break
//case IMU_Data:
// nebdev!.streamIMU(sender.selectedSegmentIndex == 1)
// break
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
for item in connectedDevices {
item.streamQuaternion(sender.selectedSegmentIndex == 1)
}
/*
nebdev.streamEulerAngle(false)
heading = false
prevTimeStamp = 0
nebdev.streamQuaternion(sender.selectedSegmentIndex == 1)*/
let i = getCmdIdx(0xf, cmdId: 1)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM:
for item in connectedDevices {
item.streamQuaternion(false)
item.streamEulerAngle(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM:
for item in connectedDevices {
item.streamExternalForce(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM:
for item in connectedDevices {
item.streamPedometer(sender.selectedSegmentIndex == 1)
}
break;
case NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD:
for item in connectedDevices {
item.recordTrajectory(sender.selectedSegmentIndex == 1)
}
break;
case NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM:
for item in connectedDevices {
item.streamTrajectoryInfo(sender.selectedSegmentIndex == 1)
}
break;
/* case NEBLINA_COMMAND_FUSION_MAG_STATE:
nebdev.streamMAG(sender.selectedSegmentIndex == 1)
break;*/
case NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE:
for item in connectedDevices {
item.lockHeadingReference()
}
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
default:
break
}
case NEBLINA_SUBSYSTEM_LED:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE)
for item in connectedDevices {
if sender.selectedSegmentIndex == 1 {
item.setLed(UInt8(row - i), Value: 255)
}
else {
item.setLed(UInt8(row - i), Value: 0)
}
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
if (sender.selectedSegmentIndex == 1) {
// flashEraseProgress = true;
}
for item in connectedDevices {
item.eraseStorage(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_RECORDER_RECORD:
for item in connectedDevices {
item.sessionRecord(sender.selectedSegmentIndex == 1, info: "")
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
for item in connectedDevices {
item.sessionPlayback(sender.selectedSegmentIndex == 1, sessionId : 0xffff)
}
if (sender.selectedSegmentIndex == 1) {
packetCnt = 0
}
break
case NEBLINA_COMMAND_RECORDER_SESSION_READ:
// curDownloadSession = 0xFFFF
// curDownloadOffset = 0
// nebdev!.sessionRead(curDownloadSession, Len: 32, Offset: curDownloadOffset)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_EEPROM:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_EEPROM_READ:
for item in connectedDevices {
item.eepromRead(0)
}
break
case NEBLINA_COMMAND_EEPROM_WRITE:
//UInt8_t eepdata[8]
//nebdev.SendCmdEepromWrite(0, eepdata)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_SENSOR:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM:
for item in connectedDevices {
item.sensorStreamAccelData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM:
for item in connectedDevices {
item.sensorStreamGyroData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM:
for item in connectedDevices {
item.sensorStreamMagData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM:
for item in connectedDevices {
item.sensorStreamPressureData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM:
for item in connectedDevices {
item.sensorStreamTemperatureData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
for item in connectedDevices {
item.sensorStreamHumidityData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
for item in connectedDevices {
item.sensorStreamAccelGyroData(sender.selectedSegmentIndex == 1)
}
//nebdev.streamAccelGyroSensorData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
for item in connectedDevices {
item.sensorStreamAccelMagData(sender.selectedSegmentIndex == 1)
}
// nebdev.streamAccelMagSensorData(sender.selectedSegmentIndex == 1)
break
default:
break
}
break
case 0xf:
switch (NebCmdList[row].CmdId) {
case CmdHeading:
for item in connectedDevices {
item.streamQuaternion(false)
item.streamEulerAngle(sender.selectedSegmentIndex == 1)
}
// Heading = sender.selectedSegmentIndex == 1
var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
i = getCmdIdx(0xF, cmdId: CmdMotionDataStream)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
case CmdMotionDataStream:
if sender.selectedSegmentIndex == 0 {
for item in connectedDevices {
item.disableStreaming()
}
break
}
for item in connectedDevices {
item.streamQuaternion(sender.selectedSegmentIndex == 1)
}
var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.sensorStreamMagData(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_SENSOR, cmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamExternalForce(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamPedometer(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamRotationInfo(sender.selectedSegmentIndex == 1, Type: 2)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
i = getCmdIdx(0xF, cmdId: CmdHeading)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
default:
break
}
break
default:
break
}
}
/* else {
switch (row - NebCmdList.count) {
case 0:
nebdev.streamQuaternion(false)
nebdev.streamEulerAngle(true)
heading = sender.selectedSegmentIndex == 1
let i = getCmdIdx(NEB_CTRL_SUBSYS_MOTION_ENG, cmdId: Quaternion)
let cell = cmdView.cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
default:
break
}
}*/
}
func updateUI(status : NeblinaSystemStatus_t) {
for idx in 0...NebCmdList.count - 1 {
switch (NebCmdList[idx].SubSysId) {
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[idx].CmdId) {
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE:
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & UInt32(status.interface) == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
default:
break
}
case NEBLINA_SUBSYSTEM_FUSION:
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & status.fusion == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
case NEBLINA_SUBSYSTEM_SENSOR:
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & UInt32(status.sensor) == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
default:
break
}
}
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == devscanView {
return foundDevices.count + 1
}
else if tableView == selectedView {
return connectedDevices.count + 1
}
else if tableView == cmdView {
return NebCmdList.count
}
return 1
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if tableView == devscanView {
if indexPath.row == 0 {
cell.textLabel!.text = String("Devices Found")
cell.selectionStyle = UITableViewCell.SelectionStyle.none
}
else {
let object = foundDevices[(indexPath as NSIndexPath).row - 1]
// cell.textLabel!.text = object.device.name
// print("\(cell.textLabel!.text)")
cell.textLabel!.text = object.device.name! + String(format: "_%lX", object.id)
}
}
else if tableView == selectedView {
if indexPath.row == 0 {
//cell.textLabel!.text = String("Connected")
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let label = cell.contentView.subviews[1] as! UILabel
label.text = String("Connected")
}
else {
let object = connectedDevices[(indexPath as NSIndexPath).row - 1]
//cell.textLabel!.text = object.device.name
let label = cell.contentView.subviews[1] as! UILabel
label.text = object.device.name! + String(format: "_%lX", object.id)
let label1 = cell.contentView.subviews[0] as! UILabel
if object == selectedDevices[0] {
label1.text = "T"
}
else if object == selectedDevices[1] {
label1.text = "B"
}
else {
label1.text?.removeAll()
}
}
}
else if tableView == cmdView {
if indexPath.row < NebCmdList.count {
let labelView = cell.viewWithTag(255) as! UILabel
labelView.text = NebCmdList[indexPath.row].Name// - FusionCmdList.count].Name
switch (NebCmdList[indexPath.row].Actuator)
{
case 1:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UISegmentedControl
control.isHidden = false
let b = cell.viewWithTag(2) as! UIButton
b.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
case 2:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UIButton
control.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
control.setTitle(NebCmdList[indexPath.row].Text, for: UIControl.State())
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
case 3:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UITextField
control.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
control.text = NebCmdList[indexPath.row].Text
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let b = cell.viewWithTag(2) as! UIButton
b.isHidden = true
break
case 4:
let tfcontrol = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UITextField
tfcontrol.isHidden = false
/* if !NebCmdList[(indexPath! as NSIndexPath).row].Text.isEmpty
{
tfcontrol.text = NebCmdList[(indexPath! as NSIndexPath).row].Text
}*/
let bucontrol = cell.viewWithTag(2) as! UIButton
bucontrol.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
bucontrol.setTitle(NebCmdList[indexPath.row].Text, for: UIControl.State())
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
default:
//switchCtrl.enabled = false
// switchCtrl.hidden = true
// buttonCtrl.hidden = true
break
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == devscanView && indexPath.row > 0 {
let dev = foundDevices.remove(at: indexPath.row - 1)
dev.device.delegate = dev
bleCentralManager.connect(dev.device, options: nil)
connectedDevices.append(dev)
//nebdev.delegate = nil
if selectedDevices.count > 1 {
selectedDevices.remove(at: 0)
}
dev.delegate = self
selectedDevices.append(dev)
for (idx, item)in selectedDevices.enumerated() {
if item == dev {
prevTimeStamp[idx] = 0
dropCnt[idx] = 0;
}
}
//nebdev = dev
//nebdev.delegate = self
devscanView.reloadData()
selectedView.reloadData()
}
else if tableView == selectedView && indexPath.row > 0 {
// Switch device to view
//nebdev.delegate = nil
let dev = connectedDevices[indexPath.row - 1]
for item in selectedDevices {
if item == dev {
return
}
}
if selectedDevices.count > 1 {
selectedDevices.remove(at: 0)
}
dev.delegate = self
selectedDevices.append(dev)
// get update status
dev.getSystemStatus()
dev.getFirmwareVersion()
}
}
// MARK: - Bluetooth
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData : [String : Any],
rssi RSSI: NSNumber) {
print("PERIPHERAL NAME: \(peripheral)\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n")
print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n")
print("IDENTIFIER: \(peripheral.identifier)\n")
if advertisementData[CBAdvertisementDataManufacturerDataKey] == nil {
return
}
let mdata = advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData
if mdata.length < 8 {
return
}
var id : UInt64 = 0
(advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&id, range: NSMakeRange(2, 8))
if (id == 0) {
return
}
var name : String? = nil
if advertisementData[CBAdvertisementDataLocalNameKey] == nil {
print("bad, no name")
name = peripheral.name
}
else {
name = advertisementData[CBAdvertisementDataLocalNameKey] as! String
}
let device = Neblina(devName: name!, devid: id, peripheral: peripheral)
for dev in foundDevices
{
if (dev.id == id)
{
return;
}
}
foundDevices.insert(device, at: 0)
devscanView.reloadData();
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
central.stopScan()
peripheral.discoverServices(nil)
print("Connected to peripheral")
}
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
for i in 0..<connectedDevices.count {
if connectedDevices[i].device == peripheral {
connectedDevices.remove(at: i)
selectedView.reloadData()
break
}
}
print("disconnected from peripheral \(error)")
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
}
func scanPeripheral(_ sender: CBCentralManager)
{
print("Scan for peripherals")
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
}
@objc func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOff:
print("CoreBluetooth BLE hardware is powered off")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered off\n"
break
case .poweredOn:
print("CoreBluetooth BLE hardware is powered on and ready")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered on and ready\n"
// We can now call scanForBeacons
let lastPeripherals = central.retrieveConnectedPeripherals(withServices: [NEB_SERVICE_UUID])
if lastPeripherals.count > 0 {
// let device = lastPeripherals.last as CBPeripheral;
//connectingPeripheral = device;
//centralManager.connectPeripheral(connectingPeripheral, options: nil)
}
//scanPeripheral(central)
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
break
case .resetting:
print("CoreBluetooth BLE hardware is resetting")
//self.sensorData.text = "CoreBluetooth BLE hardware is resetting\n"
break
case .unauthorized:
print("CoreBluetooth BLE state is unauthorized")
//self.sensorData.text = "CoreBluetooth BLE state is unauthorized\n"
break
case .unknown:
print("CoreBluetooth BLE state is unknown")
//self.sensorData.text = "CoreBluetooth BLE state is unknown\n"
break
case .unsupported:
print("CoreBluetooth BLE hardware is unsupported on this platform")
//self.sensorData.text = "CoreBluetooth BLE hardware is unsupported on this platform\n"
break
default:
break
}
}
//
// MARK: Neblina delegate
//
func didConnectNeblina(sender : Neblina) {
// prevTimeStamp[0] = 0
// prevTimeStamp[1] = 0
sender.getSystemStatus()
sender.getFirmwareVersion()
}
func didReceiveResponsePacket(sender: Neblina, subsystem: Int32, cmdRspId: Int32, data: UnsafePointer<UInt8>, dataLen: Int) {
print("didReceiveResponsePacket : \(subsystem) \(cmdRspId)")
switch subsystem {
case NEBLINA_SUBSYSTEM_GENERAL:
switch (cmdRspId) {
case NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS:
let d = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaSystemStatus_t.self)// UnsafeBufferPointer<NeblinaSystemStatus_t>(data))
print(" \(d)")
updateUI(status: d)
break
case NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION:
let vers = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaFirmwareVersion_t.self)
let b = (UInt32(vers.firmware_build.0) & 0xFF) | ((UInt32(vers.firmware_build.1) & 0xFF) << 8) | ((UInt32(vers.firmware_build.2) & 0xFF) << 16)
print("\(vers) ")
versionLabel.text = String(format: "API:%d, Firm. Ver.:%d.%d.%d-%d", vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b
)
logView.text = logView.text + String(format: "%@ - API:%d, Firm. Ver.:%d.%d.%d-%d", sender.device.name!, vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch cmdRspId {
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (cmdRspId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
flashLabel.text = String(format: "%@ - Flash erased\n", sender.device.name!)
logView.text = logView.text + String(format: "%@ - Flash erased\n", sender.device.name!)
// flashLabel.text = "Flash erased"
//flashEraseProgress = false
break
case NEBLINA_COMMAND_RECORDER_RECORD:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
// if (nebdev == sender) {
flashLabel.text = String(format: "%@ - Recording session %d", sender.device.name!, session)
// }
logView.text = logView.text + String(format: "%@ - Recording session %d\n", sender.device.name!, session)
}
else {
// if (nebdev == sender) {
flashLabel.text = String(format: "Recorded session %d", session)
// }
logView.text = logView.text + String(format: "%@ - Recorded session %d\n", sender.device.name!, session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "Playing session %d", session)
}
}
else {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "End session %d, %u", session, sender.getPacketCount())
playback = false
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(2) as! UIButton
sw.setTitle("Play", for: .normal)
}
}
}
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_SENSOR:
//nebdev?.getFirmwareVersion()
break
default:
break
}
}
func didReceiveRSSI(sender : Neblina, rssi : NSNumber) {
}
func didReceiveBatteryLevel(sender: Neblina, level: UInt8) {
}
func didReceiveGeneralData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafeRawPointer, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS:
var myStruct = NeblinaSystemStatus_t()
let status = withUnsafeMutablePointer(to: &myStruct) {_ in UnsafeMutableRawPointer(mutating: data)}
//print("Status \(status)")
let d = data.load(as: NeblinaSystemStatus_t.self)// UnsafeBufferPointer<NeblinaSystemStatus_t>(data)
//print(" \(d)")
updateUI(status: d)
break
/* case NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION:
let vers = data.load(as: NeblinaFirmwareVersion_t.self)
let b = (UInt32(vers.firmware_build.0) & 0xFF) | ((UInt32(vers.firmware_build.1) & 0xFF) << 8) | ((UInt32(vers.firmware_build.2) & 0xFF) << 16)
if selectedDevices[0] == sender {
//let vers = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaFirmwareVersion_t.self)
print("\(vers) ")
versionLabel.text = String(format: "API:%d, Firm. Ver.:%d.%d.%d-%d", vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b
)
//versionLabel.text = String(format: "API:%d, FEN:%d.%d.%d, BLE:%d.%d.%d", d.apiVersion,
// d.coreVersion.major, d.coreVersion.minor, d.coreVersion.build,
// d.bleVersion.major, d.bleVersion.minor, d.bleVersion.build)
}
logView.text = logView.text + String(format: "%@ - API:%d, Firm. Ver.:%d.%d.%d-%d", sender.device.name!, vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b)
break*/
/*case NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_GENERAL, cmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = Int(data[0])
}
cell = cmdView.cellForRow( at: IndexPath(row: i + 1, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = Int(data[1])
}
break*/
default:
break
}
}
func didReceiveFusionData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : NeblinaFusionPacket_t, errFlag : Bool) {
//let errflag = Bool(type.rawValue & 0x80 == 0x80)
//let id = FusionId(rawValue: type.rawValue & 0x7F)! as FusionId
if selectedDevices[0] == sender {
//logView.text = logView.text + String(format: "Total packet %u @ %0.2f pps\n", nebdev.getPacketCount(), nebdev.getDataRate())
}
switch (cmdRspId) {
case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM:
break
// case NEBLINA_COMMAND_FUSION_IMU_STATE:
// break
case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM:
//
// Process Euler Angle
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xrot = Float(x) / 10.0
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yrot = Float(y) / 10.0
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zrot = Float(z) / 10.0
if selectedDevices[0] == sender {
if (heading) {
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot))
}
else {
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot))
}
label.text = String("Euler - Yaw:\(xrot), Pitch:\(yrot), Roll:\(zrot)")
}
if selectedDevices[1] == sender {
if (heading) {
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot))
}
else {
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot))
}
}
break
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
//
// Process Quaternion
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = Float(x) / 32768.0
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = Float(y) / 32768.0
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = Float(z) / 32768.0
let w = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8)
let wq = Float(w) / 32768.0
for (idx, item) in selectedDevices.enumerated() {
if item == sender {
ship[idx].orientation = SCNQuaternion(yq, xq, zq, wq)
label.text = String("Quat - x:\(xq), y:\(yq), z:\(zq), w:\(wq)")
}
}
for (idx, item) in connectedDevices.enumerated() {
if (prevTimeStamp[idx] == 0 || data.timestamp <= prevTimeStamp[idx])
{
prevTimeStamp[idx] = data.timestamp;
}
else
{
let tdiff = data.timestamp - prevTimeStamp[idx];
if (tdiff > 49000)
{
dropCnt[idx] += 1
//logView.text = logView.text + String("\(dropCnt) Drop : \(tdiff)\n")
}
prevTimeStamp[idx] = data.timestamp
}
}
break
case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM:
//
// Process External Force
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = x / 1600
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = y / 1600
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = z / 1600
cnt -= 1
if (cnt <= 0) {
cnt = max_count
//if (xf != xq || yf != yq || zf != zq) {
let pos = SCNVector3(CGFloat(xf/cnt), CGFloat(yf/cnt), CGFloat(zf/cnt))
ship[0].position = pos
xf = xq
yf = yq
zf = zq
//}
}
else {
//if (abs(xf) <= abs(xq)) {
xf += xq
//}
//if (abs(yf) <= abs(yq)) {
yf += yq
//}
//if (abs(xf) <= abs(xq)) {
zf += zq
//}
}
if selectedDevices[0] == sender {
label.text = String("Extrn Force - x:\(xq), y:\(yq), z:\(zq)")
}
//print("Extrn Force - x:\(xq), y:\(yq), z:\(zq)")
break
/* case NEBLINA_COMMAND_FUSION_MAG_ST:
//
// Mag data
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = x
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = y
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = z
if nebdev == sender {
label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)")
}
//ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90))
break
*/
default:
break
}
}
func didReceivePmgntData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
let value = UInt16(data[0]) | (UInt16(data[1]) << 8)
if (cmdRspId == NEBLINA_COMMAND_POWER_CHARGE_CURRENT && selectedDevices[0] == sender)
{
let i = getCmdIdx(NEBLINA_SUBSYSTEM_POWER, cmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(3) as! UITextField
control.text = String(value)
}
}
}
func didReceiveLedData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
}
func didReceiveDebugData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
//print("Debug \(type) data \(data)")
switch (cmdRspId) {
case NEBLINA_COMMAND_DEBUG_DUMP_DATA:
if selectedDevices[0] == sender {
logView.text = logView.text + String(format: "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9],
data[10], data[11], data[12], data[13], data[14], data[15])
}
break
default:
break
}
}
func didReceiveRecorderData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
// if nebdev == sender {
// flashLabel.text = "Flash erased"
// }
flashLabel.text = String(format: "%@ - Flash erased\n", sender.device.name!)
logView.text = logView.text + String(format: "%@ - Flash erased\n", sender.device.name!)
break
case NEBLINA_COMMAND_RECORDER_RECORD:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
// if (nebdev == sender) {
flashLabel.text = String(format: "%@ - Recording session %d", sender.device.name!, session)
// }
logView.text = logView.text + String(format: "%@ - Recording session %d\n", sender.device.name!, session)
}
else {
// if (nebdev == sender) {
flashLabel.text = String(format: "Recorded session %d", session)
// }
logView.text = logView.text + String(format: "%@ - Recorded session %d\n", sender.device.name!, session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "Playing session %d", session)
}
}
else {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "End session %d, %u", session, sender.getPacketCount())
playback = false
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(2) as! UIButton
sw.setTitle("Play", for: .normal)
}
}
}
break
/* case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD:
if (errFlag == false && dataLen > 0) {
if dataLen < 4 {
break
}
let offset = UInt32(UInt32(data[0]) | (UInt32(data[1]) << 8) | (UInt32(data[2]) << 16) | (UInt32(data[3]) << 24))
if curSessionOffset != offset {
// packet loss
print("SessionDownload \(curSessionOffset), \(offset), \(data) \(dataLen)")
if downloadRecovering == false {
nebdev?.sessionDownload(false, SessionId: curSessionId, Len: 12, Offset: curSessionOffset)
downloadRecovering = true
}
}
else {
downloadRecovering = false
let d = NSData(bytes: data + 4, length: dataLen - 4)
//writing
if file != nil {
file?.write(d as Data)
}
curSessionOffset += UInt32(dataLen-4)
flashLabel.text = String(format: "Downloading session %d : %u", curSessionId, curSessionOffset)
}
//print("\(curSessionOffset), \(data)")
}
else {
print("End session \(filepath)")
print(" Download End session errflag")
flashLabel.text = String(format: "Downloaded session %d : %u", curSessionId, curSessionOffset)
if (dataLen > 0) {
let d = NSData(bytes: data, length: dataLen)
//writing
if file != nil {
file?.write(d as Data)
}
}
file?.closeFile()
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD)
if i < 0 {
break
}
// let cell = cmdView.view(atColumn: 0, row: i, makeIfNecessary: false)! as NSView // cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0))
// let sw = cell.viewWithTag(2) as! NSButton
// sw.isEnabled = true
}
break*/
default:
break
}
}
func didReceiveEepromData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_EEPROM_READ:
let pageno = UInt16(data[0]) | (UInt16(data[1]) << 8)
logView.text = logView.text + String(format: "%@ EEP page [%d] : %02x %02x %02x %02x %02x %02x %02x %02x\n", sender.device.name!,
pageno, data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9])
break
case NEBLINA_COMMAND_EEPROM_WRITE:
break;
default:
break
}
}
func didReceiveSensorData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)")
}
// rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Gyro - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
break
case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM:
//
// Mag data
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
//ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90))
break
case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM:
break
case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM:
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("IMU - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
break
default:
break
}
cmdView.setNeedsDisplay()
}
}
| mit | e04532da2b6b7b35c6ce4e377ac9c42b | 33.989965 | 196 | 0.663911 | 3.56658 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Nodes/Node.swift | 1 | 8897 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// AudioKIt connection point
open class Node {
/// Nodes providing input to this node.
open var connections: [Node] = []
/// The internal AVAudioEngine AVAudioNode
open var avAudioNode: AVAudioNode
/// The internal AVAudioUnit, which is a subclass of AVAudioNode with more capabilities
open var avAudioUnit: AVAudioUnit? {
didSet {
guard let avAudioUnit = avAudioUnit else { return }
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let param = child.value as? ParameterBase, let label = child.label {
// Property wrappers create a variable with an underscore
// prepended. Drop the underscore to look up the parameter.
let name = String(label.dropFirst())
param.projectedValue.associate(with: avAudioUnit,
identifier: name)
}
}
}
}
/// Returns either the avAudioUnit or avAudioNode (prefers the avAudioUnit if it exists)
open var avAudioUnitOrNode: AVAudioNode {
return avAudioUnit ?? avAudioNode
}
/// Initialize the node from an AVAudioUnit
/// - Parameter avAudioUnit: AVAudioUnit to initialize with
public init(avAudioUnit: AVAudioUnit) {
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
}
/// Initialize the node from an AVAudioNode
/// - Parameter avAudioNode: AVAudioNode to initialize with
public init(avAudioNode: AVAudioNode) {
self.avAudioNode = avAudioNode
}
/// Reset the internal state of the unit
/// Fixes issues such as https://github.com/AudioKit/AudioKit/issues/2046
public func reset() {
if let avAudioUnit = self.avAudioUnit {
AudioUnitReset(avAudioUnit.audioUnit, kAudioUnitScope_Global, 0)
}
}
func detach() {
if let engine = avAudioNode.engine {
engine.detach(avAudioNode)
}
for connection in connections {
connection.detach()
}
}
func makeAVConnections() {
// Are we attached?
if let engine = avAudioNode.engine {
for (bus, connection) in connections.enumerated() {
if let sourceEngine = connection.avAudioNode.engine {
if sourceEngine != avAudioNode.engine {
Log("🛑 Error: Attempt to connect nodes from different engines.")
return
}
}
engine.attach(connection.avAudioNode)
// Mixers will decide which input bus to use.
if let mixer = avAudioNode as? AVAudioMixerNode {
mixer.connect(input: connection.avAudioNode, bus: mixer.nextAvailableInputBus)
} else {
avAudioNode.connect(input: connection.avAudioNode, bus: bus)
}
connection.makeAVConnections()
}
}
}
/// Work-around for an AVAudioEngine bug.
func initLastRenderTime() {
// We don't have a valid lastRenderTime until we query it.
_ = avAudioNode.lastRenderTime
for connection in connections {
connection.initLastRenderTime()
}
}
}
/// Protocol for responding to play and stop of MIDI notes
public protocol Polyphonic {
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
/// - frequency: Play this frequency
func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, frequency: AUValue, channel: MIDIChannel)
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
///
func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel)
/// Stop a sound corresponding to a MIDI note
///
/// - parameter noteNumber: MIDI Note Number
///
func stop(noteNumber: MIDINoteNumber)
}
/// Bare bones implementation of Polyphonic protocol
open class PolyphonicNode: Node, Polyphonic {
/// Global tuning table used by PolyphonicNode (Node classes adopting Polyphonic protocol)
@objc public static var tuningTable = TuningTable()
/// MIDI Instrument
open var midiInstrument: AVAudioUnitMIDIInstrument?
/// Play a sound corresponding to a MIDI note with frequency
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
/// - frequency: Play this frequency
///
open func play(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
frequency: AUValue,
channel: MIDIChannel = 0) {
Log("Playing note: \(noteNumber), velocity: \(velocity), frequency: \(frequency), channel: \(channel), " +
"override in subclass")
}
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
///
open func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0) {
// Microtonal pitch lookup
// default implementation is 12 ET
let frequency = PolyphonicNode.tuningTable.frequency(forNoteNumber: noteNumber)
play(noteNumber: noteNumber, velocity: velocity, frequency: AUValue(frequency), channel: channel)
}
/// Stop a sound corresponding to a MIDI note
///
/// - parameter noteNumber: MIDI Note Number
///
open func stop(noteNumber: MIDINoteNumber) {
Log("Stopping note \(noteNumber), override in subclass")
}
}
/// Protocol to allow nodes to be tapped using AudioKit's tapping system (not AVAudioEngine's installTap)
public protocol Tappable {
/// Install tap on this node
func installTap()
/// Remove tap on this node
func removeTap()
/// Get the latest data for this node
/// - Parameter sampleCount: Number of samples to retrieve
/// - Returns: Float channel data for two channels
func getTapData(sampleCount: Int) -> FloatChannelData
}
/// Default functions for nodes that conform to Tappable
extension Tappable where Self: AudioUnitContainer {
/// Install tap on this node
public func installTap() {
akInstallTap(internalAU?.dsp)
}
/// Remove tap on this node
public func removeTap() {
akRemoveTap(internalAU?.dsp)
}
/// Get the latest data for this node
/// - Parameter sampleCount: Number of samples to retrieve
/// - Returns: Float channel data for two channels
public func getTapData(sampleCount: Int) -> FloatChannelData {
var leftData = [Float](repeating: 0, count: sampleCount)
var rightData = [Float](repeating: 0, count: sampleCount)
var success = false
leftData.withUnsafeMutableBufferPointer { leftPtr in
rightData.withUnsafeMutableBufferPointer { rightPtr in
success = akGetTapData(internalAU?.dsp, sampleCount, leftPtr.baseAddress!, rightPtr.baseAddress!)
}
}
if !success { return [] }
return [leftData, rightData]
}
}
/// Protocol for dictating that a node can be in a started or stopped state
public protocol Toggleable {
/// Tells whether the node is processing (ie. started, playing, or active)
var isStarted: Bool { get }
/// Function to start, play, or activate the node, all do the same thing
func start()
/// Function to stop or bypass the node, both are equivalent
func stop()
}
/// Default functions for nodes that conform to Toggleable
public extension Toggleable {
/// Synonym for isStarted that may make more sense with musical instruments
var isPlaying: Bool {
return isStarted
}
/// Antonym for isStarted
var isStopped: Bool {
return !isStarted
}
/// Antonym for isStarted that may make more sense with effects
var isBypassed: Bool {
return !isStarted
}
/// Synonym to start that may more more sense with musical instruments
func play() {
start()
}
/// Synonym for stop that may make more sense with effects
func bypass() {
stop()
}
}
public extension Toggleable where Self: AudioUnitContainer {
/// Is node started?
var isStarted: Bool {
return internalAU?.isStarted ?? false
}
/// Start node
func start() {
internalAU?.start()
}
/// Stop node
func stop() {
internalAU?.stop()
}
}
| mit | 68daac79cdd299d69f8be4129bc62d28 | 32.063197 | 114 | 0.625365 | 5.099771 | false | false | false | false |
eocleo/AlbumCore | AlbumDemo/AlbumDemo/AlbumViews/views/OverlayerView.swift | 1 | 808 | //
// OverlayerView.swift
// FileMail
//
// Created by leo on 2017/5/27.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
class OverlayerView: UIView {
var showFrame: CGRect?
func showOn(view: UIView) -> Void {
if self.showFrame != nil {
self.frame = self.showFrame!
} else {
self.frame = view.bounds
}
self.isOpaque = false
runInMain {
view.addSubview(self)
}
// self.alpha = 0.1
// UIView.animate(withDuration: 0.3) {
// self.alpha = 1.0
// }
AlbumDebug("showOn: \(self)")
}
func dismiss() -> Void {
DispatchQueue.main.async {
AlbumDebug("dismiss: \(self)")
self.removeFromSuperview()
}
}
}
| mit | 22066f01add563fc4875bc5f83d640c4 | 19.641026 | 47 | 0.515528 | 3.851675 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/TableOfContentsViewController.swift | 1 | 11754 | import UIKit
import WMF
enum TableOfContentsDisplayMode {
case inline
case modal
}
enum TableOfContentsDisplaySide {
case left
case right
}
protocol TableOfContentsViewControllerDelegate : UIViewController {
/**
Notifies the delegate that the controller will display
Use this to update the ToC if needed
*/
func tableOfContentsControllerWillDisplay(_ controller: TableOfContentsViewController)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsController(_ controller: TableOfContentsViewController,
didSelectItem item: TableOfContentsItem)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsControllerDidCancel(_ controller: TableOfContentsViewController)
var tableOfContentsArticleLanguageURL: URL? { get }
var tableOfContentsSemanticContentAttribute: UISemanticContentAttribute { get }
var tableOfContentsItems: [TableOfContentsItem] { get }
}
class TableOfContentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TableOfContentsAnimatorDelegate, Themeable {
fileprivate var theme = Theme.standard
let tableOfContentsFunnel: ToCInteractionFunnel
var semanticContentAttributeOverride: UISemanticContentAttribute {
return delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
}
let displaySide: TableOfContentsDisplaySide
var displayMode = TableOfContentsDisplayMode.modal {
didSet {
animator?.displayMode = displayMode
closeGestureRecognizer?.isEnabled = displayMode == .inline
apply(theme: theme)
}
}
var isVisible: Bool = false
var closeGestureRecognizer: UISwipeGestureRecognizer?
@objc func handleTableOfContentsCloseGesture(_ swipeGestureRecoginzer: UIGestureRecognizer) {
guard swipeGestureRecoginzer.state == .ended, isVisible else {
return
}
delegate?.tableOfContentsControllerDidCancel(self)
}
let tableView: UITableView = UITableView(frame: .zero, style: .grouped)
lazy var animator: TableOfContentsAnimator? = {
guard let delegate = delegate else {
return nil
}
let animator = TableOfContentsAnimator(presentingViewController: delegate, presentedViewController: self)
animator.apply(theme: theme)
animator.delegate = self
animator.displaySide = displaySide
animator.displayMode = displayMode
return animator
}()
weak var delegate: TableOfContentsViewControllerDelegate?
var items: [TableOfContentsItem] {
return delegate?.tableOfContentsItems ?? []
}
func reload() {
tableView.reloadData()
selectInitialItemIfNecessary()
}
// MARK: - Init
required init(delegate: TableOfContentsViewControllerDelegate?, theme: Theme, displaySide: TableOfContentsDisplaySide) {
self.theme = theme
self.delegate = delegate
self.displaySide = displaySide
tableOfContentsFunnel = ToCInteractionFunnel()
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = animator
edgesForExtendedLayout = .all
extendedLayoutIncludesOpaqueBars = true
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Sections
var indexOfSelectedItem: Int = -1
var indiciesOfHighlightedItems: Set<Int> = []
func selectInitialItemIfNecessary() {
guard indexOfSelectedItem == -1, !items.isEmpty else {
return
}
selectItem(at: 0)
}
func selectItem(at index: Int) {
guard index < items.count else {
assertionFailure("Trying to select an item out of range")
return
}
guard indexOfSelectedItem != index else {
return
}
indexOfSelectedItem = index
var newIndicies: Set<Int> = [index]
let item = items[index]
for (index, relatedItem) in items.enumerated() {
guard item.shouldBeHighlightedAlongWithItem(relatedItem) else {
continue
}
newIndicies.insert(index)
}
guard newIndicies != indiciesOfHighlightedItems else {
return
}
let indiciesToReload = newIndicies.union(indiciesOfHighlightedItems)
let indexPathsToReload = indiciesToReload.map { IndexPath(row: $0, section: 0) }
indiciesOfHighlightedItems = newIndicies
guard viewIfLoaded != nil else {
return
}
tableView.reloadRows(at: indexPathsToReload, with: .none)
}
func scrollToItem(at index: Int) {
guard index < items.count else {
assertionFailure("Trying to scroll to an item put of range")
return
}
guard viewIfLoaded != nil, index < tableView.numberOfRows(inSection: 0) else {
return
}
let indexPath = IndexPath(row: index, section: 0)
guard !(tableView.indexPathsForVisibleRows?.contains(indexPath) ?? true) else {
return
}
let shouldAnimate = (displayMode == .inline)
tableView.scrollToRow(at: indexPath, at: .top, animated: shouldAnimate)
}
// MARK: - Selection
private func didRequestClose(_ controller: TableOfContentsAnimator?) -> Bool {
tableOfContentsFunnel.logClose()
delegate?.tableOfContentsControllerDidCancel(self)
return delegate != nil
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
assert(tableView.style == .grouped, "Use grouped UITableView layout so our TableOfContentsHeader's autolayout works properly. Formerly we used a .Plain table style and set self.tableView.tableHeaderView to our TableOfContentsHeader, but doing so caused autolayout issues for unknown reasons. Instead, we now use a grouped layout and use TableOfContentsHeader with viewForHeaderInSection, which plays nicely with autolayout. (grouped layouts also used because they allow the header to scroll *with* the section cells rather than floating)")
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundView = nil
tableView.register(TableOfContentsCell.wmf_classNib(),
forCellReuseIdentifier: TableOfContentsCell.reuseIdentifier())
tableView.estimatedRowHeight = 41
tableView.rowHeight = UITableView.automaticDimension
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 32
tableView.separatorStyle = .none
view.wmf_addSubviewWithConstraintsToEdges(tableView)
tableView.contentInsetAdjustmentBehavior = .never
tableView.allowsMultipleSelection = false
tableView.semanticContentAttribute = delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
view.semanticContentAttribute = delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
let closeGR = UISwipeGestureRecognizer(target: self, action: #selector(handleTableOfContentsCloseGesture))
switch displaySide {
case .left:
closeGR.direction = .left
case .right:
closeGR.direction = .right
}
view.addGestureRecognizer(closeGR)
closeGestureRecognizer = closeGR
apply(theme: theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.delegate?.tableOfContentsControllerWillDisplay(self)
tableOfContentsFunnel.logOpen()
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableOfContentsCell.reuseIdentifier(), for: indexPath) as! TableOfContentsCell
let index = indexPath.row
let item = items[index]
let shouldHighlight = indiciesOfHighlightedItems.contains(index)
cell.backgroundColor = tableView.backgroundColor
cell.contentView.backgroundColor = tableView.backgroundColor
cell.titleIndentationLevel = item.indentationLevel
let color = item.itemType == .primary ? theme.colors.primaryText : theme.colors.secondaryText
let selectionColor = theme.colors.link
let isHighlighted = index == indexOfSelectedItem
cell.setTitleHTML(item.titleHTML, with: item.itemType.titleTextStyle, highlighted: isHighlighted, color: color, selectionColor: selectionColor)
if isHighlighted {
// This makes no difference to sighted users; it allows VoiceOver to read highlighted cell as selected.
cell.accessibilityTraits = .selected
}
cell.setNeedsLayout()
cell.setSectionSelected(shouldHighlight, animated: false)
cell.contentView.semanticContentAttribute = semanticContentAttributeOverride
cell.titleLabel.semanticContentAttribute = semanticContentAttributeOverride
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let delegate = delegate {
let header = TableOfContentsHeader.wmf_viewFromClassNib()
header?.articleURL = delegate.tableOfContentsArticleLanguageURL
header?.backgroundColor = tableView.backgroundColor
header?.semanticContentAttribute = semanticContentAttributeOverride
header?.contentsLabel.semanticContentAttribute = semanticContentAttributeOverride
header?.contentsLabel.textColor = theme.colors.secondaryText
return header
} else {
return nil
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableOfContentsFunnel.logClick()
let index = indexPath.row
selectItem(at: index)
delegate?.tableOfContentsController(self, didSelectItem: items[index])
}
func tableOfContentsAnimatorDidTapBackground(_ controller: TableOfContentsAnimator) {
_ = didRequestClose(controller)
}
// MARK: - UIAccessibilityAction
override func accessibilityPerformEscape() -> Bool {
return didRequestClose(nil)
}
// MARK: - UIAccessibilityAction
override func accessibilityPerformMagicTap() -> Bool {
return didRequestClose(nil)
}
public func apply(theme: Theme) {
self.theme = theme
self.animator?.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
if displayMode == .modal {
tableView.backgroundColor = theme.colors.paperBackground
} else {
tableView.backgroundColor = theme.colors.midBackground
}
tableView.reloadData()
}
}
| mit | 1bd2177d5d87ead95c06ab992a5908be | 35.055215 | 547 | 0.67543 | 6.061888 | false | false | false | false |
Sebastian-Hojas/BetterGCD | Source/GCD.swift | 1 | 7986 | //
// GCDPipePipe.swift
// BetterGCDPipe
//
// MIT License
//
// Copyright (c) 2016 Sebastian Hojas
//
// 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 enum BlockType<T>
{
case AdvancedExecutionBlock(GCDPipe<T>.AdvancedExecutionBlock)
case SimpleExecutionBlock(GCDPipe<T>.SimpleExecutionBlock)
case CatchBlock(GCDPipe<T>.CatchBlock)
}
public class GCD: GCDPipe<Any>{
public override init()
{
super.init()
}
private init(previous: GCD)
{
super.init(previous: previous)
}
public func async(execution: SimpleExecutionBlock) -> GCD
{
self.execution = BlockType<Any>.SimpleExecutionBlock(execution)
if self.previous?.executed == true {
self.fire(cachedReturnValue)
}
self.next = GCD(previous: self)
return self.next as! GCD
}
public override func main() -> GCD
{
super.main()
return self
}
public override func low(flags: UInt = 0) -> GCD
{
super.low(flags)
return self
}
public override func high(flags: UInt = 0) -> GCD
{
super.high(flags)
return self
}
public override func after(time: NSTimeInterval) -> GCD
{
super.after(time)
return self
}
public override func cycle(times: Int) -> GCD
{
super.cycle(times)
return self
}
public override func priority(priority: dispatch_queue_priority_t, flags: UInt = 0) -> GCD
{
super.priority(priority, flags: flags)
return self
}
}
public class GCDPipe<T> {
public typealias CatchBlock = (ErrorType) -> ()
public typealias AdvancedExecutionBlock = (T?) throws ->(T?)
public typealias SimpleExecutionBlock = () throws -> ()
private var previous: GCDPipe?
private var next: GCDPipe?
private var queue: dispatch_queue_t = dispatch_get_main_queue()
private var after: NSTimeInterval?
private var repetition: Int = 1
private var execution: BlockType<T>?
private var executed: Bool = false
private var cachedReturnValue: T? = nil
//var queue: dispatch_queue_t?
//var after: NSTimeInterval?
/**
Initiation of first chain element
- returns: initiated GCDPipe block
*/
public init()
{
self.fire(nil)
}
/**
Initiates element in execution chain
- parameter previous: Link to previous element of linked list
- returns: initiated GCDPipe block
*/
private init(previous: GCDPipe<T>)
{
self.previous = previous
// stay on the same queue by default
self.queue = previous.queue
}
/**
Starts the dispatch
- parameter chainValue: value that should be passed on to the block
*/
private func fire(chainValue: T?) {
let block: dispatch_block_t = {
guard let execution = self.execution else {
// no block available, save return value, for later
self.cachedReturnValue = chainValue
return
}
self.repetition -= 1
switch execution {
case .AdvancedExecutionBlock(let _exec):
do {
let retValue = try _exec(chainValue)
if self.repetition > 0
{
self.fire(retValue)
}
else{
self.next?.fire(retValue)
}
}
catch{
self.unwindError(error)
}
break
case .SimpleExecutionBlock(let _exec):
do {
try _exec()
if self.repetition > 0
{
self.fire(nil)
}
else{
self.next?.fire(nil)
}
}
catch{
self.unwindError(error)
}
break
case .CatchBlock:
// no need to call catch block
break
}
self.executed = true
}
guard let after = after else {
dispatch_async(queue, block)
return
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(after*Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
}
/**
Unwinds linked list to find catch block and raise error
- parameter error: risen error
*/
private func unwindError(error: ErrorType)
{
// find last element
if let next = next {
next.unwindError(error)
return
}
guard let exec = execution else {
// Do we ignore error?
print("Ignored error \(error)")
return
}
switch exec {
case .CatchBlock(let catchBlock):
// should we do that on the main thread?
catchBlock(error)
default:
print("Should not never happen")
}
}
/**
Adds a new block to the chains
- parameter execution: block that should be dispatched
- returns: next possible block
*/
public func async(execution: AdvancedExecutionBlock) -> GCDPipe<T>
{
self.execution = BlockType<T>.AdvancedExecutionBlock(execution)
if self.previous?.executed == true {
self.fire(cachedReturnValue)
}
self.next = GCDPipe<T>(previous: self)
return self.next!
}
public func catching(catchBlock: CatchBlock)
{
self.execution = BlockType<T>.CatchBlock(catchBlock)
}
public func main() -> GCDPipe<T>
{
queue = dispatch_get_main_queue()
return self
}
public func priority(priority: dispatch_queue_priority_t, flags: UInt = 0) -> GCDPipe<T>
{
queue = dispatch_get_global_queue(priority, flags)
return self
}
public func low(flags: UInt = 0) -> GCDPipe<T>
{
self.priority(DISPATCH_QUEUE_PRIORITY_LOW, flags: flags)
return self
}
public func high(flags: UInt = 0) -> GCDPipe<T>
{
self.priority(DISPATCH_QUEUE_PRIORITY_HIGH, flags: flags)
return self
}
public func after(time: NSTimeInterval) -> GCDPipe<T>
{
after = time
return self
}
public func cycle(times: Int) -> GCDPipe<T>
{
repetition = times
return self
}
}
| mit | 3d3bd0010d0828bc6a37003eae8a7554 | 24.678457 | 125 | 0.546832 | 4.884404 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Controller/Views/URLHashTextField.swift | 1 | 1415 | //
// URLHashTextField.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 23/02/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
final class URLHashTextField: UITextField {
// MARK: - Initializers and Deinitializers
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden Methods and Properties
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0)
layer.cornerRadius = 8
translatesAutoresizingMaskIntoConstraints = false
autocapitalizationType = .none
autocorrectionType = .no
spellCheckingType = .no
keyboardType = .alphabet
clearButtonMode = .whileEditing
font = UIFont.boldSystemFont(ofSize: 16)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
let padLeft: CGFloat = 5
let padRight: CGFloat = 20
let inset = CGRect(x: bounds.origin.x + padLeft,
y: bounds.origin.y,
width: bounds.width - padLeft - padRight,
height: bounds.height)
return inset
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
| mit | ce86ffe45804a19d2da250f7c2db7c81 | 27.28 | 90 | 0.619519 | 4.682119 | false | false | false | false |
remlostime/one | one/one/ViewControllers/EditUserInfoViewController.swift | 1 | 8529 | //
// EditUserInfoViewController.swift
// one
//
// Created by Kai Chen on 12/30/16.
// Copyright © 2016 Kai Chen. All rights reserved.
//
import UIKit
import Parse
import SCLAlertView
class EditUserInfoViewController: UITableViewController {
fileprivate var profileImageCell: ProfileUserImageViewCell?
fileprivate var genderPickerView: UIPickerView!
let genders = ["Male", "Female"]
var genderCell: UserInfoViewCell?
let userInfo = UserInfo.init(nil)
fileprivate var profileImage: UIImage?
fileprivate var username: String?
fileprivate var fullname: String?
fileprivate var bio: String?
fileprivate var website: String?
fileprivate var email: String?
fileprivate var mobile: String?
fileprivate var gender: String?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
genderPickerView = UIPickerView()
genderPickerView.dataSource = self
genderPickerView.delegate = self
genderPickerView.backgroundColor = UIColor.groupTableViewBackground
genderPickerView.showsSelectionIndicator = true
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Cancel", style: .plain, target: self, action: #selector(cancelButtonTapped))
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(doneButtonTapped))
}
// MARK: Action
func cancelButtonTapped() {
self.dismiss(animated: true, completion: nil)
}
func doneButtonTapped() {
// TODO: We should setup listener in email field to get email when user is done with it
let emailIndexPath = IndexPath(row: 0, section: 1)
let emailCell = tableView.cellForRow(at: emailIndexPath) as? UserInfoViewCell
let email = emailCell?.contentTextField.text
if let email = email {
if !email.isValidEmail() {
SCLAlertView().showError("Incorrect Email", subTitle: "Please provoide correct email.")
return
}
}
let websiteIndexPath = IndexPath(row: 3, section: 0)
let websiteCell = tableView.cellForRow(at: websiteIndexPath) as? UserInfoViewCell
let website = websiteCell?.contentTextField.text
if let website = website {
if !website.isValidWebsite() {
SCLAlertView().showError("Incorrect Website", subTitle: "Please provide correct website")
return
}
}
let user = PFUser.current()
let usernameIndexPath = IndexPath(row: 2, section: 0)
let usernameCell = tableView.cellForRow(at: usernameIndexPath) as? UserInfoViewCell
user?.username = usernameCell?.contentTextField.text
user?.email = emailCell?.contentTextField.text
user?[User.website.rawValue] = websiteCell?.contentTextField.text
let fullnameIndexPath = IndexPath(row: 1, section: 0)
let fullnameCell = tableView.cellForRow(at: fullnameIndexPath) as? UserInfoViewCell
user?[User.fullname.rawValue] = fullnameCell?.contentTextField.text
let bioIndexPath = IndexPath(row: 4, section: 0)
let bioCell = tableView.cellForRow(at: bioIndexPath) as? UserInfoViewCell
user?[User.bio.rawValue] = bioCell?.contentTextField.text
let mobileIndexPath = IndexPath(row: 1, section: 1)
let mobileCell = tableView.cellForRow(at: mobileIndexPath) as? UserInfoViewCell
user?[User.mobile.rawValue] = mobileCell?.contentTextField.text
let genderIndexPath = IndexPath(row: 2, section: 0)
let genderCell = tableView.cellForRow(at: genderIndexPath) as? UserInfoViewCell
user?[User.gender.rawValue] = genderCell?.contentTextField.text
let profileImageData = UIImagePNGRepresentation((profileImageCell?.profileImageView.image)!)
let profileImageFile = PFFile(name: "profile_image.png", data: profileImageData!)
user?[User.profileImage.rawValue] = profileImageFile
user?.saveInBackground(block: { (success: Bool, error: Error?) in
guard !success else {
SCLAlertView().showError("Save Error", subTitle: "Can not save, please try again!")
return
}
NotificationCenter.default.post(name: .updateUserInfo, object: nil)
})
dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 5
} else {
return 3
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0 && indexPath.row == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.profileUserImageViewCell.rawValue, for: indexPath) as? ProfileUserImageViewCell
// setup user image
cell?.delegate = self
profileImageCell = cell
let profileImageFile = userInfo.profileImageFile
profileImageFile?.getDataInBackground(block: { [weak cell](data: Data?, error: Error?) in
guard let strongCell = cell else {
return
}
strongCell.profileImageView?.image = UIImage(data: data!)
})
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.userInfoViewCell.rawValue, for: indexPath) as? UserInfoViewCell
cell?.config(indexPath, userInfo: userInfo)
if (indexPath.section == 1 && indexPath.row == 2) {
cell?.contentTextField.inputView = genderPickerView
genderCell = cell
}
return cell!
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return nil
} else {
return "Private Information"
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 150.0
} else {
return 46.0
}
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
}
extension EditUserInfoViewController: ProfileUserImageViewCellDelegate {
func showImagePicker(_ profileImageCell: ProfileUserImageViewCell) {
let imagePickerVC = UIImagePickerController()
imagePickerVC.delegate = self
imagePickerVC.sourceType = .photoLibrary
imagePickerVC.allowsEditing = true
present(imagePickerVC, animated: true, completion: nil)
}
}
extension EditUserInfoViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
profileImageCell?.profileImageView.image = info[UIImagePickerControllerEditedImage] as? UIImage
dismiss(animated: true, completion: nil)
}
}
extension EditUserInfoViewController: UINavigationControllerDelegate {
}
extension EditUserInfoViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let genderCell = genderCell {
genderCell.contentTextField.text = genders[row]
genderCell.endEditing(true)
}
}
}
extension EditUserInfoViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return genders.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return genders[row]
}
}
| gpl-3.0 | b74b27c3182b5d6d6bb0d5cbbd49a559 | 35.289362 | 159 | 0.642941 | 5.544863 | false | false | false | false |
pasmall/WeTeam | WeTools/WeTools/ViewController/Login/RegistViewController.swift | 1 | 2703 | //
// RegistViewController.swift
// WeTools
//
// Created by lhtb on 2016/11/17.
// Copyright © 2016年 lhtb. All rights reserved.
//
import UIKit
import Alamofire
class RegistViewController: BaseViewController {
let accTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 140, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入手机号码")
let psdTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入密码")
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "注册"
setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.navigationBar.isHidden = false
}
func setUI () {
view.addSubview(accTF)
view.addSubview(psdTF)
let line = UIView.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 0.4))
line.backgroundColor = backColor
view.addSubview(line)
psdTF.isSecureTextEntry = true
//登录
let logBtn = UIButton()
logBtn.frame = CGRect.init(x: 10, y: 248, width: SCREEN_WIDTH - 20, height: 44)
logBtn.backgroundColor = blueColor
logBtn.setTitle("注册", for: .normal)
logBtn.layer.cornerRadius = 4
logBtn.layer.masksToBounds = true
logBtn.addTarget(self, action: #selector(LoginViewController.tapLoginBtn), for: .touchUpInside)
view.addSubview(logBtn)
}
func tapLoginBtn() {
self.showSimpleHUD()
Alamofire.request( IP + "regist.php", method: .post, parameters: ["name":accTF.text!,"psd":psdTF.text!]).responseJSON { (data) in
if let json = data.result.value as? [String:Any]{
print(json)
if json["code"] as! Int == 200{
self.hidSimpleHUD()
_ = self.alert.showAlert("", subTitle: "注册成功", style: AlertStyle.success, buttonTitle: "返回登录", action: { (true) in
_ = self.navigationController?.popViewController(animated: true)
})
} else if json["code"] as! Int == 202{
_ = self.alert.showAlert("该账号已被注册")
}
}
}
}
}
| apache-2.0 | 6f6eac3f20171464cad65e2cd5e17fbd | 29.275862 | 137 | 0.555049 | 4.419463 | false | false | false | false |
ascode/pmn | AnimationDemo/Controller/ImageViewAnimationViewController.swift | 1 | 4830 | //
// testViewController.swift
// AnimationDemo
//
// Created by 金飞 on 2016/10/17.
// Copyright © 2016年 JL. All rights reserved.
//
import UIKit
class ImageViewAnimationViewController: UIViewController {
var img: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
img = UIImageView()
img.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 50)
img.animationImages = [
UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!,
UIImage(named: "5")!,
UIImage(named: "6")!,
UIImage(named: "7")!,
UIImage(named: "8")!,
UIImage(named: "9")!,
UIImage(named: "10")!,
UIImage(named: "11")!,
UIImage(named: "12")!,
UIImage(named: "13")!,
UIImage(named: "14")!,
UIImage(named: "15")!,
UIImage(named: "16")!,
UIImage(named: "17")!,
UIImage(named: "18")!,
UIImage(named: "19")!,
UIImage(named: "20")!,
UIImage(named: "21")!,
UIImage(named: "22")!,
UIImage(named: "23")!,
UIImage(named: "24")!,
UIImage(named: "25")!
]
img.animationDuration = 50
img.animationRepeatCount = 0
self.view.addSubview(img)
let btnStart: UIButton = UIButton()
btnStart.frame = CGRect(x: UIScreen.main.bounds.width * 0/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStart.setTitle("播放", for: UIControlState.normal)
btnStart.layer.borderColor = UIColor.white.cgColor
btnStart.layer.borderWidth = 3
btnStart.layer.cornerRadius = 3
btnStart.layer.masksToBounds = true
btnStart.backgroundColor = UIColor.blue
btnStart.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStartPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStart)
let btnStop: UIButton = UIButton()
btnStop.frame = CGRect(x: UIScreen.main.bounds.width * 1/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStop.setTitle("停止", for: UIControlState.normal)
btnStop.layer.borderColor = UIColor.white.cgColor
btnStop.layer.borderWidth = 3
btnStop.layer.cornerRadius = 3
btnStop.layer.masksToBounds = true
btnStop.backgroundColor = UIColor.blue
btnStop.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStopPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStop)
let btnBack: UIButton = UIButton()
btnBack.frame = CGRect(x: UIScreen.main.bounds.width * 2/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnBack.setTitle("返回", for: UIControlState.normal)
btnBack.layer.borderColor = UIColor.white.cgColor
btnBack.layer.borderWidth = 3
btnBack.layer.cornerRadius = 3
btnBack.layer.masksToBounds = true
btnBack.backgroundColor = UIColor.blue
btnBack.addTarget(self, action: #selector(ImageViewAnimationViewController.btnBackPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnBack)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func btnBackPressed(){
self.dismiss(animated: true) {
}
}
func btnStartPressed(){
img.startAnimating()
}
func btnStopPressed(){
img.stopAnimating()
}
/*
// 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.
}
*/
}
| mit | f838c043b64ee2d78bc27ea300b214ec | 37.488 | 156 | 0.538765 | 5.178687 | false | false | false | false |
ustwo/mockingbird | Sources/SwaggerKit/Model/HTTPMethod.swift | 1 | 582 | //
// HTTPMethod.swift
// Mockingbird
//
// Created by Aaron McTavish on 20/12/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
enum HTTPMethod: String {
case connect = "CONNECT"
case delete = "DELETE"
case get = "GET"
case head = "HEAD"
case options = "OPTIONS"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
case trace = "TRACE"
static let allValues: [HTTPMethod] = [.connect, .delete, .get, .head, .options,
.patch, .post, .put, .trace]
}
| mit | f0c7a040852e15565529a74d59373b65 | 21.346154 | 83 | 0.576592 | 3.677215 | false | false | false | false |
morizotter/BrightFutures | BrightFutures/FutureUtils.swift | 1 | 6921 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Result
//// The free functions in this file operate on sequences of Futures
/// Performs the fold operation over a sequence of futures. The folding is performed
/// on `Queue.global`.
/// (The Swift compiler does not allow a context parameter with a default value
/// so we define some functions twice)
public func fold<S: SequenceType, T, R, E where S.Generator.Element == Future<T, E>>(seq: S, zero: R, f: (R, T) -> R) -> Future<R, E> {
return fold(seq, context: Queue.global.context, zero: zero, f: f)
}
/// Performs the fold operation over a sequence of futures. The folding is performed
/// in the given context.
public func fold<S: SequenceType, T, R, E where S.Generator.Element == Future<T, E>>(seq: S, context c: ExecutionContext, zero: R, f: (R, T) -> R) -> Future<R, E> {
return seq.reduce(Future<R, E>(successValue: zero)) { zero, elem in
return zero.flatMap { zeroVal in
elem.map(context: c) { elemVal in
return f(zeroVal, elemVal)
}
}
}
}
/// Turns a sequence of T's into an array of `Future<U>`'s by calling the given closure for each element in the sequence.
/// If no context is provided, the given closure is executed on `Queue.global`
public func traverse<S: SequenceType, T, U, E where S.Generator.Element == T>(seq: S, context c: ExecutionContext = Queue.global.context, f: T -> Future<U, E>) -> Future<[U], E> {
return fold(seq.map(f), context: c, zero: [U]()) { (list: [U], elem: U) -> [U] in
return list + [elem]
}
}
/// Turns a sequence of `Future<T>`'s into a future with an array of T's (Future<[T]>)
/// If one of the futures in the given sequence fails, the returned future will fail
/// with the error of the first future that comes first in the list.
public func sequence<S: SequenceType, T, E where S.Generator.Element == Future<T, E>>(seq: S) -> Future<[T], E> {
return traverse(seq) { (fut: Future<T, E>) -> Future<T, E> in
return fut
}
}
/// See `find<S: SequenceType, T where S.Generator.Element == Future<T>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T>`
public func find<S: SequenceType, T, E: ErrorType where S.Generator.Element == Future<T, E>>(seq: S, p: T -> Bool) -> Future<T, BrightFuturesError<E>> {
return find(seq, context: Queue.global.context, p: p)
}
/// Returns a future that succeeds with the value from the first future in the given
/// sequence that passes the test `p`.
/// If any of the futures in the given sequence fail, the returned future fails with the
/// error of the first failed future in the sequence.
/// If no futures in the sequence pass the test, a future with an error with NoSuchElement is returned.
public func find<S: SequenceType, T, E: ErrorType where S.Generator.Element == Future<T, E>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T, BrightFuturesError<E>> {
return sequence(seq).mapError { error in
return BrightFuturesError(external: error)
}.flatMap(context: c) { val -> Result<T, BrightFuturesError<E>> in
for elem in val {
if (p(elem)) {
return Result(value: elem)
}
}
return Result(error: .NoSuchElement)
}
}
/// Returns a future that returns with the first future from the given sequence that completes
/// (regardless of whether that future succeeds or fails)
public func firstCompletedOf<S: SequenceType, T, E where S.Generator.Element == Future<T, E>>(seq: S) -> Future<T, E> {
let p = Promise<T, E>()
for fut in seq {
fut.onComplete(context: Queue.global.context) { res in
p.tryComplete(res)
return
}
}
return p.future
}
/// Enables the chaining of two failable operations where the second operation is asynchronous and
/// represented by a future.
/// Like map, the given closure (that performs the second operation) is only executed
/// if the first operation result is a .Success
/// If a regular `map` was used, the result would be `Result<Future<U>>`.
/// The implementation of this function uses `map`, but then flattens the result before returning it.
public func flatMap<T,U, E>(result: Result<T,E>, @noescape f: T -> Future<U, E>) -> Future<U, E> {
return flatten(result.map(f))
}
/// Returns a .Failure with the error from the outer or inner result if either of the two failed
/// or a .Success with the success value from the inner Result
public func flatten<T, E>(result: Result<Result<T,E>,E>) -> Result<T,E> {
return result.analysis(ifSuccess: { $0 }, ifFailure: { Result(error: $0) })
}
/// Returns the inner future if the outer result succeeded or a failed future
/// with the error from the outer result otherwise
public func flatten<T, E>(result: Result<Future<T, E>,E>) -> Future<T, E> {
return result.analysis(ifSuccess: { $0 }, ifFailure: { Future(error: $0) })
}
/// Turns a sequence of `Result<T>`'s into a Result with an array of T's (`Result<[T]>`)
/// If one of the results in the given sequence is a .Failure, the returned result is a .Failure with the
/// error from the first failed result from the sequence.
public func sequence<S: SequenceType, T, E where S.Generator.Element == Result<T, E>>(seq: S) -> Result<[T], E> {
return seq.reduce(Result(value: [])) { (res, elem) -> Result<[T], E> in
switch res {
case .Success(let resultSequence):
switch elem {
case .Success(let elemValue):
let newSeq = resultSequence + [elemValue]
return Result<[T], E>(value: newSeq)
case .Failure(let elemError):
return Result<[T], E>(error: elemError)
}
case .Failure(_):
return res
}
}
}
| mit | 55eb21192994c80b2faaf36acf61975c | 47.0625 | 181 | 0.670279 | 3.845 | false | false | false | false |
andykkt/BFWControls | BFWControls/Modules/Transition/Controller/SegueHandlerType.swift | 1 | 3065 | //
// SegueHandlerType.swift
//
// Created by Tom Brodhurst-Hill on 7/12/16.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
/*
Inspired by:
https://www.bignerdranch.com/blog/using-swift-enumerations-makes-segues-safer/
https://developer.apple.com/library/content/samplecode/Lister/Listings/Lister_SegueHandlerTypeType_swift.html
https://www.natashatherobot.com/protocol-oriented-segue-identifiers-swift/
but changed to allow (ie not crash) blank segue identifiers with no code handling.
Example usage:
class RootViewController: UITableViewController, SegueHandlerType {
enum SegueIdentifier: String {
case account, products, recentProducts, contacts, login
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
guard let segueIdentifier = segueIdentifier(forIdentifier: identifier)
else { return true }
let should: Bool
switch segueIdentifier {
case .account:
should = isLoggedIn
if !should {
performSegue(.login, sender: sender)
}
default:
should = true
}
return should
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueIdentifier = segueIdentifier(forIdentifier: segue.identifier)
else { return }
switch segueIdentifier {
case .account:
if let accountViewController = segue.destination as? AccountViewController {
accountViewController.account = account
}
case .products, .recentProducts:
if let productsViewController = segue.destination as? ProductsViewController {
productsViewController.products = ??
}
case .contacts:
if let contactsViewController = segue.destination as? ContactsViewController {
contactsViewController.contacts = [String]()
}
case .login:
break
}
}
}
*/
import UIKit
public protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
public extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String {
public func performSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
/// To perform the segue after already queued UI actions. For instance, use in an unwind segue to perform a forward segue after viewDidAppear has finished.
public func performOnMainQueueSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
DispatchQueue.main.async { [weak self] in
self?.performSegue(segueIdentifier, sender: sender)
}
}
public func segueIdentifier(forIdentifier identifier: String?) -> SegueIdentifier? {
return identifier.flatMap { SegueIdentifier(rawValue: $0) }
}
}
| mit | 38016da1c0b5498a77cba0426cf26df3 | 33.044444 | 159 | 0.666775 | 5.337979 | false | false | false | false |
tonystone/geofeatures2 | Sources/GeoFeatures/Bounds.swift | 1 | 2550 | ///
/// Bounds.swift
///
/// Copyright (c) 2018 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 3/24/18.
///
import Swift
///
/// Represents the min and max X Y coordinates of a collection of Coordinates (any geometry).
///
/// This object can be thought of as the bounding box and represents the lower right and upper left coordinates of a Ractangle.
///
public struct Bounds {
///
/// Min X Y values
///
public let min: (x: Double, y: Double)
///
/// Max X Y values
///
public let max: (x: Double, y: Double)
///
/// Mid X Y values
///
public var mid: (x: Double, y: Double) {
return (x: (min.x + max.x) / 2, y: (min.y + max.y) / 2)
}
///
/// Initialize a Bounds with the min and max coordinates.
///
public init(min: Coordinate, max: Coordinate) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
///
/// Initialize a Bounds with the min and max tuples.
///
public init(min: (x: Double, y: Double), max: (x: Double, y: Double)) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
}
extension Bounds {
///
/// Returns the minX, minY, maxX, maxY, of 2 `Bounds`s as a `Bounds`.
///
public func expand(other: Bounds) -> Bounds {
return Bounds(min: (x: Swift.min(self.min.x, other.min.x), y: Swift.min(self.min.y, other.min.y)),
max: (x: Swift.max(self.max.x, other.max.x), y: Swift.max(self.max.y, other.max.y)))
}
}
extension Bounds: Equatable {
public static func == (lhs: Bounds, rhs: Bounds) -> Bool {
return lhs.min == rhs.min && lhs.max == rhs.max
}
}
extension Bounds: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(type(of: self))(min: \(self.min), max: \(self.max))"
}
public var debugDescription: String {
return self.description
}
}
| apache-2.0 | c68ad2930d29f64f426f67db902b959e | 27.333333 | 127 | 0.600784 | 3.502747 | false | false | false | false |
nvh/DataSourceable | DataSourceableTests/SectionableSpec.swift | 1 | 3296 | //
// Sectionable.swift
// DataSourceable
//
// Created by Niels van Hoorn on 13/10/15.
// Copyright © 2015 Zeker Waar. All rights reserved.
//
import Foundation
import DataSourceable
import Quick
import Nimble
struct SingleSectionDataSource: Sectionable, DataContaining {
typealias Data = [Int]
typealias Section = Data
var data: Data? = nil
}
struct SectionableDataSource: Sectionable, DataContaining {
typealias Data = [Section]
typealias Section = [Int]
var data: Data? = nil
}
class SectionableSpec: QuickSpec {
override func spec() {
describe("Sectionable") {
var sectionable: SectionableDataSource!
context("data is nil") {
beforeEach {
sectionable = SectionableDataSource(data: nil)
}
it("sections is nil") {
expect(sectionable.sections).to(beNil())
}
it("numberOfSections to be 0") {
expect(sectionable.numberOfSections).to(equal(0))
}
it("should return an item count of 0") {
expect(sectionable.numberOfItems(inSection: 0)).to(equal(0))
}
}
context("data is set") {
let data = [[3,5,7,9],[2,4,6]]
beforeEach {
sectionable = SectionableDataSource(data: data)
}
it("should return two sections") {
expect(sectionable.numberOfSections).to(equal(data.count))
}
it("should return the right number of items") {
expect(sectionable.numberOfItems(inSection: 0)).to(equal(data[0].count))
}
it("should return the right items") {
for sectionIndex in 0..<sectionable.numberOfSections {
for index in 0..<sectionable.numberOfItems(inSection: sectionIndex) {
expect(sectionable.item(atIndexPath: NSIndexPath(forItem: index, inSection: sectionIndex))).to(equal(data[sectionIndex][index]))
}
}
}
}
context("single section datasource") {
var singleSection: SingleSectionDataSource!
let data = [3,1,4,1,5]
beforeEach {
singleSection = SingleSectionDataSource(data: data)
}
it("should return one section") {
expect(singleSection.numberOfSections).to(equal(1))
}
it("should return the data count for the first section") {
expect(singleSection.numberOfItems(inSection: 0)).to(equal(data.count))
}
it("should return the contents of data for the first section") {
for (index,value) in data.enumerate() {
expect(singleSection.item(atIndexPath: NSIndexPath(forItem: index, inSection: 0))).to(equal(value))
}
}
}
}
}
}
| mit | 1d06836a531709b67f49a3b851fc07c6 | 34.815217 | 152 | 0.50258 | 5.331715 | false | false | false | false |
rechsteiner/Parchment | ParchmentTests/Mocks/Mock.swift | 1 | 987 | import Foundation
enum Action: Equatable {
case collectionView(MockCollectionView.Action)
case collectionViewLayout(MockCollectionViewLayout.Action)
case delegate(MockPagingControllerDelegate.Action)
}
struct MockCall {
let datetime: Date
let action: Action
}
extension MockCall: Equatable {
static func == (lhs: MockCall, rhs: MockCall) -> Bool {
return lhs.datetime == rhs.datetime && lhs.action == rhs.action
}
}
extension MockCall: Comparable {
static func < (lhs: MockCall, rhs: MockCall) -> Bool {
return lhs.datetime < rhs.datetime
}
}
protocol Mock {
var calls: [MockCall] { get }
}
func actions(_ calls: [MockCall]) -> [Action] {
return calls.map { $0.action }
}
func combinedActions(_ a: [MockCall], _ b: [MockCall]) -> [Action] {
return actions(Array(a + b).sorted())
}
func combinedActions(_ a: [MockCall], _ b: [MockCall], _ c: [MockCall]) -> [Action] {
return actions(Array(a + b + c).sorted())
}
| mit | 15a622def5eb5e206013afa238d211f8 | 23.675 | 85 | 0.658561 | 3.767176 | false | false | false | false |
codepgq/LearningSwift | TableViewCellEdit/TableViewCellEdit/TBDataSource.swift | 1 | 3220 | //
// TBDataSource.swift
// CustomPullToRefresh
//
// Created by ios on 16/9/26.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
/**
设置Section样式,默认 Single
*/
public enum TBSectionStyle : Int {
///Default 默认没有多个Section
case Section_Single
/// 有多个Section
case Section_Has
}
typealias TBMoveCellBlock = ((item : UITableViewRowAction,index : Int) -> Void)?
class TBDataSource: NSObject,UITableViewDataSource,UITableViewDelegate {
/**
数据类型
*/
private var sectionStyle : TBSectionStyle = .Section_Single
/**
数据源
*/
private var data : NSArray?
/**
标识符
*/
private var identifier : String = "null"
/**
cell回调
*/
private var cellBlock : ((cell : AnyObject, item : AnyObject) -> ())?
private var moveBlock : TBMoveCellBlock?
/**
快速创建一个数据源,需要提前注册,数组和style要对应
- parameter identifier: 标识
- parameter data: 数据
- parameter style: 类型
- parameter cell: 回调
- returns: 数据源对象(dataSource)
*/
class func cellIdentifierWith(identifier : String , data : NSArray , style : TBSectionStyle , cell : ((cell : AnyObject, item : AnyObject) -> Void)) -> TBDataSource {
let source = TBDataSource()
source.sectionStyle = style
source.data = data
source.identifier = identifier
source.cellBlock = cell
return source
}
/**
返回数据
- parameter indexPath: indexPath
- returns: 数据
*/
private func itemWithIndexPath(indexPath : NSIndexPath) -> AnyObject{
if sectionStyle == .Section_Single {
return data![indexPath.row]
}
else{
return data![indexPath.section][indexPath.row]
}
}
/**
返回有多少个Section
- parameter tableView: tableView
- returns: section
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if sectionStyle == .Section_Single {
return 1
}
return (data?.count)!
}
/**
返回对应Section的rows
- parameter tableView: tableView
- parameter section: section
- returns: rows
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if sectionStyle == .Section_Single {
return (data?.count)!
}else{
return (data?[section].count)!
}
}
/**
返回cell,并用闭包把cell封装到外面,提供样式设置
- parameter tableView: tableView
- parameter indexPath: indexPath
- returns: cell
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
if let block = cellBlock {
block(cell: cell, item: itemWithIndexPath(indexPath))
}
return cell
}
}
| apache-2.0 | 4015e9d900f294baa1600418bf2d15df | 22.740157 | 170 | 0.585406 | 4.816294 | false | false | false | false |
swc1098/TIRO | TIRO/TIRO/ExitNode.swift | 1 | 654 | //
// ExitNode.swift
// TIRO
//
// Created by student on 11/9/16.
// Copyright © 2016 swc1098. All rights reserved.
//
import SpriteKit
class ExitNode: SKSpriteNode, EventListenerNode {
func didMoveToScene() {
print("exit added to scene")
// 97 124
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width:97, height: 124))
self.physicsBody!.isDynamic = false
self.physicsBody!.categoryBitMask = PhysicsCategory.Goal
self.physicsBody!.collisionBitMask = PhysicsCategory.None
self.physicsBody!.contactTestBitMask = PhysicsCategory.Ball
}
}
| mit | f215f9e9a5d8fd195ee2dd6f1c9103cd | 24.115385 | 84 | 0.641654 | 4.631206 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS | Aztec/Classes/Extensions/NSAttributedString+Attachments.swift | 2 | 6174 | import Foundation
import UIKit
// MARK: - NSAttributedString Extension for Attachments
//
extension NSAttributedString
{
/// Indicates the Attributed String Length of a single TextAttachment
///
static let lengthOfTextAttachment = NSAttributedString(attachment: NSTextAttachment()).length
// MARK: - Initializers
/// Helper Initializer: returns an Attributed String, with the specified attachment, styled with a given
/// collection of attributes.
///
public convenience init(attachment: NSTextAttachment, attributes: [NSAttributedString.Key: Any]) {
var attributesWithAttachment = attributes
attributesWithAttachment[.attachment] = attachment
self.init(.textAttachment, attributes: attributesWithAttachment)
}
public convenience init(attachment: NSTextAttachment, caption: NSAttributedString, attributes: [NSAttributedString.Key: Any]) {
let figure = Figure()
let figcaption = Figcaption(defaultFont: UIFont.systemFont(ofSize: 14), storing: nil)
let figureAttributes = attributes.appending(figure)
let finalString = NSMutableAttributedString(attachment: attachment, attributes: figureAttributes)
let mutableCaption = NSMutableAttributedString(attributedString: caption)
mutableCaption.append(paragraphProperty: figure)
mutableCaption.append(paragraphProperty: figcaption)
let paragraphSeparator = NSAttributedString(.paragraphSeparator, attributes: [:])
finalString.append(paragraphSeparator)
finalString.append(mutableCaption)
finalString.append(paragraphSeparator)
self.init(attributedString: finalString)
}
/// Loads any NSTextAttachment's lazy file reference, into a UIImage instance, in memory.
///
func loadLazyAttachments() {
enumerateAttachmentsOfType(NSTextAttachment.self) { (attachment, _, _) in
guard let data = attachment.fileWrapper?.regularFileContents else {
return
}
if let mediaAttachment = attachment as? MediaAttachment {
mediaAttachment.refreshIdentifier()
}
let scale = UIScreen.main.scale
let image = UIImage(data: data, scale: scale)
attachment.fileWrapper = nil
attachment.image = image
}
}
/// Enumerates all of the available NSTextAttachment's of the specified kind, in a given range.
/// For each one of those elements, the specified block will be called.
///
/// - Parameters:
/// - range: The range that should be checked. Nil wil cause the whole text to be scanned
/// - type: The kind of Attachment we're after
/// - block: Closure to be executed, for each one of the elements
///
func enumerateAttachmentsOfType<T : NSTextAttachment>(_ type: T.Type, range: NSRange? = nil, block: ((T, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)) {
let range = range ?? NSMakeRange(0, length)
enumerateAttribute(.attachment, in: range, options: []) { (object, range, stop) in
if let object = object as? T {
block(object, range, stop)
}
}
}
/// Determine the character ranges for an attachment
///
/// - Parameters:
/// - attachment: the attachment to search for
///
/// - Returns: an array of ranges where the attachement can be found
///
public func ranges(forAttachment attachment: NSTextAttachment) -> [NSRange] {
let range = NSRange(location: 0, length: length)
var attachmentRanges = [NSRange]()
enumerateAttribute(.attachment, in: range, options: []) { (value, effectiveRange, nil) in
guard let foundAttachment = value as? NSTextAttachment, foundAttachment == attachment else {
return
}
attachmentRanges.append(effectiveRange)
}
return attachmentRanges
}
// MARK: - Captions
open func caption(for attachment: NSTextAttachment) -> NSAttributedString? {
guard let captionRange = self.captionRange(for: attachment) else {
return nil
}
let string = attributedSubstring(from: captionRange).mutableCopy() as! NSMutableAttributedString
for character in Character.paragraphBreakingCharacters {
string.replaceOcurrences(of: String(character), with: "")
}
return NSAttributedString(attributedString: string)
}
public func captionRange(for attachment: NSTextAttachment) -> NSRange? {
guard let figureRange = self.figureRange(for: attachment) else {
return nil
}
return figcaptionRanges(within: figureRange).first
}
// MARK: - Captions: Figure and Figcaption property ranges
private func figcaptionRanges(within range: NSRange) -> [NSRange] {
var ranges = [NSRange]()
enumerateParagraphRanges(spanning: range) { (_, enclosingRange) in
guard let paragraphStyle = attribute(.paragraphStyle, at: enclosingRange.lowerBound, effectiveRange: nil) as? ParagraphStyle else {
return
}
if paragraphStyle.hasProperty(where: { $0 is Figcaption }) {
ranges.append(enclosingRange)
}
}
return ranges
}
private func figureRange(for attachment: NSTextAttachment) -> NSRange? {
guard let attachmentRange = ranges(forAttachment: attachment).first else {
return nil
}
let paragraphRange = self.paragraphRange(for: attachmentRange)
guard let paragraphStyle = self.attribute(.paragraphStyle, at: paragraphRange.lowerBound, effectiveRange: nil) as? ParagraphStyle,
let figure = paragraphStyle.property(where: { $0 is Figure }) as? Figure else {
return nil
}
return self.paragraphRange(around: attachmentRange) { (properties) -> Bool in
return properties.contains { $0 === figure }
}
}
}
| gpl-2.0 | 9df99c3aa242882ee69a8dc4e50a28b1 | 37.830189 | 161 | 0.643505 | 5.439648 | false | false | false | false |
lojals/semanasanta | Semana Santa/Semana Santa/Classes/ViaCrusisVC2.swift | 1 | 4937 | //
// ViaCrusisVC.swift
// Semana Santa
//
// Created by Jorge Raul Ovalle Zuleta on 3/9/15.
// Copyright (c) 2015 Jorge Ovalle. All rights reserved.
//
import UIKit
class ViaCrusisVC2: GenericContentVC {
var scroll:UIScrollView!
var imgChurch:UIImageView!
var lblTitle:UILabel!
var lblDescription:UILabel!
var lblsemiPray1:UILabel!
var lblPray1:UILabel!
var lblPray2:UILabel!
var lblPray3:UILabel!
var lblText3:UILabel!
var _id:Int!
override func viewDidLoad() {
super.viewDidLoad()
scroll = UIScrollView(frame: self.view.frame)
scroll.backgroundColor = UIColor.clearColor()
scroll.maximumZoomScale = 10
scroll.multipleTouchEnabled = false
self.view.addSubview(scroll)
lblTitle = UILabel(frame: CGRect(x: 15, y: 30, width: self.view.frame.width - 30, height: 45))
lblTitle.text = ((array.objectAtIndex(pageIndex))["TIT"]) as? String
lblTitle.textColor = UIColor.theme2()
lblTitle.textAlignment = NSTextAlignment.Center
lblTitle.font = UIFont.boldFlatFontOfSize(45)
scroll.addSubview(lblTitle)
var txt1 = ((array.objectAtIndex(pageIndex))["ALIAS"]) as? String
lblDescription = UILabel(frame: CGRect(x: 15, y: lblTitle.frame.maxY + 5, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.lightFlatFontOfSize(15), width: self.view.frame.width - 30)))
lblDescription.text = txt1
lblDescription.textColor = UIColor.theme1()
lblDescription.numberOfLines = 0
lblDescription.textAlignment = NSTextAlignment.Center
lblDescription.font = UIFont.lightFlatFontOfSize(15)
scroll.addSubview(lblDescription)
txt1 = ((array.objectAtIndex(pageIndex))["NAME"]) as? String
lblPray1 = UILabel(frame: CGRect(x: 15, y: lblDescription.frame.maxY + 8, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray1.text = txt1
lblPray1.textColor = UIColor.themeComplement()
lblPray1.numberOfLines = 0
lblPray1.textAlignment = NSTextAlignment.Center
lblPray1.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray1)
lblsemiPray1 = UILabel(frame: CGRect(x: 15, y: lblPray1.frame.maxY + 8, width: self.view.frame.width - 30, height: 45))
lblsemiPray1.text = "Te adoramos, oh Cristo, y te bendecimos. \n Pues por tu santa cruz redimiste al mundo."
lblsemiPray1.textColor = UIColor.theme2()
lblsemiPray1.numberOfLines = 0
lblsemiPray1.textAlignment = NSTextAlignment.Left
lblsemiPray1.font = UIFont.lightFlatFontOfSize(16)
scroll.addSubview(lblsemiPray1)
txt1 = ((array.objectAtIndex(pageIndex))["TEXT1"]) as? String
lblPray2 = UILabel(frame: CGRect(x: 15, y: lblsemiPray1.frame.maxY + 8, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray2.text = txt1
lblPray2.textColor = UIColor.theme1()
lblPray2.numberOfLines = 0
lblPray2.textAlignment = NSTextAlignment.Left
lblPray2.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray2)
txt1 = ((array.objectAtIndex(pageIndex))["PRAY1"]) as? String
lblPray3 = UILabel(frame: CGRect(x: 15, y: lblPray2.frame.maxY + 10, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray3.text = txt1
lblPray3.textColor = UIColor.themeComplement()
lblPray3.numberOfLines = 0
lblPray3.textAlignment = NSTextAlignment.Center
lblPray3.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray3)
txt1 = ((array.objectAtIndex(pageIndex))["TEXT2"]) as? String
lblText3 = UILabel(frame: CGRect(x: 15, y: lblPray3.frame.maxY + 10, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblText3.text = txt1
lblText3.textColor = UIColor.theme1()
lblText3.numberOfLines = 0
lblText3.textAlignment = NSTextAlignment.Left
lblText3.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblText3)
scroll.contentSize = CGSize(width: 320, height: lblText3.frame.maxY + 100)
}
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
| gpl-2.0 | 54903be4b7b0cfea3b24fbe58f6b0c5e | 45.140187 | 220 | 0.666397 | 4.121035 | false | false | false | false |
sonsongithub/numsw | Playgrounds/MatrixTextRenderer.swift | 1 | 806 | //
// MatrixTextRenderer.swift
// sandbox
//
// Created by sonson on 2017/03/14.
// Copyright © 2017年 sonson. All rights reserved.
//
import Foundation
import CoreGraphics
#if SANDBOX_APP
import numsw
#endif
#if os(iOS)
public class MatrixTextRenderer: TextRenderer {
let matrix: Matrix<Double>
public init(_ aMatrix: Matrix<Double>) {
matrix = aMatrix
var string = "\(aMatrix.rows)x\(aMatrix.columns)\n"
for i in 0..<aMatrix.rows {
let s: [String] = (0..<aMatrix.columns).map({ aMatrix.elements[i * aMatrix.columns + $0] }).flatMap({ String($0) })
let r = s.joined(separator: ", ")
string += "[ \(r) ]\n"
}
super.init(string)
}
private var compositer: CompositeRenderer?
}
#endif
| mit | b5b4285858090d1ce51235d70158881f | 22.617647 | 127 | 0.594022 | 3.52193 | false | false | false | false |
volodg/LotterySRV | Sources/App/Models/Lottery.swift | 1 | 3203 | import Vapor
import FluentProvider
import HTTP
import Node
final class Lottery: Model {
static var entity = "lotteries"
let storage = Storage()
/// The content of the lottery
var name: String
var url: String
var path: String
var lastResultsUpdateTime: Date
/// Creates a new Post
init(name: String, url: String, path: String, lastResultsUpdateTime: Date) {
self.name = name
self.url = url
self.path = path
self.lastResultsUpdateTime = lastResultsUpdateTime
}
// MARK: Fluent Serialization
/// Initializes the Post from the
/// database row
init(row: Row) throws {
name = try row.get("name")
url = try row.get("url")
path = try row.get("path")
lastResultsUpdateTime = try row.get("last_results_update_time")
}
// Serializes the Post to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("url", url)
try row.set("path", path)
try row.set("last_results_update_time", lastResultsUpdateTime)
return row
}
}
// MARK: Fluent Preparation
extension Lottery: Preparation {
/// Prepares a table/collection in the database
/// for storing Posts
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("name")
builder.string("url")
builder.string("path", length: nil, optional: false, unique: true, default: nil)
builder.date("last_results_update_time", optional: true, unique: false, default: nil)
}
try setupInitialValues(database)
}
private static func setupInitialValues(_ database: Database) throws {
let config = try Config()
struct SetupError: Error {
let description: String
}
let path = config.resourcesDir + "/" + "lotteries.json"
let json = try readJSON(path: path)
guard let lotteries = json["data"]?.array else {
throw SetupError(description: "no lotteries config")
}
let models = try lotteries.map { data -> Lottery in
let json = JSON(data)
let result = try Lottery(json: json)
return result
}
try models.forEach { entity in
try entity.save()
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
// For example when:
// - Creating a new Post (POST /posts)
// - Fetching a post (GET /posts, GET /posts/:id)
//
extension Lottery: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
name: json.get("name"),
url: json.get("url"),
path: json.get("path"),
lastResultsUpdateTime: Date(timeIntervalSince1970: 0)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("name", name)
try json.set("url", url)
try json.set("path", path)
try json.set("last_results_update_time", lastResultsUpdateTime.timeIntervalSince1970)
return json
}
}
// MARK: HTTP
// This allows Post models to be returned
// directly in route closures
extension Lottery: ResponseRepresentable { }
| mit | d0a2899c0cac8bd40d288eb6831b33b1 | 24.023438 | 91 | 0.645645 | 4.049305 | false | false | false | false |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Helpers/Helpers.swift | 1 | 719 | //
// Helpers.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright © 2016 'XLOrganizationName'. All rights reserved.
//
import Foundation
func DEBUGLog(_ message: String, file: String = #file, line: Int = #line, function: String = #function) {
#if DEBUG
let fileURL = NSURL(fileURLWithPath: file)
let fileName = fileURL.deletingPathExtension?.lastPathComponent ?? ""
print("\(Date().dblog()) \(fileName)::\(function)[L:\(line)] \(message)")
#endif
// Nothing to do if not debugging
}
func DEBUGJson(_ value: AnyObject) {
#if DEBUG
if Constants.Debug.jsonResponse {
// print(JSONStringify(value))
}
#endif
}
| mit | e3cef2ce2a85de045bc7405ec1f80e9d | 26.615385 | 105 | 0.635097 | 4.056497 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/UI/AnimatedButton/PXProgressView.swift | 1 | 3197 | import Foundation
protocol ProgressViewDelegate: AnyObject {
func didFinishProgress()
func progressTimeOut()
}
final class ProgressView: UIView {
private var timer: Timer?
private let progressAlpha: CGFloat = 0.35
private var deltaIncrementFraction: CGFloat = 6
private let progressViewHeight: CGFloat
private let progressViewEndX: CGFloat
private var progressViewDeltaIncrement: CGFloat = 0
private let timeOut: TimeInterval
private let timerInterval: TimeInterval = 0.6
private var timerCounter = 0
weak var progressDelegate: ProgressViewDelegate?
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(forView: UIView, loadingColor: UIColor = UIColor.white, timeOut: TimeInterval = 15) {
progressViewHeight = forView.frame.height
progressViewEndX = forView.frame.width
deltaIncrementFraction = CGFloat(timeOut * 0.4)
self.timeOut = timeOut
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: progressViewHeight))
self.backgroundColor = loadingColor
self.layer.cornerRadius = forView.layer.cornerRadius
self.alpha = progressAlpha
forView.layer.masksToBounds = true
forView.addSubview(self)
initTimer(everySecond: timerInterval, customSelector: #selector(ProgressView.increment))
}
@objc fileprivate func increment() {
timerCounter += 1
let incompleteWidth = self.progressViewEndX - self.frame.width
let newWidth = self.frame.width + incompleteWidth / deltaIncrementFraction
let newFrame = CGRect(x: 0, y: 0, width: (newWidth), height: self.frame.height)
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.frame = newFrame
}, completion: { [weak self] _ in
guard let self = self else { return }
if Double(self.timerCounter) * self.timerInterval > self.timeOut {
self.stopTimer()
self.progressDelegate?.progressTimeOut()
}
})
}
}
// MARK: Timer.
extension ProgressView {
fileprivate func initTimer(everySecond: TimeInterval = 0.5, customSelector: Selector) {
timer = Timer.scheduledTimer(timeInterval: everySecond, target: self, selector: customSelector, userInfo: nil, repeats: true)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
}
// MARK: Public methods.
extension ProgressView {
func doReset() {
let newFrame = CGRect(x: 0, y: 0, width: 0, height: self.frame.height)
self.frame = newFrame
}
func doComplete(completion: @escaping (_ finish: Bool) -> Void) {
let newFrame = CGRect(x: 0, y: 0, width: progressViewEndX, height: self.frame.height)
UIView.animate(withDuration: 0.5, animations: { [weak self] in
self?.frame = newFrame
}, completion: { [weak self] _ in
guard let self = self else { return }
self.stopTimer()
self.progressDelegate?.didFinishProgress()
completion(true)
})
}
}
| mit | 9476782def3a4d7fcb291152adbf9c6e | 32.652632 | 133 | 0.643416 | 4.646802 | false | false | false | false |
leoru/Brainstorage | Brainstorage-iOS/Classes/Controllers/Base/BaseTabBarViewController.swift | 1 | 1023 | //
// BaseTabBarViewController.swift
// Brainstorage-iOS
//
// Created by Kirill Kunst on 04.02.15.
// Copyright (c) 2015 Kirill Kunst. All rights reserved.
//
import UIKit
class BaseTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.barTintColor = UIColor.whiteColor();
self.tabBar.tintColor = bs_redColor;
self.tabBar.backgroundColor = UIColor.whiteColor();
self.tabBar.shadowImage = UIImage(named: "tabBar_Border");
self.tabBar.translucent=false;
var offset = UIOffset(horizontal: 0, vertical: -4);
(self.tabBar.items![0] as! UITabBarItem).selectedImage = UIImage(named: "vacancy_active");
(self.tabBar.items![0] as! UITabBarItem).setTitlePositionAdjustment(offset);
(self.tabBar.items![1] as! UITabBarItem).selectedImage = UIImage(named: "about_active");
(self.tabBar.items![1] as! UITabBarItem).setTitlePositionAdjustment(offset);
}
}
| mit | 590ad00aea32bba5c183bcc2c06fdedf | 34.275862 | 98 | 0.671554 | 4.227273 | false | false | false | false |
jorgeluis11/EmbalsesPR | Embalses/DetailViewController.swift | 1 | 3789 | //
// ViewController.swift
// Embalses
//
// Created by Jorge Perez on 9/28/15.
// Copyright © 2015 Jorge Perez. All rights reserved.
//
import UIKit
import Kanna
import Charts
class DetailViewController: UIViewController {
@IBOutlet var barChartView: BarChartView!
var county:String?
var date:String?
var meters:String?
var niveles:[Double]?
@IBOutlet var labelWater: UILabel!
var chartData = [899.56]
@IBOutlet var navigationBar: UINavigationBar!
@IBAction func backButton(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
print("Sdf")
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
override func unwindForSegue(unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
}
override func viewDidLoad() {
super.viewDidLoad()
// navigationBar.ba = backButton
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
setChart(months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
if let niveles = niveles{
var ll = ChartLimitLine(limit: niveles[0], label: "Desborde")
// ll.setLineColor(Color.RED);
//
//
// ll.setLineWidth(4f);
// ll.setTextColor(Color.BLACK);
// ll.setTextSize(12f);
barChartView.rightAxis.addLimitLine(ll)
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[1], label: "Seguridad"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[2], label: "Obervación"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[3], label: "Ajustes Operacionales"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[4], label: "Control"))
// var xAxis:ChartYAxis = barChartView.getAxis(ChartYAxis(position: 34.34))
// LimitLine ll = new LimitLine(140f, "Critical Blood Pressure");
// ll.setLineColor(Color.RED);
// ll.setLineWidth(4f);
// ll.setTextColor(Color.BLACK);
// ll.setTextSize(12f);
// .. and more styling options
//
// leftAxis.addLimitLine(ll);
}
barChartView.noDataText = "You need to provide data for the chart."
let meterDouble:Double = Double(self.meters!)!
let dataEntries: [BarChartDataEntry] = [BarChartDataEntry(value: meterDouble, xIndex: 0)]
let dataPoints2 = [self.county]
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Agua en Metros")
let chartData = BarChartData(xVals: dataPoints2, dataSet: chartDataSet)
barChartView.data = chartData
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
var newFrame:CGRect = labelWater.frame;
newFrame.origin.y = newFrame.origin.y - 615;
// newFrame.size.height = 181;
newFrame.size.height = 665;
UIView.animateWithDuration(3, animations: {
self.labelWater.frame = newFrame
})
}
}
| mit | 000727bcc43f6c33f0a60dfe24f17f39 | 31.367521 | 120 | 0.589385 | 4.524492 | false | false | false | false |
ChrisAU/CardinalHashMap | CardinalHashMap/CardinalHashMap/CardinalHashMap+Collector.swift | 1 | 2807 | //
// CardinalHashMap+Collector.swift
// CardinalHashMap
//
// Created by Chris Nevin on 1/04/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import Foundation
extension CardinalHashMap {
private func loop(start: T, directions: [CardinalDirection], seeded: Bool, `while`: ((T) -> Bool)? = nil) -> [T] {
var buffer = [T]()
if self[start] == nil {
return buffer
}
if `while` == nil || `while`?(start) == true {
buffer.append(start)
}
for direction in directions {
if let nextObject = self[start, direction] {
buffer += loop(nextObject, directions: seeded ? directions : [direction], seeded: seeded, while: `while`)
}
}
return Array(Set(buffer))
}
/// Perform the seed fill (or flood fill) algorithm in a given number of directions.
/// - parameter start: Object to start from.
/// - parameter directions: `CardinalDirection` array, each item that is found will fill in these directions as well.
/// - parameter while (Optional): Only iterate while this function is true.
/// - returns: Unsorted items that were found.
public func seedFill(start: T, directions: [CardinalDirection], `while`: ((T) -> Bool)? = nil) -> [T] {
return loop(start, directions: directions, seeded: true, while: `while`)
}
/// Iterate in direction as long as `while` passes and it is possible to navigate in that direction.
/// - parameter start: First object to validate and iterate from.
/// - parameter direction: `CardinalDirection` to travel in.
/// - parameter while (Optional): Validate `object`, if `false` is returned function will exit and return. If not specified or nil is specified it will assume `true`.
/// - returns: `object` and all other objects in that direction that pass `while` validation.
public func collect(start: T, direction: CardinalDirection, `while`: ((T) -> Bool)? = nil) -> [T] {
return collect(start, directions: [direction], while: `while`)
}
/// Iterate in direction as long as `while` passes and it is possible to navigate in each direction given.
/// - parameter start: First object to validate and iterate from.
/// - parameter directions: `CardinalDirection` array.
/// - parameter while (Optional): Validate `object`, if `false` is returned function will exit and return. If not specified or nil is specified it will assume `true`.
/// - returns: `object` and all other objects in given directions that pass `while` validation.
public func collect(start: T, directions: [CardinalDirection], `while`: ((T) -> Bool)? = nil) -> [T] {
return loop(start, directions: directions, seeded: false, while: `while`)
}
} | mit | bf5f700782c5dbb103a3036da8fe2a03 | 49.125 | 170 | 0.644334 | 4.316923 | false | false | false | false |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Tests/HiddenRowsTests.swift | 2 | 13121 | // HiddenRowsTests.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Eureka
class HiddenRowsTests: BaseEurekaTests {
var form : Form!
let row10 = IntRow("int1_hrt"){
$0.hidden = "$IntRow_s1 > 23"
}
let row11 = TextRow("txt1_hrt"){
$0.hidden = .function(["NameRow_s1"], { form in
if let r1 : NameRow = form.rowBy(tag: "NameRow_s1") {
return r1.value?.contains(" is ") ?? false
}
return false
})
}
let sec2 = Section("Whatsoever") {
$0.tag = "s3_hrt"
$0.hidden = "$NameRow_s1 contains 'God'"
}
let row20 = TextRow("txt2_hrt"){
$0.hidden = .function(["IntRow_s1", "NameRow_s1"], { form in
if let r1 : IntRow = form.rowBy(tag: "IntRow_s1"), let r2 : NameRow = form.rowBy(tag: "NameRow_s1") {
return r1.value == 88 || r2.value?.hasSuffix("real") ?? false
}
return false
})
}
let inlineDateRow21 = DateInlineRow() {
$0.hidden = "$IntRow_s1 > 23"
}
override func setUp() {
super.setUp()
form = shortForm
+++ row10
<<< row11
+++ sec2
<<< row20
<<< inlineDateRow21
}
func testAddRowToObserver(){
let intDep = form.rowObservers["IntRow_s1"]?[.hidden]
let nameDep = form.rowObservers["NameRow_s1"]?[.hidden]
// make sure we can unwrap
XCTAssertNotNil(intDep)
XCTAssertNotNil(nameDep)
// test rowObservers
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
//This should not change when some rows hide ...
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
//check everything is still the same
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
// ...nor if they reappear
form[0][0].baseValue = "blah blah blah"
form[0][1].baseValue = 1
//check everything is still the same
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
// Test a condition with nil
let newRow = TextRow("new_row") {
$0.hidden = "$txt1_hrt == nil"
}
form.last! <<< newRow
XCTAssertTrue(newRow.hiddenCache)
}
func testItemsByTag(){
// test that all rows and sections with tag are there
XCTAssertEqual(form.rowBy(tag: "NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowBy(tag: "IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowBy(tag: "int1_hrt"), row10)
XCTAssertEqual(form.rowBy(tag: "txt1_hrt"), row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowBy(tag: "txt2_hrt"), row20)
// check that these are all in there
XCTAssertEqual(form.rowsByTag.count, 5)
// what happens after hiding the rows? Let's cause havoc
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
// we still want the same results here
XCTAssertEqual(form.rowBy(tag: "NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowBy(tag: "IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowBy(tag: "int1_hrt"), row10)
XCTAssertEqual(form.rowBy(tag: "txt1_hrt"), row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowBy(tag: "txt2_hrt"), row20)
XCTAssertEqual(form.rowsByTag.count, 5)
// and let them come up again
form[0][0].baseValue = "blah blah"
form[0][1].baseValue = 1
// we still want the same results here
XCTAssertEqual(form.rowsByTag["NameRow_s1"], form[0][0])
XCTAssertEqual(form.rowsByTag["IntRow_s1"], form[0][1])
XCTAssertEqual(form.rowsByTag["int1_hrt"], row10)
XCTAssertEqual(form.rowsByTag["txt1_hrt"], row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowsByTag["txt2_hrt"], row20)
XCTAssertEqual(form.rowsByTag.count, 5)
}
func testCorrectValues(){
//initial empty values (none is hidden)
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
// false values
form[0][0].baseValue = "Hi there"
form[0][1].baseValue = 15
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
// hide 'int1_hrt' row
form[0][1].baseValue = 24
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 1)
XCTAssertEqual(sec2.count, 1)
XCTAssertEqual(form[1][0].tag, "txt1_hrt")
// hide 'txt1_hrt' and 'txt2_hrt'
form[0][0].baseValue = " is real"
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(sec2.count, 0)
// let the last section disappear
form[0][0].baseValue = "God is real"
XCTAssertEqual(form.count, 2)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
// and see if they come back to live
form[0][0].baseValue = "blah"
form[0][1].baseValue = 2
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
}
func testInlineRows(){
//initial empty values (none is hidden)
XCTAssertEqual(sec2.count, 2)
// change dependency value
form[0][1].baseValue = 25
XCTAssertEqual(sec2.count, 1)
// change dependency value
form[0][1].baseValue = 10
XCTAssertEqual(sec2.count, 2)
//hide inline row when expanded
inlineDateRow21.expandInlineRow()
// check that the row is expanded
XCTAssertEqual(sec2.count, 3)
// hide expanded inline row
form[0][1].baseValue = 25
XCTAssertEqual(sec2.count, 1)
// make inline row visible again
form[0][1].baseValue = 10
XCTAssertEqual(sec2.count, 2)
}
func testHiddenSections(){
let s1 = Section(){
$0.hidden = "$NameRow_s1 contains 'hello'"
$0.tag = "s1_ths"
}
let s2 = Section(){
$0.hidden = "$NameRow_s1 contains 'morning'"
$0.tag = "s2_ths"
}
form.insert(s1, at: 1)
form.insert(s2, at: 3)
/* what we should have here
shortForm (1 section)
s1
{ row10, row11 }
s2
sec2 (2 rows)
*/
XCTAssertEqual(form.count, 5)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(form[2].count, 2)
XCTAssertEqual(form[3].count, 0)
XCTAssertEqual(form[4].count, 2)
form[0][0].baseValue = "hello, good morning!"
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(form[2].count, 2)
form[0][0].baseValue = "whatever"
XCTAssertEqual(form.count, 5)
XCTAssertEqual(form[1].tag, "s1_ths")
XCTAssertEqual(form[3].tag, "s2_ths")
XCTAssertEqual(form[4].tag, "s3_hrt")
}
func testInsertionIndex(){
let r1 = CheckRow("check1_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'morning'" }
let r2 = CheckRow("check2_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'morning'" }
let r3 = CheckRow("check3_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'good'" }
let r4 = CheckRow("check4_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'good'" }
form[0].insert(r1, at: 1)
form[1].insert(contentsOf: [r2,r3], at: 0)
//test correct insert
XCTAssertEqual(form[0].count, 3)
XCTAssertEqual(form[0][1].tag, "check1_tii_hrt")
XCTAssertEqual(form[1].count, 4)
XCTAssertEqual(form[1][0].tag, "check2_tii_hrt")
XCTAssertEqual(form[1][1].tag, "check3_tii_hrt")
// hide these rows
form[0][0].baseValue = "hello, good morning!"
// insert another row
form[1].insert(r4, at: 1)
XCTAssertEqual(form[1].count, 2) // all inserted rows should be hidden
XCTAssertEqual(form[1][0].tag, "int1_hrt")
XCTAssertEqual(form[1][1].tag, "txt1_hrt")
form[0][0].baseValue = "whatever"
// we inserted r4 at index 1 but there were two rows hidden before it as well so it shall be at index 3
XCTAssertEqual(form[1].count, 5)
XCTAssertEqual(form[1][0].tag, "check2_tii_hrt")
XCTAssertEqual(form[1][1].tag, "check3_tii_hrt")
XCTAssertEqual(form[1][2].tag, "int1_hrt")
XCTAssertEqual(form[1][3].tag, "check4_tii_hrt")
XCTAssertEqual(form[1][4].tag, "txt1_hrt")
form[0][0].baseValue = "hello, good morning!"
//check that hidden rows get removed as well
form[1].removeAll()
//inserting 2 rows at the end, deleting 1
form[2].replaceSubrange(1..<2, with: [r2, r4])
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(form[2].count, 1)
XCTAssertEqual(form[2][0].tag, "txt2_hrt")
form[0][0].baseValue = "whatever"
XCTAssertEqual(form[2].count, 3)
XCTAssertEqual(form[2][0].tag, "txt2_hrt")
XCTAssertEqual(form[2][1].tag, "check2_tii_hrt")
XCTAssertEqual(form[2][2].tag, "check4_tii_hrt")
}
}
| mit | 6c44ac43be08ea0add7d896b961963eb | 35.960563 | 126 | 0.563753 | 3.924918 | false | false | false | false |
ahoppen/swift | test/SILGen/objc_imported_generic.swift | 2 | 7899 |
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic %s | %FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-emit-ir(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared [serialized] [ossa] @$sSo12GenericClassC5thingAByxGSgxSg_tcfC
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C17MethodOnAnyObject{{[_0-9a-zA-Z]*}}F
// CHECK: objc_method {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF'
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]] : $AnyObject to $@opened([[TAG:.*]]) AnyObject
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG]]) AnyObject, #GenericClass.subscript!getter.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
// CHECK: } // end sil function '$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF'
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF'
public protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
public protocol Ansible: class {
associatedtype Anser: ThingHolder
}
public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C13BlockBridging{{[_0-9a-zA-Z]*}}F
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @$sxxIeyBya_xxIeggo_21objc_imported_generic7AnsibleRzlTR
// CHECK: partial_apply [callee_guaranteed] [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @$sxxIeggo_xxIeyBya_21objc_imported_generic7AnsibleRzlTR
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil private [ossa] @$s21objc_imported_generic0C4FuncyyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
// CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type
// CHECK: [[INIT:%.*]] = function_ref @$sSo12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
// CHECK: apply [[INIT]]<V>([[META]])
// CHECK: return
func genericFunc<V: AnyObject>(_ v: V.Type) {
let _ = {
var _ = GenericClass<V>()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s21objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> ()
// CHECK: enum $Optional<Dictionary<GenericOption, Any>>, #Optional.none!enumelt
// CHECK: return
func configureWithoutOptions() {
_ = GenericClass<NSObject>(options: nil)
}
// CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfcTO
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
// foreign to native thunk for init(options:), uses GenericOption : Hashable
// conformance
// CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC7optionsAByxGSgSDySo0A6OptionaypGSg_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
// CHECK: [[FN:%.*]] = function_ref @$sSD10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: return
// Make sure we emitted the witness table for the above conformance
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK: method #Hashable.hashValue!getter: {{.*}}: @$sSo13GenericOptionaSHSCSH9hashValueSivgTW
// CHECK: }
| apache-2.0 | 5302330baefd54c427f956e8203fe981 | 58.150376 | 274 | 0.689717 | 3.501113 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/ReactiveSwift/Scheduler.swift | 2 | 19521 | //
// Scheduler.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Dispatch
import Foundation
#if os(Linux)
import let CDispatch.NSEC_PER_SEC
#endif
/// Represents a serial queue of work items.
public protocol Scheduler: class {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// - parameters:
/// - action: The action to be scheduled.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(_ action: @escaping () -> Void) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateScheduler: Scheduler {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministically return a known date (e.g.,
/// for testing purposes).
var currentDate: Date { get }
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, action: @escaping () -> Void) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given date.
///
/// - parameters:
/// - date: The start date.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition.
/// - action: A closure of the action to be performed.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: Scheduler {
public init() {}
/// Immediately calls passed in `action`.
///
/// - parameters:
/// - action: A closure of the action to be performed.
///
/// - returns: `nil`.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main queue, as soon as possible.
///
/// If the caller is already running on the main queue when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: Scheduler {
private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>()
private static let dispatchSpecificValue = UInt8.max
private static var __once: () = {
DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey,
value: dispatchSpecificValue)
}()
#if os(Linux)
private var queueLength: Atomic<Int32> = Atomic(0)
#else
// `inout` references do not guarantee atomicity. Use `UnsafeMutablePointer`
// instead.
//
// https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161205/004147.html
private let queueLength: UnsafeMutablePointer<Int32> = {
let memory = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
memory.initialize(to: 0)
return memory
}()
deinit {
queueLength.deinitialize(count: 1)
queueLength.deallocate()
}
#endif
/// Initializes `UIScheduler`
public init() {
/// This call is to ensure the main queue has been setup appropriately
/// for `UIScheduler`. It is only called once during the application
/// lifetime, since Swift has a `dispatch_once` like mechanism to
/// lazily initialize global variables and static variables.
_ = UIScheduler.__once
}
/// Queues an action to be performed on main queue. If the action is called
/// on the main thread and no work is queued, no scheduling takes place and
/// the action is called instantly.
///
/// - parameters:
/// - action: A closure of the action to be performed on the main thread.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let positionInQueue = enqueue()
// If we're already running on the main queue, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if positionInQueue == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue {
action()
dequeue()
return nil
} else {
let disposable = AnyDisposable()
DispatchQueue.main.async {
defer { self.dequeue() }
guard !disposable.isDisposed else { return }
action()
}
return disposable
}
}
private func dequeue() {
#if os(Linux)
queueLength.modify { $0 -= 1 }
#else
OSAtomicDecrement32(queueLength)
#endif
}
private func enqueue() -> Int32 {
#if os(Linux)
return queueLength.modify { value -> Int32 in
value += 1
return value
}
#else
return OSAtomicIncrement32(queueLength)
#endif
}
}
/// A `Hashable` wrapper for `DispatchSourceTimer`. `Hashable` conformance is
/// based on the identity of the wrapper object rather than the wrapped
/// `DispatchSourceTimer`, so two wrappers wrapping the same timer will *not*
/// be equal.
private final class DispatchSourceTimerWrapper: Hashable {
private let value: DispatchSourceTimer
#if swift(>=4.1.50)
fileprivate func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
#else
fileprivate var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
#endif
fileprivate init(_ value: DispatchSourceTimer) {
self.value = value
}
fileprivate static func ==(lhs: DispatchSourceTimerWrapper, rhs: DispatchSourceTimerWrapper) -> Bool {
// Note that this isn't infinite recursion thanks to `===`.
return lhs === rhs
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateScheduler {
/// A singleton `QueueScheduler` that always targets the main thread's GCD
/// queue.
///
/// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a
/// future date, and will always schedule asynchronously (even if
/// already running on the main thread).
public static let main = QueueScheduler(internalQueue: DispatchQueue.main)
public var currentDate: Date {
return Date()
}
public let queue: DispatchQueue
private var timers: Atomic<Set<DispatchSourceTimerWrapper>>
internal init(internalQueue: DispatchQueue) {
queue = internalQueue
timers = Atomic(Set())
}
/// Initializes a scheduler that will target the given queue with its
/// work.
///
/// - note: Even if the queue is concurrent, all work items enqueued with
/// the `QueueScheduler` will be serial with respect to each other.
///
/// - warning: Obsoleted in OS X 10.11
@available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead")
@available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.")
public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") {
self.init(internalQueue: DispatchQueue(label: name, target: queue))
}
/// Initializes a scheduler that creates a new serial queue with the
/// given quality of service class.
///
/// - parameters:
/// - qos: Dispatch queue's QoS value.
/// - name: A name for the queue in the form of reverse domain.
/// - targeting: (Optional) The queue on which this scheduler's work is
/// targeted
@available(OSX 10.10, *)
public convenience init(
qos: DispatchQoS = .default,
name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler",
targeting targetQueue: DispatchQueue? = nil
) {
self.init(internalQueue: DispatchQueue(
label: name,
qos: qos,
target: targetQueue
))
}
/// Schedules action for dispatch on internal queue
///
/// - parameters:
/// - action: A closure of the action to be scheduled.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.async {
if !d.isDisposed {
action()
}
}
return d
}
private func wallTime(with date: Date) -> DispatchWallTime {
let (seconds, frac) = modf(date.timeIntervalSince1970)
let nsec: Double = frac * Double(NSEC_PER_SEC)
let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))
return DispatchWallTime(timespec: walltime)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.asyncAfter(wallDeadline: wallTime(with: date)) {
if !d.isDisposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval and beginning at the
/// given start date. A reasonable default timer interval leeway is
/// provided.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - action: Closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action)
}
/// Schedules a recurring action at the given interval with provided leeway,
/// beginning at the given start time.
///
/// - precondition: `interval` must be non-negative number.
/// - precondition: `leeway` must be non-negative number.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
precondition(interval.timeInterval >= 0)
precondition(leeway.timeInterval >= 0)
let timer = DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: queue
)
#if swift(>=4.0)
timer.schedule(wallDeadline: wallTime(with: date),
repeating: interval,
leeway: leeway)
#else
timer.scheduleRepeating(wallDeadline: wallTime(with: date),
interval: interval,
leeway: leeway)
#endif
timer.setEventHandler(handler: action)
timer.resume()
let wrappedTimer = DispatchSourceTimerWrapper(timer)
timers.modify { timers in
timers.insert(wrappedTimer)
}
return AnyDisposable { [weak self] in
timer.cancel()
if let scheduler = self {
scheduler.timers.modify { timers in
timers.remove(wrappedTimer)
}
}
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateScheduler {
private final class ScheduledAction {
let date: Date
let action: () -> Void
init(date: Date, action: @escaping () -> Void) {
self.date = date
self.action = action
}
func less(_ rhs: ScheduledAction) -> Bool {
return date < rhs.date
}
}
private let lock = NSRecursiveLock()
private var _currentDate: Date
/// The virtual date that the scheduler is currently at.
public var currentDate: Date {
let d: Date
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
///
/// - parameters:
/// - startDate: The start date of the scheduler.
public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler"
_currentDate = startDate
}
private func schedule(_ action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sort { $0.less($1) }
lock.unlock()
return AnyDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
/// Enqueues an action on the scheduler.
///
/// - note: The work is executed on `currentDate` as it is understood by the
/// scheduler.
///
/// - parameters:
/// - action: An action that will be performed on scheduler's
/// `currentDate`.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution after some delay.
///
/// - parameters:
/// - delay: A delay for execution.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), action: action)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: A starting date.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start date.
///
/// - precondition: `interval` must be non-negative.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - disposable: A disposable.
/// - action: A closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) {
precondition(interval.timeInterval >= 0)
disposable.inner = schedule(after: date) { [unowned self] in
action()
self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action)
}
}
/// Schedules a recurring action after given delay repeated at the given,
/// interval, beginning at the given interval counted from `currentDate`.
///
/// - parameters:
/// - delay: A delay for action's dispatch.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action)
}
/// Schedules a recurring action at the given interval with
/// provided leeway, beginning at the given start date.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
let disposable = SerialDisposable()
schedule(after: date, interval: interval, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advance(by: .nanoseconds(1))
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
///
/// - parameters:
/// - interval: Interval by which the current date will be advanced.
public func advance(by interval: DispatchTimeInterval) {
lock.lock()
advance(to: currentDate.addingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
///
/// - parameters:
/// - newDate: Future date to which the virtual clock will be advanced.
public func advance(to newDate: Date) {
lock.lock()
assert(currentDate <= newDate)
while scheduledActions.count > 0 {
if newDate < scheduledActions[0].date {
break
}
_currentDate = scheduledActions[0].date
let scheduledAction = scheduledActions.remove(at: 0)
scheduledAction.action()
}
_currentDate = newDate
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `Date.distantFuture()`.
public func run() {
advance(to: Date.distantFuture)
}
/// Rewinds the virtualized clock by the given interval.
/// This simulates that user changes device date.
///
/// - parameters:
/// - interval: An interval by which the current date will be retreated.
public func rewind(by interval: DispatchTimeInterval) {
lock.lock()
let newDate = currentDate.addingTimeInterval(-interval)
assert(currentDate >= newDate)
_currentDate = newDate
lock.unlock()
}
}
| mit | 817a0f0890d2f42a288377d7dbe1e212 | 30.845024 | 179 | 0.686953 | 3.877831 | false | false | false | false |
cenfoiOS/ImpesaiOSCourse | NewsWithRealm/News/NewsTableViewCell.swift | 2 | 1088 | //
// NewsTableViewCell.swift
// News
//
// Created by Cesar Brenes on 5/23/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import UIKit
class NewsTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setupCell(news: News){
titleLabel.text = news.titleNews
descriptionLabel.text = news.descriptionNews
dateLabel.text = news.createdAt.toString(dateFormat: "yyyy-MM-dd HH:mm:ss")
}
}
extension Date{
func toString(dateFormat: String ) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: self)
}
}
| mit | c5d4208ba372e30b96436b4fa5483c6b | 23.133333 | 83 | 0.660221 | 4.660944 | false | false | false | false |
SquidKit/SquidKit | Examples/SquidKitExample/SquidKitExampleTests/SquidKitExampleTests.swift | 1 | 1997 | //
// SquidKitExampleTests.swift
// SquidKitExampleTests
//
// Created by Mike Leavy on 8/21/14.
// Copyright (c) 2014 SquidKit. All rights reserved.
//
import UIKit
import XCTest
import SquidKit
class SquidKitExampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
func testCache() {
let stringCache = Cache<NSString, NSString>()
stringCache.insert("foo", key: "a")
stringCache.insert("bar", key: "b")
let a = stringCache.get("a")
let b = stringCache.get("b")
XCTAssertEqual(a, "foo", "key a is not \"foo\"")
XCTAssertEqual(b, "bar", "key b is not \"bar\"")
// test that all caches of type NSString, NSString are the same
let anotherStringCache = Cache<NSString, NSString>()
let anotherA = anotherStringCache["a"]
XCTAssertEqual(anotherA, "foo", "key a is not \"foo\"")
let numberCache = Cache<NSString, NSNumber>()
numberCache.insert(12, key: "12")
numberCache.insert(24, key: "24")
var twelve = numberCache.get("12")
XCTAssertEqual(12, twelve, "cache entry for \"12\" is not 12")
numberCache.remove(forKey: "12")
twelve = numberCache["12"]
XCTAssertNil(twelve, "expected nil result for key \"12\"")
}
}
| mit | e447ee6fa21d4fb4d3baf44b40b2479b | 29.257576 | 111 | 0.587381 | 4.418142 | false | true | false | false |
dockwa/EmailPicker | Sources/EmailPicker/EmailPickerCell.swift | 1 | 3777 | import UIKit
class EmailPickerCell: UITableViewCell {
@objc static let height: CGFloat = 60
static var reuseIdentifier: String {
String(describing: self)
}
lazy var thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
return imageView
}()
lazy var label: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 18)
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(thumbnailImageView)
contentView.addSubview(label)
imageViewConstraints()
labelConstraints()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func imageViewConstraints() {
thumbnailImageView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: thumbnailImageView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: 10)
let leading = NSLayoutConstraint(item: thumbnailImageView,
attribute: .leading,
relatedBy: .equal,
toItem: contentView,
attribute: .leading,
multiplier: 1,
constant: 10)
let centerY = NSLayoutConstraint(item: thumbnailImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0)
let width = NSLayoutConstraint(item: thumbnailImageView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40)
thumbnailImageView.addConstraint(width)
contentView.addConstraints([top, leading, centerY])
}
private func labelConstraints() {
label.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: label,
attribute: .leading,
relatedBy: .equal,
toItem: thumbnailImageView,
attribute: .trailing,
multiplier: 1,
constant: 10)
let centerY = NSLayoutConstraint(item: label,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0)
contentView.addConstraints([leading, centerY])
}
}
| mit | bec7f229ca5a4c5926fbee462202186f | 42.918605 | 79 | 0.434472 | 7.708163 | false | false | false | false |
FotiosTragopoulos/Anemos | Anemos/ViewController.swift | 1 | 2503 | //
// ViewController.swift
// Anemos
//
// Created by Fotios Tragopoulos on 01/02/2018.
// Copyright © 2018 Fotios Tragopoulos. All rights reserved.
//
import UIKit
import WebKit
import SafariServices
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var backButton: UIBarButtonItem!
@IBOutlet weak var frontButton: UIBarButtonItem!
@IBOutlet weak var searchButton: UIBarButtonItem!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var stopButton: UIBarButtonItem!
var timeBool: Bool!
var timer: Timer!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url: URL = URL(string: "https://duckduckgo.com")!
let urlRequest: URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
@IBAction func backButtonTapped(_ sender: Any) {
if webView.canGoBack {
webView.goBack()
}
}
@IBAction func frontButtonTapped(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
@IBAction func searchPage(_ sender: Any) {
viewDidAppear(true)
}
@IBAction func reloadPage(_ sender: Any) {
webView.reload()
}
@IBAction func stopLoading(_ sender: Any) {
webView.stopLoading()
progressBar.isHidden = true
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
backButton.isEnabled = webView.canGoBack
frontButton.isEnabled = webView.canGoForward
progressBar.isHidden = false
progressBar.progress = 0.0
timeBool = false
timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(ViewController.timerCallBack), userInfo: nil, repeats: true)
}
@objc func timerCallBack() {
if timeBool != nil {
if progressBar.progress >= 1 {
progressBar.isHidden = true
timer.invalidate()
} else {
progressBar.progress += 0.1
}
} else {
progressBar.progress += 0.01
if progressBar.progress >= 0.95 {
progressBar.progress = 0.95
}
}
}
}
| mit | e5bcbecd72d62da0da1fa9886f03aea2 | 27.431818 | 151 | 0.615907 | 4.896282 | false | false | false | false |
Bartlebys/Bartleby | Inspector/Inspector/InspectorViewController.swift | 1 | 19735 | //
// InspectorViewController.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 15/07/2016.
//
//
import Cocoa
import BartlebyKit
protocol FilterPredicateDelegate {
func filterSelectedIndex()->Int
func filterExpression()->String
}
class InspectorViewController: NSViewController,DocumentDependent,FilterPredicateDelegate{
override var nibName : NSNib.Name { return NSNib.Name("InspectorViewController") }
@IBOutlet var listOutlineView: NSOutlineView!
@IBOutlet var topBox: NSBox!
@IBOutlet var bottomBox: NSBox!
// Provisionned View controllers
@IBOutlet var sourceEditor: SourceEditor!
@IBOutlet var operationViewController: OperationViewController!
@IBOutlet var changesViewController: ChangesViewController!
@IBOutlet var metadataViewController: MetadataDetails!
@IBOutlet var contextualMenu: NSMenu!
@IBOutlet weak var filterPopUp: NSPopUpButton!
@IBOutlet weak var filterField: NSSearchField!
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
return true
}
// The currently associated View Controller
fileprivate var _topViewController:NSViewController?
fileprivate var _bottomViewController:NSViewController?
//MARK:- Menu Actions
@IBAction func resetAllSupervisionCounter(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
documentReference.metadata.currentUser?.changedKeys.removeAll()
documentReference.iterateOnCollections({ (collection) in
if let o = collection as? ManagedModel{
o.changedKeys.removeAll()
}
})
documentReference.superIterate({ (element) in
if let o = element as? ManagedModel{
o.changedKeys.removeAll()
}
})
}
NotificationCenter.default.post(name: Notification.Name(rawValue: DocumentInspector.CHANGES_HAS_BEEN_RESET_NOTIFICATION), object: nil)
}
@IBAction func commitChanges(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
do {
try documentReference.commitPendingChanges()
} catch {
}
}
}
@IBAction func openWebStack(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument() {
if let url=document.metadata.currentUser?.signInURL(for:document){
NSWorkspace.shared.open(url)
}
}
}
@IBAction func saveDocument(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
documentReference.save(sender)
}
}
@IBAction func deleteOperations(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
for operation in documentReference.pushOperations.reversed(){
documentReference.pushOperations.removeObject(operation, commit: false)
}
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func cleanupOperationQuarantine(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument() {
document.metadata.operationsQuarantine.removeAll()
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func forceDataIntegration(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument(){
document.forceDataIntegration()
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func deleteBSFSOrpheans(_ sender: NSMenuItem) {
if let document=self.documentProvider?.getDocument(){
document.blocks.reversed().forEach({ (block) in
if block.ownedBy.count == 0{
try? block.erase()
}
})
document.nodes.reversed().forEach({ (node) in
if node.ownedBy.count == 0{
try? node.erase()
}
})
document.boxes.reversed().forEach({ (box) in
if box.ownedBy.count == 0{
try? box.erase()
}
})
}
}
@IBAction func deleteSelectedEntity(_ sender: NSMenuItem) {
if let item = self.listOutlineView.item(atRow: self.listOutlineView.selectedRow) as? ManagedModel{
try? item.erase()
}
}
//MARK:- Collections
fileprivate var _collectionListDelegate:CollectionListDelegate?
// MARK - DocumentDependent
internal var documentProvider: DocumentProvider?{
didSet{
if let documentReference=self.documentProvider?.getDocument(){
self._collectionListDelegate=CollectionListDelegate(documentReference:documentReference,filterDelegate:self,outlineView:self.listOutlineView,onSelection: {(selected) in
self.updateRepresentedObject(selected)
})
self._topViewController=self.sourceEditor
self._bottomViewController=self.changesViewController
self.topBox.contentView=self._topViewController!.view
self.bottomBox.contentView=self._bottomViewController!.view
self.listOutlineView.delegate = self._collectionListDelegate
self.listOutlineView.dataSource = self._collectionListDelegate
self._collectionListDelegate?.reloadData()
self.metadataViewController.documentProvider=self.documentProvider
}
}
}
func providerHasADocument() {}
//MARK: - initialization
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidAppear() {
super.viewDidAppear()
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: DocumentInspector.CHANGES_HAS_BEEN_RESET_NOTIFICATION), object: nil, queue: nil) {(notification) in
self._collectionListDelegate?.reloadData()
}
}
override func viewWillDisappear() {
super.viewWillDisappear()
NotificationCenter.default.removeObserver(self)
}
/**
Updates and adapts the children viewControllers to the Represented Object
- parameter selected: the outline selected Object
*/
func updateRepresentedObject(_ selected:Any?) -> () {
if let document=self.documentProvider?.getDocument(){
if selected==nil {
document.log("Represented object is nil", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}else{
glog("Document provider fault", file: #file, function: #function, line: #line, category: Default.LOG_FAULT, decorative: false)
}
if let object=selected as? ManagedModel{
// Did the type of represented object changed.
if object.runTimeTypeName() != (self._bottomViewController?.representedObject as? Collectible)?.runTimeTypeName(){
switch object {
case _ where object is PushOperation :
self._topViewController=self.sourceEditor
self._bottomViewController=self.operationViewController
break
default:
self._topViewController=self.sourceEditor
self._bottomViewController=self.changesViewController
}
}
}else{
// It a UnManagedModel
if let _ = selected as? DocumentMetadata{
self._topViewController=self.sourceEditor
self._bottomViewController=self.metadataViewController
}
}
if let object = selected as? NSObject{
if self.topBox.contentView != self._topViewController!.view{
self.topBox.contentView=self._topViewController!.view
}
if self.bottomBox.contentView != self._bottomViewController!.view{
self.bottomBox.contentView=self._bottomViewController!.view
}
if (self._topViewController?.representedObject as? NSObject) != object{
self._topViewController?.representedObject=object
}
if (self._bottomViewController?.representedObject as? NSObject) != object {
self._bottomViewController?.representedObject=object
}
}
}
// MARK - Filtering
@IBAction func firstPartOfPredicateDidChange(_ sender: Any) {
let idx=self.filterPopUp.indexOfSelectedItem
if idx==0{
self.filterField.isEnabled=false
}else{
self.filterField.isEnabled=true
}
self._collectionListDelegate?.updateFilter()
}
@IBAction func filterOperandDidChange(_ sender: Any) {
self._collectionListDelegate?.updateFilter()
}
// MARK - FilterPredicateDelegate
public func filterSelectedIndex()->Int{
return self.filterPopUp.indexOfSelectedItem
}
public func filterExpression()->String{
return PString.trim(self.filterField.stringValue)
}
}
// MARK: - CollectionListDelegate
class CollectionListDelegate:NSObject,NSOutlineViewDelegate,NSOutlineViewDataSource,Identifiable{
fileprivate var _filterPredicateDelegate:FilterPredicateDelegate
fileprivate var _documentReference:BartlebyDocument
fileprivate var _outlineView:NSOutlineView!
fileprivate var _selectionHandler:((_ selected:Any)->())
fileprivate var _collections:[BartlebyCollection]=[BartlebyCollection]()
fileprivate var _filteredCollections:[BartlebyCollection]=[BartlebyCollection]()
var UID: String = Bartleby.createUID()
required init(documentReference:BartlebyDocument,filterDelegate:FilterPredicateDelegate,outlineView:NSOutlineView,onSelection:@escaping ((_ selected:Any)->())) {
self._documentReference=documentReference
self._outlineView=outlineView
self._selectionHandler=onSelection
self._filterPredicateDelegate=filterDelegate
super.init()
self._documentReference.iterateOnCollections { (collection) in
self._collections.append(collection)
collection.addChangesSuperviser(self, closure: { (key, oldValue, newValue) in
self.reloadData()
})
}
// No Filter by default
self._filteredCollections=self._collections
}
public func updateFilter(){
let idx=self._filterPredicateDelegate.filterSelectedIndex()
let expression=self._filterPredicateDelegate.filterExpression()
if (idx == 0 || expression=="" && idx < 8){
self._filteredCollections=self._collections
}else{
self._filteredCollections=[BartlebyCollection]()
for collection in self._collections {
let filteredCollection=collection.filteredCopy({ (instance) -> Bool in
if let o=instance as? ManagedModel{
if idx==1{
// UID contains
return o.UID.contains(expression, compareOptions: NSString.CompareOptions.caseInsensitive)
}else if idx==2{
// ExternalId contains
return o.externalID.contains(expression, compareOptions: NSString.CompareOptions.caseInsensitive)
}else if idx==4{
// ---------
// Is owned by <UID>
return o.ownedBy.contains(expression)
}else if idx==5{
// Owns <UID>
return o.owns.contains(expression)
}else if idx==6{
//Is related to <UID>
return o.freeRelations.contains(expression)
}else if idx==8{
// --------- NO Expression required after this separator
//Changes Count > 0
return o.changedKeys.count > 0
}
}
return false
})
if filteredCollection.count>0{
if let casted=filteredCollection as? BartlebyCollection{
self._filteredCollections.append(casted)
}
}
}
}
self.reloadData()
}
func reloadData(){
// Data reload must be async to support deletions.
Async.main{
var selectedIndexes=self._outlineView.selectedRowIndexes
self._outlineView.reloadData()
if selectedIndexes.count==0 && self._outlineView.numberOfRows > 0 {
selectedIndexes=IndexSet(integer: 0)
}
self._outlineView.selectRowIndexes(selectedIndexes, byExtendingSelection: false)
}
}
//MARK: - NSOutlineViewDataSource
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item==nil{
return self._filteredCollections.count + 1
}
if let object=item as? ManagedModel{
if let collection = object as? BartlebyCollection {
return collection.count
}
}
return 0
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item==nil{
// Root of the tree
// Return the Metadata
if index==0{
return self._documentReference.metadata
}else{
// Return the collections with a shifted index
return self._filteredCollections[index-1]
}
}
if let object=item as? ManagedModel{
if let collection = object as? BartlebyCollection {
if let element=collection.item(at: index){
return element
}
return "<!>\(object.runTimeTypeName())"
}
}
return "ERROR #\(index)"
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let object=item as? ManagedModel{
return object is BartlebyCollection
}
return false
}
func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
if let object=item as? ManagedModel {
return object.alias().serialize()
}
return nil
}
func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
if let data = object as? Data{
if let alias = try? Alias.deserialize(from:data) {
return Bartleby.instance(from:alias)
}
}
return nil
}
//MARK: - NSOutlineViewDelegate
public func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if let object = item as? ManagedModel{
if let casted=object as? BartlebyCollection {
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CollectionCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = casted.d_collectionName
}
self.configureInlineButton(view, object: casted)
return view
}else if let casted=object as? User {
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "UserCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
if casted.UID==self._documentReference.currentUser.UID{
textField.stringValue = "Current User"
}else{
textField.stringValue = casted.UID
}
}
self.configureInlineButton(view, object: casted)
return view
}else{
let casted=object
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = casted.UID
}
self.configureInlineButton(view, object: casted)
return view
}
}else{
// Value Object
if let object = item as? DocumentMetadata{
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = "Document Metadata"
}
self.configureInlineButton(view, object: object)
return view
}else{
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
if let s=item as? String{
textField.stringValue = s
}else{
textField.stringValue = "Anomaly"
}
}
return view
}
}
}
fileprivate func configureInlineButton(_ view:NSView,object:Any){
if let inlineButton = view.viewWithTag(2) as? NSButton{
if let casted=object as? Collectible{
if let casted=object as? BartlebyCollection {
inlineButton.isHidden=false
inlineButton.title="\(casted.count) | \(casted.changedKeys.count)"
return
}else if object is DocumentMetadata{
inlineButton.isHidden=true
inlineButton.title=""
}else{
if casted.changedKeys.count > 0 {
inlineButton.isHidden=false
inlineButton.title="\(casted.changedKeys.count)"
return
}
}
}
inlineButton.isHidden=true
}
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
if let object=item as? ManagedModel {
if object is BartlebyCollection { return 20 }
return 20 // Any ManagedModel
}
if item is DocumentMetadata { return 20 }
if item is String{ return 20 }
return 30 // This is not normal.
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
return true
}
func outlineViewSelectionDidChange(_ notification: Notification) {
syncOnMain{
let selected=self._outlineView.selectedRow
if let item=self._outlineView.item(atRow: selected){
self._selectionHandler(item)
}
}
}
}
| apache-2.0 | 443d15a9c70c426a3cc57f58f723f416 | 35.142857 | 184 | 0.593696 | 5.696882 | false | false | false | false |
zcfsmile/Swifter | BasicSyntax/023错误处理/023ErrorHandling.playground/Contents.swift | 1 | 4561 | //: Playground - noun: a place where people can play
import UIKit
//: 错误处理
//: 错误处理(Error handling)是响应错误以及从错误中恢复的过程。
//: 表示并抛出错误
//: 在 Swift 中,错误用符合Error协议的类型的值来表示。这个空协议表明该类型可以用于错误处理。
enum VendingMachineError: Error {
case invalidSelection
case insufficienFunds(coinsNeeded: Int)
case outOfStock
}
//: 抛出一个错误可以让你表明有意外情况发生,导致正常的执行流程无法继续执行。抛出错误使用throw关键字。
throw VendingMachineError.insufficienFunds(coinsNeeded: 5)
//: 处理错误
//: 用 throwing 函数传递错误
//: 为了表示一个函数、方法或构造器可以抛出错误,在函数声明的参数列表之后加上throws关键字。一个标有throws关键字的函数被称作throwing 函数。如果这个函数指明了返回值类型,throws关键词需要写在箭头(->)的前面。
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 14)
]
var coinsDeposited = 0
func dispenseSnack(snack: String) {
print("Dispensing \(snack)")
}
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficienFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name] = newItem
print("Dispensing \(name)")
}
}
// vend(itemNamed name: String) 方法会返回错误,可以继续通过 throwing 函数传递
let favoriteSnacks = [
"Alice": "Chips",
"Bob": "Licorice",
"Eve": "Pretzels"
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let sanckName = favoriteSnacks[person] ?? "Candy Bar"
// 因为vend(itemNamed:)方法能抛出错误,所以在调用的它时候在它前面加了try关键字。
try vendingMachine.vend(itemNamed: sanckName)
}
// throwing构造器能像throwing函数一样传递错误.
//struct PurchasedSnack {
// let name: String
// init(name: String, vendingMachine: VendingMachine) throws {
// try vendingMachine.vend(itemNamed: name)
// self.name = name
// }
//}
//: 使用 Do-Catch 处理错误
//: 可以使用一个do-catch语句运行一段闭包代码来处理错误。如果在do子句中的代码抛出了一个错误,这个错误会与catch子句做匹配,从而决定哪条子句能处理它。
var VM = VendingMachine()
VM.coinsDeposited = 8
do {
try buyFavoriteSnack(person: "Alice", vendingMachine: VM)
} catch VendingMachineError.invalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
print("Out of Stock.")
} catch VendingMachineError.insufficienFunds(let coinsNeed) {
print("Insufficient funds. Please insert an additional \(coinsNeed) coins.")
}
//: 将错误转换为可选值
//: 可以使用try?通过将错误转换成一个可选值来处理错误。
//: 禁用错误传递
//: 有时你知道某个throwing函数实际上在运行时是不会抛出错误的,在这种情况下,你可以在表达式前面写try!来禁用错误传递,这会把调用包装在一个不会有错误抛出的运行时断言中。如果真的抛出了错误,你会得到一个运行时错误。
//: defer
//: 可以使用defer语句在即将离开当前代码块时执行一系列语句。该语句让你能执行一些必要的清理工作,不管是以何种方式离开当前代码块的——无论是由于抛出错误而离开,还是由于诸如return或者break的语句。
//func processFile(filename: String) throws {
// if exists(filename) {
// let file = open(filename)
// defer {
// close(file)
// }
// while let line = try file.readline() {
// // 处理文件。
// }
// // close(file) 会在这里被调用,即作用域的最后。
// }
//}
//: 即使没有涉及到错误处理,你也可以使用defer语句。
| mit | 0adb4fad450717c3e584c5bcf83777eb | 26.644628 | 119 | 0.671749 | 3.311881 | false | false | false | false |
khizkhiz/swift | test/SourceKit/DocumentStructure/Inputs/main.swift | 8 | 1506 | class Foo : Bar {
var test : Int
@IBOutlet var testOutlet : Int
func testMethod() {
if test {
}
}
@IBAction func testAction() {
}
}
@IBDesignable
class Foo2 {}
class Foo3 {
@IBInspectable var testInspectable : Int
}
protocol MyProt {}
class OuterCls {
class InnerCls1 {}
}
extension OuterCls {
class InnerCls2 {}
}
class GenCls<T1, T2> {}
class TestParamAndCall {
func testParams(arg1: Int, name: String) {
if (arg1) {
testParams(0, name:"testing")
}
}
func testParamAndArg(arg1: Int, param par: Int) {
}
}
// FIXME: Whatever.
class TestMarkers {
// TODO: Something.
func test(arg1: Bool) -> Int {
// FIXME: Blah.
if (arg1) {
// FIXME: Blah.
return 0
}
return 1
}
}
func test2(arg1: Bool) {
if (arg1) {
// http://whatever FIXME: http://whatever/fixme.
}
}
extension Foo {
func anExtendedFooFunction() {
}
}
// rdar://19539259
var (sd2: Qtys)
{
417(d: nil)
}
for i in 0...5 {}
for var i = 0, i2 = 1; i == 0; ++i {}
while var v = o, z = o where v > z {}
repeat {} while v == 0
if var v = o, z = o where v > z {}
switch v {
case 1: break;
case 2, 3: break;
default: break;
}
let myArray = [1, 2, 3]
let myDict = [1:1, 2:2, 3:3]
// rdar://21203366
@objc
class ClassObjcAttr : NSObject {
@objc
func m() {}
}
@objc(Blah)
class ClassObjcAttr2 : NSObject {
@objc(Foo)
func m() {}
}
| apache-2.0 | 2601317eafe610e2acf1ec379d1bcdc2 | 14.06 | 56 | 0.539841 | 3 | false | true | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/apiinteraction/sync/server/FileUploadProgress.swift | 4 | 2196 | //
// FileUploadProgress.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 03/11/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
//package mediabrowser.apiinteraction.sync.server;
//
//import mediabrowser.apiinteraction.device.IDevice;
//import mediabrowser.apiinteraction.sync.SyncProgress;
//import mediabrowser.apiinteraction.tasks.CancellationToken;
//import mediabrowser.apiinteraction.tasks.Progress;
//import mediabrowser.model.devices.LocalFileInfo;
//
//import java.util.ArrayList;
public class FileUploadProgress<T>: ProgressProtocol<T> { // extends Progress<Double> {
// private ContentUploader contentUploader;
// private IDevice device;
// private ArrayList<LocalFileInfo> files;
// private int index;
// private SyncProgress progress;
// private CancellationToken cancellationToken;
// private LocalFileInfo file;
//
// public FileUploadProgress(ContentUploader contentUploader, IDevice device, ArrayList<LocalFileInfo> files, int index, SyncProgress progress, CancellationToken cancellationToken) {
// this.contentUploader = contentUploader;
// this.device = device;
// this.files = files;
// this.index = index;
// this.progress = progress;
// this.cancellationToken = cancellationToken;
//
// file = files.get(index);
// }
//
// private void GoNext() {
//
// double numComplete = index+ 1;
// numComplete /= files.size();
// progress.report(numComplete * 100);
//
// contentUploader.UploadNext(files, index + 1, device, cancellationToken, progress);
// }
//
// @Override
// public void onComplete() {
//
// progress.onFileUploaded(file);
// GoNext();
// }
//
// @Override
// public void onError(Exception ex) {
//
// progress.onFileUploadError(file, ex);
// GoNext();
// }
//
// @Override
// public void onCancelled() {
//
// GoNext();
// }
//
// @Override
// public void onProgress(Double value) {
//
// // TODO: This is progress for the individual file
// }
} | mit | fd6de1bc7f987dd50b11598884351376 | 27.894737 | 185 | 0.635535 | 3.954955 | false | false | false | false |
coryoso/HanekeSwift | Haneke/Format.swift | 1 | 2648 | //
// Format.swift
// Haneke
//
// Created by Hermes Pique on 8/27/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public struct Format<T> {
public let name: String
public let diskCapacity : UInt64
public var transform : ((T) -> (T))?
public var convertToData : (T -> NSData)?
public init(name: String, diskCapacity : UInt64 = UINT64_MAX, transform: ((T) -> (T))? = nil) {
self.name = name
self.diskCapacity = diskCapacity
self.transform = transform
}
public func apply(value : T) -> T {
var transformed = value
if let transform = self.transform {
transformed = transform(value)
}
return transformed
}
var isIdentity : Bool {
return self.transform == nil
}
}
public struct ImageResizer {
public enum ScaleMode: String {
case Fill = "fill", AspectFit = "aspectfit", AspectFill = "aspectfill", None = "none"
}
public typealias T = Image
public let allowUpscaling : Bool
public let size : CGSize
public let scaleMode: ScaleMode
public let compressionQuality : Float
public init(size: CGSize = CGSizeZero, scaleMode: ScaleMode = .None, allowUpscaling: Bool = true, compressionQuality: Float = 1.0) {
self.size = size
self.scaleMode = scaleMode
self.allowUpscaling = allowUpscaling
self.compressionQuality = compressionQuality
}
public func resizeImage(image: Image) -> Image {
var resizeToSize: CGSize
switch self.scaleMode {
case .Fill:
resizeToSize = self.size
case .AspectFit:
resizeToSize = image.size.hnk_aspectFitSize(self.size)
case .AspectFill:
resizeToSize = image.size.hnk_aspectFillSize(self.size)
case .None:
return image
}
assert(self.size.width > 0 && self.size.height > 0, "Expected non-zero size. Use ScaleMode.None to avoid resizing.")
// If does not allow to scale up the image
if (!self.allowUpscaling) {
if (resizeToSize.width > image.size.width || resizeToSize.height > image.size.height) {
return image
}
}
// Avoid unnecessary computations
if (resizeToSize.width == image.size.width && resizeToSize.height == image.size.height) {
return image
}
let resizedImage = image.hnk_imageByScalingToSize(resizeToSize)
return resizedImage
}
}
| apache-2.0 | 5e6ac3891d897e36a2c2e174a9c7ebeb | 26.298969 | 136 | 0.595166 | 4.542024 | false | false | false | false |
Raizlabs/ios-template | PRODUCTNAME/app/Services/API/APISerialization.swift | 1 | 2006 | ///
// APISerialization.swift
// PRODUCTNAME
//
// Created by LEADDEVELOPER on TODAYSDATE.
// Copyright © THISYEAR ORGANIZATION. All rights reserved.
//
import Alamofire
import Swiftilities
private func ResponseSerializer<T>(_ serializer: @escaping (Data) throws -> T) -> DataResponseSerializer<T> {
return DataResponseSerializer { _, _, data, error in
guard let data = data else {
return .failure(error ?? APIError.noData)
}
if let error = error {
do {
let knownError = try JSONDecoder.default.decode(PRODUCTNAMEError.self, from: data)
return .failure(knownError)
} catch let decodeError {
let string = String(data: data, encoding: .utf8)
Log.info("Could not decode error, falling back to generic error: \(decodeError) \(String(describing: string))")
}
if let errorDictionary = (try? JSONSerialization.jsonObject(with: data, options: [.allowFragments])) as? [String: Any] {
return .failure(PRODUCTNAMEError.unknown(errorDictionary))
}
return .failure(error)
}
do {
return .success(try serializer(data))
} catch let decodingError {
return .failure(decodingError)
}
}
}
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Void> where Endpoint.ResponseType == Payload.Empty {
return ResponseSerializer { data in
endpoint.log(data)
}
}
/// Response serializer to import JSON Object using JSONDecoder and return an object
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Endpoint.ResponseType> where Endpoint.ResponseType: Decodable {
return ResponseSerializer { data in
endpoint.log(data)
let decoder = JSONDecoder.default
return try decoder.decode(Endpoint.ResponseType.self, from: data)
}
}
| mit | 0397d82d452cb7c9a79dc04b7118a9e0 | 38.313725 | 167 | 0.655362 | 4.9022 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | the-blue-alliance-ios/View Elements/Teams/TeamHeaderView.swift | 1 | 6857 | import Foundation
import UIKit
class TeamHeaderView: UIView {
var viewModel: TeamHeaderViewModel {
didSet {
configureView()
}
}
private var baseAvatarColor: UIColor {
// Some teams look better in Red, some teams look better in Blue.
// One team looks better in Black.
if viewModel.teamNumber == 148 {
return UIColor.black
}
let redTeams = [1114, 2337]
if redTeams.contains(viewModel.teamNumber) {
return UIColor.avatarRed
}
return UIColor.avatarBlue
}
private lazy var rootStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [avatarImageView, teamInfoStackView, yearStackView])
stackView.axis = .horizontal
stackView.spacing = 8
stackView.alignment = .center
return stackView
}()
private lazy var avatarImageView = AvatarImageView(baseColor: baseAvatarColor)
private lazy var teamNumberLabel: UILabel = {
let label = TeamHeaderView.teamHeaderLabel()
let font = UIFont.preferredFont(forTextStyle: .title1)
let fontMetrics = UIFontMetrics(forTextStyle: .title1)
label.font = fontMetrics.scaledFont(for: UIFont.systemFont(ofSize: font.pointSize, weight: .semibold))
label.adjustsFontSizeToFitWidth = true
return label
}()
private lazy var teamNameLabel: UILabel = {
let label = TeamHeaderView.teamHeaderLabel()
label.font = UIFont.preferredFont(forTextStyle: .title3)
label.numberOfLines = 0
return label
}()
private lazy var teamInfoStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [teamNumberLabel, teamNameLabel])
stackView.axis = .vertical
return stackView
}()
let yearButton = YearButton()
private lazy var yearStackView: UIStackView = {
let spacerView = UIView()
spacerView.setContentHuggingPriority(.defaultLow, for: .vertical)
let stackView = UIStackView(arrangedSubviews: [spacerView, yearButton])
stackView.axis = .vertical
yearButton.autoSetDimension(.width, toSize: 60, relation: .greaterThanOrEqual)
yearButton.autoSetDimension(.height, toSize: 30, relation: .greaterThanOrEqual)
yearButton.setContentCompressionResistancePriority(.required, for: .horizontal)
return stackView
}()
init(_ viewModel: TeamHeaderViewModel) {
self.viewModel = viewModel
super.init(frame: .zero)
backgroundColor = UIColor.navigationBarTintColor
configureView()
addSubview(rootStackView)
rootStackView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), excludingEdge: .top)
rootStackView.autoSetDimension(.height, toSize: 55, relation: .greaterThanOrEqual)
let topConstraint = rootStackView.autoPinEdge(toSuperviewEdge: .top, withInset: 16)
// Allow our top spacing constraint to be unsatisfied - this will allow the view to glide under the navigation bar while scrolling
topConstraint.priority = .defaultLow
yearStackView.autoMatch(.height, to: .height, of: rootStackView)
avatarImageView.autoSetDimensions(to: .init(width: 55, height: 55))
avatarImageView.setContentCompressionResistancePriority(.required, for: .vertical)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private Methods
private func configureView() {
avatarImageView.image = viewModel.avatar
avatarImageView.isHidden = viewModel.avatar == nil
teamNumberLabel.text = viewModel.teamNumberNickname
teamNameLabel.text = viewModel.nickname
teamNumberLabel.isHidden = viewModel.nickname == nil
let yearString: String = {
if let year = viewModel.year {
return String(year)
} else {
return "----"
}
}()
yearButton.setTitle(yearString, for: .normal)
}
static func teamHeaderLabel() -> UILabel {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.textColor = UIColor.white
return label
}
func changeAvatarBorder() {
avatarImageView.avatarTapped()
}
}
private class AvatarImageView: UIView {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.clear
return imageView
}()
var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
}
}
init(baseColor: UIColor) {
super.init(frame: .zero)
backgroundColor = baseColor
isUserInteractionEnabled = true
addSubview(imageView)
imageView.autoPinEdgesToSuperviewEdges(with: .init(top: 5, left: 5, bottom: 5, right: 5))
layer.borderColor = baseColor.cgColor
layer.borderWidth = 5
layer.masksToBounds = true
layer.cornerRadius = 5
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(avatarTapped))
addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UI Methods
@objc func avatarTapped() {
let newColor = backgroundColor == .avatarBlue ? UIColor.avatarRed : UIColor.avatarBlue
backgroundColor = newColor
layer.borderColor = newColor.cgColor
}
}
class YearButton: UIButton {
override open var isHighlighted: Bool {
didSet {
UIView.animate(withDuration: 0.125) {
self.backgroundColor = self.isHighlighted ? UIColor.lightGray : UIColor.white
}
}
}
init() {
super.init(frame: .zero)
tintColor = UIColor.navigationBarTintColor
backgroundColor = UIColor.white
setTitle("----", for: .normal)
setTitleColor(UIColor.navigationBarTintColor, for: .normal)
setImage(UIImage(systemName: "chevron.down"), for: .normal)
setContentHuggingPriority(.defaultHigh, for: .horizontal)
titleLabel?.font = UIFont.preferredFont(forTextStyle: .callout, compatibleWith: nil).bold()
layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentEdgeInsets = UIEdgeInsets(top: 0, left: frame.size.height * 0.5, bottom: 0, right: frame.size.height * 0.5)
layer.cornerRadius = frame.size.height * 0.5
}
}
| mit | a183eb7a9b909875763a2bdbafdf4dc2 | 31.192488 | 138 | 0.652326 | 5.182918 | false | false | false | false |
mattiaberretti/MBControlli | MBControlli/Classes/BaseFotoViewController.swift | 1 | 4996 | //
// BaseFotoViewController.swift
// MBControlli
//
// Created by Mattia Berretti on 23/12/16.
// Copyright © 2016 Mattia Berretti. All rights reserved.
//
import UIKit
@IBDesignable
open class BaseFotoViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AnteprimaFotoViewControllerDelegate {
@IBOutlet
public weak var immagine : UIImageView?
@IBOutlet
public weak var btnFoto : UIBarButtonItem?
@IBInspectable
open var mostraAnteprima : Bool = true
public var fotoModificata = false
open override func viewDidLoad() {
super.viewDidLoad()
if let immagine = self.immagine {
immagine.isUserInteractionEnabled = true
immagine.layer.borderWidth = 1
immagine.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.toccoFoto(_:))))
if let bottone = self.btnFoto {
bottone.target = self
bottone.action = #selector(self.toccoBottone(_:))
}
}
}
func toccoFoto(_ sender : UITapGestureRecognizer){
if self.mostraAnteprima == true && self.immagine?.image != nil {
let controller = AnteprimaFotoViewController()
controller.immagine = self.immagine?.image
controller.delegate = self
controller.anteprimaFoto(controller: self)
}
else{
self.messaggioSelezione(bottone: false)
}
}
func toccoBottone(_ sender : UIBarButtonItem){
self.messaggioSelezione(bottone: true)
}
func messaggioSelezione(bottone : Bool){
let msg = UIAlertController(title: "Seleziona immagine", message: "", preferredStyle: .actionSheet)
msg.modalPresentationStyle = .popover
if bottone {
msg.popoverPresentationController?.barButtonItem = self.btnFoto
}
else{
msg.popoverPresentationController?.sourceRect = self.immagine!.frame
msg.popoverPresentationController?.sourceView = self.immagine
}
msg.addAction(UIAlertAction(title: "Fotocamera", style: .default, handler: { (a) in
self.selezionaImmagine(bottone: bottone, sorgente: .camera)
}))
msg.addAction(UIAlertAction(title: "Libreria immagini", style: .default, handler: { (a) in
self.selezionaImmagine(bottone: bottone, sorgente: .photoLibrary)
}))
if self.immagine?.image != nil {
msg.addAction(UIAlertAction(title: "Elimina foto", style: .destructive, handler: { (a) in
self.immagine?.image = nil
}))
}
msg.addAction(UIAlertAction(title: "Annulla", style: .cancel, handler: nil))
self.present(msg, animated: true, completion: nil)
}
func selezionaImmagine(bottone : Bool, sorgente : UIImagePickerControllerSourceType){
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = sorgente
if sorgente != .camera {
picker.modalPresentationStyle = .popover
if bottone {
picker.popoverPresentationController?.barButtonItem = self.btnFoto
}
else{
picker.popoverPresentationController?.sourceView = self.immagine
picker.popoverPresentationController?.sourceRect = self.immagine!.frame
}
}
else{
picker.cameraCaptureMode = .photo
}
self.present(picker, animated: true, completion: nil)
}
//=======================================
//image picher
//=======================================
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let immagine = (info[UIImagePickerControllerEditedImage] as? UIImage) ?? info[UIImagePickerControllerOriginalImage] as! UIImage
picker.dismiss(animated: true) {
self.immagine?.image = immagine
self.fotoModificata = true
}
}
//=======================================
//AnteprimaFotoViewControllerDelegate
//=======================================
func immagineEliminata(controller: UIViewController) {
controller.dismiss(animated: true) {
self.immagine?.image = nil
}
}
func fotoModificata(immagine: UIImage, controller: UIViewController) {
controller.dismiss(animated: true) {
self.immagine?.image = immagine
self.fotoModificata = true
}
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 734d61ecf5e8c5c85b396ee1d350f3c8 | 35.195652 | 157 | 0.611011 | 5.241343 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/split-linked-list-in-parts.swift | 2 | 2955 | /**
* https://leetcode.com/problems/split-linked-list-in-parts/
*
*
*/
// Date: Wed Sep 29 19:25:43 PDT 2021
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func splitListToParts(_ head: ListNode?, _ k: Int) -> [ListNode?] {
var count = 0
var node = head
while node != nil {
count += 1
node = node?.next
}
let size = count / k
var pre = size == 0 ? 0 : count - k * size
var result = [ListNode?]()
node = head
count = 0
var fooNode: ListNode? = ListNode()
var cNode: ListNode? = fooNode
var flag = false
while node != nil {
count += 1
cNode?.next = node
if count < size {
cNode = cNode?.next
node = node?.next
} else {
if !flag, result.count < pre {
cNode = cNode?.next
node = node?.next
flag = true
} else {
flag = false
count = 0
result.append(fooNode?.next)
fooNode = ListNode()
cNode = fooNode
let next = node?.next
node?.next = nil
node = next
}
}
}
if count > 0 {
result.append(fooNode?.next)
}
if result.count < k {
for _ in result.count ..< k {
result.append(nil)
}
}
return result
}
}/**
* https://leetcode.com/problems/split-linked-list-in-parts/
*
*
*/
// Date: Mon Oct 4 19:13:19 PDT 2021
class Solution {
func canPartitionKSubsets(_ nums: [Int], _ k: Int) -> Bool {
let sum = nums.reduce(0) { $0 + $1 }
guard sum % k == 0 else { return false }
let target = sum / k
func dfs(_ candidates: inout [Bool], _ start: Int, _ cSum: Int, _ group: Int) -> Bool {
if group == 1 { return true }
if cSum == target {
return dfs(&candidates, 0, 0, group - 1)
}
for index in start ..< nums.count {
if candidates[index] == true || cSum + nums[index] > target { continue }
candidates[index] = true
if dfs(&candidates, index + 1, cSum + nums[index], group) { return true }
candidates[index] = false
}
return false
}
var cand = Array(repeating: false, count: nums.count)
return dfs(&cand, 0, 0, k)
}
} | mit | ec9462d886eccb6ee88a64ec9eea274a | 29.791667 | 95 | 0.45313 | 4.150281 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Effects/Distortion/Decimator/AKDecimator.swift | 1 | 3243 | //
// AKDecimator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// AudioKit version of Apple's Decimator from the Distortion Audio Unit
///
open class AKDecimator: AKNode, AKToggleable, AUEffect, AKInput {
// MARK: - Properties
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_Distortion)
private var au: AUWrapper
private var lastKnownMix: Double = 1
/// Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var decimation: Double = 0.5 {
didSet {
decimation = (0...1).clamp(decimation)
au[kDistortionParam_Decimation] = decimation * 100
}
}
/// Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
@objc open dynamic var rounding: Double = 0 {
didSet {
rounding = (0...1).clamp(rounding)
au[kDistortionParam_Rounding] = rounding * 100
}
}
/// Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
@objc open dynamic var mix: Double = 1 {
didSet {
mix = (0...1).clamp(mix)
au[kDistortionParam_FinalMix] = mix * 100
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted = true
// MARK: - Initialization
/// Initialize the decimator node
///
/// - Parameters:
/// - input: Input node to process
/// - decimation: Decimation (Normalized Value) ranges from 0 to 1 (Default: 0.5)
/// - rounding: Rounding (Normalized Value) ranges from 0 to 1 (Default: 0)
/// - mix: Mix (Normalized Value) ranges from 0 to 1 (Default: 1)
///
@objc public init(
_ input: AKNode? = nil,
decimation: Double = 0.5,
rounding: Double = 0,
mix: Double = 1) {
self.decimation = decimation
self.rounding = rounding
self.mix = mix
let effect = _Self.effect
au = AUWrapper(effect)
super.init(avAudioNode: effect, attach: true)
input?.connect(to: self)
// Since this is the Decimator, mix it to 100% and use the final mix as the mix parameter
au[kDistortionParam_Decimation] = decimation * 100
au[kDistortionParam_Rounding] = rounding * 100
au[kDistortionParam_FinalMix] = mix * 100
au[kDistortionParam_PolynomialMix] = 0
au[kDistortionParam_RingModMix] = 0
au[kDistortionParam_DelayMix] = 0
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
if isStopped {
mix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
if isPlaying {
lastKnownMix = mix
mix = 0
isStarted = false
}
}
/// Disconnect the node
override open func disconnect() {
stop()
AudioKit.detach(nodes: [self.avAudioNode])
}
}
| mit | d90e34b5c67124b4cc54a0860b7889b8 | 29.018519 | 113 | 0.602714 | 4.392954 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/Services/Style.swift | 1 | 743 | //
// Style.swift
// SAS Coffee
//
// Created by Duy Cao on 9/1/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
class Style: NSObject {
static let colorPrimary : UIColor = .init(rgb: 0x00b9e6)
static let colorPrimaryDark : UIColor = .init(rgb: 0x2f82c3)
static let colorSecondary : UIColor = .init(rgb: 0xF5A623)
static let colorWhite : UIColor = .init(rgb: 0xffffff)
static let colorWhiteTrans : UIColor = .init(argb: 0xffffff)
static let colorWhiteHard : UIColor = .init(rgb: 0xeeeeee)
static let colorYellow : UIColor = .init(rgb: 0xF9DC15)
static let colorPrimaryLight : UIColor = .init(rgb: 0xCBF0F9)
static let colorSupplementary1 : UIColor = .init(rgb: 0x556080)
}
| gpl-3.0 | 1b65c01b49b135fda1f44b9450d821ba | 31.26087 | 67 | 0.691375 | 3.254386 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | Colour/Sources/ICCColourParser.swift | 1 | 3740 | //
// ICCColourParser.swift
// Scalar2D
//
// Created by Glenn Howes on 10/12/16.
// Copyright © 2016-2019 Generally Helpful Software. All rights reserved.
//
//
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// 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
public struct ICCColourParser : ColourParser
{
public func deserializeString(source: String, colorContext: ColorContext? = nil) throws -> Colour?
{
guard source.hasPrefix("icc-color") else
{
return nil
}
let leftParenComponents = source.components(separatedBy: "(")
guard leftParenComponents.count == 2 else
{
throw ColourParsingError.unexpectedCharacter(source)
}
guard leftParenComponents.first!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "icc-color" else
{ // something between the icc-color prefix and the leading (
throw ColourParsingError.unexpectedCharacter(source)
}
let rightSide = leftParenComponents.last!
guard rightSide.hasSuffix(")") else
{
throw ColourParsingError.incomplete(source)
}
let rightParenComponents = rightSide.components(separatedBy: ")") // source is assumed to be trimmed so it should terminate on the )
guard rightParenComponents.count == 2 && rightParenComponents.last!.isEmpty else
{
throw ColourParsingError.unexpectedCharacter(source)
}
let payload = rightParenComponents.first!
var stringComponents = payload.components(separatedBy: ",")
guard stringComponents.count >= 2 else
{// need at least a name and and at least 1 colour component
throw ColourParsingError.incomplete(source)
}
let profileName = stringComponents.removeFirst().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let doubleComponents = stringComponents.map{Double($0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))}
let noNullDoubleComponents = doubleComponents.compactMap{$0}
guard noNullDoubleComponents.count == doubleComponents.count else
{
// one of the components was not convertable to a Double, so bad format
throw ColourParsingError.unexpectedCharacter(source)
}
let colourFloatComponents = noNullDoubleComponents.map{ColourFloat($0)}
return Colour.icc(profileName: profileName, components: colourFloatComponents, source: source)
}
public init()
{
}
}
| mit | d94f460b5e4eb8636a0f7a5743c8cd08 | 38.357895 | 140 | 0.685477 | 4.985333 | false | false | false | false |
xingfukun/IQKeyboardManager | IQKeyboardManagerSwift/Categories/IQNSArray+Sort.swift | 18 | 2396 | //
// IQNSArray+Sort.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/**
UIView.subviews sorting category.
*/
internal extension Array {
///--------------
/// MARK: Sorting
///--------------
/**
Returns the array by sorting the UIView's by their tag property.
*/
internal func sortedArrayByTag() -> [T] {
return sorted({ (obj1 : T, obj2 : T) -> Bool in
let view1 = obj1 as! UIView
let view2 = obj2 as! UIView
return (view1.tag < view2.tag)
})
}
/**
Returns the array by sorting the UIView's by their tag property.
*/
internal func sortedArrayByPosition() -> [T] {
return sorted({ (obj1 : T, obj2 : T) -> Bool in
let view1 = obj1 as! UIView
let view2 = obj2 as! UIView
let x1 = CGRectGetMinX(view1.frame)
let y1 = CGRectGetMinY(view1.frame)
let x2 = CGRectGetMinX(view2.frame)
let y2 = CGRectGetMinY(view2.frame)
if y1 != y2 {
return y1 < y2
} else {
return x1 < x2
}
})
}
}
| mit | 29014e0a19b7d5a1e19e0cae63945756 | 31.821918 | 80 | 0.615192 | 4.512241 | false | false | false | false |
jasonhenderson/examples-ios | WebServices/Pods/Toast-Swift/Toast/Toast.swift | 2 | 28211 | //
// Toast.swift
// Toast-Swift
//
// Copyright (c) 2017 Charles Scalesse.
//
// 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 ObjectiveC
/**
Toast is a Swift extension that adds toast notifications to the `UIView` object class.
It is intended to be simple, lightweight, and easy to use. Most toast notifications
can be triggered with a single line of code.
The `makeToast` methods create a new view and then display it as toast.
The `showToast` methods display any view as toast.
*/
public extension UIView {
/**
Keys used for associated objects.
*/
private struct ToastKeys {
static var timer = "com.toast-swift.timer"
static var duration = "com.toast-swift.duration"
static var point = "com.toast-swift.point"
static var completion = "com.toast-swift.completion"
static var activeToast = "com.toast-swift.activeToast"
static var activityView = "com.toast-swift.activityView"
static var queue = "com.toast-swift.queue"
}
/**
Swift closures can't be directly associated with objects via the
Objective-C runtime, so the (ugly) solution is to wrap them in a
class that can be used with associated objects.
*/
private class ToastCompletionWrapper {
var completion: ((Bool) -> Void)?
init(_ completion: ((Bool) -> Void)?) {
self.completion = completion
}
}
private enum ToastError: Error {
case insufficientData
}
private var queue: NSMutableArray {
get {
if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray {
return queue
} else {
let queue = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return queue
}
}
}
// MARK: - Make Toast Methods
/**
Creates and presents a new toast view.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, position: position, completion: completion)
} catch ToastError.insufficientData {
print("Error: message, title, and image are all nil")
} catch {}
}
/**
Creates a new toast view and presents it at a given center point.
@param message The message to be displayed
@param duration The toast duration
@param point The toast's center point
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, point: point, completion: completion)
} catch ToastError.insufficientData {
print("Error: message, title, and image cannot all be nil")
} catch {}
}
// MARK: - Show Toast Methods
/**
Displays any view as toast at a provided position and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param position The toast's position
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) {
let point = position.centerPoint(forToast: toast, inSuperview: self)
showToast(toast, duration: duration, point: point, completion: completion)
}
/**
Displays any view as toast at a provided center point and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param point The toast's center point
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) {
objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if let _ = objc_getAssociatedObject(self, &ToastKeys.activeToast) as? UIView, ToastManager.shared.isQueueEnabled {
objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
queue.add(toast)
} else {
showToast(toast, duration: duration, point: point)
}
}
// MARK: - Hide Toast Methods
/**
Hides all toast views and clears the queue.
// @TODO: FIXME: this doesn't work then there's more than 1 active toast in the view
*/
public func hideAllToasts() {
queue.removeAllObjects()
if let activeToast = objc_getAssociatedObject(self, &ToastKeys.activeToast) as? UIView {
hideToast(activeToast)
}
}
// MARK: - Activity Methods
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param position The toast's position
*/
public func makeToastActivity(_ position: ToastPosition) {
// sanity
if let _ = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView {
return
}
let toast = createToastActivityView()
let point = position.centerPoint(forToast: toast, inSuperview: self)
makeToastActivity(toast, point: point)
}
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param point The toast's center point
*/
public func makeToastActivity(_ point: CGPoint) {
// sanity
if let _ = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView {
return
}
let toast = createToastActivityView()
makeToastActivity(toast, point: point)
}
/**
Dismisses the active toast activity indicator view.
*/
public func hideToastActivity() {
if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - Private Activity Methods
private func makeToastActivity(_ toast: UIView, point: CGPoint) {
toast.alpha = 0.0
toast.center = point
objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: {
toast.alpha = 1.0
})
}
private func createToastActivityView() -> UIView {
let style = ToastManager.shared.style
let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height))
activityView.backgroundColor = style.backgroundColor
activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
activityView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
activityView.layer.shadowColor = style.shadowColor.cgColor
activityView.layer.shadowOpacity = style.shadowOpacity
activityView.layer.shadowRadius = style.shadowRadius
activityView.layer.shadowOffset = style.shadowOffset
}
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0)
activityView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
return activityView
}
// MARK: - Private Show/Hide Methods
private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) {
toast.center = point
toast.alpha = 0.0
if ToastManager.shared.isTapToDismissEnabled {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:)))
toast.addGestureRecognizer(recognizer)
toast.isUserInteractionEnabled = true
toast.isExclusiveTouch = true
}
objc_setAssociatedObject(self, &ToastKeys.activeToast, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: {
toast.alpha = 1.0
}) { _ in
let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func hideToast(_ toast: UIView) {
hideToast(toast, fromTap: false)
}
private func hideToast(_ toast: UIView, fromTap: Bool) {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.activeToast, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion {
completion(fromTap)
}
if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue {
self.queue.removeObject(at: 0)
self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue)
}
}
}
// MARK: - Events
func handleToastTapped(_ recognizer: UITapGestureRecognizer) {
guard let toast = recognizer.view, let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer else { return }
timer.invalidate()
hideToast(toast, fromTap: true)
}
func toastTimerDidFinish(_ timer: Timer) {
guard let toast = timer.userInfo as? UIView else { return }
hideToast(toast)
}
// MARK: - Toast Construction
/**
Creates a new toast view with any combination of message, title, and image.
The look and feel is configured via the style. Unlike the `makeToast` methods,
this method does not present the toast view automatically. One of the `showToast`
methods must be used to present the resulting view.
@warning if message, title, and image are all nil, this method will throw
`ToastError.InsufficientData`
@param message The message to be displayed
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@throws `ToastError.InsufficientData` when message, title, and image are all nil
@return The newly created toast view
*/
public func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView {
// sanity
guard message != nil || title != nil || image != nil else {
throw ToastError.insufficientData
}
var messageLabel: UILabel?
var titleLabel: UILabel?
var imageView: UIImageView?
let wrapperView = UIView()
wrapperView.backgroundColor = style.backgroundColor
wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
wrapperView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
wrapperView.layer.shadowColor = UIColor.black.cgColor
wrapperView.layer.shadowOpacity = style.shadowOpacity
wrapperView.layer.shadowRadius = style.shadowRadius
wrapperView.layer.shadowOffset = style.shadowOffset
}
if let image = image {
imageView = UIImageView(image: image)
imageView?.contentMode = .scaleAspectFit
imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height)
}
var imageRect = CGRect.zero
if let imageView = imageView {
imageRect.origin.x = style.horizontalPadding
imageRect.origin.y = style.verticalPadding
imageRect.size.width = imageView.bounds.size.width
imageRect.size.height = imageView.bounds.size.height
}
if let title = title {
titleLabel = UILabel()
titleLabel?.numberOfLines = style.titleNumberOfLines
titleLabel?.font = style.titleFont
titleLabel?.textAlignment = style.titleAlignment
titleLabel?.lineBreakMode = .byTruncatingTail
titleLabel?.textColor = style.titleColor
titleLabel?.backgroundColor = UIColor.clear
titleLabel?.text = title;
let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let titleSize = titleLabel?.sizeThatFits(maxTitleSize)
if let titleSize = titleSize {
titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height)
}
}
if let message = message {
messageLabel = UILabel()
messageLabel?.text = message
messageLabel?.numberOfLines = style.messageNumberOfLines
messageLabel?.font = style.messageFont
messageLabel?.textAlignment = style.messageAlignment
messageLabel?.lineBreakMode = .byTruncatingTail;
messageLabel?.textColor = style.messageColor
messageLabel?.backgroundColor = UIColor.clear
let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let messageSize = messageLabel?.sizeThatFits(maxMessageSize)
if let messageSize = messageSize {
let actualWidth = min(messageSize.width, maxMessageSize.width)
let actualHeight = min(messageSize.height, maxMessageSize.height)
messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
}
}
var titleRect = CGRect.zero
if let titleLabel = titleLabel {
titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
titleRect.origin.y = style.verticalPadding
titleRect.size.width = titleLabel.bounds.size.width
titleRect.size.height = titleLabel.bounds.size.height
}
var messageRect = CGRect.zero
if let messageLabel = messageLabel {
messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding
messageRect.size.width = messageLabel.bounds.size.width
messageRect.size.height = messageLabel.bounds.size.height
}
let longerWidth = max(titleRect.size.width, messageRect.size.width)
let longerX = max(titleRect.origin.x, messageRect.origin.x)
let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding))
let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0)))
wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight)
if let titleLabel = titleLabel {
titleRect.size.width = longerWidth
titleLabel.frame = titleRect
wrapperView.addSubview(titleLabel)
}
if let messageLabel = messageLabel {
messageRect.size.width = longerWidth
messageLabel.frame = messageRect
wrapperView.addSubview(messageLabel)
}
if let imageView = imageView {
wrapperView.addSubview(imageView)
}
return wrapperView
}
}
// MARK: - Toast Style
/**
`ToastStyle` instances define the look and feel for toast views created via the
`makeToast` methods as well for toast views created directly with
`toastViewForMessage(message:title:image:style:)`.
@warning `ToastStyle` offers relatively simple styling options for the default
toast view. If you require a toast view with more complex UI, it probably makes more
sense to create your own custom UIView subclass and present it with the `showToast`
methods.
*/
public struct ToastStyle {
public init() {}
/**
The background color. Default is `UIColor.blackColor()` at 80% opacity.
*/
public var backgroundColor = UIColor.black.withAlphaComponent(0.8)
/**
The title color. Default is `UIColor.whiteColor()`.
*/
public var titleColor = UIColor.white
/**
The message color. Default is `UIColor.whiteColor()`.
*/
public var messageColor = UIColor.white
/**
A percentage value from 0.0 to 1.0, representing the maximum width of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's width).
*/
public var maxWidthPercentage: CGFloat = 0.8 {
didSet {
maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
}
}
/**
A percentage value from 0.0 to 1.0, representing the maximum height of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's height).
*/
public var maxHeightPercentage: CGFloat = 0.8 {
didSet {
maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0)
}
}
/**
The spacing from the horizontal edge of the toast view to the content. When an image
is present, this is also used as the padding between the image and the text.
Default is 10.0.
*/
public var horizontalPadding: CGFloat = 10.0
/**
The spacing from the vertical edge of the toast view to the content. When a title
is present, this is also used as the padding between the title and the message.
Default is 10.0.
*/
public var verticalPadding: CGFloat = 10.0
/**
The corner radius. Default is 10.0.
*/
public var cornerRadius: CGFloat = 10.0;
/**
The title font. Default is `UIFont.boldSystemFontOfSize(16.0)`.
*/
public var titleFont = UIFont.boldSystemFont(ofSize: 16.0)
/**
The message font. Default is `UIFont.systemFontOfSize(16.0)`.
*/
public var messageFont = UIFont.systemFont(ofSize: 16.0)
/**
The title text alignment. Default is `NSTextAlignment.Left`.
*/
public var titleAlignment = NSTextAlignment.left
/**
The message text alignment. Default is `NSTextAlignment.Left`.
*/
public var messageAlignment = NSTextAlignment.left
/**
The maximum number of lines for the title. The default is 0 (no limit).
*/
public var titleNumberOfLines = 0
/**
The maximum number of lines for the message. The default is 0 (no limit).
*/
public var messageNumberOfLines = 0
/**
Enable or disable a shadow on the toast view. Default is `false`.
*/
public var displayShadow = false
/**
The shadow color. Default is `UIColor.blackColor()`.
*/
public var shadowColor = UIColor.black
/**
A value from 0.0 to 1.0, representing the opacity of the shadow.
Default is 0.8 (80% opacity).
*/
public var shadowOpacity: Float = 0.8 {
didSet {
shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
}
}
/**
The shadow radius. Default is 6.0.
*/
public var shadowRadius: CGFloat = 6.0
/**
The shadow offset. The default is 4 x 4.
*/
public var shadowOffset = CGSize(width: 4.0, height: 4.0)
/**
The image size. The default is 80 x 80.
*/
public var imageSize = CGSize(width: 80.0, height: 80.0)
/**
The size of the toast activity view when `makeToastActivity(position:)` is called.
Default is 100 x 100.
*/
public var activitySize = CGSize(width: 100.0, height: 100.0)
/**
The fade in/out animation duration. Default is 0.2.
*/
public var fadeDuration: TimeInterval = 0.2
}
// MARK: - Toast Manager
/**
`ToastManager` provides general configuration options for all toast
notifications. Backed by a singleton instance.
*/
public class ToastManager {
/**
The `ToastManager` singleton instance.
*/
public static let shared = ToastManager()
/**
The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called
with with a nil style.
*/
public var style = ToastStyle()
/**
Enables or disables tap to dismiss on toast views. Default is `true`.
*/
public var isTapToDismissEnabled = true
/**
Enables or disables queueing behavior for toast views. When `true`,
toast views will appear one after the other. When `false`, multiple toast
views will appear at the same time (potentially overlapping depending
on their positions). This has no effect on the toast activity view,
which operates independently of normal toast views. Default is `true`.
*/
public var isQueueEnabled = true
/**
The default duration. Used for the `makeToast` and
`showToast` methods that don't require an explicit duration.
Default is 3.0.
*/
public var duration: TimeInterval = 3.0
/**
Sets the default position. Used for the `makeToast` and
`showToast` methods that don't require an explicit position.
Default is `ToastPosition.Bottom`.
*/
public var position = ToastPosition.bottom
}
// MARK: - ToastPosition
public enum ToastPosition {
case top
case center
case bottom
fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint {
let padding: CGFloat = ToastManager.shared.style.verticalPadding
switch self {
case .top:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + padding)
case .center:
return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0)
case .bottom:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - padding)
}
}
}
| gpl-3.0 | 8f9533d9934ebe3ba53cddfc1ec4e81b | 38.958924 | 297 | 0.651448 | 4.937172 | false | false | false | false |
domenicosolazzo/practice-swift | CoreData/Performing Batch Updates/Performing Batch Updates/AppDelegate.swift | 1 | 8494 | //
// AppDelegate.swift
// Performing Batch Updates
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let entityName = NSStringFromClass(Person.classForCoder())
//- MARK: Helper methods
func populateDatabase(){
for counter in 0..<1000{
let person = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext!) as! Person
person.firstName = "First Name \(counter)"
person.lastName = "Last Name \(counter)"
person.age = NSNumber(unsignedInt: arc4random_uniform(120))
}
var savingError: NSError?
do {
try managedObjectContext!.save()
print("Managed to populate the database")
} catch let error1 as NSError {
savingError = error1
if let error = savingError{
print("Error populating the database. Error \(error)")
}
}
}
//- MARK: Application
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let batch = NSBatchUpdateRequest(entityName: entityName)
// Properties to Update
batch.propertiesToUpdate = ["age":18]
// Predicate
batch.predicate = NSPredicate(format:"age < %@", 18 as NSNumber)
// Result type
batch.resultType = NSBatchUpdateRequestResultType.UpdatedObjectsCountResultType
var batchError: NSError?
let result: NSPersistentStoreResult?
do {
result = try managedObjectContext!.executeRequest(batch)
} catch let error as NSError {
batchError = error
result = nil
}
if result != nil{
if let theResult = result as? NSBatchUpdateResult{
if let numberOfAffectedPersons = theResult.result as? Int{
print("Number of people who were previously younger than " +
"18 years old and whose age is now set to " +
"18 is \(numberOfAffectedPersons)")
}
}
}else{
if let error = batchError{
print("Could not perform batch request. Error = \(error)")
}
}
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.domenicosolazzo.swift.Performing_Batch_Updates" 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("Performing_Batch_Updates", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Performing_Batch_Updates.sqlite")
var error: NSError? = nil
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 var error1 as NSError {
error = error1
coordinator = nil
// 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
error = 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | 9923a36d120197086075eb1df95acfce | 47.816092 | 290 | 0.667648 | 5.801913 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Internal/NSManagedObjectContext+Transaction.swift | 1 | 6536 | //
// NSManagedObjectContext+Transaction.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSManagedObjectContext
internal extension NSManagedObjectContext {
// MARK: Internal
internal weak var parentTransaction: BaseDataTransaction? {
get {
return getAssociatedObjectForKey(
&PropertyKeys.parentTransaction,
inObject: self
)
}
set {
setAssociatedWeakObject(
newValue,
forKey: &PropertyKeys.parentTransaction,
inObject: self
)
}
}
internal var isSavingSynchronously: Bool? {
get {
let value: NSNumber? = getAssociatedObjectForKey(
&PropertyKeys.isSavingSynchronously,
inObject: self
)
return value?.boolValue
}
set {
setAssociatedWeakObject(
newValue.flatMap { NSNumber(bool: $0) },
forKey: &PropertyKeys.isSavingSynchronously,
inObject: self
)
}
}
internal func isRunningInAllowedQueue() -> Bool {
guard let parentTransaction = self.parentTransaction else {
return false
}
return parentTransaction.isRunningInAllowedQueue()
}
internal func temporaryContextInTransactionWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: concurrencyType)
context.parentContext = self
context.parentStack = self.parentStack
context.setupForCoreStoreWithContextName("com.corestore.temporarycontext")
context.shouldCascadeSavesToParent = (self.parentStack?.rootSavingContext == self)
context.retainsRegisteredObjects = true
return context
}
internal func saveSynchronously() -> SaveResult {
var result = SaveResult(hasChanges: false)
self.performBlockAndWait {
guard self.hasChanges else {
return
}
do {
self.isSavingSynchronously = true
try self.save()
self.isSavingSynchronously = nil
}
catch {
let saveError = error as NSError
CoreStore.handleError(
saveError,
"Failed to save \(typeName(NSManagedObjectContext))."
)
result = SaveResult(saveError)
return
}
if let parentContext = self.parentContext where self.shouldCascadeSavesToParent {
switch parentContext.saveSynchronously() {
case .Success:
result = SaveResult(hasChanges: true)
case .Failure(let error):
result = SaveResult(error)
}
}
else {
result = SaveResult(hasChanges: true)
}
}
return result
}
internal func saveAsynchronouslyWithCompletion(completion: ((result: SaveResult) -> Void) = { _ in }) {
self.performBlock {
guard self.hasChanges else {
GCDQueue.Main.async {
completion(result: SaveResult(hasChanges: false))
}
return
}
do {
self.isSavingSynchronously = false
try self.save()
self.isSavingSynchronously = nil
}
catch {
let saveError = error as NSError
CoreStore.handleError(
saveError,
"Failed to save \(typeName(NSManagedObjectContext))."
)
GCDQueue.Main.async {
completion(result: SaveResult(saveError))
}
return
}
if let parentContext = self.parentContext where self.shouldCascadeSavesToParent {
parentContext.saveAsynchronouslyWithCompletion(completion)
}
else {
GCDQueue.Main.async {
completion(result: SaveResult(hasChanges: true))
}
}
}
}
internal func refreshAndMergeAllObjects() {
if #available(iOS 8.3, OSX 10.11, *) {
self.refreshAllObjects()
}
else {
self.registeredObjects.forEach { self.refreshObject($0, mergeChanges: true) }
}
}
// MARK: Private
private struct PropertyKeys {
static var parentTransaction: Void?
static var isSavingSynchronously: Void?
}
}
| apache-2.0 | 3c470bb1781c43a1a72fe209d3147867 | 29.537383 | 150 | 0.533588 | 6.400588 | false | false | false | false |
ps2/rileylink_ios | OmniKitUI/Views/PodLifeHUDView.swift | 1 | 5680 | //
// PodLifeHUDView.swift
// OmniKit
//
// Based on OmniKitUI/Views/PodLifeHUDView.swift
// Created by Pete Schwamb on 10/22/18.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKitUI
import MKRingProgressView
public enum PodAlertState {
case none
case warning
case fault
}
public class PodLifeHUDView: BaseHUDView, NibLoadable {
override public var orderPriority: HUDViewOrderPriority {
return 12
}
@IBOutlet private weak var timeLabel: UILabel! {
didSet {
// Setting this color in code because the nib isn't being applied correctly
if #available(iOSApplicationExtension 13.0, *) {
timeLabel.textColor = .label
}
}
}
@IBOutlet private weak var progressRing: RingProgressView!
@IBOutlet private weak var alertLabel: UILabel! {
didSet {
alertLabel.alpha = 0
alertLabel.textColor = UIColor.white
alertLabel.layer.cornerRadius = 9
alertLabel.clipsToBounds = true
}
}
@IBOutlet private weak var backgroundRing: UIImageView! {
didSet {
if #available(iOSApplicationExtension 13.0, iOS 13.0, *) {
backgroundRing.tintColor = .systemGray5
} else {
backgroundRing.tintColor = UIColor(red: 198 / 255, green: 199 / 255, blue: 201 / 255, alpha: 1)
}
}
}
private var startTime: Date?
private var lifetime: TimeInterval?
private var timer: Timer?
public var alertState: PodAlertState = .none {
didSet {
updateAlertStateLabel()
}
}
public class func instantiate() -> PodLifeHUDView {
return nib().instantiate(withOwner: nil, options: nil)[0] as! PodLifeHUDView
}
public func setPodLifeCycle(startTime: Date, lifetime: TimeInterval) {
self.startTime = startTime
self.lifetime = lifetime
updateProgressCircle()
if timer == nil {
self.timer = Timer.scheduledTimer(withTimeInterval: .seconds(10), repeats: true) { [weak self] _ in
self?.updateProgressCircle()
}
}
}
override open func stateColorsDidUpdate() {
super.stateColorsDidUpdate()
updateProgressCircle()
updateAlertStateLabel()
}
private var endColor: UIColor? {
didSet {
let primaryColor = endColor ?? UIColor(red: 198 / 255, green: 199 / 255, blue: 201 / 255, alpha: 1)
self.progressRing.endColor = primaryColor
self.progressRing.startColor = primaryColor
}
}
private lazy var timeFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.maximumUnitCount = 1
formatter.unitsStyle = .abbreviated
return formatter
}()
private func updateAlertStateLabel() {
var alertLabelAlpha: CGFloat = 1
if alertState == .fault {
timer = nil
}
switch alertState {
case .fault:
alertLabel.text = "!"
alertLabel.backgroundColor = stateColors?.error
case .warning:
alertLabel.text = "!"
alertLabel.backgroundColor = stateColors?.warning
case .none:
alertLabelAlpha = 0
}
alertLabel.alpha = alertLabelAlpha
UIView.animate(withDuration: 0.25, animations: {
self.alertLabel.alpha = alertLabelAlpha
})
}
private func updateProgressCircle() {
if let startTime = startTime, let lifetime = lifetime {
let age = -startTime.timeIntervalSinceNow
let progress = Double(age / lifetime)
progressRing.progress = progress
if progress < 0.75 {
self.endColor = stateColors?.normal
progressRing.shadowOpacity = 0
} else if progress < 1.0 {
self.endColor = stateColors?.warning
progressRing.shadowOpacity = 0.5
} else {
self.endColor = stateColors?.error
progressRing.shadowOpacity = 0.8
}
let remaining = (lifetime - age)
// Update time label and caption
if alertState == .fault {
timeLabel.isHidden = true
caption.text = LocalizedString("Fault", comment: "Pod life HUD view label")
} else if remaining > .hours(24) {
timeLabel.isHidden = true
caption.text = LocalizedString("Pod Age", comment: "Label describing pod age view")
} else if remaining > 0 {
let remainingFlooredToHour = remaining > .hours(1) ? remaining - remaining.truncatingRemainder(dividingBy: .hours(1)) : remaining
if let timeString = timeFormatter.string(from: remainingFlooredToHour) {
timeLabel.isHidden = false
timeLabel.text = timeString
}
caption.text = LocalizedString("Remaining", comment: "Label describing time remaining view")
} else {
timeLabel.isHidden = true
caption.text = LocalizedString("Replace Pod", comment: "Label indicating pod replacement necessary")
}
}
}
func pauseUpdates() {
timer?.invalidate()
timer = nil
}
override public func awakeFromNib() {
super.awakeFromNib()
}
}
| mit | 452674cd0fe5e5253efc4a3eddf7e109 | 31.267045 | 145 | 0.578975 | 5.292637 | false | false | false | false |
delannoyk/GIFRefreshControl | GIFRefreshControlExample/GIFRefreshControlExample/ViewController.swift | 1 | 1550 | //
// ViewController.swift
// GIFRefreshControlExample
//
// Created by Kevin DELANNOY on 01/06/15.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
var count = 1
let refreshControl = GIFRefreshControl()
//MARK: Refresh control
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.animatedImage = GIFAnimatedImage(data: try! Data(contentsOf: Bundle.main.url(forResource: "giphy", withExtension: "gif")!))
refreshControl.contentMode = .scaleAspectFill
refreshControl.addTarget(self, action: #selector(ViewController.refresh), for: .valueChanged)
tableView.addSubview(refreshControl)
}
//MARK: Refresh
func refresh() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.count += 1
self.refreshControl.endRefreshing()
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(item: 0, section: 0)],
with: .none)
self.tableView.endUpdates()
}
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
}
}
| mit | 1d568810af2f0961e99b43d81d5a3e37 | 28.245283 | 146 | 0.670323 | 4.983923 | false | false | false | false |
wscqs/FMDemo- | FMDemo/Classes/Module/Course/CourceHeadTbView.swift | 1 | 2881 | //
// CourceHeadTbView.swift
// FMDemo
//
// Created by mba on 17/2/9.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
//protocol CourceHeadTbViewDelegate: NSObjectProtocol{
// func clickOKChangceTitle(courceHeadTbView: CourceHeadTbView, title: String)
//}
class CourceHeadTbView: UIView {
// weak var delegate: CourceHeadTbViewDelegate?
var cid: String!
@IBOutlet weak var tbHeadNormalView: BorderBackgroundView!
@IBOutlet weak var tbHeadChangceView: BorderBackgroundView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var courceStatusLabel: UILabel!
@IBOutlet weak var changceBtn: UIView!
@IBOutlet weak var textView: BorderTextView!
@IBOutlet weak var okBtn: UIButton!
class func courceHeadTbView() -> CourceHeadTbView {
let view: CourceHeadTbView = Bundle.main.loadNibNamed("CourceHeadTbView", owner: self, options: nil)!.last as! CourceHeadTbView
view.frame.size.width = SCREEN_WIDTH
view.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor)
return view
}
override init(frame: CGRect) {
super.init(frame: frame)
// setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// setupUI()
}
override func awakeFromNib() {
superview?.awakeFromNib()
tbHeadChangceView.isHidden = true
// setupUI()
textView.setPlaceholder(kCreatCourceTitleString, maxTip: 50)
changceBtn.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(actionChangce(_:)))
changceBtn.addGestureRecognizer(tapGes)
}
func actionChangce(_ sender: UIView) {
textView.clearBorder = true
tbHeadChangceView.isHidden = false
textView.text = titleLabel.text
}
var isRequest: Bool = false
@IBAction func actionOk(_ sender: UIButton) {
if textView.text.isEmpty {
MBAProgressHUD.showInfoWithStatus("课程标题不能为空")
return
}
if titleLabel.text != textView.text {
if isRequest {
return
}
isRequest = true
KeService.actionSaveCourse(title: textView.text, cid: cid, success: { (bean) in
self.titleLabel.text = self.textView.text
self.tbHeadChangceView.isHidden = true
self.isRequest = false
}) { (error) in
MBAProgressHUD.showInfoWithStatus("课程标题修改失败,请重试")
self.tbHeadChangceView.isHidden = true
self.isRequest = false
}
} else {
self.tbHeadChangceView.isHidden = true
}
endEditing(true)
}
}
| apache-2.0 | 11b19e0509ad16a7cbff7bd94a05553b | 29.847826 | 135 | 0.622622 | 4.777778 | false | false | false | false |
cottonBuddha/Qsic | Qsic/QSLoginWidget.swift | 1 | 1499 | //
// QSLoginWidget.swift
// Qsic
//
// Created by cottonBuddha on 2017/8/2.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
class QSLoginWidget: QSWidget {
var accountInput: QSInputWidget?
var passwordInput: QSInputWidget?
var accountLength: Int = 0
var passwordLength: Int = 0
convenience init(startX:Int, startY:Int) {
self.init(startX: startX, startY: startY, width: Int(COLS - Int32(startX + 1)), height: 3)
}
override func drawWidget() {
super.drawWidget()
self.drawLoginWidget()
wrefresh(self.window)
}
private func drawLoginWidget() {
mvwaddstr(self.window, 0, 0, "需要登录~")
mvwaddstr(self.window, 1, 0, "账号:")
mvwaddstr(self.window, 2, 0, "密码:")
}
public func getInputContent(completionHandler:(String,String)->()) {
accountInput = QSInputWidget.init(startX: 6, startY: 1, width: 40, height: 1)
self.addSubWidget(widget: accountInput!)
let account = accountInput?.input()
accountLength = account!.lengthInCurses()
passwordInput = QSInputWidget.init(startX: 6, startY: 2, width: 40, height: 1)
self.addSubWidget(widget: passwordInput!)
let password = passwordInput?.input()
passwordLength = password!.lengthInCurses()
completionHandler(account!,password!)
}
public func hide() {
eraseSelf()
}
}
| mit | fb2b9fadb55da786f224f08da6179706 | 28.019608 | 98 | 0.621622 | 3.86423 | false | false | false | false |
carolight/sample-code | swift/05-Lighting/Lighting/MBEMesh.swift | 1 | 1396 | //
// MBEMesh.swift
// Lighting
//
// Created by Caroline Begbie on 30/12/2015.
// Copyright © 2015 Caroline Begbie. All rights reserved.
//
import Foundation
import MetalKit
class MBEMesh {
let mesh: MTKMesh?
var submeshes: [MBESubmesh] = []
init(mesh: MTKMesh, mdlMesh: MDLMesh, device: MTLDevice) {
self.mesh = mesh
for i in 0 ..< mesh.submeshes.count {
let submesh = MBESubmesh(submesh: mesh.submeshes[i], mdlSubmesh: mdlMesh.submeshes?[i] as! MDLSubmesh, device: device)
submeshes.append(submesh)
}
}
func renderWithEncoder(encoder:MTLRenderCommandEncoder) {
guard let mesh = mesh else { return }
for (index, vertexBuffer) in mesh.vertexBuffers.enumerated() {
encoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, at: index)
}
for submesh in submeshes {
submesh.renderWithEncoder(encoder: encoder)
}
}
}
class MBESubmesh {
let submesh:MTKSubmesh?
init(submesh:MTKSubmesh, mdlSubmesh:MDLSubmesh, device: MTLDevice) {
self.submesh = submesh
}
func renderWithEncoder(encoder:MTLRenderCommandEncoder) {
guard let submesh = submesh else { return }
encoder.drawIndexedPrimitives(submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: submesh.indexBuffer.offset)
}
}
| mit | 6fe3c45716f83619a1a6c687f3872a84 | 27.469388 | 206 | 0.712545 | 3.940678 | false | false | false | false |
gwyndurbridge/GDSilentDetector | Example/GDSilentDetector/ViewController.swift | 1 | 1276 | //
// ViewController.swift
// GDSilentDetector
//
// Created by Gwyn Durbridge on 09/16/2017.
// Copyright (c) 2017 Gwyn Durbridge. All rights reserved.
//
import UIKit
import GDSilentDetector
struct Platform {
static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
class ViewController: UIViewController {
var silentChecker: GDSilentDetector!
@IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
silentChecker = GDSilentDetector()
silentChecker.delegate = self
checkSilent(self)
}
@IBAction func checkSilent(_ sender: Any) {
if Platform.isSimulator {
self.statusLabel.text = "Cannot detect silent switch on simulator"
}
else {
silentChecker.checkSilent()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: GDSilentDetectorDelegate {
func gotSilentStatus(isSilent: Bool) {
DispatchQueue.main.async {
self.statusLabel.text = isSilent ? "SILENT ENABLED" : "SILENT DISABLED"
}
}
}
| mit | 2c1b5d3c48dcbd43e9bb1d60c687b922 | 22.2 | 83 | 0.630878 | 4.656934 | false | false | false | false |
amraboelela/SwiftPusher | Sources/NWHub.swift | 1 | 13874 | // Converted with Swiftify v1.0.6276 - https://objectivec2swift.com/
//
// NWHub.swift
// Pusher
//
// Copyright (c) 2014 noodlewerk. All rights reserved.
//
// Modified by: Amr Aboelela on 3/16/17.
//
import Foundation
/** Allows callback on errors while pushing to and reading from server.
Check out `NWHub` for more details.
*/
protocol NWHubDelegate: NSObjectProtocol {
/** The notification failed during or after pushing. */
func notification(_ notification: NWNotification, didFailWithError error: Error?)
}
/** Helper on top of `NWPusher` that hides the details of pushing and reading.
This class provides a more convenient way of pushing notifications to the APNs. It deals with the trouble of assigning a unique identifier to every notification and the handling of error responses from the server. It hides the latency that comes with transmitting the pushes, allowing you to simply push your notifications and getting notified of errors through the delegate. If this feels over-abstracted, then definitely check out the `NWPusher` class, which will give you full control.
There are two set of methods for pushing notifications: the easy and the pros. The former will just do the pushing and reconnect if the connection breaks. This is your low-worry solution, provided that you call `readFailed` every so often (seconds) to handle error data from the server. The latter will give you a little more control and a little more responsibility.
*/
class NWHub: NSObject {
/** @name Properties */
/** The pusher instance that does the actual work. */
var pusher: NWPusher!
/** Assign a delegate to get notified when something fails during or after pushing. */
weak var delegate: NWHubDelegate?
/** The type of notification serialization we'll be using. */
var type = NWNotificationType()
/** The timespan we'll hold on to a notification after pushing, allowing the server to respond. */
var feedbackSpan = TimeInterval()
/** The index incremented on every notification push, used as notification identifier. */
var index: Int = 0
/** @name Initialization */
/** Create and return a hub object with a delegate object assigned. */
convenience init(delegate: NWHubDelegate) {
return self.init(NWPusher(), delegate: delegate)
}
/** Create and return a hub object with a delegate and pusher object assigned. */
override init(pusher: NWPusher, delegate: NWHubDelegate) {
super.init()
self.index = 1
self.feedbackSpan = 30
self.pusher = pusher
self.delegate = delegate
self.notificationForIdentifier = [:]
self.type = kNWNotificationType2
}
/** Create, connect and returns an instance with delegate and identity. */
class func connect(with delegate: NWHubDelegate, identity: NWIdentityRef, environment: NWEnvironment, error: Error?) -> Self {
var hub = NWHub(delegate: delegate)
return identity && (try? hub.connect(withIdentity: identity, environment: environment)) ? hub : nil!
}
/** Create, connect and returns an instance with delegate and identity. */
class func connect(with delegate: NWHubDelegate, pkcs12Data data: Data, password: String, environment: NWEnvironment, error: Error?) -> Self {
var hub = NWHub(delegate: delegate)
return data && (try? hub.connect(withPKCS12Data: data, password: password, environment: environment)) ? hub : nil!
}
/** @name Connecting */
/** Connect the pusher using the identity to setup the SSL connection. */
func connect(withIdentity identity: NWIdentityRef, environment: NWEnvironment) throws {
return try? self.pusher.connect(withIdentity: identity, environment: environment)!
}
/** Connect the pusher using the PKCS #12 data to setup the SSL connection. */
func connect(withPKCS12Data data: Data, password: String, environment: NWEnvironment) throws {
return try? self.pusher.connect(withPKCS12Data: data, password: password, environment: environment)!
}
/** Reconnect with the server, to recover from a closed or defect connection. */
func reconnect() throws {
return try? self.pusher.reconnect()!
}
/** Close the connection, allows reconnecting. */
override func disconnect() {
self.pusher.disconnect()
}
/** @name Pushing (easy) */
/** Push a JSON string payload to a device with token string.
@see pushNotifications:
*/
func pushPayload(_ payload: String, token: String) -> Int {
var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0)
return self.pushNotifications([notification])
}
/** Push a JSON string payload to multiple devices with token strings.
@see pushNotifications:
*/
func pushPayload(_ payload: String, tokens: [Any]) -> Int {
var notifications: [Any] = []
for token: String in tokens {
var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0)
notifications.append(notification)
}
return self.pushNotifications(notifications)
}
/** Push multiple JSON string payloads to a device with token string.
@see pushNotifications:
*/
func pushPayloads(_ payloads: [Any], token: String) -> Int {
var notifications: [Any] = []
for payload: String in payloads {
var notification = NWNotification(payload: payload, token: token, identifier: 0, expiration: nil, priority: 0)
notifications.append(notification)
}
return self.pushNotifications(notifications)
}
/** Push multiple notifications, each representing a payload and a device token.
This will assign each notification a unique identifier if none was set yet. If pushing fails it will reconnect. This method can be used rather carelessly; any thing goes. However, this also means that a failed notification might break the connection temporarily, losing a notification here or there. If you are sending bulk and don't care too much about this, then you'll be fine. If not, consider using `pushNotification:autoReconnect:error:`.
Make sure to call `readFailed` on a regular basis to allow server error responses to be handled and the delegate to be called.
Returns the number of notifications that failed, preferably zero.
@see readFailed
*/
func pushNotifications(_ notifications: [Any]) -> Int {
var fails: Int = 0
for notification: NWNotification in notifications {
var success: Bool? = try? self.push(notification, autoReconnect: true)
if success == nil {
fails += 1
}
}
return fails
}
/** Read the response from the server to see if any pushes have failed.
Due to transmission latency it usually takes a couple of milliseconds for the server to respond to errors. This methods reads the server response and handles the errors. Make sure to call this regularly to catch up on malformed notifications.
@see pushNotifications:
*/
func readFailed() -> Int {
var failed: [Any]? = nil
try? self.readFailed(failed, max: 1000, autoReconnect: true)
return failed?.count!
}
/** @name Pushing (pros) */
/** Push a notification and reconnect if anything failed.
This will assign the notification a unique (incremental) identifier and feed it to the internal pusher. If this succeeds, the notification is stored for later lookup by `readFailed:autoReconnect:error:`. If it fails, the delegate will be invoked and it will reconnect if set to auto-reconnect.
@see readFailed:autoReconnect:error:
*/
func push(_ notification: NWNotification, autoReconnect reconnect: Bool) throws {
if !notification.identifier {
notification.identifier = self.index += 1
}
var e: Error? = nil
var pushed: Bool? = try? self.pusher.push(notification, type: self.type)
if pushed == nil {
if error != nil {
error = e
}
if self.delegate.responds(to: Selector("notification:didFailWithError:")) {
self.delegate.notification(notification, didFailWithError: e)
}
if reconnect && e?.code == kNWErrorWriteClosedGraceful {
try? self.reconnect()
}
return pushed!
}
self.notificationForIdentifier[(notification.identifier)] = [notification, Date()]
return true
}
/** Read the response from the server and reconnect if anything failed.
If the APNs finds something wrong with a notification, it will write back the identifier and error code. As this involves transmission to and from the server, it takes just a little while to get this failure info. This method should therefore be invoked a little (say a second) after pushing to see if anything was wrong. On a slow connection this might take longer than the interval between push messages, in which case the reported notification was *not* the last one sent.
From the server we only get the notification identifier and the error message. This method translates this back into the original notification by keeping track of all notifications sent in the past 30 seconds. If somehow the original notification cannot be found, it will assign `NSNull`.
Usually, when a notification fails, the server will drop the connection. To prevent this from causing any more problems, the connection can be reestablished by setting it to reconnect automatically.
@see trimIdentifiers
@see feedbackSpan
*/
func readFailed(_ notification: NWNotification, autoReconnect reconnect: Bool) throws {
var identifier: Int = 0
var apnError: Error? = nil
var read: Bool? = try? self.pusher.readFailedIdentifier(identifier, apnError: apnError)
if read == nil {
return read!
}
if apnError != nil {
var n: NWNotification? = self.notificationForIdentifier[(identifier)][0]
if notification {
notification = n ?? (NSNull() as? NWNotification)
}
if self.delegate.responds(to: Selector("notification:didFailWithError:")) {
self.delegate.notification(n, didFailWithError: apnError)
}
if reconnect {
try? self.reconnect()
}
}
return true
}
/** Let go of old notification, after you read the failed notifications.
This class keeps track of all notifications sent so we can look them up later based on their identifier. This allows it to translate identifiers back into the original notification. To limit the amount of memory all older notifications should be trimmed from this lookup, which is done by this method. This is done based on the `feedbackSpan`, which defaults to 30 seconds.
Be careful not to call this function without first reading all failed notifications, using `readFailed:autoReconnect:error:`.
@see readFailed:autoReconnect:error:
@see feedbackSpan
*/
func trimIdentifiers() -> Bool {
var oldBefore = Date(timeIntervalSinceNow: -self.feedbackSpan)
var old: [Any] = Array(self.notificationForIdentifier.keysOfEntries(passingTest: {(_ key: Any, _ obj: Any, _ stop: Bool) -> BOOL in
return oldBefore.compare(obj[1]) == .orderedDescending
}))
for k in old { self.notificationForIdentifier.removeValueForKey(k) }
return !!old.count
}
// deprecated
class func connect(with delegate: NWHubDelegate, identity: NWIdentityRef, error: Error?) -> Self {
return try? self.connect(with: delegate, identity: identity, environment: NWEnvironmentAuto)!
}
class func connect(with delegate: NWHubDelegate, pkcs12Data data: Data, password: String, error: Error?) -> Self {
return try? self.connect(with: delegate, identity: data, environment: NWEnvironmentAuto)!
}
func connect(withIdentity identity: NWIdentityRef) throws {
return try? self.connect(withIdentity: identity, environment: NWEnvironmentAuto)!
}
func connect(withPKCS12Data data: Data, password: String) throws {
return try? self.connect(withPKCS12Data: data, password: password, environment: NWEnvironmentAuto)!
}
var notificationForIdentifier = [AnyHashable: Any]()
convenience override init() {
return self.init(NWPusher(), delegate: nil)
}
// MARK: - Connecting
// MARK: - Pushing without NSError
// MARK: - Pushing with NSError
func pushNotifications(_ notifications: [Any], autoReconnect reconnect: Bool) throws {
for notification: NWNotification in notifications {
var success: Bool? = try? self.push(notification, autoReconnect: reconnect)
if success == nil {
return success!
}
}
return true
}
// MARK: - Reading failed
func readFailed(_ notifications: [Any], max: Int, autoReconnect reconnect: Bool) throws {
var n: [Any] = []
for i in 0..<max {
var notification: NWNotification? = nil
var read: Bool? = try? self.readFailed(notification, autoReconnect: reconnect)
if read == nil {
return read!
}
if notification == nil {
break
}
n.append(notification)
}
if !notifications.isEmpty {
notifications = n
}
self.trimIdentifiers()
return true
}
// MARK: - Deprecated
}
| bsd-2-clause | ec5709ca5fa1cb05fec78013a3abac47 | 45.871622 | 489 | 0.672121 | 4.93561 | false | false | false | false |
LawrenceHan/ActionStageSwift | ActionStageSwift/AppDelegate.swift | 1 | 4569 | //
// AppDelegate.swift
// ActionStageSwift
//
// Created by Hanguang on 2017/3/7.
// Copyright © 2017年 Hanguang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
LHWActor.registerActorClass(AddCellActor.self)
LHWActor.registerActorClass(BlockActor.self)
// let stageQueueSpecific = "com.hanguang.app.ActionStageSwift.StageDispatchQueue"
// let stageQueueSpecificKey = DispatchSpecificKey<String>()
// let mainStageQueue: DispatchQueue
// let globalStageQueue: DispatchQueue
// let highPriorityStageQueue: DispatchQueue
//
//
// var str1: [String] = []
// var str2: [String] = []
// for i in 0..<30 {
// str1.append("\(i)")
// }
// let item1: [String] = str1
//
// for i in 30..<60 {
// str2.append("\(i)")
// }
// let item2: [String] = str2
//
// for text in item1 {
// globalGraphQueue.async {
// print(text)
// }
// }
//
// for text in item2 {
// highPriorityGraphQueue.async {
// print(text)
// }
// }
// let house1Folks = ["Joe", "Jack", "Jill"];
// let house2Folks = ["Irma", "Irene", "Ian"];
//
// let partyLine = DispatchQueue(label: "party line")
// let house1Queue = DispatchQueue(label: "house 1", attributes: .concurrent, target: partyLine)
// let house2Queue = DispatchQueue(label: "house 2", attributes: .concurrent, target: partyLine)
//
// for caller in house1Folks {
// house1Queue.async { [unowned self] in
// self.makeCall(queue: house1Queue, caller: caller, callees: house2Folks)
// }
// }
//
// for caller in house2Folks {
// house2Queue.async { [unowned self] in
// self.makeCall(queue: house1Queue, caller: caller, callees: house1Folks)
// }
// }
return true
}
func makeCall(queue: DispatchQueue, caller: String, callees: [String]) {
let targetIndex: Int = Int(arc4random()) % callees.count
let callee = callees[targetIndex]
print("\(caller) is calling \(callee)")
sleep(1)
print("...\(caller) is done calling \(callee)")
queue.asyncAfter(deadline: .now() + (Double(Int(arc4random()) % 1000)) * 0.001) { [unowned self] in
self.makeCall(queue: queue, caller: caller, callees: callees)
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 82d09f8e409ae6b4b1344b3ca0ec343a | 40.135135 | 285 | 0.632939 | 4.543284 | false | false | false | false |
alexames/flatbuffers | swift/Sources/FlatBuffers/Constants.swift | 1 | 3103 | /*
* Copyright 2021 Google Inc. 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.
*/
#if !os(WASI)
#if os(Linux)
import CoreFoundation
#else
import Foundation
#endif
#else
import SwiftOverlayShims
#endif
/// A boolean to see if the system is littleEndian
let isLitteEndian: Bool = {
let number: UInt32 = 0x12345678
return number == number.littleEndian
}()
/// Constant for the file id length
let FileIdLength = 4
/// Type aliases
public typealias Byte = UInt8
public typealias UOffset = UInt32
public typealias SOffset = Int32
public typealias VOffset = UInt16
/// Maximum size for a buffer
public let FlatBufferMaxSize = UInt32
.max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
/// Protocol that All Scalars should conform to
///
/// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
public protocol Scalar: Equatable {
associatedtype NumericValue
var convertedEndian: NumericValue { get }
}
extension Scalar where Self: Verifiable {}
extension Scalar where Self: FixedWidthInteger {
/// Converts the value from BigEndian to LittleEndian
///
/// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
public var convertedEndian: NumericValue {
self as! Self.NumericValue
}
}
extension Double: Scalar, Verifiable {
public typealias NumericValue = UInt64
public var convertedEndian: UInt64 {
bitPattern.littleEndian
}
}
extension Float32: Scalar, Verifiable {
public typealias NumericValue = UInt32
public var convertedEndian: UInt32 {
bitPattern.littleEndian
}
}
extension Bool: Scalar, Verifiable {
public var convertedEndian: UInt8 {
self == true ? 1 : 0
}
public typealias NumericValue = UInt8
}
extension Int: Scalar, Verifiable {
public typealias NumericValue = Int
}
extension Int8: Scalar, Verifiable {
public typealias NumericValue = Int8
}
extension Int16: Scalar, Verifiable {
public typealias NumericValue = Int16
}
extension Int32: Scalar, Verifiable {
public typealias NumericValue = Int32
}
extension Int64: Scalar, Verifiable {
public typealias NumericValue = Int64
}
extension UInt8: Scalar, Verifiable {
public typealias NumericValue = UInt8
}
extension UInt16: Scalar, Verifiable {
public typealias NumericValue = UInt16
}
extension UInt32: Scalar, Verifiable {
public typealias NumericValue = UInt32
}
extension UInt64: Scalar, Verifiable {
public typealias NumericValue = UInt64
}
public func FlatBuffersVersion_22_10_26() {}
| apache-2.0 | fa3f5d47fa4edd66cc847f276f585b31 | 24.434426 | 127 | 0.745085 | 4.297784 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/UserInterface/Notifications/AppNotifications.swift | 1 | 27150 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
/// There are two primary components in our system notification integration:
///
/// 1. The `NotificationPresenter` shows system notifications to the user.
/// 2. The `NotificationActionHandler` handles the users interactions with these
/// notifications.
///
/// The NotificationPresenter is driven by the adapter pattern to provide a unified interface to
/// presenting notifications on iOS9, which uses UINotifications vs iOS10+ which supports
/// UNUserNotifications.
///
/// The `NotificationActionHandler`s also need slightly different integrations for UINotifications
/// vs. UNUserNotifications, but because they are integrated at separate system defined callbacks,
/// there is no need for an Adapter, and instead the appropriate NotificationActionHandler is
/// wired directly into the appropriate callback point.
enum AppNotificationCategory: CaseIterable {
case incomingMessage
case incomingMessageFromNoLongerVerifiedIdentity
case infoOrErrorMessage
case threadlessErrorMessage
case incomingCall
case missedCall
case missedCallFromNoLongerVerifiedIdentity
}
enum AppNotificationAction: CaseIterable {
case answerCall
case callBack
case declineCall
case markAsRead
case reply
case showThread
}
struct AppNotificationUserInfoKey {
static let threadId = "Signal.AppNotificationsUserInfoKey.threadId"
static let callBackAddress = "Signal.AppNotificationsUserInfoKey.callBackAddress"
static let localCallId = "Signal.AppNotificationsUserInfoKey.localCallId"
}
extension AppNotificationCategory {
var identifier: String {
switch self {
case .incomingMessage:
return "Signal.AppNotificationCategory.incomingMessage"
case .incomingMessageFromNoLongerVerifiedIdentity:
return "Signal.AppNotificationCategory.incomingMessageFromNoLongerVerifiedIdentity"
case .infoOrErrorMessage:
return "Signal.AppNotificationCategory.infoOrErrorMessage"
case .threadlessErrorMessage:
return "Signal.AppNotificationCategory.threadlessErrorMessage"
case .incomingCall:
return "Signal.AppNotificationCategory.incomingCall"
case .missedCall:
return "Signal.AppNotificationCategory.missedCall"
case .missedCallFromNoLongerVerifiedIdentity:
return "Signal.AppNotificationCategory.missedCallFromNoLongerVerifiedIdentity"
}
}
var actions: [AppNotificationAction] {
switch self {
case .incomingMessage:
return [.markAsRead, .reply]
case .incomingMessageFromNoLongerVerifiedIdentity:
return [.markAsRead, .showThread]
case .infoOrErrorMessage:
return [.showThread]
case .threadlessErrorMessage:
return []
case .incomingCall:
return [.answerCall, .declineCall]
case .missedCall:
return [.callBack, .showThread]
case .missedCallFromNoLongerVerifiedIdentity:
return [.showThread]
}
}
}
extension AppNotificationAction {
var identifier: String {
switch self {
case .answerCall:
return "Signal.AppNotifications.Action.answerCall"
case .callBack:
return "Signal.AppNotifications.Action.callBack"
case .declineCall:
return "Signal.AppNotifications.Action.declineCall"
case .markAsRead:
return "Signal.AppNotifications.Action.markAsRead"
case .reply:
return "Signal.AppNotifications.Action.reply"
case .showThread:
return "Signal.AppNotifications.Action.showThread"
}
}
}
// Delay notification of incoming messages when it's likely to be read by a linked device to
// avoid notifying a user on their phone while a conversation is actively happening on desktop.
let kNotificationDelayForRemoteRead: TimeInterval = 5
let kAudioNotificationsThrottleCount = 2
let kAudioNotificationsThrottleInterval: TimeInterval = 5
protocol NotificationPresenterAdaptee: class {
func registerNotificationSettings() -> Promise<Void>
func notify(category: AppNotificationCategory, title: String?, body: String, threadIdentifier: String?, userInfo: [AnyHashable: Any], sound: OWSSound?)
func notify(category: AppNotificationCategory, title: String?, body: String, threadIdentifier: String?, userInfo: [AnyHashable: Any], sound: OWSSound?, replacingIdentifier: String?)
func cancelNotifications(threadId: String)
func clearAllNotifications()
var hasReceivedSyncMessageRecently: Bool { get }
}
extension NotificationPresenterAdaptee {
var hasReceivedSyncMessageRecently: Bool {
return OWSDeviceManager.shared().hasReceivedSyncMessage(inLastSeconds: 60)
}
}
@objc(OWSNotificationPresenter)
public class NotificationPresenter: NSObject, NotificationsProtocol {
private let adaptee: NotificationPresenterAdaptee
@objc
public override init() {
if #available(iOS 10, *) {
self.adaptee = UserNotificationPresenterAdaptee()
} else {
self.adaptee = LegacyNotificationPresenterAdaptee()
}
super.init()
AppReadiness.runNowOrWhenAppDidBecomeReady {
NotificationCenter.default.addObserver(self, selector: #selector(self.handleMessageRead), name: .incomingMessageMarkedAsRead, object: nil)
}
SwiftSingletons.register(self)
}
// MARK: - Dependencies
var contactsManager: OWSContactsManager {
return Environment.shared.contactsManager
}
var identityManager: OWSIdentityManager {
return OWSIdentityManager.shared()
}
var preferences: OWSPreferences {
return Environment.shared.preferences
}
var previewType: NotificationType {
return preferences.notificationPreviewType()
}
// MARK: -
// It is not safe to assume push token requests will be acknowledged until the user has
// registered their notification settings.
//
// e.g. in the case that Background Fetch is disabled, token requests will be ignored until
// we register user notification settings.
//
// For modern UNUserNotificationSettings, the registration takes a callback, so "waiting" for
// notification settings registration is straight forward, however for legacy UIUserNotification
// settings, the settings request is confirmed in the AppDelegate, where we call this method
// to inform the adaptee it's safe to proceed.
@objc
public func didRegisterLegacyNotificationSettings() {
guard let legacyAdaptee = adaptee as? LegacyNotificationPresenterAdaptee else {
owsFailDebug("unexpected notifications adaptee: \(adaptee)")
return
}
legacyAdaptee.didRegisterUserNotificationSettings()
}
@objc
func handleMessageRead(notification: Notification) {
AssertIsOnMainThread()
switch notification.object {
case let incomingMessage as TSIncomingMessage:
Logger.debug("canceled notification for message: \(incomingMessage)")
cancelNotifications(threadId: incomingMessage.uniqueThreadId)
default:
break
}
}
// MARK: - Presenting Notifications
func registerNotificationSettings() -> Promise<Void> {
return adaptee.registerNotificationSettings()
}
func presentIncomingCall(_ call: SignalCall, callerName: String) {
let remoteAddress = call.remoteAddress
let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress)
let notificationTitle: String?
let threadIdentifier: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .nameNoPreview, .namePreview:
notificationTitle = callerName
threadIdentifier = thread.uniqueId
}
let notificationBody = NotificationStrings.incomingCallBody
let userInfo = [
AppNotificationUserInfoKey.threadId: thread.uniqueId,
AppNotificationUserInfoKey.localCallId: call.localId.uuidString
]
DispatchQueue.main.async {
self.adaptee.notify(category: .incomingCall,
title: notificationTitle,
body: notificationBody,
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: .defaultiOSIncomingRingtone,
replacingIdentifier: call.localId.uuidString)
}
}
func presentMissedCall(_ call: SignalCall, callerName: String) {
let remoteAddress = call.remoteAddress
let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress)
let notificationTitle: String?
let threadIdentifier: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .nameNoPreview, .namePreview:
notificationTitle = callerName
threadIdentifier = thread.uniqueId
}
let notificationBody = NotificationStrings.missedCallBody
let userInfo: [String: Any] = [
AppNotificationUserInfoKey.threadId: thread.uniqueId,
AppNotificationUserInfoKey.callBackAddress: remoteAddress
]
DispatchQueue.main.async {
let sound = self.requestSound(thread: thread)
self.adaptee.notify(category: .missedCall,
title: notificationTitle,
body: notificationBody,
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: sound,
replacingIdentifier: call.localId.uuidString)
}
}
public func presentMissedCallBecauseOfNoLongerVerifiedIdentity(call: SignalCall, callerName: String) {
let remoteAddress = call.remoteAddress
let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress)
let notificationTitle: String?
let threadIdentifier: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .nameNoPreview, .namePreview:
notificationTitle = callerName
threadIdentifier = thread.uniqueId
}
let notificationBody = NotificationStrings.missedCallBecauseOfIdentityChangeBody
let userInfo = [
AppNotificationUserInfoKey.threadId: thread.uniqueId
]
DispatchQueue.main.async {
let sound = self.requestSound(thread: thread)
self.adaptee.notify(category: .missedCallFromNoLongerVerifiedIdentity,
title: notificationTitle,
body: notificationBody,
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: sound,
replacingIdentifier: call.localId.uuidString)
}
}
public func presentMissedCallBecauseOfNewIdentity(call: SignalCall, callerName: String) {
let remoteAddress = call.remoteAddress
let thread = TSContactThread.getOrCreateThread(contactAddress: remoteAddress)
let notificationTitle: String?
let threadIdentifier: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .nameNoPreview, .namePreview:
notificationTitle = callerName
threadIdentifier = thread.uniqueId
}
let notificationBody = NotificationStrings.missedCallBecauseOfIdentityChangeBody
let userInfo: [String: Any] = [
AppNotificationUserInfoKey.threadId: thread.uniqueId,
AppNotificationUserInfoKey.callBackAddress: remoteAddress
]
DispatchQueue.main.async {
let sound = self.requestSound(thread: thread)
self.adaptee.notify(category: .missedCall,
title: notificationTitle,
body: notificationBody,
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: sound,
replacingIdentifier: call.localId.uuidString)
}
}
public func notifyUser(for incomingMessage: TSIncomingMessage, in thread: TSThread, transaction: SDSAnyReadTransaction) {
guard !thread.isMuted else {
return
}
// While batch processing, some of the necessary changes have not been commited.
let rawMessageText = incomingMessage.previewText(with: transaction)
let messageText = rawMessageText.filterStringForDisplay()
let senderName = contactsManager.displayName(for: incomingMessage.authorAddress)
let notificationTitle: String?
let threadIdentifier: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .nameNoPreview, .namePreview:
switch thread {
case is TSContactThread:
notificationTitle = senderName
case let groupThread as TSGroupThread:
notificationTitle = String(format: NotificationStrings.incomingGroupMessageTitleFormat,
senderName,
groupThread.groupNameOrDefault)
default:
owsFailDebug("unexpected thread: \(thread)")
return
}
threadIdentifier = thread.uniqueId
}
let notificationBody: String?
switch previewType {
case .noNameNoPreview, .nameNoPreview:
notificationBody = NotificationStrings.incomingMessageBody
case .namePreview:
notificationBody = messageText
}
assert((notificationBody ?? notificationTitle) != nil)
var category = AppNotificationCategory.incomingMessage
// Don't reply from lockscreen if anyone in this conversation is
// "no longer verified".
for address in thread.recipientAddresses {
if self.identityManager.verificationState(for: address) == .noLongerVerified {
category = AppNotificationCategory.incomingMessageFromNoLongerVerifiedIdentity
break
}
}
let userInfo = [
AppNotificationUserInfoKey.threadId: thread.uniqueId
]
DispatchQueue.main.async {
let sound = self.requestSound(thread: thread)
self.adaptee.notify(category: category,
title: notificationTitle,
body: notificationBody ?? "",
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: sound)
}
}
public func notifyForFailedSend(inThread thread: TSThread) {
let notificationTitle: String?
switch previewType {
case .noNameNoPreview:
notificationTitle = nil
case .nameNoPreview, .namePreview:
notificationTitle = contactsManager.displayNameWithSneakyTransaction(thread: thread)
}
let notificationBody = NotificationStrings.failedToSendBody
let threadId = thread.uniqueId
let userInfo = [
AppNotificationUserInfoKey.threadId: threadId
]
DispatchQueue.main.async {
let sound = self.requestSound(thread: thread)
self.adaptee.notify(category: .infoOrErrorMessage,
title: notificationTitle,
body: notificationBody,
threadIdentifier: nil, // show ungrouped
userInfo: userInfo,
sound: sound)
}
}
public func notifyUser(for errorMessage: TSErrorMessage, thread: TSThread, transaction: SDSAnyWriteTransaction) {
notifyUser(for: errorMessage as TSMessage, thread: thread, wantsSound: true, transaction: transaction)
}
public func notifyUser(for infoMessage: TSInfoMessage, thread: TSThread, wantsSound: Bool, transaction: SDSAnyWriteTransaction) {
notifyUser(for: infoMessage as TSMessage, thread: thread, wantsSound: wantsSound, transaction: transaction)
}
private func notifyUser(for infoOrErrorMessage: TSMessage, thread: TSThread, wantsSound: Bool, transaction: SDSAnyWriteTransaction) {
let notificationTitle: String?
let threadIdentifier: String?
switch self.previewType {
case .noNameNoPreview:
notificationTitle = nil
threadIdentifier = nil
case .namePreview, .nameNoPreview:
notificationTitle = contactsManager.displayName(for: thread, transaction: transaction)
threadIdentifier = thread.uniqueId
}
let notificationBody = infoOrErrorMessage.previewText(with: transaction)
let threadId = thread.uniqueId
let userInfo = [
AppNotificationUserInfoKey.threadId: threadId
]
transaction.addCompletion {
let sound = wantsSound ? self.requestSound(thread: thread) : nil
self.adaptee.notify(category: .infoOrErrorMessage,
title: notificationTitle,
body: notificationBody,
threadIdentifier: threadIdentifier,
userInfo: userInfo,
sound: sound)
}
}
public func notifyUser(for errorMessage: ThreadlessErrorMessage, transaction: SDSAnyWriteTransaction) {
let notificationBody = errorMessage.previewText(with: transaction)
transaction.addCompletion {
let sound = self.checkIfShouldPlaySound() ? OWSSounds.globalNotificationSound() : nil
self.adaptee.notify(category: .threadlessErrorMessage,
title: nil,
body: notificationBody,
threadIdentifier: nil,
userInfo: [:],
sound: sound)
}
}
@objc
public func cancelNotifications(threadId: String) {
self.adaptee.cancelNotifications(threadId: threadId)
}
@objc
public func clearAllNotifications() {
adaptee.clearAllNotifications()
}
// MARK: -
var mostRecentNotifications = TruncatedList<UInt64>(maxLength: kAudioNotificationsThrottleCount)
private func requestSound(thread: TSThread) -> OWSSound? {
guard checkIfShouldPlaySound() else {
return nil
}
return OWSSounds.notificationSound(for: thread)
}
private func checkIfShouldPlaySound() -> Bool {
AssertIsOnMainThread()
guard UIApplication.shared.applicationState == .active else {
return true
}
guard preferences.soundInForeground() else {
return false
}
let now = NSDate.ows_millisecondTimeStamp()
let recentThreshold = now - UInt64(kAudioNotificationsThrottleInterval * Double(kSecondInMs))
let recentNotifications = mostRecentNotifications.filter { $0 > recentThreshold }
guard recentNotifications.count < kAudioNotificationsThrottleCount else {
return false
}
mostRecentNotifications.append(now)
return true
}
}
class NotificationActionHandler {
static let shared: NotificationActionHandler = NotificationActionHandler()
// MARK: - Dependencies
var signalApp: SignalApp {
return SignalApp.shared()
}
var messageSender: MessageSender {
return SSKEnvironment.shared.messageSender
}
var callUIAdapter: CallUIAdapter {
return AppEnvironment.shared.callService.callUIAdapter
}
var notificationPresenter: NotificationPresenter {
return AppEnvironment.shared.notificationPresenter
}
private var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
// MARK: -
func answerCall(userInfo: [AnyHashable: Any]) throws -> Promise<Void> {
guard let localCallIdString = userInfo[AppNotificationUserInfoKey.localCallId] as? String else {
throw NotificationError.failDebug("localCallIdString was unexpectedly nil")
}
guard let localCallId = UUID(uuidString: localCallIdString) else {
throw NotificationError.failDebug("unable to build localCallId. localCallIdString: \(localCallIdString)")
}
callUIAdapter.answerCall(localId: localCallId)
return Promise.value(())
}
func callBack(userInfo: [AnyHashable: Any]) throws -> Promise<Void> {
guard let address = userInfo[AppNotificationUserInfoKey.callBackAddress] as? SignalServiceAddress else {
throw NotificationError.failDebug("address was unexpectedly nil")
}
callUIAdapter.startAndShowOutgoingCall(address: address, hasLocalVideo: false)
return Promise.value(())
}
func declineCall(userInfo: [AnyHashable: Any]) throws -> Promise<Void> {
guard let localCallIdString = userInfo[AppNotificationUserInfoKey.localCallId] as? String else {
throw NotificationError.failDebug("localCallIdString was unexpectedly nil")
}
guard let localCallId = UUID(uuidString: localCallIdString) else {
throw NotificationError.failDebug("unable to build localCallId. localCallIdString: \(localCallIdString)")
}
callUIAdapter.localHangupCall(localId: localCallId)
return Promise.value(())
}
private func threadWithSneakyTransaction(threadId: String) -> TSThread? {
return databaseStorage.readReturningResult { transaction in
return TSThread.anyFetch(uniqueId: threadId, transaction: transaction)
}
}
func markAsRead(userInfo: [AnyHashable: Any]) throws -> Promise<Void> {
guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else {
throw NotificationError.failDebug("threadId was unexpectedly nil")
}
guard let thread = threadWithSneakyTransaction(threadId: threadId) else {
throw NotificationError.failDebug("unable to find thread with id: \(threadId)")
}
return markAsRead(thread: thread)
}
func reply(userInfo: [AnyHashable: Any], replyText: String) throws -> Promise<Void> {
guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else {
throw NotificationError.failDebug("threadId was unexpectedly nil")
}
guard let thread = threadWithSneakyTransaction(threadId: threadId) else {
throw NotificationError.failDebug("unable to find thread with id: \(threadId)")
}
return markAsRead(thread: thread).then { () -> Promise<Void> in
let sendPromise = ThreadUtil.sendMessageNonDurably(text: replyText,
thread: thread,
quotedReplyModel: nil,
messageSender: self.messageSender)
return sendPromise.recover { error in
Logger.warn("Failed to send reply message from notification with error: \(error)")
self.notificationPresenter.notifyForFailedSend(inThread: thread)
}
}
}
func showThread(userInfo: [AnyHashable: Any]) throws -> Promise<Void> {
guard let threadId = userInfo[AppNotificationUserInfoKey.threadId] as? String else {
throw NotificationError.failDebug("threadId was unexpectedly nil")
}
// If this happens when the the app is not, visible we skip the animation so the thread
// can be visible to the user immediately upon opening the app, rather than having to watch
// it animate in from the homescreen.
let shouldAnimate = UIApplication.shared.applicationState == .active
signalApp.presentConversationAndScrollToFirstUnreadMessage(forThreadId: threadId, animated: shouldAnimate)
return Promise.value(())
}
private func markAsRead(thread: TSThread) -> Promise<Void> {
return databaseStorage.writePromise { transaction in
thread.markAllAsRead(with: transaction)
}
}
}
extension ThreadUtil {
static var databaseStorage: SDSDatabaseStorage {
return SSKEnvironment.shared.databaseStorage
}
class func sendMessageNonDurably(text: String, thread: TSThread, quotedReplyModel: OWSQuotedReplyModel?, messageSender: MessageSender) -> Promise<Void> {
return Promise { resolver in
self.databaseStorage.read { transaction in
_ = self.sendMessageNonDurably(withText: text,
in: thread,
quotedReplyModel: quotedReplyModel,
transaction: transaction,
messageSender: messageSender,
completion: resolver.resolve)
}
}
}
}
enum NotificationError: Error {
case assertionError(description: String)
}
extension NotificationError {
static func failDebug(_ description: String) -> NotificationError {
owsFailDebug(description)
return NotificationError.assertionError(description: description)
}
}
struct TruncatedList<Element> {
let maxLength: Int
private var contents: [Element] = []
init(maxLength: Int) {
self.maxLength = maxLength
}
mutating func append(_ newElement: Element) {
var newElements = self.contents
newElements.append(newElement)
self.contents = Array(newElements.suffix(maxLength))
}
}
extension TruncatedList: Collection {
typealias Index = Int
var startIndex: Index {
return contents.startIndex
}
var endIndex: Index {
return contents.endIndex
}
subscript (position: Index) -> Element {
return contents[position]
}
func index(after i: Index) -> Index {
return contents.index(after: i)
}
}
| gpl-3.0 | 0722ab306681c64822403377cacdca6d | 36.551867 | 185 | 0.642615 | 6.113488 | false | false | false | false |
AbooJan/AJ_UIKit | AJ_UIKit/AJ_UIKit/Classes/CommonButton.swift | 1 | 2201 | //
// CommonButton.swift
// AJ_UIKit
//
// Created by aboojan on 16/4/10.
// Copyright © 2016年 aboojan. All rights reserved.
//
import UIKit
class CommonButton: UIButton {
//MARK: 重写
override init(frame: CGRect) {
super.init(frame: frame);
setupView();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
setupView();
}
override var backgroundColor: UIColor?{
didSet{
let btnImgSize = CGSizeMake(5.0, 5.0);
let normalColor = backgroundColor;
let highlightColor = darkedColor(normalColor!);
let normalImg = imageWithColor(normalColor!, size: btnImgSize);
let highlightImg = imageWithColor(highlightColor, size: btnImgSize);
super.setBackgroundImage(normalImg, forState: .Normal);
super.setBackgroundImage(highlightImg, forState: .Selected);
super.setBackgroundImage(highlightImg, forState: .Highlighted)
}
}
//MARK: 自定义
private func setupView() {
self.layer.cornerRadius = CommonDefine().CORNER_RADIUS;
self.layer.masksToBounds = true;
}
private func darkedColor(originalColor:UIColor) -> UIColor{
let components = CGColorGetComponents(originalColor.CGColor);
let r = Float.init(components[0]);
let g = Float.init(components[1]) - 0.2;
let b = Float.init(components[2]) - 0.1;
let changedColor = UIColor.init(colorLiteralRed: r, green: g, blue: b, alpha: 1.0);
return changedColor;
}
private func imageWithColor(color:UIColor, size:CGSize) -> UIImage{
let rect = CGRectMake(0.0, 0.0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
let context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
let theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
}
| mit | cb0c58a703b60ea429f212b61ebf1449 | 28.173333 | 91 | 0.604205 | 4.851441 | false | false | false | false |
huonw/swift | test/IRGen/protocol_metadata.swift | 1 | 7155 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
// REQUIRES: CPU=x86_64
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// CHECK: @"$S17protocol_metadata1AMp" = hidden constant %swift.protocol {
// -- size 72
// -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[A_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1AMp", i32 0, i32 11) to i64)) to i32)
// CHECK-SAME: }
// CHECK: @"$S17protocol_metadata1BMp" = hidden constant %swift.protocol {
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[B_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1BMp", i32 0, i32 11) to i64)) to i32)
// CHECK: }
// CHECK: @"$S17protocol_metadata1CMp" = hidden constant %swift.protocol {
// -- flags: 1 = Swift | 4 = Needs Witness Table
// CHECK-SAME: i32 72, i32 5,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x %swift.protocol_requirement]* [[C_REQTS:@".*"]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata1CMp", i32 0, i32 11) to i64)) to i32)
// CHECK-SAME: }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, [1 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// CHECK: [[A_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }]
// CHECK: [[B_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }]
// CHECK: [[C_REQTS]] = internal constant [1 x %swift.protocol_requirement] [%swift.protocol_requirement { i32 17, i32 0, i32 0 }]
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 2,
// CHECK: %swift.protocol* @"$S17protocol_metadata1AMp",
// CHECK: %swift.protocol* @"$S17protocol_metadata1BMp"
// CHECK: }
// CHECK: [[AB_REQTS:@".*"]] = internal constant [3 x %swift.protocol_requirement] [%swift.protocol_requirement zeroinitializer, %swift.protocol_requirement zeroinitializer, %swift.protocol_requirement { i32 17, i32 0, i32 0 }]
// CHECK: @"$S17protocol_metadata2ABMp" = hidden constant %swift.protocol {
// CHECK-SAME: [[AB_INHERITED]]
// CHECK-SAME: i32 72, i32 7,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x %swift.protocol_requirement]* [[AB_REQTS]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.protocol, %swift.protocol* @"$S17protocol_metadata2ABMp", i32 0, i32 11) to i64)) to i32)
// CHECK-SAME: }
// CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 3,
// CHECK: %swift.protocol* @"$S17protocol_metadata1AMp",
// CHECK: %swift.protocol* @"$S17protocol_metadata1BMp",
// CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_
// CHECK: }
protocol Comprehensive {
associatedtype Assoc : A
init()
func instanceMethod()
static func staticMethod()
var instance: Assoc { get set }
static var global: Assoc { get set }
}
// CHECK: [[COMPREHENSIVE_REQTS:@".*"]] = internal constant [11 x %swift.protocol_requirement]
// CHECK-SAME: [%swift.protocol_requirement { i32 6, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 21, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 5, i32 0, i32 0 }]
// CHECK: [[COMPREHENSIVE_ASSOC_NAME:@.*]] = private constant [6 x i8] c"Assoc\00"
// CHECK: @"$S17protocol_metadata13ComprehensiveMp" = hidden constant %swift.protocol
// CHECK-SAME: i32 72, i32 7, i32 11,
// CHECK-SAME: [11 x %swift.protocol_requirement]* [[COMPREHENSIVE_REQTS]]
// CHECK-SAME: i32 0
// CHECK-SAME: i32 trunc
// CHECK-SAME: [6 x i8]* [[COMPREHENSIVE_ASSOC_NAME]]
func reify_metadata<T>(_ x: T) {}
// CHECK: define hidden swiftcc void @"$S17protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F"
func protocol_types(_ a: A,
abc: A & B & C,
abco: A & B & C & O) {
// CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp"
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, %swift.protocol** {{%.*}})
reify_metadata(a)
// CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp"
// CHECK: store %swift.protocol* @"$S17protocol_metadata1BMp"
// CHECK: store %swift.protocol* @"$S17protocol_metadata1CMp"
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, %swift.protocol** {{%.*}})
reify_metadata(abc)
// CHECK: store %swift.protocol* @"$S17protocol_metadata1AMp"
// CHECK: store %swift.protocol* @"$S17protocol_metadata1BMp"
// CHECK: store %swift.protocol* @"$S17protocol_metadata1CMp"
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol*
// CHECK: store %swift.protocol* [[O_REF_BITCAST]]
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, %swift.protocol** {{%.*}})
reify_metadata(abco)
}
| apache-2.0 | 050667f5746e1c61f445c6d7057db092 | 50.847826 | 251 | 0.662753 | 3.092048 | false | false | false | false |
peteratseneca/dps923winter2015 | Week_10/Places/Classes/CDStack.swift | 1 | 6341 | //
// CDStack.swift
// Classes
//
// Created by Peter McIntyre on 2015-02-01.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import CoreData
class CDStack {
// MARK: - Public property with lazy initializer
lazy var managedObjectContext: NSManagedObjectContext? = {
// Create the MOC
var moc = NSManagedObjectContext()
// Configure it
if self.persistentStoreCoordinator != nil {
moc.persistentStoreCoordinator = self.persistentStoreCoordinator
return moc
} else {
// If this code block executes, there's a problem in the MOM or PSC
return nil
}
}()
// MARK: - Internal properties with lazy initializers
lazy private var applicationDocumentsDirectory: NSURL = {
return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as! NSURL
}()
lazy private var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// Create the PSC
var psc: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
// Get the NSURL to the store file
let storeURL: NSURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ObjectStore.sqlite")
// Configure lightweight migration
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
// Prepare an error object
var error: NSError? = nil
// Configure the PSC with the store file
if (psc!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) == nil) {
// This code block will run if there is an error
assert(false, "Persistent store coordinator is nil")
println("Persistent store coordinator could not be created (CDStack)")
println("Error \(error), \(error!.userInfo)")
}
return psc
}()
lazy private var managedObjectModel: NSManagedObjectModel = {
// Get the NSURL to the data model file
let modelURL = NSBundle.mainBundle().URLForResource("ObjectModel", withExtension: "momd")!
if let mom = NSManagedObjectModel(contentsOfURL: modelURL) {
// Return the result
return mom
} else {
// This code block will run if there is an error
assert(false, "Managed object model is nil")
println("Object model was not found (CDStack)")
}
}()
// MARK: - Public methods
// Save the managed object context
func saveContext() {
// Create an error object
var error: NSError? = nil
// If there are changes to save, attempt to save them
if self.managedObjectContext!.hasChanges && !self.managedObjectContext!.save(&error) {
// This code block will run if there is an error
assert(false, "Unable to save the changes")
println("Unable to save the changes (CDStack)")
println("Error \(error), \(error!.userInfo)")
}
}
// Fetched results controller factory
func frcForEntityNamed(entityName: String, withPredicateFormat predicate: String?, predicateObject: [AnyObject]?, sortDescriptors: String?, andSectionNameKeyPath sectionName: String?) -> NSFetchedResultsController {
// This method will create and return a fully-configured fetched results controller (frc)
// Its arguments are simple strings, for entity name, predicate, and sort descriptors
// sortDescriptors can be nil, or a comma-separated list of attribute-boolean (true or false) pairs
// After initialization, the code can change the configuration if needed
// Before using an frc, you must call the performFetch method
// Create the fetch request
//NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
var fetchRequest: NSFetchRequest = NSFetchRequest()
// Configure the entity name
let entity: NSEntityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: self.managedObjectContext!)!
fetchRequest.entity = entity
// Set the batch size to a reasonable number
fetchRequest.fetchBatchSize = 20
// Configure the predicate
if predicate != nil {
fetchRequest.predicate = NSPredicate(format: predicate!, argumentArray: predicateObject!)
}
// Configure the sort descriptors
if sortDescriptors != nil {
// Create an array to accumulate the sort descriptors
var sdArray: [NSSortDescriptor] = []
// Make an array from the passed-in string
// Examples include...
// nil
// attribute1,true
// attribute1,true,attribute2,false
// etc.
var sdStrings: [String] = sortDescriptors!.componentsSeparatedByString(",")
// Iterate through the sdStrings array, and make sort descriptor objects
for var i = 0; i < sdStrings.count; i+=2 {
let sd: NSSortDescriptor = NSSortDescriptor(key: sdStrings[i], ascending: NSString(string: sdStrings[i + 1]).boolValue)
// Add to the sort descriptors array
sdArray.append(sd)
}
fetchRequest.sortDescriptors = sdArray
}
// Important note!
// This factory does NOT configure a cache for the fetched results controller
// Therefore, if your app is complex and you need the cache,
// replace "nil" with "entityName" in the following statement
return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: sectionName, cacheName: nil)
}
}
| mit | 190c4b146e02606987164a76b4a0b75a | 37.664634 | 219 | 0.61331 | 5.976437 | false | true | false | false |
samwyndham/DictateSRS | Pods/CSV.swift/Sources/CSV+init.swift | 1 | 1074 | //
// CSV+init.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/13.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
extension CSV {
// TODO: Documentation
/// No overview available.
public init(
stream: InputStream,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
{
try self.init(stream: stream, codecType: UTF8.self, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
}
extension CSV {
// TODO: Documentation
/// No overview available.
public init(
string: String,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter)
throws
{
let iterator = string.unicodeScalars.makeIterator()
try self.init(iterator: iterator, hasHeaderRow: hasHeaderRow, trimFields: trimFields, delimiter: delimiter)
}
}
| mit | d2f6fe86857b3dc587988b21592100c9 | 24.547619 | 133 | 0.650513 | 4.855204 | false | false | false | false |
StYaphet/firefox-ios | UITests/SecurityTests.swift | 6 | 7029 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import EarlGrey
@testable import Client
class SecurityTests: KIFTestCase {
fileprivate var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
BrowserUtils.configEarlGrey()
BrowserUtils.dismissFirstRunUI()
super.setUp()
}
override func beforeEach() {
let testURL = "\(webRoot!)/localhostLoad.html"
//enterUrl(url: testURL)
BrowserUtils.enterUrlAddressBar(typeUrl: testURL)
tester().waitForView(withAccessibilityLabel: "Web content")
tester().waitForWebViewElementWithAccessibilityLabel("Session exploit")
}
/// Tap the Session exploit button, which tries to load the session restore page on localhost
/// in the current tab. Make sure nothing happens.
func testSessionExploit() {
tester().tapWebViewElementWithAccessibilityLabel("Session exploit")
tester().wait(forTimeInterval: 1)
// Make sure the URL doesn't change.
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
XCTAssertEqual(webView.url!.path, "/localhostLoad.html")
// Also make sure the XSS alert doesn't appear.
XCTAssertFalse(tester().viewExistsWithLabel("Local page loaded"))
}
/// Tap the Error exploit button, which tries to load the error page on localhost
/// in a new tab via window.open(). Make sure nothing happens.
func testErrorExploit() {
// We should only have one tab open.
let tabcount:String?
if BrowserUtils.iPad() {
tabcount = tester().waitForView(withAccessibilityIdentifier: "TopTabsViewController.tabsButton")?.accessibilityValue
} else {
tabcount = tester().waitForView(withAccessibilityIdentifier: "TabToolbar.tabsButton")?.accessibilityValue
}
// make sure a new tab wasn't opened.
tester().tapWebViewElementWithAccessibilityLabel("Error exploit")
tester().wait(forTimeInterval: 1.0)
let newTabcount:String?
if BrowserUtils.iPad() {
newTabcount = tester().waitForView(withAccessibilityIdentifier: "TopTabsViewController.tabsButton")?.accessibilityValue
} else {
newTabcount = tester().waitForView(withAccessibilityIdentifier: "TabToolbar.tabsButton")?.accessibilityValue
}
XCTAssert(tabcount != nil && tabcount == newTabcount)
}
/// Tap the New tab exploit button, which tries to piggyback off of an error page
/// to load the session restore exploit. A new tab will load showing an error page,
/// but we shouldn't be able to load session restore.
func testWindowExploit() {
tester().tapWebViewElementWithAccessibilityLabel("New tab exploit")
tester().wait(forTimeInterval: 5)
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
// Make sure the URL doesn't change.
XCTAssert(webView.url == nil)
// Also make sure the XSS alert doesn't appear.
XCTAssertFalse(tester().viewExistsWithLabel("Local page loaded"))
}
/// Tap the URL spoof button, which opens a new window to a host with an invalid port.
/// Since the window has no origin before load, the page is able to modify the document,
/// so make sure we don't show the URL.
func testSpoofExploit() {
tester().tapWebViewElementWithAccessibilityLabel("URL spoof")
// Wait for the window to open.
tester().waitForTappableView(withAccessibilityLabel: "Show Tabs", value: "2", traits: UIAccessibilityTraits.button)
tester().waitForAnimationsToFinish()
// Make sure the URL bar doesn't show the URL since it hasn't loaded.
XCTAssertFalse(tester().viewExistsWithLabel("http://1.2.3.4:1234/"))
// Since the newly opened tab doesn't have a URL/title we can't find its accessibility
// element to close it in teardown. Workaround: load another page first.
BrowserUtils.enterUrlAddressBar(typeUrl: webRoot!)
}
// For blob URLs, just show "blob:" to the user (see bug 1446227)
func testBlobUrlShownAsSchemeOnly() {
let url = "\(webRoot!)/blobURL.html"
// script that will load a blob url
BrowserUtils.enterUrlAddressBar(typeUrl: url)
tester().wait(forTimeInterval: 1)
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
XCTAssert(webView.url!.absoluteString.starts(with: "blob:http://")) // webview internally has "blob:<rest of url>"
let bvc = UIApplication.shared.keyWindow!.rootViewController?.children[0] as! BrowserViewController
XCTAssertEqual(bvc.urlBar.locationView.urlTextField.text, "blob:") // only display "blob:"
}
// Web pages can't have firefox: urls, these should be used external to the app only (see bug 1447853)
func testFirefoxSchemeBlockedOnWebpages() {
let url = "\(webRoot!)/firefoxScheme.html"
BrowserUtils.enterUrlAddressBar(typeUrl: url)
tester().tapWebViewElementWithAccessibilityLabel("go")
tester().wait(forTimeInterval: 1)
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
// Make sure the URL doesn't change.
XCTAssertEqual(webView.url!.absoluteString, url)
}
func closeAllTabs() {
let closeButtonMatchers: [GREYMatcher] =
[grey_accessibilityID("TabTrayController.deleteButton.closeAll"),
grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")!)]
EarlGrey.selectElement(with: grey_accessibilityID("TabTrayController.removeTabsButton")).perform(grey_tap())
EarlGrey.selectElement(with: grey_allOf(closeButtonMatchers)).perform(grey_tap())
}
func testDataURL() {
// Check data urls that are valid
["data-url-ok-1", "data-url-ok-2"].forEach { buttonName in
tester().tapWebViewElementWithAccessibilityLabel(buttonName)
tester().wait(forTimeInterval: 1)
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
XCTAssert(webView.url!.absoluteString.hasPrefix("data:")) // indicates page loaded ok
BrowserUtils.resetToAboutHome()
beforeEach()
}
// Check data url that is not allowed
tester().tapWebViewElementWithAccessibilityLabel("data-url-html-bad")
tester().wait(forTimeInterval: 1)
let webView = tester().waitForView(withAccessibilityLabel: "Web content") as! WKWebView
XCTAssert(webView.url == nil) // indicates page load was blocked
}
override func tearDown() {
BrowserUtils.resetToAboutHome()
super.tearDown()
}
}
| mpl-2.0 | e0060cc717a40ba9cddf8ea8e7fba01f | 44.642857 | 131 | 0.681463 | 5.119446 | false | true | false | false |
alsedi/RippleEffectView | Demo/RippleEffectDemo/RippleEffectView.swift | 1 | 9981 | //
// RippleEffectView.swift
// RippleEffectView
//
// Created by Alex Sergeev on 8/14/16.
// Copyright © 2016 ALSEDI Group. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
enum RippleType {
case oneWave
case heartbeat
}
@IBDesignable
class RippleEffectView: UIView {
typealias CustomizationClosure = (_ totalRows:Int, _ totalColumns:Int, _ currentRow:Int, _ currentColumn:Int, _ originalImage:UIImage)->(UIImage)
typealias VoidClosure = () -> ()
var cellSize:CGSize?
var rippleType: RippleType = .oneWave
var tileImage:UIImage!
var magnitude: CGFloat = -0.6
var animationDuration: Double = 3.5
var isAnimating: Bool = false
fileprivate var tiles = [GridItemView]()
fileprivate var isGridRendered: Bool = false
var tileImageCustomizationClosure: CustomizationClosure? = nil {
didSet {
stopAnimating()
removeGrid()
renderGrid()
}
}
var animationDidStop: VoidClosure?
func setupView() {
if isAnimating {
stopAnimating()
}
removeGrid()
renderGrid()
}
}
// MARK: View operations
extension RippleEffectView {
override func willMove(toSuperview newSuperview: UIView?) {
if let parent = newSuperview, newSuperview != nil {
self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height)
}
}
override func layoutSubviews() {
guard let parent = superview else { return }
self.frame = CGRect(x: 0, y: 0, width: parent.frame.width, height: parent.frame.height)
setupView()
}
}
//MARK: Animations
extension RippleEffectView {
func stopAnimating() {
isAnimating = false
layer.removeAllAnimations()
}
func simulateAnimationEnd() {
waitAndRun(animationDuration){
if let callback = self.animationDidStop {
callback()
}
if self.isAnimating {
self.simulateAnimationEnd()
}
}
}
func startAnimating() {
guard superview != nil else {
return
}
if isGridRendered == false {
renderGrid()
}
isAnimating = true
layer.shouldRasterize = true
simulateAnimationEnd()
for tile in tiles {
let distance = self.distance(fromPoint:tile.position, toPoint:self.center)
var vector = self.normalizedVector(fromPoint:tile.position, toPoint:self.center)
vector = CGPoint(x:vector.x * magnitude * distance, y: vector.y * magnitude * distance)
tile.startAnimatingWithDuration(animationDuration, rippleDelay: animationDuration - 0.0006666 * TimeInterval(distance), rippleOffset: vector)
}
}
}
//MARK: Grid operations
extension RippleEffectView {
func removeGrid() {
for tile in tiles {
tile.removeAllAnimations()
tile.removeFromSuperlayer()
}
tiles.removeAll()
isGridRendered = false
}
func renderGrid() {
guard isGridRendered == false else { return }
guard tileImage != nil else { return }
isGridRendered = true
let itemWidth = (cellSize == nil) ? tileImage.size.width : cellSize!.width
let itemHeight = (cellSize == nil) ? tileImage.size.height : cellSize!.height
let rows = ((self.rows % 2 == 0) ? self.rows + 3 : self.rows + 2)
let columns = ((self.columns % 2 == 0) ? self.columns + 3 : self.columns + 2)
let offsetX = columns / 2
let offsetY = rows / 2
let startPoint = CGPoint(x: center.x - (CGFloat(offsetX) * itemWidth), y: center.y - (CGFloat(offsetY) * itemHeight))
for row in 0..<rows {
for column in 0..<columns {
let tileLayer = GridItemView()
if let imageCustomization = tileImageCustomizationClosure {
tileLayer.tileImage = imageCustomization(self.rows, self.columns, row, column, (tileLayer.tileImage == nil) ? tileImage : tileLayer.tileImage!)
tileLayer.contents = tileLayer.tileImage?.cgImage
} else {
tileLayer.contents = tileImage.cgImage
}
tileLayer.rippleType = rippleType
tileLayer.frame.size = CGSize(width: itemWidth, height: itemHeight)
tileLayer.contentsScale = contentScaleFactor
tileLayer.contentsGravity = kCAGravityResize
tileLayer.position = startPoint
tileLayer.position.x = tileLayer.position.x + (CGFloat(column) * itemWidth)
tileLayer.position.y = tileLayer.position.y + (CGFloat(row) * itemHeight)
tileLayer.shouldRasterize = true
layer.addSublayer(tileLayer)
tiles.append(tileLayer)
}
}
}
var rows: Int {
var size = tileImage.size
if let _ = cellSize {
size = cellSize!
}
return Int(self.frame.height / size.height)
}
var columns: Int {
var size = tileImage.size
if let _ = cellSize {
size = cellSize!
}
return Int(self.frame.width / size.width)
}
}
//MARK: Helper methods
private extension UIView {
func distance(fromPoint:CGPoint,toPoint:CGPoint)->CGFloat {
let nX = (fromPoint.x - toPoint.x)
let nY = (fromPoint.y - toPoint.y)
return sqrt(nX*nX + nY*nY)
}
func normalizedVector(fromPoint:CGPoint,toPoint:CGPoint)->CGPoint {
let length = distance(fromPoint:fromPoint, toPoint:toPoint)
guard length > 0 else { return CGPoint.zero }
return CGPoint(x:(fromPoint.x - toPoint.x)/length, y:(fromPoint.y - toPoint.y)/length)
}
}
private class GridItemView: CALayer {
var tileImage:UIImage?
var rippleType:RippleType = .oneWave
func startAnimatingWithDuration(_ duration: TimeInterval, rippleDelay: TimeInterval, rippleOffset: CGPoint) {
let timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0, 0.2, 1)
let linearFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let zeroPointValue = NSValue(cgPoint: CGPoint.zero)
var animations = [CAAnimation]()
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
if rippleType == .heartbeat {
scaleAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 0.735, 1]
scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, timingFunction]
scaleAnimation.values = [1, 1, 1.35, 1.05, 1.20, 0.95, 1, 1]
} else {
scaleAnimation.keyTimes = [0, 0.5, 0.6, 1]
scaleAnimation.values = [1, 1, 1.15, 1]
scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction]
}
scaleAnimation.beginTime = 0.0
scaleAnimation.duration = duration
animations.append(scaleAnimation)
let positionAnimation = CAKeyframeAnimation(keyPath: "position")
positionAnimation.duration = duration
if rippleType == .heartbeat {
let secondBeat = CGPoint(x:rippleOffset.x, y:rippleOffset.y)
positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, timingFunction, timingFunction, linearFunction]
positionAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 1]
positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(cgPoint:rippleOffset), zeroPointValue, NSValue(cgPoint:secondBeat), NSValue(cgPoint:CGPoint(x:-rippleOffset.x*0.3,y:-rippleOffset.y*0.3)),zeroPointValue, zeroPointValue]
} else {
positionAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction]
positionAnimation.keyTimes = [0, 0.5, 0.6, 1]
positionAnimation.values = [zeroPointValue, zeroPointValue, NSValue(cgPoint:rippleOffset), zeroPointValue]
}
positionAnimation.isAdditive = true
animations.append(positionAnimation)
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = duration
if rippleType == .heartbeat {
opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction]
opacityAnimation.keyTimes = [0, 0.3, 0.4, 0.5, 0.6, 0.69, 1]
opacityAnimation.values = [1, 1, 0.85, 0.75, 0.90, 1, 1]
} else {
opacityAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction]
opacityAnimation.keyTimes = [0, 0.5, 0.6, 0.94, 1]
opacityAnimation.values = [1, 1, 0.45, 1, 1]
}
animations.append(opacityAnimation)
let groupAnimation = CAAnimationGroup()
groupAnimation.repeatCount = Float.infinity
groupAnimation.fillMode = kCAFillModeBackwards
groupAnimation.duration = duration
groupAnimation.beginTime = rippleDelay
groupAnimation.isRemovedOnCompletion = false
groupAnimation.animations = animations
groupAnimation.timeOffset = 0.35 * duration
shouldRasterize = true
add(groupAnimation, forKey: "ripple")
}
func stopAnimating() {
removeAllAnimations()
}
}
func waitAndRun(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
| mit | 7032f3c1f2e609bfd4c20a15a755754a | 34.516014 | 243 | 0.691884 | 4.369527 | false | false | false | false |
puttin/Curator | Curator/CuratorLocation.swift | 1 | 916 | import Foundation
public protocol CuratorLocation {
func asURL() throws -> URL
}
extension CuratorLocation {
func fileReferenceURL() throws -> URL {
let url = try self.standardizedFileURL() as NSURL
guard let fileReferenceURL = url.fileReferenceURL() else {
throw Curator.Error.unableToObtainFileReferenceURL(from: self)
}
return fileReferenceURL as URL
}
func standardizedFileURL() throws -> URL {
let location = self
let url = try location.asURL()
guard url.isFileURL else {
throw Curator.Error.unableToConvertToFileURL(from: location)
}
let standardizedURL = url.standardized
let path = standardizedURL.path
guard !path.isEmpty else {
throw Curator.Error.invalidLocation(location)
}
return standardizedURL
}
}
| mit | 7cc165920cad4cd0dea575fca343b3c8 | 26.757576 | 74 | 0.618996 | 5.264368 | false | false | false | false |
Alexiuce/Tip-for-day | XCWebook/XCWebook/DIVModel.swift | 1 | 761 | //
// DIVModel.swift
// XCWebook
//
// Created by alexiuce on 2017/8/15.
// Copyright © 2017年 alexiuce . All rights reserved.
//
import UIKit
class DIVModel: NSObject {
var href = ""
var text = ""
init(div: String) {
super.init()
let begingRange = (div as NSString).range(of: "href=")
let endRange = (div as NSString).range(of: "</a>")
let hrefLocation = begingRange.location + begingRange.length + 1
href = (div as NSString).substring(with: NSMakeRange(hrefLocation, 20))
let textLocation = hrefLocation + 22
let textLenght = endRange.location - textLocation
text = (div as NSString).substring(with: NSMakeRange(textLocation, textLenght))
}
}
| mit | 9c3d2dde44e8bc92742494d927fd2d88 | 25.068966 | 87 | 0.613757 | 3.818182 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/SwiftImageLoader/UIImageViewExtensions.swift | 1 | 11124 |
#if os(iOS)
import UIKit
// MARK: - UIImageView Associated Value Keys
fileprivate var indexPathIdentifierAssociationKey: UInt8 = 0
fileprivate var completionAssociationKey: UInt8 = 0
// MARK: - UIImageView Extensions
extension UIImageView: AssociatedValue {}
public extension UIImageView {
// MARK: - Associated Values
final internal var indexPathIdentifier: Int {
get {
return getAssociatedValue(key: &indexPathIdentifierAssociationKey, defaultValue: -1)
}
set {
setAssociatedValue(key: &indexPathIdentifierAssociationKey, value: newValue)
}
}
final internal var completion: ((_ finished: Bool, _ error: Error?) -> Void)? {
get {
return getAssociatedValue(key: &completionAssociationKey, defaultValue: nil)
}
set {
setAssociatedValue(key: &completionAssociationKey, value: newValue)
}
}
// MARK: - Image Loading Methods
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a URL `String`.
- parameter urlString: The image URL in the form of a `String`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(urlString: String,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
guard let url = URL(string: urlString) else {
DispatchQueue.main.async {
completion?(false, nil)
}
return
}
loadImage(url: url, placeholder: placeholder, completion: completion)
}
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a `URL`.
- parameter url: The image `URL`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(url: URL,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
let cacheManager = ImageCacheManager.shared
var request = URLRequest(url: url, cachePolicy: cacheManager.session.configuration.requestCachePolicy, timeoutInterval: cacheManager.session.configuration.timeoutIntervalForRequest)
request.addValue("image/*", forHTTPHeaderField: "Accept")
loadImage(request: request, placeholder: placeholder, completion: completion)
}
/**
Asynchronously downloads an image and loads it into the `UIImageView` using a `URLRequest`.
- parameter request: The image URL in the form of a `URLRequest`.
- parameter placeholder: `UIImage?` representing a placeholder image that is loaded into the view while the asynchronous download takes place. The default value is `nil`.
- parameter completion: An optional closure that is called to indicate completion of the intended purpose of this method. It returns two values: the first is a `Bool` indicating whether everything was successful, and the second is `Error?` which will be non-nil should an error occur. The default value is `nil`.
*/
final func loadImage(request: URLRequest,
placeholder: UIImage? = nil,
completion: ((_ success: Bool, _ error: Error?) -> Void)? = nil)
{
self.completion = completion
self.indexPathIdentifier = -1
guard let urlAbsoluteString = request.url?.absoluteString else {
self.completion?(false, nil)
return
}
let cacheManager = ImageCacheManager.shared
let fadeAnimationDuration = cacheManager.fadeAnimationDuration
let sharedURLCache = URLCache.shared
func loadImage(_ image: UIImage) -> Void {
UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: {
self.image = image
})
self.completion?(true, nil)
}
// If there's already a cached image, load it into the image view.
if let image = cacheManager[urlAbsoluteString] {
loadImage(image)
}
// If there's already a cached response, load the image data into the image view.
else if let cachedResponse = sharedURLCache.cachedResponse(for: request), let image = UIImage(data: cachedResponse.data), let creationTimestamp = cachedResponse.userInfo?["creationTimestamp"] as? CFTimeInterval, (Date.timeIntervalSinceReferenceDate - creationTimestamp) < Double(cacheManager.diskCacheMaxAge) {
loadImage(image)
cacheManager[urlAbsoluteString] = image
}
// Either begin downloading the image or become an observer for an existing request.
else {
// Remove the stale disk-cached response (if any).
sharedURLCache.removeCachedResponse(for: request)
// Set the placeholder image if it was provided.
if let placeholder = placeholder {
self.image = placeholder
}
var parentView = self.superview
// Should the image be shown in a cell, walk the view hierarchy to retrieve the index path from the tableview or collectionview.
while parentView != nil {
switch parentView {
case let tableViewCell as UITableViewCell:
// Every tableview cell must be directly embedded within a tableview.
if let tableView = tableViewCell.superview as? UITableView,
let indexPath = tableView.indexPathForRow(at: tableViewCell.center)
{
self.indexPathIdentifier = indexPath.hashValue
}
case let collectionViewCell as UICollectionViewCell:
// Every collectionview cell must be directly embedded within a collectionview.
if let collectionView = collectionViewCell.superview as? UICollectionView,
let indexPath = collectionView.indexPathForItem(at: collectionViewCell.center)
{
self.indexPathIdentifier = indexPath.hashValue
}
default:
break
}
parentView = parentView?.superview
}
let initialIndexIdentifier = self.indexPathIdentifier
// If the image isn't already being downloaded, begin downloading the image.
if cacheManager.isDownloadingFromURL(urlAbsoluteString) == false {
cacheManager.setIsDownloadingFromURL(true, urlString: urlAbsoluteString)
let dataTask = cacheManager.session.dataTask(with: request) {
taskData, taskResponse, taskError in
guard let data = taskData, let response = taskResponse, let image = UIImage(data: data), taskError == nil else {
DispatchQueue.main.async {
cacheManager.setIsDownloadingFromURL(false, urlString: urlAbsoluteString)
cacheManager.removeImageCacheObserversForKey(urlAbsoluteString)
self.completion?(false, taskError)
}
return
}
DispatchQueue.main.async {
if initialIndexIdentifier == self.indexPathIdentifier {
UIView.transition(with: self, duration: fadeAnimationDuration, options: .transitionCrossDissolve, animations: {
self.image = image
})
}
cacheManager[urlAbsoluteString] = image
let responseDataIsCacheable = cacheManager.diskCacheMaxAge > 0 &&
Double(data.count) <= 0.05 * Double(sharedURLCache.diskCapacity) &&
(cacheManager.session.configuration.requestCachePolicy == .returnCacheDataElseLoad ||
cacheManager.session.configuration.requestCachePolicy == .returnCacheDataDontLoad) &&
(request.cachePolicy == .returnCacheDataElseLoad ||
request.cachePolicy == .returnCacheDataDontLoad)
if let httpResponse = response as? HTTPURLResponse, let url = httpResponse.url, responseDataIsCacheable {
if var allHeaderFields = httpResponse.allHeaderFields as? [String: String] {
allHeaderFields["Cache-Control"] = "max-age=\(cacheManager.diskCacheMaxAge)"
if let cacheControlResponse = HTTPURLResponse(url: url, statusCode: httpResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: allHeaderFields) {
let cachedResponse = CachedURLResponse(response: cacheControlResponse, data: data, userInfo: ["creationTimestamp": Date.timeIntervalSinceReferenceDate], storagePolicy: .allowed)
sharedURLCache.storeCachedResponse(cachedResponse, for: request)
}
}
}
self.completion?(true, nil)
}
}
dataTask.resume()
}
// Since the image is already being downloaded and hasn't been cached, register the image view as a cache observer.
else {
weak var weakSelf = self
cacheManager.addImageCacheObserver(weakSelf!, initialIndexIdentifier: initialIndexIdentifier, key: urlAbsoluteString)
}
}
}
}
#endif
| mit | bbb78b27dbe072d4d451754eaaef3a65 | 51.720379 | 320 | 0.592952 | 6.211055 | false | false | false | false |
hovansuit/FoodAndFitness | FoodAndFitness/Controllers/Analysis/AnalysisViewModel.swift | 1 | 6944 | //
// AnalysisViewModel.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/30/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import RealmS
import RealmSwift
import SwiftDate
fileprivate enum FoodNutritionType {
case calories
case protein
case carbs
case fat
}
fileprivate enum ExerciseType {
case calories
case duration
}
fileprivate enum TrackingType {
case calories
case duration
case distance
}
class AnalysisViewModel {
private var eatenCalories: [Int] = [Int]()
private var burnedCalories: [Int] = [Int]()
private var proteins: [Int] = [Int]()
private var carbs: [Int] = [Int]()
private var fat: [Int] = [Int]()
private var durations: [Int] = [Int]()
private var distances: [Int] = [Int]()
init() {
let now = DateInRegion(absoluteDate: Date())
for i in 0..<7 {
let date = now - (7 - i).days
let eaten = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .calories)
let burned = AnalysisViewModel.burnedCalories(at: date.absoluteDate)
let protein = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .protein)
let carbs = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .carbs)
let fat = AnalysisViewModel.nutritionValue(at: date.absoluteDate, type: .fat)
let durationsValue = AnalysisViewModel.durationFitness(at: date.absoluteDate)
let distancesValue = AnalysisViewModel.distanceFitness(at: date.absoluteDate)
self.eatenCalories.append(eaten)
self.burnedCalories.append(burned)
self.proteins.append(protein)
self.carbs.append(carbs)
self.fat.append(fat)
self.durations.append(durationsValue)
self.distances.append(distancesValue)
}
}
func dataForChartView() -> ChartViewCell.Data {
return ChartViewCell.Data(eatenCalories: eatenCalories, burnedCalories: burnedCalories)
}
func dataForFitnessCell() -> AnalysisFitnessCell.Data? {
let caloriesBurnSum = burnedCalories.reduce(0) { (result, value) -> Int in
return result + value
}
let calories = "\(caloriesBurnSum)\(Strings.kilocalories)"
let durationsSum = durations.reduce(0) { (result, value) -> Int in
return result + value
}
let minutes = durationsSum.toMinutes
var duration = ""
if minutes < 1 {
duration = "\(durationsSum)\(Strings.seconds)"
} else {
duration = "\(minutes)\(Strings.minute)"
}
let distanceSum = distances.reduce(0) { (result, value) -> Int in
return result + value
}
let distance = "\(distanceSum)\(Strings.metters)"
return AnalysisFitnessCell.Data(calories: calories, duration: duration, distance: distance)
}
func dataForNutritionCell() -> AnalysisNutritionCell.Data? {
let caloriesSum = eatenCalories.reduce(0) { (result, value) -> Int in
return result + value
}
let calories = "\(caloriesSum)\(Strings.kilocalories)"
let proteinSum = proteins.reduce(0) { (result, value) -> Int in
return result + value
}
let protein = "\(proteinSum)\(Strings.gam)"
let carbsSum = self.carbs.reduce(0) { (result, value) -> Int in
return result + value
}
let carbs = "\(carbsSum)\(Strings.gam)"
let fatSum = self.fat.reduce(0) { (result, value) -> Int in
return result + value
}
let fat = "\(fatSum)\(Strings.gam)"
return AnalysisNutritionCell.Data(calories: calories, protein: protein, carbs: carbs, fat: fat)
}
private class func exerciseValue(at date: Date, type: ExerciseType) -> Int {
let userExercises = RealmS().objects(UserExercise.self).filter { (userExercise) -> Bool in
guard let me = User.me, let user = userExercise.userHistory?.user else { return false }
return me.id == user.id && userExercise.createdAt.isInSameDayOf(date: date)
}
let value = userExercises.map { (userExercise) -> Int in
switch type {
case .calories:
return userExercise.calories
case .duration:
return userExercise.duration
}
}.reduce(0) { (result, value) -> Int in
return result + value
}
return value
}
private class func trackingValue(at date: Date, type: TrackingType) -> Int {
let trackings = RealmS().objects(Tracking.self).filter { (tracking) -> Bool in
guard let me = User.me, let user = tracking.userHistory?.user else { return false }
return me.id == user.id && tracking.createdAt.isInSameDayOf(date: date)
}
let value = trackings.map { (tracking) -> Int in
switch type {
case .calories:
return tracking.caloriesBurn
case .duration:
return tracking.duration
case .distance:
return tracking.distance
}
}.reduce(0) { (result, value) -> Int in
return result + value
}
return value
}
private class func nutritionValue(at date: Date, type: FoodNutritionType) -> Int {
let userFoods = RealmS().objects(UserFood.self).filter { (userFood) -> Bool in
guard let me = User.me, let user = userFood.userHistory?.user else { return false }
return me.id == user.id && userFood.createdAt.isInSameDayOf(date: date)
}
let value = userFoods.map { (userFood) -> Int in
switch type {
case .calories:
return userFood.calories
case .protein:
return userFood.protein
case .carbs:
return userFood.carbs
case .fat:
return userFood.fat
}
}.reduce(0) { (result, value) -> Int in
return result + value
}
return value
}
private class func burnedCalories(at date: Date) -> Int {
let exercisesBurn = AnalysisViewModel.exerciseValue(at: date, type: .calories)
let trackingsBurn = AnalysisViewModel.trackingValue(at: date, type: .calories)
return exercisesBurn + trackingsBurn
}
private class func durationFitness(at date: Date) -> Int {
let exerciseDuration = AnalysisViewModel.exerciseValue(at: date, type: .duration)
let trackingDuration = AnalysisViewModel.trackingValue(at: date, type: .duration)
return exerciseDuration + trackingDuration
}
private class func distanceFitness(at date: Date) -> Int {
let distace = AnalysisViewModel.trackingValue(at: date, type: .distance)
return distace
}
}
| mit | 766a72cb88c30461f5cff66eae34b3b5 | 35.930851 | 103 | 0.604638 | 4.490944 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/Link/Controllers/PayWithLinkViewController-WalletViewModel.swift | 1 | 9638 | //
// PayWithLinkViewController-WalletViewModel.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 3/30/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeUICore
@_spi(STP) import StripePaymentsUI
protocol PayWithLinkWalletViewModelDelegate: AnyObject {
func viewModelDidChange(_ viewModel: PayWithLinkViewController.WalletViewModel)
}
extension PayWithLinkViewController {
final class WalletViewModel {
let context: Context
let linkAccount: PaymentSheetLinkAccount
private(set) var paymentMethods: [ConsumerPaymentDetails]
weak var delegate: PayWithLinkWalletViewModelDelegate?
/// Index of currently selected payment method.
var selectedPaymentMethodIndex: Int {
didSet {
if oldValue != selectedPaymentMethodIndex {
delegate?.viewModelDidChange(self)
}
}
}
var supportedPaymentMethodTypes: Set<ConsumerPaymentDetails.DetailsType> {
return linkAccount.supportedPaymentDetailsTypes(for: context.intent)
}
var cvc: String? {
didSet {
if oldValue != cvc {
delegate?.viewModelDidChange(self)
}
}
}
var expiryDate: CardExpiryDate? {
didSet {
if oldValue != expiryDate {
delegate?.viewModelDidChange(self)
}
}
}
/// Currently selected payment method.
var selectedPaymentMethod: ConsumerPaymentDetails? {
guard paymentMethods.indices.contains(selectedPaymentMethodIndex) else {
return nil
}
return paymentMethods[selectedPaymentMethodIndex]
}
/// Whether or not the view should show the instant debit mandate text.
var shouldShowInstantDebitMandate: Bool {
switch selectedPaymentMethod?.details {
case .bankAccount(_):
// Instant debit mandate should be shown when paying with bank account.
return true
default:
return false
}
}
var noticeText: String? {
if shouldRecollectCardExpiryDate {
return STPLocalizedString(
"This card has expired. Update your card info or choose a different payment method.",
"A text notice shown when the user selects an expired card."
)
}
if shouldRecollectCardCVC {
return STPLocalizedString(
"For security, please re-enter your card’s security code.",
"""
A text notice shown when the user selects a card that requires
re-entering the security code (CVV/CVC).
"""
)
}
return nil
}
var shouldShowNotice: Bool {
return noticeText != nil
}
var shouldShowRecollectionSection: Bool {
return (
shouldRecollectCardCVC ||
shouldRecollectCardExpiryDate
)
}
var shouldShowApplePayButton: Bool {
return (
context.shouldOfferApplePay &&
context.configuration.isApplePayEnabled
)
}
var shouldUseCompactConfirmButton: Bool {
// We should use a compact confirm button whenever we display the Apple Pay button.
return shouldShowApplePayButton
}
var cancelButtonConfiguration: Button.Configuration {
return shouldShowApplePayButton ? .linkPlain() : .linkSecondary()
}
/// Whether or not we must re-collect the card CVC.
var shouldRecollectCardCVC: Bool {
switch selectedPaymentMethod?.details {
case .card(let card):
return card.shouldRecollectCardCVC || card.hasExpired
default:
// Only cards have CVC.
return false
}
}
var shouldRecollectCardExpiryDate: Bool {
switch selectedPaymentMethod?.details {
case .card(let card):
return card.hasExpired
case .bankAccount(_), .none:
// Only cards have expiry date.
return false
}
}
/// CTA
var confirmButtonCallToAction: ConfirmButton.CallToActionType {
return context.intent.callToAction
}
var confirmButtonStatus: ConfirmButton.Status {
if selectedPaymentMethod == nil {
return .disabled
}
if !selectedPaymentMethodIsSupported {
// Selected payment method not supported
return .disabled
}
if shouldRecollectCardCVC && cvc == nil {
return .disabled
}
if shouldRecollectCardExpiryDate && expiryDate == nil {
return .disabled
}
return .enabled
}
var cardBrand: STPCardBrand? {
switch selectedPaymentMethod?.details {
case .card(let card):
return card.brand
default:
return nil
}
}
var selectedPaymentMethodIsSupported: Bool {
guard let selectedPaymentMethod = selectedPaymentMethod else {
return false
}
return supportedPaymentMethodTypes.contains(selectedPaymentMethod.type)
}
init(
linkAccount: PaymentSheetLinkAccount,
context: Context,
paymentMethods: [ConsumerPaymentDetails]
) {
self.linkAccount = linkAccount
self.context = context
self.paymentMethods = paymentMethods
self.selectedPaymentMethodIndex = Self.determineInitiallySelectedPaymentMethod(
context: context,
paymentMethods: paymentMethods
)
}
func deletePaymentMethod(at index: Int, completion: @escaping (Result<Void, Error>) -> Void) {
let paymentMethod = paymentMethods[index]
linkAccount.deletePaymentDetails(id: paymentMethod.stripeID) { [self] result in
switch result {
case .success:
paymentMethods.remove(at: index)
delegate?.viewModelDidChange(self)
case .failure(_):
break
}
completion(result)
}
}
func setDefaultPaymentMethod(
at index: Int,
completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void
) {
let paymentMethod = paymentMethods[index]
linkAccount.updatePaymentDetails(
id: paymentMethod.stripeID,
updateParams: UpdatePaymentDetailsParams(isDefault: true, details: nil)
) { [self] result in
if case let .success(updatedPaymentDetails) = result {
paymentMethods.forEach({ $0.isDefault = false })
paymentMethods[index] = updatedPaymentDetails
}
completion(result)
}
}
func updatePaymentMethod(_ paymentMethod: ConsumerPaymentDetails) -> Int? {
guard let index = paymentMethods.firstIndex(where: {$0.stripeID == paymentMethod.stripeID}) else {
return nil
}
if paymentMethod.isDefault {
paymentMethods.forEach({ $0.isDefault = false })
}
paymentMethods[index] = paymentMethod
delegate?.viewModelDidChange(self)
return index
}
func updateExpiryDate(completion: @escaping (Result<ConsumerPaymentDetails, Error>) -> Void) {
guard
let id = selectedPaymentMethod?.stripeID,
let expiryDate = self.expiryDate
else {
assertionFailure("Called with no selected payment method or expiry date provided.")
return
}
linkAccount.updatePaymentDetails(
id: id,
updateParams: UpdatePaymentDetailsParams(details: .card(expiryDate: expiryDate)),
completion: completion
)
}
}
}
private extension PayWithLinkViewController.WalletViewModel {
static func determineInitiallySelectedPaymentMethod(
context: PayWithLinkViewController.Context,
paymentMethods: [ConsumerPaymentDetails]
) -> Int {
var indexOfLastAddedPaymentMethod: Int? {
guard let lastAddedID = context.lastAddedPaymentDetails?.stripeID else {
return nil
}
return paymentMethods.firstIndex(where: { $0.stripeID == lastAddedID })
}
var indexOfDefaultPaymentMethod: Int? {
return paymentMethods.firstIndex(where: { $0.isDefault })
}
return indexOfLastAddedPaymentMethod ?? indexOfDefaultPaymentMethod ?? 0
}
}
/// Helper functions for ConsumerPaymentDetails
private extension ConsumerPaymentDetails {
var paymentMethodType: PaymentSheet.PaymentMethodType {
switch details {
case .card:
return .card
case .bankAccount:
return .linkInstantDebit
}
}
}
| mit | 923b88bb373e9fcc13127a8cbd2f0cb7 | 30.694079 | 110 | 0.565439 | 6.355541 | false | false | false | false |
yisimeng/YSMFactory-swift | YSMFactory-swift/Vendor/YSMWaterFallFlowLayout/YSMWaterFallFlowReadMe.swift | 1 | 2853 | //
// YSMWaterFallFlowReadMe.swift
// YSMFactory-swift
//
// Created by 忆思梦 on 2016/12/8.
// Copyright © 2016年 忆思梦. All rights reserved.
//
/* 瀑布流布局快速使用
class ViewController: UIViewController {
//item的信息(现在为每个item的高度)
var modelArray:[CGFloat] = [CGFloat]()
var collectionView:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
let flowLayout = YSMFlowLayout()
//最小的行间距
flowLayout.minimumLineSpacing = 10
//最小的列间距
flowLayout.minimumInteritemSpacing = 10
//内边距
flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
//设置数据源
flowLayout.dataSource = self
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), collectionViewLayout: flowLayout)
collectionView.dataSource = self
collectionView.backgroundColor = .white
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCellId")
view.addSubview(collectionView)
let blackView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
blackView.backgroundColor = .black
view.addSubview(blackView)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapg))
blackView.addGestureRecognizer(tap)
loadData()
}
func loadData() {
for _ in 0...4 {
let num = CGFloat(arc4random_uniform(200)+50)
modelArray.append(num)
}
collectionView.reloadData()
}
func tapg() {
loadData()
}
}
extension ViewController:UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return modelArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCellId", for: indexPath)
cell.backgroundColor = UIColor.randomColor()
return cell
}
}
extension ViewController : YSMWaterFallLayoutDataSource{
//返回列数
func numberOfRows(in layout: YSMFlowLayout) -> Int {
return 2
}
//获取每个item的高度
func layout(_ layout: YSMFlowLayout, heightForRowAt indexPath: IndexPath) -> CGFloat {
return modelArray[indexPath.row]
}
}
*/
| mit | ef63860f784a1244e7630c647d879880 | 30.402299 | 157 | 0.642753 | 4.967273 | false | false | false | false |
aidenluo177/GitHubber | GitHubber/Pods/CoreStore/CoreStore/Importing Data/BaseDataTransaction+Importing.swift | 2 | 9572 | //
// BaseDataTransaction+Importing.swift
// CoreStore
//
// Copyright (c) 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - BaseDataTransaction
public extension BaseDataTransaction {
// MARK: Public
/**
Creates an `ImportableObject` by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from
- returns: the created `ImportableObject` instance, or `nil` if the import was ignored
*/
public func importObject<T where T: NSManagedObject, T: ImportableObject>(
into: Into<T>,
source: T.ImportSource) throws -> T? {
CoreStore.assert(
self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(),
"Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
guard T.shouldInsertFromImportSource(source, inTransaction: self) else {
return nil
}
let object = self.create(into)
try object.didInsertFromImportSource(source, inTransaction: self)
return object
}
}
/**
Creates multiple `ImportableObject`s by importing from the specified array of import sources.
- parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from
- returns: the array of created `ImportableObject` instances
*/
public func importObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableObject, S.Generator.Element == T.ImportSource>(
into: Into<T>,
sourceArray: S) throws -> [T] {
CoreStore.assert(
self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(),
"Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
return try sourceArray.flatMap { (source) -> T? in
guard T.shouldInsertFromImportSource(source, inTransaction: self) else {
return nil
}
return try autoreleasepool {
let object = self.create(into)
try object.didInsertFromImportSource(source, inTransaction: self)
return object
}
}
}
}
/**
Updates an existing `ImportableUniqueObject` or creates a new instance by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from
- returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored
*/
public func importUniqueObject<T where T: NSManagedObject, T: ImportableUniqueObject>(
into: Into<T>,
source: T.ImportSource) throws -> T? {
CoreStore.assert(
self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(),
"Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
let uniqueIDKeyPath = T.uniqueIDKeyPath
guard let uniqueIDValue = try T.uniqueIDFromImportSource(source, inTransaction: self) else {
return nil
}
if let object = self.fetchOne(From(T), Where(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) {
try object.updateFromImportSource(source, inTransaction: self)
return object
}
else {
guard T.shouldInsertFromImportSource(source, inTransaction: self) else {
return nil
}
let object = self.create(into)
object.uniqueIDValue = uniqueIDValue
try object.didInsertFromImportSource(source, inTransaction: self)
return object
}
}
}
/**
Updates existing `ImportableUniqueObject`s or creates them by importing from the specified array of import sources.
- parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from
- parameter preProcess: a closure that lets the caller tweak the internal `UniqueIDType`-to-`ImportSource` mapping to be used for importing. Callers can remove from/add to/update `mapping` and return the updated array from the closure.
- returns: the array of created/updated `ImportableUniqueObject` instances
*/
public func importUniqueObjects<T, S: SequenceType where T: NSManagedObject, T: ImportableUniqueObject, S.Generator.Element == T.ImportSource>(
into: Into<T>,
sourceArray: S,
@noescape preProcess: (mapping: [T.UniqueIDType: T.ImportSource]) throws -> [T.UniqueIDType: T.ImportSource] = { $0 }) throws -> [T] {
CoreStore.assert(
self.bypassesQueueing || self.transactionQueue.isCurrentExecutionContext(),
"Attempted to import an object of type \(typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
var mapping = Dictionary<T.UniqueIDType, T.ImportSource>()
let sortedIDs = try autoreleasepool {
return try sourceArray.flatMap { (source) -> T.UniqueIDType? in
guard let uniqueIDValue = try T.uniqueIDFromImportSource(source, inTransaction: self) else {
return nil
}
mapping[uniqueIDValue] = source
return uniqueIDValue
}
}
mapping = try autoreleasepool { try preProcess(mapping: mapping) }
var objects = Dictionary<T.UniqueIDType, T>()
for object in self.fetchAll(From(T), Where(T.uniqueIDKeyPath, isMemberOf: mapping.keys)) ?? [] {
try autoreleasepool {
let uniqueIDValue = object.uniqueIDValue
guard let source = mapping.removeValueForKey(uniqueIDValue)
where T.shouldUpdateFromImportSource(source, inTransaction: self) else {
return
}
try object.updateFromImportSource(source, inTransaction: self)
objects[uniqueIDValue] = object
}
}
for (uniqueIDValue, source) in mapping {
try autoreleasepool {
guard T.shouldInsertFromImportSource(source, inTransaction: self) else {
return
}
let object = self.create(into)
object.uniqueIDValue = uniqueIDValue
try object.didInsertFromImportSource(source, inTransaction: self)
objects[uniqueIDValue] = object
}
}
return sortedIDs.flatMap { objects[$0] }
}
}
}
| mit | 5f0b3a4369bfd3c46c9758831582d638 | 42.707763 | 239 | 0.553489 | 6.135897 | false | false | false | false |
nikHowlett/WatchHealthMedicalDoctor | mobile/GraphView.swift | 1 | 5458 | import UIKit
@IBDesignable class GraphView: UIView {
//Weekly sample data
var graphPoints:[Int] = [0, 1, 2, 3, 4, 5, 6]
//1 - the properties for the gradient
@IBInspectable var startColor: UIColor = UIColor.redColor()
@IBInspectable var endColor: UIColor = UIColor.greenColor()
override func drawRect(rect: CGRect) {
let width = rect.width
let height = rect.height
//set up background clipping area
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.AllCorners,
cornerRadii: CGSize(width: 8.0, height: 8.0))
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.CGColor, endColor.CGColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradientCreateWithColors(colorSpace,
colors,
colorLocations)
//6 - draw the gradient
var startPoint = CGPoint.zeroPoint
var endPoint = CGPoint(x:0, y:self.bounds.height)
CGContextDrawLinearGradient(context,
gradient,
startPoint,
endPoint,
0)
//calculate the x point
let margin:CGFloat = 20.0
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
// calculate the y point
let topBorder:CGFloat = 60
let bottomBorder:CGFloat = 50
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.maxElement()
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) /
CGFloat(maxValue!) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
// draw the line graph
UIColor.whiteColor().setFill()
UIColor.whiteColor().setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.moveToPoint(CGPoint(x:columnXPoint(0),
y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i),
y:columnYPoint(graphPoints[i]))
graphPath.addLineToPoint(nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
CGContextSaveGState(context)
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLineToPoint(CGPoint(
x: columnXPoint(graphPoints.count - 1),
y:height))
clippingPath.addLineToPoint(CGPoint(
x:columnXPoint(0),
y:height))
clippingPath.closePath()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue!)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0)
CGContextRestoreGState(context)
//draw the line on top of the clipped gradient
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalInRect:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.moveToPoint(CGPoint(x:margin, y: topBorder))
linePath.addLineToPoint(CGPoint(x: width - margin,
y:topBorder))
//center line
linePath.moveToPoint(CGPoint(x:margin,
y: graphHeight/2 + topBorder))
linePath.addLineToPoint(CGPoint(x:width - margin,
y:graphHeight/2 + topBorder))
//bottom line
linePath.moveToPoint(CGPoint(x:margin,
y:height - bottomBorder))
linePath.addLineToPoint(CGPoint(x:width - margin,
y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: 0.3)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
} | mit | 16c8d539e53632ffaf8e1f2e84f0c22a | 32.906832 | 82 | 0.561195 | 5.011938 | false | false | false | false |
CoderJackyHuang/iOSLoadWebViewImage | iOSLoadWebviewImageSwift/Pods/AlamofireImage/Source/ImageCache.swift | 23 | 12396 | // ImageCache.swift
//
// Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
#if os(iOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
// MARK: ImageCache
/// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache.
public protocol ImageCache {
/// Adds the image to the cache with the given identifier.
func addImage(image: Image, withIdentifier identifier: String)
/// Removes the image from the cache matching the given identifier.
func removeImageWithIdentifier(identifier: String) -> Bool
/// Removes all images stored in the cache.
func removeAllImages() -> Bool
/// Returns the image in the cache associated with the given identifier.
func imageWithIdentifier(identifier: String) -> Image?
}
/// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and
/// fetching images from a cache given an `NSURLRequest` and additional identifier.
public protocol ImageRequestCache: ImageCache {
/// Adds the image to the cache using an identifier created from the request and additional identifier.
func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String?)
/// Removes the image from the cache using an identifier created from the request and additional identifier.
func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool
/// Returns the image from the cache associated with an identifier created from the request and additional identifier.
func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Image?
}
// MARK: -
/// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When
/// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously
/// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the
/// internal access date of the image is updated.
public class AutoPurgingImageCache: ImageRequestCache {
private class CachedImage {
let image: Image
let identifier: String
let totalBytes: UInt64
var lastAccessDate: NSDate
init(_ image: Image, identifier: String) {
self.image = image
self.identifier = identifier
self.lastAccessDate = NSDate()
self.totalBytes = {
#if os(iOS) || os(watchOS)
let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
#elseif os(OSX)
let size = CGSize(width: image.size.width, height: image.size.height)
#endif
let bytesPerPixel: CGFloat = 4.0
let bytesPerRow = size.width * bytesPerPixel
let totalBytes = UInt64(bytesPerRow) * UInt64(size.height)
return totalBytes
}()
}
func accessImage() -> Image {
lastAccessDate = NSDate()
return image
}
}
// MARK: Properties
/// The current total memory usage in bytes of all images stored within the cache.
public var memoryUsage: UInt64 {
var memoryUsage: UInt64 = 0
dispatch_sync(synchronizationQueue) { memoryUsage = self.currentMemoryUsage }
return memoryUsage
}
/// The total memory capacity of the cache in bytes.
public let memoryCapacity: UInt64
/// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory
/// capacity drops below this limit.
public let preferredMemoryUsageAfterPurge: UInt64
private let synchronizationQueue: dispatch_queue_t
private var cachedImages: [String: CachedImage]
private var currentMemoryUsage: UInt64
// MARK: Initialization
/**
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
after purge limit.
- parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default.
- parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default.
- returns: The new `AutoPurgingImageCache` instance.
*/
public init(memoryCapacity: UInt64 = 100 * 1024 * 1024, preferredMemoryUsageAfterPurge: UInt64 = 60 * 1024 * 1024) {
self.memoryCapacity = memoryCapacity
self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge
self.cachedImages = [:]
self.currentMemoryUsage = 0
self.synchronizationQueue = {
let name = String(format: "com.alamofire.autopurgingimagecache-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
#if os(iOS)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "removeAllImages",
name: UIApplicationDidReceiveMemoryWarningNotification,
object: nil
)
#endif
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Add Image to Cache
/**
Adds the image to the cache using an identifier created from the request and optional identifier.
- parameter image: The image to add to the cache.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
*/
public func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
addImage(image, withIdentifier: requestIdentifier)
}
/**
Adds the image to the cache with the given identifier.
- parameter image: The image to add to the cache.
- parameter identifier: The identifier to use to uniquely identify the image.
*/
public func addImage(image: Image, withIdentifier identifier: String) {
dispatch_barrier_async(synchronizationQueue) {
let cachedImage = CachedImage(image, identifier: identifier)
if let previousCachedImage = self.cachedImages[identifier] {
self.currentMemoryUsage -= previousCachedImage.totalBytes
}
self.cachedImages[identifier] = cachedImage
self.currentMemoryUsage += cachedImage.totalBytes
}
dispatch_barrier_async(synchronizationQueue) {
if self.currentMemoryUsage > self.memoryCapacity {
let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge
var sortedImages = [CachedImage](self.cachedImages.values)
sortedImages.sortInPlace {
let date1 = $0.lastAccessDate
let date2 = $1.lastAccessDate
return date1.timeIntervalSinceDate(date2) < 0.0
}
var bytesPurged = UInt64(0)
for cachedImage in sortedImages {
self.cachedImages.removeValueForKey(cachedImage.identifier)
bytesPurged += cachedImage.totalBytes
if bytesPurged >= bytesToPurge {
break
}
}
self.currentMemoryUsage -= bytesPurged
}
}
}
// MARK: Remove Image from Cache
/**
Removes the image from the cache using an identifier created from the request and optional identifier.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
- returns: `true` if the image was removed, `false` otherwise.
*/
public func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
return removeImageWithIdentifier(requestIdentifier)
}
/**
Removes the image from the cache matching the given identifier.
- parameter identifier: The unique identifier for the image.
- returns: `true` if the image was removed, `false` otherwise.
*/
public func removeImageWithIdentifier(identifier: String) -> Bool {
var removed = false
dispatch_barrier_async(synchronizationQueue) {
if let cachedImage = self.cachedImages.removeValueForKey(identifier) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
return removed
}
/**
Removes all images stored in the cache.
- returns: `true` if images were removed from the cache, `false` otherwise.
*/
@objc public func removeAllImages() -> Bool {
var removed = false
dispatch_sync(synchronizationQueue) {
if !self.cachedImages.isEmpty {
self.cachedImages.removeAll()
self.currentMemoryUsage = 0
removed = true
}
}
return removed
}
// MARK: Fetch Image from Cache
/**
Returns the image from the cache associated with an identifier created from the request and optional identifier.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
- returns: The image if it is stored in the cache, `nil` otherwise.
*/
public func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) -> Image? {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
return imageWithIdentifier(requestIdentifier)
}
/**
Returns the image in the cache associated with the given identifier.
- parameter identifier: The unique identifier for the image.
- returns: The image if it is stored in the cache, `nil` otherwise.
*/
public func imageWithIdentifier(identifier: String) -> Image? {
var image: Image?
dispatch_sync(synchronizationQueue) {
if let cachedImage = self.cachedImages[identifier] {
image = cachedImage.accessImage()
}
}
return image
}
// MARK: Private - Helper Methods
private func imageCacheKeyFromURLRequest(
request: NSURLRequest,
withAdditionalIdentifier identifier: String?)
-> String
{
var key = request.URLString
if let identifier = identifier {
key += "-\(identifier)"
}
return key
}
}
| mit | b132555a0e052a76f183c9761d9d6596 | 37.377709 | 126 | 0.666989 | 5.458388 | false | false | false | false |
ccwuzhou/WWZSwift | Source/Views/WWZTableViewCell.swift | 1 | 8159 | //
// WWZTableViewCell.swift
// wwz_swift
//
// Created by wwz on 17/2/28.
// Copyright © 2017年 tijio. All rights reserved.
//
import UIKit
public enum WWZTableViewCellStyle : Int {
case none = 0
case subTitle = 1
case rightTitle = 2
case switchView = 4
case subAndRight = 3
case subAndSwitch = 5
}
public protocol WWZTableViewCellDelegate: NSObjectProtocol {
func tableViewCell(cell: WWZTableViewCell, didChangedSwitch isOn: Bool)
}
open class WWZTableViewCell: UITableViewCell {
// MARK: -属性
public weak var tableViewCellDelegate : WWZTableViewCellDelegate?
/// sub label
public var subLabel : UILabel?
/// right label
public var rightLabel : UILabel?
/// switch
public var mySwitch : UISwitch?
/// text label 与 sub label 间距
public var titleSpaceH : CGFloat = 4.0
/// 是否为最后一行cell
public var isLastCell : Bool = false
/// line
public lazy var lineView : UIView = {
let line = UIView()
line.backgroundColor = UIColor.colorFromRGBA(0, 0, 0, 0.1)
return line
}()
// MARK: -类方法
class public func wwz_cell(tableView: UITableView, style: WWZTableViewCellStyle) -> WWZTableViewCell {
let reuseID = "WWZ_REUSE_CELL_ID"
var cell = tableView.dequeueReusableCell(withIdentifier: reuseID)
if cell == nil {
cell = self.init(style: style, reuseIdentifier: reuseID)
}
return cell as! WWZTableViewCell
}
public required init(style: WWZTableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.p_setupCell()
self.p_addSubTitleLabel(style: style)
self.p_addRightTitleLabel(style: style)
self.p_addSwitchView(style: style)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -布局
override open func layoutSubviews() {
super.layoutSubviews()
// imageView
let imageX : CGFloat = 15.0
let imageY : CGFloat = 7.0
let imageWH : CGFloat = self.height - imageY*2
var imageSize = CGSize(width: imageWH, height: imageWH)
if self.imageView?.image != nil {
if self.imageView!.image!.size.width > imageWH || self.imageView!.image!.size.height > imageWH {
self.imageView?.contentMode = .scaleAspectFit
}else{
self.imageView?.contentMode = .center
imageSize = self.imageView!.image!.size
}
self.imageView?.frame = CGRect(x: imageX, y: (self.height-imageSize.height)*0.5, width: imageSize.width, height: imageSize.height)
}
// textLabel
guard let titleLabel = self.textLabel else {
return
}
titleLabel.sizeToFit()
titleLabel.x = self.imageView?.image == nil ? 15.0 : self.imageView!.right + 10
titleLabel.y = (self.height-titleLabel.height)*0.5
// text label 右边距
let textLabelRightSpace : CGFloat = 10.0
// text label 最大宽度
var textLMaxWidth = self.contentView.width - titleLabel.x - textLabelRightSpace
titleLabel.width = titleLabel.width < textLMaxWidth ? titleLabel.width : textLMaxWidth
// right label
if let rightTitleLabel = self.rightLabel, let _ = self.rightLabel!.text, self.rightLabel!.text!.characters.count > 0 {
rightTitleLabel.sizeToFit()
// 右边距
let rightSpacing : CGFloat = self.accessoryType == .none ? 16.0 : 0
// right label 最小宽度
let rightLMinWidth : CGFloat = 60.0;
// right label 最大宽度
let rightLMaxWidth = self.contentView.width - titleLabel.right - textLabelRightSpace - rightSpacing
if rightLMaxWidth < rightLMinWidth {
rightTitleLabel.width = rightTitleLabel.width < rightLMinWidth ? rightTitleLabel.width : rightLMinWidth
}else{
rightTitleLabel.width = rightTitleLabel.width < rightLMaxWidth ? rightTitleLabel.width : rightLMaxWidth
}
rightTitleLabel.x = self.contentView.width - rightTitleLabel.width - rightSpacing
rightTitleLabel.y = (self.height - rightTitleLabel.height) * 0.5
textLMaxWidth = rightTitleLabel.x - titleLabel.x - textLabelRightSpace
}
titleLabel.width = titleLabel.width < textLMaxWidth ? titleLabel.width : textLMaxWidth
// sub label
if let subTitleLabel = self.subLabel, let _ = self.subLabel!.text, self.subLabel!.text!.characters.count > 0{
subTitleLabel.sizeToFit()
subTitleLabel.width = subTitleLabel.width < textLMaxWidth ? subTitleLabel.width : textLMaxWidth
titleLabel.y = (self.height - titleLabel.height - subTitleLabel.height - self.titleSpaceH) * 0.5
subTitleLabel.x = titleLabel.x
subTitleLabel.y = titleLabel.bottom + self.titleSpaceH
}
self.selectedBackgroundView?.frame = self.bounds
let leftX = self.isLastCell ? 0 : self.textLabel!.x
let lineH : CGFloat = 0.5
self.lineView.frame = CGRect(x: leftX, y: self.height - lineH, width: self.width-leftX, height: lineH)
}
}
// MARK: -私有方法
extension WWZTableViewCell {
// MARK: -设置cell
fileprivate func p_setupCell() {
self.backgroundColor = UIColor.white
// text label
self.textLabel?.backgroundColor = UIColor.clear
self.textLabel?.font = UIFont.systemFont(ofSize: 17)
self.textLabel?.textColor = UIColor.black
// selected background color
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = UIColor.colorFromRGBA(217, 217, 217, 1)
// line
self.contentView.addSubview(self.lineView)
}
// MARK: -添加sub label
fileprivate func p_addSubTitleLabel(style: WWZTableViewCellStyle) {
guard (style.rawValue & WWZTableViewCellStyle.subTitle.rawValue) > 0 else { return }
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.colorFromRGBA(153, 153, 153, 1)
label.textAlignment = .left
label.numberOfLines = 1
self.addSubview(label)
self.subLabel = label
}
// MARK: -添加right label
fileprivate func p_addRightTitleLabel(style: WWZTableViewCellStyle) {
guard (style.rawValue & WWZTableViewCellStyle.rightTitle.rawValue) > 0 else { return }
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.colorFromRGBA(153, 153, 153, 1)
label.textAlignment = .right
label.numberOfLines = 1
self.addSubview(label)
self.rightLabel = label
}
// MARK: -添加switch
fileprivate func p_addSwitchView(style: WWZTableViewCellStyle) {
guard (style.rawValue & WWZTableViewCellStyle.switchView.rawValue) > 0 else { return }
let onSwitch = UISwitch()
onSwitch.addTarget(self, action: #selector(WWZTableViewCell.p_changeSwitch), for: .valueChanged)
self.accessoryView = onSwitch
self.mySwitch = onSwitch
}
// MARK: -点击事件
@objc fileprivate func p_changeSwitch(sender: UISwitch) {
self.tableViewCellDelegate?.tableViewCell(cell: self, didChangedSwitch: sender.isOn)
}
}
| mit | 27a535b6368145efea8a90ead4111ef1 | 30.460938 | 142 | 0.594984 | 5.021197 | false | false | false | false |
qvacua/vimr | VimR/VimR/MainWindow+Delegates.swift | 1 | 8753 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import NvimView
import RxPack
import RxSwift
import RxNeovim
import Workspace
// MARK: - NvimViewDelegate
extension MainWindow {
// Use only when Cmd-Q'ing
func waitTillNvimExits() {
self.neoVimView.waitTillNvimExits()
}
func neoVimStopped() {
if self.isClosing { return }
self.prepareClosing()
self.windowController.close()
self.set(dirtyStatus: false)
self.emit(self.uuidAction(for: .close))
}
func prepareClosing() {
self.isClosing = true
// If we close the window in the full screen mode, either by clicking the close button or by invoking :q
// the main thread crashes. We exit the full screen mode here as a quick and dirty hack.
if self.window.styleMask.contains(.fullScreen) {
self.window.toggleFullScreen(nil)
}
guard let cliPipePath = self.cliPipePath,
FileManager.default.fileExists(atPath: cliPipePath)
else {
return
}
let fd = Darwin.open(cliPipePath, O_RDWR)
guard fd != -1 else {
return
}
let handle = FileHandle(fileDescriptor: fd)
handle.closeFile()
_ = Darwin.close(fd)
}
func set(title: String) {
self.window.title = title
self.set(repUrl: self.window.representedURL, themed: self.titlebarThemed)
}
func set(dirtyStatus: Bool) {
self.emit(self.uuidAction(for: .setDirtyStatus(dirtyStatus)))
}
func cwdChanged() {
self.emit(self.uuidAction(for: .cd(to: self.neoVimView.cwd)))
}
func bufferListChanged() {
self.neoVimView
.allBuffers()
.subscribe(onSuccess: { buffers in
self.emit(self.uuidAction(for: .setBufferList(buffers.filter { $0.isListed })))
})
.disposed(by: self.disposeBag)
}
func bufferWritten(_ buffer: NvimView.Buffer) {
self.emit(self.uuidAction(for: .bufferWritten(buffer)))
}
func newCurrentBuffer(_ currentBuffer: NvimView.Buffer) {
self.emit(self.uuidAction(for: .newCurrentBuffer(currentBuffer)))
}
func tabChanged() {
self.neoVimView
.currentBuffer()
.subscribe(onSuccess: {
self.newCurrentBuffer($0)
})
.disposed(by: self.disposeBag)
}
func colorschemeChanged(to nvimTheme: NvimView.Theme) {
self
.updateCssColors()
.subscribe(onSuccess: { colors in
self.emit(
self.uuidAction(
for: .setTheme(Theme(from: nvimTheme, additionalColorDict: colors))
)
)
})
.disposed(by: self.disposeBag)
}
func guifontChanged(to font: NSFont) {
self.emit(self.uuidAction(for: .setFont(font)))
}
func ipcBecameInvalid(reason: String) {
let alert = NSAlert()
alert.addButton(withTitle: "Close")
alert.messageText = "Sorry, an error occurred."
alert
.informativeText =
"VimR encountered an error from which it cannot recover. This window will now close.\n"
+ reason
alert.alertStyle = .critical
alert.beginSheetModal(for: self.window) { _ in
self.windowController.close()
}
}
func scroll() {
self.scrollDebouncer.call(.scroll(to: Marked(self.neoVimView.currentPosition)))
}
func cursor(to position: Position) {
if position == self.editorPosition.payload {
return
}
self.editorPosition = Marked(position)
self.cursorDebouncer.call(.setCursor(to: self.editorPosition))
}
private func updateCssColors() -> Single<[String: CellAttributes]> {
let colorNames = [
"Normal", // color and background-color
"Directory", // a
"Question", // blockquote foreground
"CursorColumn", // code background and foreground
]
typealias HlResult = [String: RxNeovimApi.Value]
typealias ColorNameHlResultTuple = (colorName: String, hlResult: HlResult)
typealias ColorNameObservableTuple = (colorName: String, observable: Observable<HlResult>)
return Observable
.from(colorNames.map { colorName -> ColorNameObservableTuple in
(
colorName: colorName,
observable: self.neoVimView.api
.getHlByName(name: colorName, rgb: true)
.asObservable()
)
})
.flatMap { tuple -> Observable<(String, HlResult)> in
Observable.zip(Observable.just(tuple.colorName), tuple.observable)
}
.reduce([ColorNameHlResultTuple]()) { (result, element: ColorNameHlResultTuple) in
result + [element]
}
.map { (array: [ColorNameHlResultTuple]) in
Dictionary(uniqueKeysWithValues: array)
.mapValues { value in
CellAttributes(withDict: value, with: self.neoVimView.defaultCellAttributes)
}
}
.asSingle()
}
}
// MARK: - NSWindowDelegate
extension MainWindow {
func windowWillEnterFullScreen(_: Notification) {
self.unthemeTitlebar(dueFullScreen: true)
}
func windowDidExitFullScreen(_: Notification) {
if self.titlebarThemed {
self.themeTitlebar(grow: true)
}
}
func windowDidBecomeMain(_: Notification) {
self
.emit(
self
.uuidAction(for: .becomeKey(isFullScreen: self.window.styleMask.contains(.fullScreen)))
)
self.neoVimView.didBecomeMain().subscribe().disposed(by: self.disposeBag)
}
func windowDidResignMain(_: Notification) {
self.neoVimView.didResignMain().subscribe().disposed(by: self.disposeBag)
}
func windowDidMove(_: Notification) {
self.emit(self.uuidAction(for: .frameChanged(to: self.window.frame)))
}
func windowDidResize(_: Notification) {
if self.window.styleMask.contains(.fullScreen) {
return
}
self.emit(self.uuidAction(for: .frameChanged(to: self.window.frame)))
}
func windowShouldClose(_: NSWindow) -> Bool {
defer { self.closeWindow = false }
if self.neoVimView.isBlocked().syncValue() ?? false {
let alert = NSAlert()
alert.messageText = "Nvim is waiting for your input."
alert.alertStyle = .informational
alert.runModal()
return false
}
if self.closeWindow {
if self.neoVimView.hasDirtyBuffers().syncValue() == true {
self.discardCloseActionAlert().beginSheetModal(for: self.window) { response in
if response == .alertSecondButtonReturn {
try? self.neoVimView.quitNeoVimWithoutSaving().wait()
}
}
} else {
try? self.neoVimView.quitNeoVimWithoutSaving().wait()
}
return false
}
guard self.neoVimView.isCurrentBufferDirty().syncValue() ?? false else {
try? self.neoVimView.closeCurrentTab().wait()
return false
}
self.discardCloseActionAlert().beginSheetModal(for: self.window) { response in
if response == .alertSecondButtonReturn {
try? self.neoVimView.closeCurrentTabWithoutSaving().wait()
}
}
return false
}
private func discardCloseActionAlert() -> NSAlert {
let alert = NSAlert()
let cancelButton = alert.addButton(withTitle: "Cancel")
let discardAndCloseButton = alert.addButton(withTitle: "Discard and Close")
cancelButton.keyEquivalent = "\u{1b}"
alert.messageText = "The current buffer has unsaved changes!"
alert.alertStyle = .warning
discardAndCloseButton.keyEquivalentModifierMask = .command
discardAndCloseButton.keyEquivalent = "d"
return alert
}
}
// MARK: - WorkspaceDelegate
extension MainWindow {
func resizeWillStart(workspace _: Workspace, tool _: WorkspaceTool?) {
self.neoVimView.enterResizeMode()
}
func resizeDidEnd(workspace _: Workspace, tool: WorkspaceTool?) {
self.neoVimView.exitResizeMode()
if let workspaceTool = tool, let toolIdentifier = self.toolIdentifier(for: workspaceTool) {
self.emit(self.uuidAction(for: .setState(for: toolIdentifier, with: workspaceTool)))
}
}
func toggled(tool: WorkspaceTool) {
if let toolIdentifier = self.toolIdentifier(for: tool) {
self.emit(self.uuidAction(for: .setState(for: toolIdentifier, with: tool)))
}
}
func moved(tool: WorkspaceTool) {
let tools = self.workspace.orderedTools
.compactMap { (tool: WorkspaceTool) -> (Tools, WorkspaceTool)? in
guard let toolId = self.toolIdentifier(for: tool) else {
return nil
}
return (toolId, tool)
}
self.emit(self.uuidAction(for: .setToolsState(tools)))
}
private func toolIdentifier(for tool: WorkspaceTool) -> Tools? {
if tool == self.fileBrowserContainer {
return .fileBrowser
}
if tool == self.buffersListContainer {
return .buffersList
}
if tool == self.previewContainer {
return .preview
}
if tool == self.htmlPreviewContainer {
return .htmlPreview
}
return nil
}
}
| mit | 6685a8ea8a881e165e1e3cc15703e2d5 | 26.438871 | 108 | 0.662059 | 4.218313 | false | false | false | false |
codestergit/swift | stdlib/public/core/Collection.swift | 3 | 76619 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with forward
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias IndexableBase = _IndexableBase
public protocol _IndexableBase {
// FIXME(ABI)#24 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library; it is used to deduce things like the `SubSequence` and
// `Iterator` type from a minimal collection, but it is also used in
// exposed places like as a constraint on `IndexingIterator`.
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
///
/// - SeeAlso: endIndex
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.index(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
// The declaration of _Element and subscript here is a trick used to
// break a cyclic conformance/deduction that Swift can't handle. We
// need something other than a Collection.Iterator.Element that can
// be used as IndexingIterator<T>'s Element. Here we arrange for
// the Collection itself to have an Element type that's deducible from
// its subscript. Ideally we'd like to constrain this Element to be the same
// as Collection.Iterator.Element (see below), but we have no way of
// expressing it today.
associatedtype _Element
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
subscript(position: Index) -> _Element { get }
// WORKAROUND: rdar://25214066
// FIXME(ABI)#178 (Type checker)
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
/// Accesses the subsequence bounded by the given range.
///
/// - Parameter bounds: A range of the collection's indices. The upper and
/// lower bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(1)
subscript(bounds: Range<Index>) -> SubSequence { get }
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
///
/// - SeeAlso: `index(after:)`
func formIndex(after i: inout Index)
}
/// A type that provides subscript access to its elements, with forward index
/// traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias Indexable = _Indexable
public protocol _Indexable : _IndexableBase {
/// A type that represents the number of steps between two indices, where
/// one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
associatedtype IndexDistance : SignedInteger = Int
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(_ i: inout Index, offsetBy n: IndexDistance)
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// The `CollectionOfTwo` type uses the default iterator type,
/// `IndexingIterator`, because it doesn't define its own `makeIterator()`
/// method or `Iterator` associated type. This example shows how a
/// `CollectionOfTwo` instance can be created holding the values of a point,
/// and then iterated over using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
@_fixed_layout
public struct IndexingIterator<
Elements : _IndexableBase
// FIXME(ABI)#97 (Recursive Protocol Constraints):
// Should be written as:
// Elements : Collection
> : IteratorProtocol, Sequence {
@_inlineable
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
@_inlineable
public mutating func next() -> Elements._Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
@_versioned
internal let _elements: Elements
@_versioned
internal var _position: Elements.Index
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by indexed subscript.
///
/// Collections are used extensively throughout the standard library. When you
/// use arrays, dictionaries, views of a string's contents and other types,
/// you benefit from the operations that the `Collection` protocol declares
/// and implements.
///
/// In addition to the methods that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position when using a collection.
///
/// For example, if you want to print only the first word in a string, search
/// for the index of the first space and then create a subsequence up to that
/// position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.characters.index(of: " ") {
/// print(String(text.characters.prefix(upTo: firstSpace)))
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text.characters`
/// collection. `firstSpace` is the position of the first space in the
/// collection. You can store indices in variables, and pass them to
/// collection algorithms or use them later to access the corresponding
/// element. In the example above, `firstSpace` is used to extract the prefix
/// that contains elements up to that index.
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations; for
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript with any
/// valid index except the collection's `endIndex` property, a "past the end"
/// index that does not correspond with any element of the collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text.characters[text.characters.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations for
/// many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of `text`
/// using the `first` property, which has the value of the first element of
/// the collection, or `nil` if the collection is empty.
///
/// print(text.characters.first)
/// // Prints "Optional("B")"
///
/// Accessing Slices of a Collection
/// ================================
///
/// You can access a slice of a collection through its ranged subscript or by
/// calling methods like `prefix(_:)` or `suffix(from:)`. A slice of a
/// collection can contain zero or more of the original collection's elements
/// and shares the original collection's semantics.
///
/// The following example, creates a `firstWord` constant by using the
/// `prefix(_:)` method to get a slice of the `text` string's `characters`
/// view.
///
/// let firstWord = text.characters.prefix(7)
/// print(String(firstWord))
/// // Prints "Buffalo"
///
/// You can retrieve the same slice using other methods, such as finding the
/// terminating index, and then using the `prefix(upTo:)` method, which takes
/// an index as its parameter, or by using the view's ranged subscript.
///
/// if let firstSpace = text.characters.index(of: " ") {
/// print(text.characters.prefix(upTo: firstSpace))
/// // Prints "Buffalo"
///
/// let start = text.characters.startIndex
/// print(text.characters[start..<firstSpace])
/// // Prints "Buffalo"
/// }
///
/// The retrieved slice of `text.characters` is equivalent in each of these
/// cases.
///
/// Slices Share Indices
/// --------------------
///
/// A collection and its slices share the same indices. An element of a
/// collection is located under the same index in a slice as in the base
/// collection, as long as neither the collection nor the slice has been
/// mutated since the slice was created.
///
/// For example, suppose you have an array holding the number of absences from
/// each class during a session.
///
/// var absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You're tasked with finding the day with the most absences in the second
/// half of the session. To find the index of the day in question, follow
/// these steps:
///
/// 1) Create a slice of the `absences` array that holds the second half of the
/// days.
/// 2) Use the `max(by:)` method to determine the index of the day with the
/// most absences.
/// 3) Print the result using the index found in step 2 on the original
/// `absences` array.
///
/// Here's an implementation of those steps:
///
/// let secondHalf = absences.suffix(absences.count / 2)
/// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {
/// print("Highest second-half absences: \(absences[i])")
/// }
/// // Prints "Highest second-half absences: 3"
///
/// Slice Inherit Collection Semantics
/// ----------------------------------
///
/// A slice inherits the value or reference semantics of its base collection.
/// That is, when working with a slice of a mutable
/// collection that has value semantics, such as an array, mutating the
/// original collection triggers a copy of that collection, and does not
/// affect the contents of the slice.
///
/// For example, if you update the last element of the `absences` array from
/// `0` to `2`, the `secondHalf` slice is unchanged.
///
/// absences[7] = 2
/// print(absences)
/// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]"
/// print(secondHalf)
/// // Prints "[0, 3, 1, 0]"
///
/// Traversing a Collection
/// =======================
///
/// Although a sequence can be consumed as it is traversed, a collection is
/// guaranteed to be multipass: Any element may be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range of
/// the positions of the collection's elements. This guarantees the safety of
/// operations that depend on a sequence being finite, such as checking to see
/// whether a collection contains an element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word.characters {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.characters.indices {
/// print(word.characters[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, make sure that its type conforms to the `Collection` protocol in
/// order to give a more useful and more efficient interface for sequence and
/// collection operations. To add `Collection` conformance to your type, you
/// must declare at least the four following requirements:
///
/// - the `startIndex` and `endIndex` properties,
/// - a subscript that provides at least read-only access to your type's
/// elements, and
/// - the `index(after:)` method for advancing an index into your collection.
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the `startIndex`
/// and `endIndex` properties and subscript access to elements as O(1)
/// operations. Types that are not able to guarantee that expected performance
/// must document the departure, because many collection operations depend on
/// O(1) subscripting performance for their own performance guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, will be
/// able to calculate its `count` property in O(1) time. Conversely, because a
/// forward or bidirectional collection must traverse the entire collection to
/// count the number of contained elements, accessing its `count` property is
/// an O(*n*) operation.
public protocol Collection : _Indexable, Sequence {
/// A type that represents the number of steps between a pair of
/// indices.
associatedtype IndexDistance = Int
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator = IndexingIterator<Self>
// FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence : _IndexableBase, Sequence = Slice<Self>
// FIXME(ABI)#98 (Recursive Protocol Constraints):
// FIXME(ABI)#99 (Associated Types with where clauses):
// associatedtype SubSequence : Collection
// where
// Iterator.Element == SubSequence.Iterator.Element,
// SubSequence.Index == Index,
// SubSequence.Indices == Indices,
// SubSequence.SubSequence == SubSequence
//
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
//
// These constraints allow processing collections in generic code by
// repeatedly slicing them in a loop.
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
subscript(position: Index) -> Iterator.Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : _Indexable, Sequence = DefaultIndices<Self>
// FIXME(ABI)#68 (Associated Types with where clauses):
// FIXME(ABI)#100 (Recursive Protocol Constraints):
// associatedtype Indices : Collection
// where
// Indices.Iterator.Element == Index,
// Indices.Index == Index,
// Indices.SubSequence == Indices
// = DefaultIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: IndexDistance { get }
// The following requirement enables dispatching for index(of:) when
// the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*)
func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index??
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Iterator.Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: IndexDistance) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> IndexDistance
}
/// Default implementation for forward collections.
extension _Indexable {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inline(__always)
public func formIndex(after i: inout Index) {
i = index(after: i)
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"out of bounds: index >= endIndex")
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"out of bounds: index < startIndex")
_precondition(
index <= bounds.upperBound,
"out of bounds: index > endIndex")
}
@_inlineable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - SeeAlso: `index(_:offsetBy:limitedBy:)`, `formIndex(_:offsetBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count: IndexDistance = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Do not use this method directly; call advanced(by: n) instead.
@_inlineable
@_versioned
@inline(__always)
internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@_inlineable
@_versioned
@inline(__always)
internal
func _advanceForward(
_ i: Index, by n: IndexDistance, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
@inline(__always)
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@_inlineable
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@_inlineable
public mutating func popFirst() -> Iterator.Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.characters.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
@_inlineable
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
@_inlineable
public var first: Iterator.Element? {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Iterator.Element? {
// return isEmpty ? nil : self[startIndex]
// }
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@_inlineable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return numericCast(count)
}
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@_inlineable
public var count: IndexDistance {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.index(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: O(`count`).
@_inlineable
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercaseString }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.characters.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@_inlineable
public func map<T>(
_ transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the following
let count: Int = numericCast(self.count)
if count == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(count)
var i = self.startIndex
for _ in 0..<count {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(of: self, is: i)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
@_inlineable
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: numericCast(n), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, numericCast(count) - n)
let end = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence by skipping elements while `predicate` returns
/// `true` and returning the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be skipped or `false` if it should be included. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func drop(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
var start = startIndex
while try start != endIndex && predicate(self[start]) {
formIndex(after: &start)
}
return self[start..<endIndex]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
@_inlineable
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: numericCast(maxLength), limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence containing the initial elements until `predicate`
/// returns `false` and skipping the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be included or `false` if it should be excluded. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func prefix(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
var end = startIndex
while try end != endIndex && predicate(self[end]) {
formIndex(after: &end)
}
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, numericCast(count) - maxLength)
let start = index(startIndex,
offsetBy: numericCast(amount), limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
@_inlineable
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
@_inlineable
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.index(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
@_inlineable
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
/// Returns the longest possible subsequences of the collection, in order,
/// that don't contain elements satisfying the given predicate.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(
/// line.characters.split(
/// maxSplits: 1, whereSeparator: { $0 == " " }
/// ).map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " })
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@_inlineable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
extension Collection where Iterator.Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.characters.split(separator: " ")
/// .map(String.init))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.characters.split(separator: " ", maxSplits: 1)
/// .map(String.init))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.characters.split(separator: " ", omittingEmptySubsequences: false)
/// .map(String.init))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@_inlineable
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
/// - SeeAlso: `popFirst()`
@_inlineable
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
// TODO: swift-3-indexing-model - review the following
_precondition(!isEmpty, "can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
@_inlineable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: numericCast(n))..<endIndex]
}
}
extension Collection {
@_inlineable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
@available(*, unavailable, message: "Bit enum has been removed. Please use Int instead.")
public enum Bit {}
@available(*, unavailable, renamed: "IndexingIterator")
public struct IndexingGenerator<Elements : _IndexableBase> {}
@available(*, unavailable, renamed: "Collection")
public typealias CollectionType = Collection
extension Collection {
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(*, unavailable, renamed: "makeIterator()")
public func generate() -> Iterator {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "getter:underestimatedCount()")
public func underestimateCount() -> Int {
Builtin.unreachable()
}
@available(*, unavailable, message: "Please use split(maxSplits:omittingEmptySubsequences:whereSeparator:) instead")
public func split(
_ maxSplit: Int = Int.max,
allowEmptySlices: Bool = false,
whereSeparator isSeparator: (Iterator.Element) throws -> Bool
) rethrows -> [SubSequence] {
Builtin.unreachable()
}
}
extension Collection where Iterator.Element : Equatable {
@available(*, unavailable, message: "Please use split(separator:maxSplits:omittingEmptySubsequences:) instead")
public func split(
_ separator: Iterator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [SubSequence] {
Builtin.unreachable()
}
}
@available(*, unavailable, message: "PermutationGenerator has been removed in Swift 3")
public struct PermutationGenerator<C : Collection, Indices : Sequence> {}
| apache-2.0 | 434376dd9c63c0acebb75f0ef8d80152 | 38.968179 | 118 | 0.644984 | 4.20406 | false | false | false | false |
PoissonBallon/EasyRealm | Example/Tests/TestDelete.swift | 1 | 2777 | //
// Test_Delete.swift
// EasyRealm
//
// Created by Allan Vialatte on 10/03/2017.
//
import XCTest
import RealmSwift
import EasyRealm
class TestDelete: XCTestCase {
let testPokemon = ["Bulbasaur", "Ivysaur", "Venusaur","Charmander","Charmeleon","Charizard"]
override func setUp() {
super.setUp()
Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name
}
override func tearDown() {
super.tearDown()
let realm = try! Realm()
try! realm.write { realm.deleteAll() }
}
func testDeleteAll() {
HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) }
try! Pokemon.er.deleteAll()
let count = try! Pokemon.er.all().count
XCTAssertEqual(count, 0)
}
func testDeleteUnmanaged() {
let pokemons = HelpPokemon.pokemons(with: self.testPokemon)
pokemons.forEach {
try! $0.er.save(update: true)
}
pokemons.forEach { pokemon in
XCTAssert(pokemon.realm == nil)
try! pokemon.er.delete()
}
let count = try! Pokemon.er.all().count
XCTAssertEqual(count, 0)
}
func testDeleteManaged() {
HelpPokemon.pokemons(with: self.testPokemon).forEach {
try! $0.er.save(update: true)
}
let pokemons = try! Pokemon.er.all()
pokemons.forEach {
XCTAssert($0.realm != nil)
try! $0.er.delete()
}
let count = try! Pokemon.er.all().count
XCTAssertEqual(count, 0)
}
func testDeleteCascadeComplexManagedObject() {
let trainer = Trainer()
let pokedex = Pokedex()
trainer.pokemons.append(objectsIn: HelpPokemon.allPokedex())
trainer.pokedex = pokedex
try! trainer.er.save(update: true)
XCTAssertEqual(try! Trainer.er.all().count, 1)
XCTAssertEqual(try! Pokedex.er.all().count, 1)
XCTAssertEqual(try! Pokemon.er.all().count, HelpPokemon.allPokedex().count)
let managed = trainer.er.managed!
try! managed.er.delete(with: .cascade)
XCTAssertEqual(try! Trainer.er.all().count, 0)
XCTAssertEqual(try! Pokedex.er.all().count, 0)
XCTAssertEqual(try! Pokemon.er.all().count, 0)
}
func testDeleteCascadeComplexUnManagedObject() {
let trainer = Trainer()
let pokedex = Pokedex()
trainer.pokemons.append(objectsIn: HelpPokemon.allPokedex())
trainer.pokedex = pokedex
try! trainer.er.save(update: true)
XCTAssertEqual(try! Trainer.er.all().count, 1)
XCTAssertEqual(try! Pokedex.er.all().count, 1)
XCTAssertEqual(try! Pokemon.er.all().count, HelpPokemon.allPokedex().count)
try! trainer.er.delete(with: .cascade)
XCTAssertEqual(try! Trainer.er.all().count, 0)
XCTAssertEqual(try! Pokedex.er.all().count, 0)
XCTAssertEqual(try! Pokemon.er.all().count, 0)
}
}
| mit | d3cb0075159d0910a1b31d6b130725da | 25.961165 | 94 | 0.661505 | 3.793716 | false | true | false | false |
rnystrom/GitHawk | Local Pods/GitHubAPI/Pods/Apollo/Sources/Apollo/ApolloClient.swift | 1 | 10019 | import Foundation
import Dispatch
/// An object that can be used to cancel an in progress action.
public protocol Cancellable: class {
/// Cancel an in progress action.
func cancel()
}
/// A cache policy that specifies whether results should be fetched from the server or loaded from the local cache.
public enum CachePolicy {
/// Return data from the cache if available, else fetch results from the server.
case returnCacheDataElseFetch
/// Always fetch results from the server.
case fetchIgnoringCacheData
/// Return data from the cache if available, else return nil.
case returnCacheDataDontFetch
/// Return data from the cache if available, and always fetch results from the server.
case returnCacheDataAndFetch
}
/// A handler for operation results.
///
/// - Parameters:
/// - result: The result of the performed operation, or `nil` if an error occurred.
/// - error: An error that indicates why the mutation failed, or `nil` if the mutation was succesful.
public typealias OperationResultHandler<Operation: GraphQLOperation> = (_ result: GraphQLResult<Operation.Data>?, _ error: Error?) -> Void
/// The `ApolloClient` class provides the core API for Apollo. This API provides methods to fetch and watch queries, and to perform mutations.
public class ApolloClient {
let networkTransport: NetworkTransport
let store: ApolloStore
public var cacheKeyForObject: CacheKeyForObject? {
get {
return store.cacheKeyForObject
}
set {
store.cacheKeyForObject = newValue
}
}
private let queue: DispatchQueue
private let operationQueue: OperationQueue
/// Creates a client with the specified network transport and store.
///
/// - Parameters:
/// - networkTransport: A network transport used to send operations to a server.
/// - store: A store used as a local cache. Defaults to an empty store backed by an in memory cache.
public init(networkTransport: NetworkTransport, store: ApolloStore = ApolloStore(cache: InMemoryNormalizedCache())) {
self.networkTransport = networkTransport
self.store = store
queue = DispatchQueue(label: "com.apollographql.ApolloClient", attributes: .concurrent)
operationQueue = OperationQueue()
}
/// Creates a client with an HTTP network transport connecting to the specified URL.
///
/// - Parameter url: The URL of a GraphQL server to connect to.
public convenience init(url: URL) {
self.init(networkTransport: HTTPNetworkTransport(url: url))
}
/// Clears apollo cache
///
/// - Returns: Promise
public func clearCache() -> Promise<Void> {
return store.clearCache()
}
/// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy.
///
/// - Parameters:
/// - query: The query to fetch.
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server and when data should be loaded from the local cache.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - resultHandler: An optional closure that is called when query results are available or when an error occurs.
/// - Returns: An object that can be used to cancel an in progress fetch.
@discardableResult public func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Query>? = nil) -> Cancellable {
return _fetch(query: query, cachePolicy: cachePolicy, queue: queue, resultHandler: resultHandler)
}
func _fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) -> Cancellable {
// If we don't have to go through the cache, there is no need to create an operation
// and we can return a network task directly
if cachePolicy == .fetchIgnoringCacheData {
return send(operation: query, context: context, handlerQueue: queue, resultHandler: resultHandler)
} else {
let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, handlerQueue: queue, resultHandler: resultHandler)
operationQueue.addOperation(operation)
return operation
}
}
/// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned query watcher object will get notified whenever any of the data the query result depends on changes in the local cache, and calls the result handler again with the new result.
///
/// - Parameters:
/// - query: The query to fetch.
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server or from the local cache.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - resultHandler: An optional closure that is called when query results are available or when an error occurs.
/// - Returns: A query watcher object that can be used to control the watching behavior.
public func watch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping OperationResultHandler<Query>) -> GraphQLQueryWatcher<Query> {
let watcher = GraphQLQueryWatcher(client: self, query: query, handlerQueue: queue, resultHandler: resultHandler)
watcher.fetch(cachePolicy: cachePolicy)
return watcher
}
/// Performs a mutation by sending it to the server.
///
/// - Parameters:
/// - mutation: The mutation to perform.
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
/// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs.
/// - Returns: An object that can be used to cancel an in progress mutation.
@discardableResult public func perform<Mutation: GraphQLMutation>(mutation: Mutation, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Mutation>? = nil) -> Cancellable {
return _perform(mutation: mutation, queue: queue, resultHandler: resultHandler)
}
func _perform<Mutation: GraphQLMutation>(mutation: Mutation, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Mutation>?) -> Cancellable {
return send(operation: mutation, context: context, handlerQueue: queue, resultHandler: resultHandler)
}
fileprivate func send<Operation: GraphQLOperation>(operation: Operation, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Operation>?) -> Cancellable {
func notifyResultHandler(result: GraphQLResult<Operation.Data>?, error: Error?) {
guard let resultHandler = resultHandler else { return }
handlerQueue.async {
resultHandler(result, error)
}
}
return networkTransport.send(operation: operation) { (response, error) in
guard let response = response else {
notifyResultHandler(result: nil, error: error)
return
}
firstly {
try response.parseResult(cacheKeyForObject: self.store.cacheKeyForObject)
}.andThen { (result, records) in
notifyResultHandler(result: result, error: nil)
if let records = records {
self.store.publish(records: records, context: context).catch { error in
preconditionFailure(String(describing: error))
}
}
}.catch { error in
notifyResultHandler(result: nil, error: error)
}
}
}
}
private final class FetchQueryOperation<Query: GraphQLQuery>: AsynchronousOperation, Cancellable {
let client: ApolloClient
let query: Query
let cachePolicy: CachePolicy
let context: UnsafeMutableRawPointer?
let handlerQueue: DispatchQueue
let resultHandler: OperationResultHandler<Query>?
private var networkTask: Cancellable?
init(client: ApolloClient, query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) {
self.client = client
self.query = query
self.cachePolicy = cachePolicy
self.context = context
self.handlerQueue = handlerQueue
self.resultHandler = resultHandler
}
override public func start() {
if isCancelled {
state = .finished
return
}
state = .executing
if cachePolicy == .fetchIgnoringCacheData {
fetchFromNetwork()
return
}
client.store.load(query: query) { (result, error) in
if error == nil {
self.notifyResultHandler(result: result, error: nil)
if self.cachePolicy != .returnCacheDataAndFetch {
self.state = .finished
return
}
}
if self.isCancelled {
self.state = .finished
return
}
if self.cachePolicy == .returnCacheDataDontFetch {
self.notifyResultHandler(result: nil, error: nil)
self.state = .finished
return
}
self.fetchFromNetwork()
}
}
func fetchFromNetwork() {
networkTask = client.send(operation: query, context: context, handlerQueue: handlerQueue) { (result, error) in
self.notifyResultHandler(result: result, error: error)
self.state = .finished
return
}
}
override public func cancel() {
super.cancel()
networkTask?.cancel()
}
func notifyResultHandler(result: GraphQLResult<Query.Data>?, error: Error?) {
guard let resultHandler = resultHandler else { return }
handlerQueue.async {
resultHandler(result, error)
}
}
}
| mit | 238ace2411891e6f6a23705de863389a | 41.634043 | 391 | 0.712147 | 4.933038 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | watchOS2/time Notification/timezoneModel.swift | 1 | 1584 | //
// timezones.swift
// timeNotification
//
// Created by Luis Castillo on 1/21/16.
// Copyright © 2016 LC. All rights reserved.
//
import UIKit
class timezoneModel: NSObject
{
private var timezones:NSArray?
override init()
{
if let pathOfFile = NSBundle .mainBundle() .pathForResource("timezones", ofType: "plist")
{
if let timezonesFromFile = NSArray(contentsOfFile: pathOfFile)
{
timezones = timezonesFromFile
}//
}//
}
//MARK: - Load Timezones
func reloadTimeZones()
{
if let pathOfFile = NSBundle .mainBundle() .pathForResource("timezones", ofType: "plist")
{
if let timezonesFromFile = NSArray(contentsOfFile: pathOfFile)
{
timezones = timezonesFromFile
}//
}//
}//eom
func getTimeZones()->NSArray?
{
let copyOfTimezones:NSArray? = timezones?.mutableCopy() as? NSArray
return copyOfTimezones
}
func getTimeZoneByAbbrev(abbrev: String)-> String
{
var timeString:String = ""
//
let time:NSDate = NSDate()
let timeZone = NSTimeZone(abbreviation: abbrev)
let formatter:NSDateFormatter = NSDateFormatter()
formatter.timeZone = timeZone
formatter.dateFormat = "h:mm a"
timeString = formatter.stringFromDate(time)
return timeString
}//eom
}
| mit | db44a13c7d3387daba9fe57302f8b301 | 24.95082 | 98 | 0.543272 | 5.106452 | false | false | false | false |
box/box-ios-sdk | Sources/Modules/FileRequestsModule.swift | 1 | 4010 | //
// FileRequestsModule.swift
// BoxSDK-iOS
//
// Created by Artur Jankowski on 09/08/2022.
// Copyright © 2022 box. All rights reserved.
//
import Foundation
/// Provides management of FileRequests
public class FileRequestsModule {
/// Required for communicating with Box APIs.
weak var boxClient: BoxClient!
// swiftlint:disable:previous implicitly_unwrapped_optional
/// Initializer
///
/// - Parameter boxClient: Required for communicating with Box APIs.
init(boxClient: BoxClient) {
self.boxClient = boxClient
}
/// Retrieves the information about a file request by ID.
///
/// - Parameters:
/// - fileRequestId: The unique identifier that represent a file request.
/// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError.
public func get(
fileRequestId: String,
completion: @escaping Callback<FileRequest>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Updates a file request. This can be used to activate or deactivate a file request.
///
/// - Parameters:
/// - fileRequestId: The unique identifier that represent a file request.
/// - ifMatch: Ensures this item hasn't recently changed before making changes.
/// Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. (optional)
/// - updateRequest: The `FileRequestUpdateRequest` object which provides the fields that can be updated.
/// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError.
public func update(
fileRequestId: String,
ifMatch: String? = nil,
updateRequest: FileRequestUpdateRequest,
completion: @escaping Callback<FileRequest>
) {
var headers: BoxHTTPHeaders = [:]
if let unwrappedIfMatch = ifMatch {
headers[BoxHTTPHeaderKey.ifMatch] = unwrappedIfMatch
}
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration),
httpHeaders: headers,
json: updateRequest.bodyDict,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Copies an existing file request that is already present on one folder, and applies it to another folder.
///
/// - Parameters:
/// - fileRequestId: The unique identifier that represent a file request.
/// - copyRequest: The `FileRequestCopyRequest` object which provides required and optional fields used when copying, like: folder(required), title(optional), etc.
/// - completion: Returns a FileRequest response object if successful otherwise a BoxSDKError.
public func copy(
fileRequestId: String,
copyRequest: FileRequestCopyRequest,
completion: @escaping Callback<FileRequest>
) {
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)/copy", configuration: boxClient.configuration),
json: copyRequest.bodyDict,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Deletes a file request permanently.
///
/// - Parameters:
/// - fileRequestId: The unique identifier that represent a file request.
/// - completion: Returns response object if successful otherwise a BoxSDKError.
public func delete(
fileRequestId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/file_requests/\(fileRequestId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
}
| apache-2.0 | 4ec0df15d1ad2adb2f5bcf7f35ef4a2d | 39.908163 | 169 | 0.670242 | 5.02381 | false | true | false | false |
boluomeng/Charts | ChartsRealm/Classes/Data/RealmBarDataSet.swift | 1 | 8946 | //
// RealmBarDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
import Charts
import Realm
import Realm.Dynamic
open class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet
{
open override func initialize()
{
self.highlightColor = NSUIColor.black
}
public required init()
{
super.init()
}
public override init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, label: String?)
{
super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label)
}
public init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, stackValueField: String, label: String?)
{
_stackValueField = stackValueField
super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, xIndexField: String?, stackValueField: String)
{
self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, stackValueField: stackValueField, label: "DataSet")
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String, label: String)
{
self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String)
{
self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField)
}
public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?)
{
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String, label: String?)
{
_stackValueField = stackValueField
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: nil)
}
open override func notifyDataSetChanged()
{
_cache.removeAll()
ensureCache(start: 0, end: entryCount - 1)
self.calcStackSize(_cache as! [BarChartDataEntry])
super.notifyDataSetChanged()
}
// MARK: - Data functions and accessors
internal var _stackValueField: String?
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
internal override func buildEntryFromResultObject(_ object: RLMObject, atIndex: UInt) -> ChartDataEntry
{
let value = object[_yValueField!]
let entry: BarChartDataEntry
if value is RLMArray
{
var values = [Double]()
for val in value as! RLMArray
{
values.append(val[_stackValueField!] as! Double)
}
entry = BarChartDataEntry(values: values, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int)
}
else
{
entry = BarChartDataEntry(value: value as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int)
}
return entry
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(_ yVals: [BarChartDataEntry]!)
{
for i in 0 ..< yVals.count
{
if let vals = yVals[i].values
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
open override func calcMinMax(start : Int, end: Int)
{
let yValCount = self.entryCount
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
ensureCache(start: start, end: endValue)
if _cache.count == 0
{
return
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for i in stride(from: start, through: endValue, by: 1)
{
if let e = _cache[i - _cacheFirst] as? BarChartDataEntry
{
if !e.value.isNaN
{
if e.values == nil
{
if e.value < _yMin
{
_yMin = e.value
}
if e.value > _yMax
{
_yMax = e.value
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the maximum number of bars that can be stacked upon another in this DataSet.
open var stackSize: Int
{
return _stackSize
}
/// - returns: true if this DataSet is stacked (stacksize > 1) or not.
open var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
open var barSpace: CGFloat = 0.15
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = super.copyWithZone(zone) as! RealmBarDataSet
copy._stackSize = _stackSize
copy.stackLabels = stackLabels
copy.barSpace = barSpace
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
| apache-2.0 | f750250b404f1fd44e224bb677ed88b8 | 33.407692 | 173 | 0.584954 | 5.04 | false | false | false | false |
plutoless/fgo-pluto | FgoPluto/FgoPluto/model/Material.swift | 1 | 2266 | //
// Material.swift
// FgoPluto
//
// Created by Zhang, Qianze on 17/09/2017.
// Copyright © 2017 Plutoless Studio. All rights reserved.
//
import Foundation
import UIKit
import RealmSwift
class Material:BaseObject
{
dynamic var id:Int = 0
dynamic var text:String = ""
dynamic var quantity:Int64 = 0
dynamic var kind:Int{
get{
return self.kindFromId()
}
}
dynamic lazy var image:UIImage? = {
return UIImage(named: "material-\(self.id).jpg")
}()
override func fillvalues(realm: Realm, data: [String : AnyObject]) {
super.fillvalues(realm: realm, data: data)
guard let id = Int(data["id"] as? String ?? "0") else {return}
self.id = id
}
override static func primaryKey() -> String? {
return "id"
}
override static func indexedProperties() -> [String] {
return ["id"]
}
override static func ignoredProperties() -> [String] {
return ["image", "kind"]
}
private func kindFromId() -> Int{
let mid = self.id
if(mid >= 100 && mid < 110){
return 0
} else if(mid >= 110 && mid < 120){
return 1
} else if(mid >= 200 && mid < 210){
return 2
} else if(mid >= 210 && mid < 220){
return 3
} else if(mid >= 220 && mid < 230){
return 4
} else if(mid >= 300 && mid < 400){
return 5
} else if(mid >= 400 && mid < 500){
return 6
} else if(mid >= 500 && mid < 600){
return 7
} else if(mid == 800 || mid == 900){
return 8
}
return -1
}
internal static func kind_name(kind:Int) -> String{
switch kind {
case 0:
return "银棋"
case 1:
return "金棋"
case 2:
return "辉石"
case 3:
return "魔石"
case 4:
return "秘石"
case 5:
return "铜素材"
case 6:
return "银素材"
case 7:
return "金素材"
case 8:
return "特殊素材"
default:
return "\(kind)"
}
}
}
| apache-2.0 | 7af48a60cdc9e412f29f72b1bd53c5f6 | 22.606383 | 72 | 0.474087 | 4.012658 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.