repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xeo-it/poggy | refs/heads/master | Poggy/ViewControllers/PoggyToolbar.swift | apache-2.0 | 1 | //
// PoggyToolbar.swift
// Poggy
//
// Created by Francesco Pretelli on 30/04/16.
// Copyright © 2016 Francesco Pretelli. All rights reserved.
//
import Foundation
import UIKit
protocol PoggyToolbarDelegate{
func onPoggyToolbarButtonTouchUpInside()
}
class PoggyToolbar:UIToolbar{
var mainButton:UIButton = UIButton(type: UIButtonType.Custom)
var poggyDelegate:PoggyToolbarDelegate?
override func layoutSubviews() {
super.layoutSubviews()
barStyle = UIBarStyle.BlackOpaque
backgroundColor = UIColor.clearColor()// PoggyConstants.POGGY_BLUE
mainButton.backgroundColor = PoggyConstants.POGGY_BLUE
//mainButton.titleLabel?.font = YNCSS.sharedInstance.getFont(21, style: YNCSS.FontStyle.REGULAR)
mainButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
mainButton.frame = CGRect(x: 0,y: 0,width: frame.width, height: frame.height)
mainButton.addTarget(self, action: #selector(self.onButtonTouchUpInside(_:)), forControlEvents: .TouchUpInside)
addSubview(mainButton)
}
func setButtonTitle(title:String){
mainButton.setTitle(title,forState: UIControlState.Normal)
}
func onButtonTouchUpInside(sender: UIButton!) {
poggyDelegate?.onPoggyToolbarButtonTouchUpInside()
}
} | e0a80ce894d083995613f79c9b58644a | 30.97619 | 119 | 0.707899 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SILGen/resilient_assign_by_wrapper.swift | apache-2.0 | 12 | // RUN: %target-swift-emit-silgen %s -emit-verbose-sil -enable-library-evolution | %FileCheck %s
@propertyWrapper
public struct WrapGod<T> {
private var value: T
public init(wrappedValue: T) {
value = wrappedValue
}
public var wrappedValue: T {
get { value }
set { value = newValue }
}
}
public protocol Existential {}
public enum AddressOnlyEnum {
case some
case value(Existential?)
}
public class AddressOnlySetter {
@WrapGod var value: AddressOnlyEnum = .value(nil)
init() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17AddressOnlySetterCACycfc
// CHECK: [[E1:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK: [[W:%.*]] = alloc_stack $WrapGod<AddressOnlyEnum>
// CHECK: [[I:%.*]] = function_ref @$s27resilient_assign_by_wrapper17AddressOnlySetterC5valueAA0eF4EnumOvpfP : $@convention(thin) (@in AddressOnlyEnum) -> @out WrapGod<AddressOnlyEnum>
// CHECK: apply [[I]]([[W]], [[E1]])
// CHECK: [[E2:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK-NEXT: inject_enum_addr [[E2]] : $*AddressOnlyEnum, #AddressOnlyEnum.some!enumelt
// CHECK: [[S:%.*]] = partial_apply [callee_guaranteed] {{%.*}}({{%.*}}) : $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
// CHECK: assign_by_wrapper [[E2]] : $*AddressOnlyEnum
// CHECK-SAME: set [[S]] : $@callee_guaranteed (@in AddressOnlyEnum) -> ()
self.value = .some
}
func testAssignment() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17AddressOnlySetterC14testAssignmentyyF
// CHECK: [[E:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK: inject_enum_addr [[E]] : $*AddressOnlyEnum, #AddressOnlyEnum.some!enumelt
// CHECK: [[S:%.*]] = class_method %0 : $AddressOnlySetter, #AddressOnlySetter.value!setter : (AddressOnlySetter) -> (AddressOnlyEnum) -> (), $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
// CHECK: apply [[S]]([[E]], %0) : $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
self.value = .some
}
}
public struct SubstitutedSetter<T> {
@WrapGod var value: T
}
extension SubstitutedSetter where T == Bool {
init() {
// CHECK-LABEL: hidden [ossa] @$s27resilient_assign_by_wrapper17SubstitutedSetterVAASbRszlEACySbGycfC
// CHECK: [[W:%.*]] = struct_element_addr {{%.*}} : $*SubstitutedSetter<Bool>, #SubstitutedSetter._value
// CHECK: [[B:%.*]] = alloc_stack $Bool
// CHECK: assign_by_wrapper [[B]] : $*Bool to [[W]] : $*WrapGod<Bool>
// CHECK-SAME: init {{%.*}} : $@callee_guaranteed (@in Bool) -> @out WrapGod<Bool>
// CHECK-SAME: set {{%.*}} : $@callee_guaranteed (@in Bool) -> ()
self.value = true
}
}
public struct ReabstractedSetter<T> {
@WrapGod var value: (T) -> ()
}
extension ReabstractedSetter where T == Int {
init() {
// CHECK-LABEL: hidden [ossa] @$s27resilient_assign_by_wrapper18ReabstractedSetterVAASiRszlEACySiGycfC
// CHECK: [[F:%.*]] = function_ref @$s27resilient_assign_by_wrapper18ReabstractedSetterVAASiRszlEACySiGycfcySicfU_ : $@convention(thin) (Int) -> ()
// CHECK: [[TH_F:%.*]] = thin_to_thick_function [[F]] : $@convention(thin) (Int) -> () to $@callee_guaranteed (Int) -> ()
// CHECK: [[THUNK_REF:%.*]] = function_ref @$sSiIegy_SiIegn_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> ()) -> ()
// CHECK: [[CF:%.*]] = partial_apply [callee_guaranteed] [[THUNK_REF]]([[TH_F]]) : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> ()) -> ()
// CHECK: [[CF2:%.*]] = convert_function [[CF]]
// CHECK: assign_by_wrapper [[CF2]]
// CHECK-SAME: to {{%.*}} : $*WrapGod<(Int) -> ()>
self.value = { x in }
}
}
public struct ObjectifiedSetter<T: AnyObject> {
@WrapGod var value: T
}
public class SomeObject {}
extension ObjectifiedSetter where T == SomeObject {
init() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17ObjectifiedSetterV5valuexvs : $@convention(method) <T where T : AnyObject> (@owned T, @inout ObjectifiedSetter<T>) -> () {
// CHECK: [[OBJ:%.*]] = apply {{%.*}}({{%.*}}) : $@convention(method) (@thick SomeObject.Type) -> @owned SomeObject
// CHECK: [[STORAGE:%.*]] = struct_element_addr {{%.*}} : $*ObjectifiedSetter<SomeObject>, #ObjectifiedSetter._value
// CHECK: assign_by_wrapper [[OBJ]] : $SomeObject to [[STORAGE]] : $*WrapGod<SomeObject>
// CHECK-SAME: init {{%.*}} : $@callee_guaranteed (@owned SomeObject) -> @out WrapGod<SomeObject>
// CHECK-SAME: set {{%.*}} : $@callee_guaranteed (@owned SomeObject) -> ()
self.value = SomeObject()
}
}
| 1ba6ab7a763ad742e641f58d9e729833 | 44.398058 | 225 | 0.640505 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/DiscoveryFilters/Datasource/DiscoveryFiltersDataSource.swift | apache-2.0 | 1 | import Library
import UIKit
internal final class DiscoveryFiltersDataSource: ValueCellDataSource {
internal enum Section: Int {
case collectionsHeader
case collections
case categoriesLoader
case favoritesHeader
case favorites
case categoriesHeader
case categories
}
internal func load(topRows rows: [SelectableRow], categoryId: Int?) {
self.set(
values: [(title: Strings.Collections(), categoryId: categoryId)],
cellClass: DiscoveryFiltersStaticRowCell.self,
inSection: Section.collectionsHeader.rawValue
)
let rowsAndId = rows.map { (row: $0, categoryId: categoryId) }
self.set(
values: rowsAndId,
cellClass: DiscoverySelectableRowCell.self,
inSection: Section.collections.rawValue
)
}
internal func load(favoriteRows rows: [SelectableRow], categoryId: Int?) {
self.set(
values: [(title: Strings.Bookmarks(), categoryId: categoryId)],
cellClass: DiscoveryFiltersStaticRowCell.self,
inSection: Section.favoritesHeader.rawValue
)
let rowsAndId = rows.map { (row: $0, categoryId: categoryId) }
self.set(
values: rowsAndId,
cellClass: DiscoverySelectableRowCell.self,
inSection: Section.favorites.rawValue
)
}
internal func load(categoryRows rows: [ExpandableRow], categoryId: Int?) {
self.set(
values: [(title: Strings.discovery_filters_categories_title(), categoryId: categoryId)],
cellClass: DiscoveryFiltersStaticRowCell.self,
inSection: Section.categoriesHeader.rawValue
)
self.clearValues(section: Section.categories.rawValue)
for row in rows {
self.appendRow(
value: (row: row, categoryId: categoryId),
cellClass: DiscoveryExpandableRowCell.self,
toSection: Section.categories.rawValue
)
if row.isExpanded {
for selectableRow in row.selectableRows {
self.appendRow(
value: (row: selectableRow, categoryId: categoryId),
cellClass: DiscoveryExpandedSelectableRowCell.self,
toSection: Section.categories.rawValue
)
}
}
}
}
internal func loadCategoriesLoaderRow() {
self.set(
values: [()],
cellClass: DiscoveryFiltersLoaderCell.self,
inSection: Section.categoriesLoader.rawValue
)
}
internal func deleteCategoriesLoaderRow(_ tableView: UITableView) -> [IndexPath]? {
if self.numberOfSections(in: tableView) > Section.categoriesLoader.rawValue,
!self[section: Section.categoriesLoader.rawValue].isEmpty {
self.clearValues(section: Section.categoriesLoader.rawValue)
return [IndexPath(row: 0, section: Section.categoriesLoader.rawValue)]
}
return nil
}
internal func selectableRow(indexPath: IndexPath) -> SelectableRow? {
if let (row, _) = self[indexPath] as? (SelectableRow, Int?) {
return row
}
return nil
}
internal func expandableRow(indexPath: IndexPath) -> ExpandableRow? {
if let (row, _) = self[indexPath] as? (ExpandableRow, Int?) {
return row
}
return nil
}
internal func indexPath(forCategoryId categoryId: Int?) -> IndexPath? {
for (idx, value) in self[section: Section.categories.rawValue].enumerated() {
guard let (row, _) = value as? (ExpandableRow, Int?) else { continue }
if row.params.category?.intID == categoryId {
return IndexPath(item: idx, section: Section.categories.rawValue)
}
}
return nil
}
internal func expandedRow() -> Int? {
for (idx, value) in self[section: Section.categories.rawValue].enumerated() {
guard let (row, _) = value as? (ExpandableRow, Int?) else { continue }
if row.isExpanded {
return idx
}
}
return nil
}
internal override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) {
switch (cell, value) {
case let (cell as DiscoverySelectableRowCell, value as (SelectableRow, Int?)):
cell.configureWith(value: value)
case let (cell as DiscoveryExpandableRowCell, value as (ExpandableRow, Int?)):
cell.configureWith(value: value)
case let (cell as DiscoveryExpandedSelectableRowCell, value as (SelectableRow, Int?)):
cell.configureWith(value: value)
case let (cell as DiscoveryFiltersStaticRowCell, value as (String, Int?)):
cell.configureWith(value: value)
case let (cell as DiscoveryFiltersLoaderCell, value as Void):
cell.configureWith(value: value)
default:
fatalError("Unrecognized combo (\(cell), \(value)).")
}
}
}
| c336ce2ccc9f61297a2c03c8ff6247c2 | 30.613793 | 95 | 0.679538 | false | false | false | false |
AndrewBennet/readinglist | refs/heads/master | ReadingList/ViewControllers/Settings/General.swift | gpl-3.0 | 1 | import SwiftUI
class GeneralSettingsObservable: ObservableObject {
@Published var addBooksToTop: Bool = GeneralSettings.addBooksToTopOfCustom {
didSet {
GeneralSettings.addBooksToTopOfCustom = addBooksToTop
}
}
@Published var progressType = GeneralSettings.defaultProgressType {
didSet { GeneralSettings.defaultProgressType = progressType }
}
@Published var prepopulateLastLanguageSelection = GeneralSettings.prepopulateLastLanguageSelection {
didSet {
GeneralSettings.prepopulateLastLanguageSelection = prepopulateLastLanguageSelection
if !prepopulateLastLanguageSelection { LightweightDataStore.lastSelectedLanguage = nil }
}
}
@Published var restrictSearchResultsTo: LanguageSelection = {
if let languageRestriction = GeneralSettings.searchLanguageRestriction {
return .some(languageRestriction)
} else {
return LanguageSelection.none
}
}() {
didSet {
if case .some(let selection) = restrictSearchResultsTo {
GeneralSettings.searchLanguageRestriction = selection
} else {
GeneralSettings.searchLanguageRestriction = .none
}
}
}
}
struct General: View {
@EnvironmentObject var hostingSplitView: HostingSettingsSplitView
@ObservedObject var settings = GeneralSettingsObservable()
private var inset: Bool {
hostingSplitView.isSplit
}
private let languageOptions = [LanguageSelection.none] + LanguageIso639_1.allCases.filter { $0.canFilterGoogleSearchResults }.map { .some($0) }
var body: some View {
SwiftUI.List {
Section(
header: HeaderText("Sort Options", inset: hostingSplitView.isSplit),
footer: FooterText("""
Configure whether newly added books get added to the top or the bottom of the \
reading list when Custom ordering is used.
""", inset: hostingSplitView.isSplit
)
) {
Toggle(isOn: $settings.addBooksToTop) {
Text("Add Books to Top")
}
}
Section(
header: HeaderText("Progress", inset: inset),
footer: FooterText("Choose whether to default to Page Number or Percentage when setting progress.", inset: inset)
) {
NavigationLink(
destination: SelectionForm<ProgressType>(
options: [.page, .percentage],
selectedOption: $settings.progressType
).navigationBarTitle("Default Progress Type")
) {
HStack {
Text("Progress Type")
Spacer()
Text(settings.progressType.description)
.foregroundColor(.secondary)
}
}
}
Section(
header: HeaderText("Language", inset: inset),
footer: FooterText("""
By default, Reading List prioritises search results based on their language and your location. To instead \
restrict search results to be of a specific language only, select a language above.
""", inset: inset)
) {
Toggle(isOn: $settings.prepopulateLastLanguageSelection) {
Text("Remember Last Selection")
}
NavigationLink(
destination: SelectionForm<LanguageSelection>(
options: languageOptions,
selectedOption: $settings.restrictSearchResultsTo
).navigationBarTitle("Language Restriction")
) {
HStack {
Text("Restrict Search Results")
Spacer()
Text(settings.restrictSearchResultsTo.description).foregroundColor(.secondary)
}
}
}
}
.possiblyInsetGroupedListStyle(inset: hostingSplitView.isSplit)
}
}
extension ProgressType: Identifiable {
var id: Int { rawValue }
}
extension LanguageSelection: Identifiable {
var id: String {
switch self {
case .none: return ""
// Not in practise used by this form; return some arbitrary unique value
case .blank: return "!"
case .some(let language): return language.rawValue
}
}
}
struct General_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
General().environmentObject(HostingSettingsSplitView())
}
}
}
| 4781c2d61b59c7df10ad0b333d611138 | 36.292308 | 147 | 0.570338 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Jetpack/Branding/Coordinator/JetpackBrandingCoordinator.swift | gpl-2.0 | 1 | import UIKit
/// A class containing convenience methods for the the Jetpack branding experience
class JetpackBrandingCoordinator {
static func presentOverlay(from viewController: UIViewController, redirectAction: (() -> Void)? = nil) {
let action = redirectAction ?? {
JetpackRedirector.redirectToJetpack()
}
let jetpackOverlayViewController = JetpackOverlayViewController(viewFactory: makeJetpackOverlayView, redirectAction: action)
let bottomSheet = BottomSheetViewController(childViewController: jetpackOverlayViewController, customHeaderSpacing: 0)
bottomSheet.show(from: viewController)
}
static func makeJetpackOverlayView(redirectAction: (() -> Void)? = nil) -> UIView {
JetpackOverlayView(buttonAction: redirectAction)
}
static func shouldShowBannerForJetpackDependentFeatures() -> Bool {
let phase = JetpackFeaturesRemovalCoordinator.generalPhase()
switch phase {
case .two:
fallthrough
case .three:
return true
default:
return false
}
}
}
| 337366c7f9fce60c6f55f6ea1526500c | 34.09375 | 132 | 0.691006 | false | false | false | false |
Himnshu/LoginLib | refs/heads/master | Example/LoginLib/LoginCoordinator.swift | mit | 1 | //
// LoginCoordinator.swift
// LoginFramework
//
// Created by OSX on 28/07/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import LoginLib
class LoginCoordinator: LoginLib.LoginCoordinator
{
override func start() {
super.start()
configureAppearance()
}
override func finish() {
super.finish()
}
func configureAppearance() {
// Customize LoginKit. All properties have defaults, only set the ones you want.
// Customize the look with background & logo images
backgroundImage = #imageLiteral(resourceName: "background")
mainLogoImage = #imageLiteral(resourceName: "parseImage")
secondaryLogoImage = #imageLiteral(resourceName: "parseImage")
// Change colors
tintColor = UIColor(red: 52.0/255.0, green: 152.0/255.0, blue: 219.0/255.0, alpha: 1)
errorTintColor = UIColor(red: 253.0/255.0, green: 227.0/255.0, blue: 167.0/255.0, alpha: 1)
// Change placeholder & button texts, useful for different marketing style or language.
loginButtonText = "Sign In"
signupButtonText = "Create Account"
forgotPasswordButtonText = "Forgot password?"
recoverPasswordButtonText = "Recover"
namePlaceholder = "Full Name"
emailPlaceholder = "E-Mail"
passwordPlaceholder = "Password!"
repeatPasswordPlaceholder = "Confirm password!"
}
// MARK: - Completion Callbacks
override func login(profile: LoginProfile) {
// Handle login via your API
print("Login with: email =\(profile.email) username = \(profile.userName)")
}
override func signup(profile: SignUpProfile) {
// Handle signup via your API
print("Signup with: name = \(profile.userName) email =\(profile.email)")
}
override func loginError(error: NSError) {
// Handle login error via your API
let errorString = error.userInfo["error"] as? String
print("Error: \(errorString)")
}
override func signUpError(error: NSError) {
// Handle login error via your API
print(error)
}
override func enterWithFacebook(profile: FacebookProfile) {
// Handle Facebook login/signup via your API
print("Login/Signup via Facebook with: FB profile =\(profile)")
}
override func enterWithTwitter(profile: TwitterProfile) {
// Handle Facebook login/signup via your API
print("Login/Signup via Facebook with: FB profile =\(profile)")
}
override func recoverPassword(success: Bool) {
// Handle password recovery via your API
print(success)
}
override func recoverPasswordError(error: NSError) {
print(error)
}
}
| 3a80d2193fafd7d92129591aabf73328 | 31.344828 | 99 | 0.633618 | false | false | false | false |
Diego5529/animated-tab-bar | refs/heads/master | MNTApp/RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift | mit | 3 | // AnimationTabBarController.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class RAMAnimatedTabBarItem: UITabBarItem {
@IBOutlet weak var animation: RAMItemAnimation!
@IBInspectable var textColor: UIColor = UIColor.blackColor()
func playAnimation(icon: UIImageView, textLabel: UILabel) {
assert(animation != nil, "add animation in UITabBarItem")
if animation != nil {
animation.playAnimation(icon, textLabel: textLabel)
}
}
func deselectAnimation(icon: UIImageView, textLabel: UILabel) {
if animation != nil {
animation.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor)
}
}
func selectedState(icon: UIImageView, textLabel: UILabel) {
if animation != nil {
animation.selectedState(icon, textLabel: textLabel)
}
}
}
class RAMAnimatedTabBarController: UITabBarController {
var iconsView: [(icon: UIImageView, textLabel: UILabel)] = Array()
// MARK: life circle
override func viewDidLoad() {
super.viewDidLoad()
let containers = createViewContainers()
createCustomIcons(containers)
}
// MARK: create methods
func createCustomIcons(containers : NSDictionary) {
if let items = tabBar.items {
let itemsCount = tabBar.items!.count as Int - 1
var index = 0
for item in self.tabBar.items as [RAMAnimatedTabBarItem] {
assert(item.image != nil, "add image icon in UITabBarItem")
var container : UIView = containers["container\(itemsCount-index)"] as UIView
container.tag = index
var icon = UIImageView(image: item.image)
icon.setTranslatesAutoresizingMaskIntoConstraints(false)
icon.tintColor = UIColor.clearColor()
// text
var textLabel = UILabel()
textLabel.text = item.title
textLabel.backgroundColor = UIColor.clearColor()
textLabel.textColor = item.textColor
textLabel.font = UIFont.systemFontOfSize(10)
textLabel.textAlignment = NSTextAlignment.Center
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
container.addSubview(icon)
createConstraints(icon, container: container, size: item.image!.size, yOffset: -5)
container.addSubview(textLabel)
let textLabelWidth = tabBar.frame.size.width / CGFloat(tabBar.items!.count) - 5.0
createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16)
let iconsAndLabels = (icon:icon, textLabel:textLabel)
iconsView.append(iconsAndLabels)
if 0 == index { // selected first elemet
item.selectedState(icon, textLabel: textLabel)
}
item.image = nil
item.title = ""
index++
}
}
}
func createConstraints(view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) {
var constX = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0)
container.addConstraint(constX)
var constY = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: yOffset)
container.addConstraint(constY)
var constW = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.width)
view.addConstraint(constW)
var constH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.height)
view.addConstraint(constH)
}
func createViewContainers() -> NSDictionary {
var containersDict = NSMutableDictionary()
let itemsCount : Int = tabBar.items!.count as Int - 1
for index in 0...itemsCount {
var viewContainer = createViewContainer()
containersDict.setValue(viewContainer, forKey: "container\(index)")
}
var keys = containersDict.allKeys
var formatString = "H:|-(0)-[container0]"
for index in 1...itemsCount {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
var constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
options:NSLayoutFormatOptions.DirectionRightToLeft,
metrics: nil,
views: containersDict)
view.addConstraints(constranints)
return containersDict
}
func createViewContainer() -> UIView {
var viewContainer = UIView();
viewContainer.backgroundColor = UIColor.clearColor() // for test
viewContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(viewContainer)
// add gesture
var tapGesture = UITapGestureRecognizer(target: self, action: "tapHeandler:")
tapGesture.numberOfTouchesRequired = 1
viewContainer.addGestureRecognizer(tapGesture)
// add constrains
var constY = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0)
view.addConstraint(constY)
var constH = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: tabBar.frame.size.height)
viewContainer.addConstraint(constH)
return viewContainer
}
// MARK: actions
func tapHeandler(gesture:UIGestureRecognizer) {
let items = tabBar.items as [RAMAnimatedTabBarItem]
let currentIndex = gesture.view!.tag
if selectedIndex != currentIndex {
var animationItem : RAMAnimatedTabBarItem = items[currentIndex]
var icon = iconsView[currentIndex].icon
var textLabel = iconsView[currentIndex].textLabel
animationItem.playAnimation(icon, textLabel: textLabel)
let deselelectIcon = iconsView[selectedIndex].icon
let deselelectTextLabel = iconsView[selectedIndex].textLabel
let deselectItem = items[selectedIndex]
deselectItem.deselectAnimation(deselelectIcon, textLabel: deselelectTextLabel)
selectedIndex = gesture.view!.tag
}
}
}
| 6d91f7dd378f2824bc0d29c036ff45d8 | 36.940928 | 129 | 0.609875 | false | false | false | false |
omniprog/SwiftZSTD | refs/heads/master | Sources/ZSTDProcessor.swift | bsd-3-clause | 1 | //
// ZSTDProcessor.swift
//
// Created by Anatoli on 12/06/16.
// Copyright © 2016 Anatoli Peredera. All rights reserved.
//
import Foundation
/**
* Class that supports compression/decompression of an in-memory buffer without using
* a dictionary. A compression/decompression context can be used optionally to speed
* up processing of multiple buffers.
*/
public class ZSTDProcessor
{
let commonProcessor : ZSTDProcessorCommon
var currentCL : Int32 = 0
/**
* Initializer.
*
* - paremeter useContext : true if use of context is desired
*/
public init(useContext : Bool = false)
{
commonProcessor = ZSTDProcessorCommon(useContext: useContext)
}
/**
* Compress a buffer. Input is sent to the C API without copying by using the
* Data.withUnsafeBytes() method. The C API places the output straight into the newly-
* created Data instance, which is possible because there are no other references
* to the instance at this point, so calling withUnsafeMutableBytes() does not trigger
* a copy-on-write.
*
* - parameter dataIn : input Data
* - parameter compressionLevel : must be 1-22, levels >= 20 to be used with caution
* - returns: compressed frame
*/
public func compressBuffer(_ dataIn : Data, compressionLevel : Int32) throws -> Data
{
guard isValidCompressionLevel(compressionLevel) else {
throw ZSTDError.invalidCompressionLevel(cl: compressionLevel)
}
currentCL = compressionLevel
return try commonProcessor.compressBufferCommon(dataIn, compressFrameHelper)
}
/**
* A private helper passed to commonProcessor.compressBufferCommon().
*/
private func compressFrameHelper(dst : UnsafeMutableRawPointer,
dstCapacity : Int,
src : UnsafeRawPointer,
srcSize : Int) -> Int {
if commonProcessor.compCtx != nil {
return ZSTD_compressCCtx(commonProcessor.compCtx, dst, dstCapacity, src, srcSize, currentCL);
} else {
return ZSTD_compress(dst, dstCapacity, src, srcSize, currentCL)
}
}
/**
* Decompress a frame that resulted from a previous compression of a buffer by a call
* to compressBuffer().
*
* - parameter dataIn: frame to be decompressed
* - returns: a Data instance wrapping the decompressed buffer
*/
public func decompressFrame(_ dataIn : Data) throws -> Data
{
return try commonProcessor.decompressFrameCommon(dataIn, decompressFrameHelper)
}
/**
* A private helper passed to commonProcessor.decompressFrameCommon().
*/
private func decompressFrameHelper(dst : UnsafeMutableRawPointer,
dstCapacity : Int,
src : UnsafeRawPointer, srcSize : Int) -> Int {
if commonProcessor.decompCtx != nil {
return ZSTD_decompressDCtx(commonProcessor.decompCtx, dst, dstCapacity, src, srcSize);
} else {
return ZSTD_decompress(dst, dstCapacity, src, srcSize)
}
}
}
| 1895766c54e55623aa4e5b29b8d567bf | 34.94382 | 105 | 0.6402 | false | false | false | false |
wangyuanou/Coastline | refs/heads/master | Coastline/System/MultiLanguage.swift | mit | 1 | //
// MultiLanguage.swift
// Coastline
//
// Created by 王渊鸥 on 2016/12/20.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import Foundation
public class MultiLanguage {
public static var shareInstance:MultiLanguage = { MultiLanguage() }()
var bundle:Bundle?
init() {
if let path = Bundle.main.path(forResource: langName, ofType: "lproj") {
bundle = Bundle(path: path)
}
}
public var langName:String {
get {
let ud = UserDefaults.standard
if let lang = ud.object(forKey: "cur_lang") as? String {
return lang
} else {
var lang = "Base"
if let langs = ud.object(forKey: "AppleLanguages") as? [String] , langs.count > 0 {
if langs[0].hasPrefix("zh") {
lang = "zh-Hans"
}
}
ud.set(lang, forKey: "cur_lang")
OperationQueue().addOperation {
let ud = UserDefaults.standard
ud.synchronize()
}
return lang
}
}
set {
if let path = Bundle.main.path(forResource: langName, ofType: "lproj") {
bundle = Bundle(path: path)
OperationQueue().addOperation {
let ud = UserDefaults.standard
ud.set(newValue, forKey: "cur_lang")
ud.synchronize()
}
}
}
}
public func str(key:String) -> String? {
return bundle?.localizedString(forKey: key, value: nil, table: nil)
}
public func str(table:String, key:String) -> String? {
return bundle?.localizedString(forKey: key, value: nil, table: table)
}
public func storyboard(name:String) -> UIStoryboard {
return UIStoryboard(name: name, bundle: bundle)
}
}
public extension String {
var l:String {
return NSLocalizedString(self, comment: self)
}
}
| c888ddd5ce5cac253cadb36c344dc5cd | 21.424658 | 87 | 0.64325 | false | false | false | false |
LeeShiYoung/DouYu | refs/heads/master | DouYuAPP/DouYuAPP/Classes/Home/View/Yo_HomeGameViewCell.swift | apache-2.0 | 1 | //
// Yo_HomeGameViewCell.swift
// DouYuAPP
//
// Created by shying li on 2017/4/1.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
class Yo_HomeGameViewCell: Yo_BaseCollectionViewCell {
override func configureView() {
super.configureView()
setupUI()
}
public lazy var gameName: UILabel = {[weak self] in
let gameName = UILabel()
gameName.textColor = UIColor.white
gameName.font = UIFont.systemFont(ofSize: 12)
gameName.textColor = UIColor.colorWithHex("#c9c9cd")
self?.contentView.addSubview(gameName)
return gameName
}()
}
extension Yo_HomeGameViewCell {
fileprivate func setupUI() {
coverImage.snp.remakeConstraints { (maker) in
maker.centerX.equalTo(contentView.snp.centerX)
maker.centerY.equalTo(contentView.snp.centerY).offset(-10)
maker.width.height.equalTo(45)
}
gameName.snp.makeConstraints { (maker) in
maker.top.equalTo(coverImage.snp.bottom).offset(7)
maker.centerX.equalTo(coverImage.snp.centerX)
}
}
}
extension Yo_HomeGameViewCell {
override func configure(Item: Any, indexPath: IndexPath) {
let model = Item as? Yo_AnchorBaseGroup
gameName.text = model?.tag_name
if let iconUrl = URL(string: model?.icon_url ?? "") {
coverImage.yo_setImage(iconUrl, placeholder: "", radius: 104)
} else {
coverImage.image = UIImage(named: "home_more_btn")
}
}
}
| d43f7a7aeaeaf8a1605cb107d7acec1e | 26.964286 | 73 | 0.619413 | false | true | false | false |
material-motion/material-motion-swift | refs/heads/develop | Pods/MaterialMotion/src/operators/valve.swift | apache-2.0 | 2 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import IndefiniteObservable
extension MotionObservableConvertible {
/**
A valve creates control flow for a stream.
The upstream will be subscribed to when valveStream emits true, and the subscription terminated
when the valveStream emits false.
*/
public func valve<O: MotionObservableConvertible>(openWhenTrue valveStream: O) -> MotionObservable<T> where O.T == Bool {
return MotionObservable<T> { observer in
var upstreamSubscription: Subscription?
let valveSubscription = valveStream.subscribeToValue { shouldOpen in
if shouldOpen && upstreamSubscription == nil {
upstreamSubscription = self.asStream().subscribeAndForward(to: observer)
}
if !shouldOpen && upstreamSubscription != nil {
upstreamSubscription?.unsubscribe()
upstreamSubscription = nil
}
}
return {
valveSubscription.unsubscribe()
upstreamSubscription?.unsubscribe()
upstreamSubscription = nil
}
}
}
}
| 661fb05aa6f39ce88ced2896b5c05d0b | 32.244898 | 123 | 0.722529 | false | false | false | false |
atrick/swift | refs/heads/main | SwiftCompilerSources/Sources/SIL/Argument.swift | apache-2.0 | 2 | //===--- Argument.swift - Defines the Argument classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
/// A basic block argument.
///
/// Maps to both, SILPhiArgument and SILFunctionArgument.
public class Argument : Value, Equatable {
public var definingInstruction: Instruction? { nil }
public var block: BasicBlock {
return SILArgument_getParent(bridged).block
}
var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) }
public var index: Int {
return block.arguments.firstIndex(of: self)!
}
public static func ==(lhs: Argument, rhs: Argument) -> Bool {
lhs === rhs
}
}
final public class FunctionArgument : Argument {
public var isExclusiveIndirectParameter: Bool {
SILArgument_isExclusiveIndirectParameter(bridged) != 0
}
}
final public class BlockArgument : Argument {
public var isPhiArgument: Bool {
block.predecessors.allSatisfy {
let term = $0.terminator
return term is BranchInst || term is CondBranchInst
}
}
public var incomingPhiOperands: LazyMapSequence<PredecessorList, Operand> {
assert(isPhiArgument)
let idx = index
return block.predecessors.lazy.map {
switch $0.terminator {
case let br as BranchInst:
return br.operands[idx]
case let condBr as CondBranchInst:
if condBr.trueBlock == self.block {
assert(condBr.falseBlock != self.block)
return condBr.trueOperands[idx]
} else {
assert(condBr.falseBlock == self.block)
return condBr.falseOperands[idx]
}
default:
fatalError("wrong terminator for phi-argument")
}
}
}
public var incomingPhiValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> {
incomingPhiOperands.lazy.map { $0.value }
}
}
// Bridging utilities
extension BridgedArgument {
var argument: Argument { obj.getAs(Argument.self) }
var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) }
}
| 26c81ff5d95ee470e10da0119acd0e61 | 28.987805 | 99 | 0.664091 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/ConversationMessageCellTableViewAdapter.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
import UIKit
protocol ConversationMessageCellMenuPresenter: AnyObject {
func showMenu()
}
extension UITableViewCell {
@objc func willDisplayCell() {
// to be overriden in subclasses
}
@objc func didEndDisplayingCell() {
// to be overriden in subclasses
}
}
class ConversationMessageCellTableViewAdapter<C: ConversationMessageCellDescription>: UITableViewCell, SelectableView, HighlightableView, ConversationMessageCellMenuPresenter {
var cellView: C.View
var ephemeralCountdownView: EphemeralCountdownView
var cellDescription: C? {
didSet {
longPressGesture.isEnabled = cellDescription?.supportsActions == true
doubleTapGesture.isEnabled = cellDescription?.supportsActions == true
singleTapGesture.isEnabled = cellDescription?.supportsActions == true
}
}
var topMargin: Float = 0 {
didSet {
top.constant = CGFloat(topMargin)
}
}
var isFullWidth: Bool = false {
didSet {
configureConstraints(fullWidth: isFullWidth)
}
}
override var accessibilityIdentifier: String? {
get {
return cellDescription?.accessibilityIdentifier
}
set {
super.accessibilityIdentifier = newValue
}
}
override var accessibilityLabel: String? {
get {
return cellDescription?.accessibilityLabel
}
set {
super.accessibilityLabel = newValue
}
}
private var leading: NSLayoutConstraint!
private var top: NSLayoutConstraint!
private var trailing: NSLayoutConstraint!
private var bottom: NSLayoutConstraint!
private var ephemeralTop: NSLayoutConstraint!
private var longPressGesture: UILongPressGestureRecognizer!
private var doubleTapGesture: UITapGestureRecognizer!
private var singleTapGesture: UITapGestureRecognizer!
var showsMenu = false
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
self.cellView = C.View(frame: .zero)
self.cellView.translatesAutoresizingMaskIntoConstraints = false
self.ephemeralCountdownView = EphemeralCountdownView()
self.ephemeralCountdownView.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.focusStyle = .custom
self.selectionStyle = .none
self.backgroundColor = .clear
self.isOpaque = false
contentView.addSubview(cellView)
contentView.addSubview(ephemeralCountdownView)
leading = cellView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)
trailing = cellView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
top = cellView.topAnchor.constraint(equalTo: contentView.topAnchor)
bottom = cellView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
bottom.priority = UILayoutPriority(999)
ephemeralTop = ephemeralCountdownView.topAnchor.constraint(equalTo: cellView.topAnchor)
NSLayoutConstraint.activate([
ephemeralCountdownView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
ephemeralCountdownView.trailingAnchor.constraint(equalTo: cellView.leadingAnchor),
ephemeralTop,
leading,
trailing,
top,
bottom
])
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress))
contentView.addGestureRecognizer(longPressGesture)
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTap))
doubleTapGesture.numberOfTapsRequired = 2
contentView.addGestureRecognizer(doubleTapGesture)
singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onSingleTap))
cellView.addGestureRecognizer(singleTapGesture)
singleTapGesture.require(toFail: doubleTapGesture)
singleTapGesture.delegate = self
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(with object: C.View.Configuration, fullWidth: Bool, topMargin: Float) {
cellView.configure(with: object, animated: false)
self.isFullWidth = fullWidth
self.topMargin = topMargin
self.ephemeralCountdownView.isHidden = cellDescription?.showEphemeralTimer == false
self.ephemeralCountdownView.message = cellDescription?.message
}
func configureConstraints(fullWidth: Bool) {
let margins = conversationHorizontalMargins
leading.constant = fullWidth ? 0 : margins.left
trailing.constant = fullWidth ? 0 : -margins.right
ephemeralTop.constant = cellView.ephemeralTimerTopInset
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
configureConstraints(fullWidth: isFullWidth)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
UIView.animate(withDuration: 0.35, animations: {
self.cellView.isSelected = selected
self.layoutIfNeeded()
})
}
// MARK: - Menu
@objc
private func onLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == .began {
showMenu()
}
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
guard let actionController = cellDescription?.actionController else {
return false
}
return actionController.canPerformAction(action) == true
}
override func forwardingTarget(for aSelector: Selector!) -> Any? {
return cellDescription?.actionController
}
func showMenu() {
guard cellDescription?.supportsActions == true else {
return
}
let needsFirstResponder = cellDescription?.delegate?.conversationMessageShouldBecomeFirstResponderWhenShowingMenuForCell(self)
registerMenuObservers()
let menu = UIMenuController.shared
menu.menuItems = ConversationMessageActionController.allMessageActions
if needsFirstResponder != false {
self.becomeFirstResponder()
}
menu.showMenu(from: selectionView, rect: selectionRect)
}
// MARK: - Single Tap Action
@objc private func onSingleTap(_ gestureRecognizer: UITapGestureRecognizer) {
if gestureRecognizer.state == .recognized && cellDescription?.supportsActions == true {
cellDescription?.actionController?.performSingleTapAction()
}
}
// MARK: - Double Tap Action
@objc private func onDoubleTap(_ gestureRecognizer: UITapGestureRecognizer) {
if gestureRecognizer.state == .recognized && cellDescription?.supportsActions == true {
cellDescription?.actionController?.performDoubleTapAction()
}
}
// MARK: - Target / Action
private func registerMenuObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(menuWillShow), name: UIMenuController.willShowMenuNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(menuDidHide), name: UIMenuController.didHideMenuNotification, object: nil)
}
@objc private func menuWillShow(_ note: Notification) {
showsMenu = true
setSelectedByMenu(true, animated: true)
NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil)
}
@objc private func menuDidHide(_ note: Notification) {
showsMenu = false
setSelectedByMenu(false, animated: true)
NotificationCenter.default.removeObserver(self, name: UIMenuController.didHideMenuNotification, object: nil)
}
func setSelectedByMenu(_ isSelected: Bool, animated: Bool) {
let animations = {
self.selectionView.alpha = isSelected ? 0.4 : 1
}
UIView.animate(withDuration: 0.32, animations: animations)
}
// MARK: - SelectableView
var selectionView: UIView! {
return cellView.selectionView ?? self
}
var selectionRect: CGRect {
if cellView.selectionView != nil {
return cellView.selectionRect
} else {
return self.bounds
}
}
var highlightContainer: UIView {
return self
}
override func willDisplayCell() {
cellDescription?.willDisplayCell()
cellView.willDisplay()
ephemeralCountdownView.startCountDown()
}
override func didEndDisplayingCell() {
cellDescription?.didEndDisplayingCell()
cellView.didEndDisplaying()
ephemeralCountdownView.stopCountDown()
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == singleTapGesture else { return super.gestureRecognizerShouldBegin(gestureRecognizer) }
// We fail the single tap gesture recognizer if there's no single tap action to perform, which gives
// other gesture recognizers the opportunity to fire.
return cellDescription?.actionController?.singleTapAction != nil
}
}
extension UITableView {
func register<C: ConversationMessageCellDescription>(cell: C.Type) {
let reuseIdentifier = String(describing: C.self)
register(ConversationMessageCellTableViewAdapter<C>.self, forCellReuseIdentifier: reuseIdentifier)
}
func dequeueConversationCell<C: ConversationMessageCellDescription>(with description: C, for indexPath: IndexPath) -> ConversationMessageCellTableViewAdapter<C> {
let reuseIdentifier = String(describing: C.self)
let cell = dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as Any as! ConversationMessageCellTableViewAdapter<C>
cell.cellDescription = description
cell.configure(with: description.configuration, fullWidth: description.isFullWidth, topMargin: description.topMargin)
return cell
}
}
| 9094809b233390c82ab34554c2962a55 | 33.70405 | 176 | 0.699192 | false | false | false | false |
ppraveentr/MobileCore | refs/heads/master | Sources/CoreUtility/Extensions/AttributedLabelProtocol.swift | mit | 1 | //
// AttributedLabelProtocol.swift
// MobileCore-CoreUtility
//
// Created by Praveen P on 20/10/19.
//
import Foundation
import UIKit
public typealias LabelLinkHandler = (LinkHandlerModel) -> Void
// For Visual update of 'Theme' & 'attributedText'
public protocol OptionalLayoutSubview {
func updateVisualThemes()
}
protocol AttributedLabelProtocol where Self: UILabel {
// Link handler
var linkRanges: [LinkHandlerModel]? { get set }
var linkHandler: LabelLinkHandler? { get set }
var tapGestureRecognizer: UITapGestureRecognizer { get }
// layout
var layoutManager: NSLayoutManager { get }
var styleProperties: AttributedDictionary { get set }
}
private extension AssociatedKey {
static var textContainer = "textContainer"
static var layoutManager = "layoutManager"
static var styleProperties = "styleProperties"
static var linkRanges = "linkRanges"
static var islinkDetectionEnabled = "islinkDetectionEnabled"
static var isLinkUnderLineEnabled = "isLinkUnderLineEnabled"
static var linkHandler = "linkHandler"
static var tapGestureRecognizer = "tapGestureRecognizer"
}
extension UILabel: AttributedLabelProtocol {
public var linkRanges: [LinkHandlerModel]? {
get { AssociatedObject.getAssociated(self, key: &AssociatedKey.linkRanges) }
set { AssociatedObject<[LinkHandlerModel]>.setAssociated(self, value: newValue, key: &AssociatedKey.linkRanges) }
}
// LabelThemeProtocol
public var islinkDetectionEnabled: Bool {
get { AssociatedObject.getAssociated(self, key: &AssociatedKey.islinkDetectionEnabled) { true }! }
set { AssociatedObject<Bool>.setAssociated(self, value: newValue, key: &AssociatedKey.islinkDetectionEnabled) }
}
public var isLinkUnderLineEnabled: Bool {
get { AssociatedObject.getAssociated(self, key: &AssociatedKey.isLinkUnderLineEnabled) { false }! }
set { AssociatedObject<Bool>.setAssociated(self, value: newValue, key: &AssociatedKey.isLinkUnderLineEnabled) }
}
public var linkHandler: LabelLinkHandler? {
get { AssociatedObject.getAssociated(self, key: &AssociatedKey.linkHandler) }
set {
AssociatedObject<LabelLinkHandler>.setAssociated(self, value: newValue, key: &AssociatedKey.linkHandler)
self.isUserInteractionEnabled = true
self.addGestureRecognizer(self.tapGestureRecognizer)
}
}
public var tapGestureRecognizer: UITapGestureRecognizer {
AssociatedObject.getAssociated(self, key: &AssociatedKey.tapGestureRecognizer) { UILabel.tapGesture(targer: self) }!
}
public var layoutManager: NSLayoutManager {
AssociatedObject.getAssociated(self, key: &AssociatedKey.layoutManager) { NSLayoutManager() }!
}
public var textContainer: NSTextContainer {
let local: NSTextContainer = AssociatedObject.getAssociated(self, key: &AssociatedKey.textContainer) { self.getTextContainer() }!
local.lineFragmentPadding = 0.0
local.maximumNumberOfLines = self.numberOfLines
local.lineBreakMode = self.lineBreakMode
local.widthTracksTextView = true
local.heightTracksTextView = true
local.size = self.bounds.size
return local
}
public var styleProperties: AttributedDictionary {
get { AssociatedObject.getAssociated(self, key: &AssociatedKey.styleProperties) { self.defaultStyleProperties }! }
set { AssociatedObject<AttributedDictionary>.setAssociated(self, value: newValue, key: &AssociatedKey.styleProperties) }
}
public var htmlText: String {
get { "" }
set { updateWithHtmlString(text: newValue) }
}
}
extension UILabel: OptionalLayoutSubview {
@objc
public func updateVisualThemes() {
if islinkDetectionEnabled, self.text.isHTMLString, let newValue = self.text {
self.text = newValue.stripHTML()
self.numberOfLines = 0
updateWithHtmlString(text: newValue)
}
}
private static func tapGesture(targer: AnyObject?) -> UITapGestureRecognizer {
UITapGestureRecognizer(target: targer, action: #selector(UILabel.tapGestureRecognized(_:)))
}
@objc
func tapGestureRecognized(_ gesture: UITapGestureRecognizer) {
if self == gesture.view, let link = self.didTapAttributedText(gesture)?.first {
self.linkHandler?(link)
}
}
fileprivate var offsetXDivisor: CGFloat {
switch self.textAlignment {
case .center: return 0.5
case .right: return 1.0
default: return 0.0
}
}
private func getTextContainer() -> NSTextContainer {
let container = NSTextContainer()
container.replaceLayoutManager(self.layoutManager)
self.layoutManager.addTextContainer(container)
return container
}
private var defaultStyleProperties: AttributedDictionary {
let paragrahStyle = NSMutableParagraphStyle()
paragrahStyle.alignment = self.textAlignment
paragrahStyle.lineBreakMode = self.lineBreakMode
var properties: AttributedDictionary = [
.paragraphStyle: paragrahStyle,
.backgroundColor: self.backgroundColor ?? UIColor.clear
]
if let font = self.font {
properties[.font] = font
}
if let color = self.textColor {
properties[.foregroundColor] = color
}
return properties
}
}
extension UILabel {
// MARK: Text Formatting
func updateWithHtmlString(text: String?) {
let att = text?.htmlAttributedString()
self.updateTextWithAttributedString(attributedString: att)
}
func updateTextContainerSize() {
var localSize = self.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
localSize.width = min(localSize.width, self.preferredMaxLayoutWidth)
self.frame = CGRect(origin: frame.origin, size: localSize)
}
func updateTextWithAttributedString(attributedString: NSAttributedString?) {
if let attributedString = attributedString {
let sanitizedString = self.sanitizeAttributedString(attributedString: attributedString)
sanitizedString.addAttributes(self.styleProperties, range: sanitizedString.nsRange())
if islinkDetectionEnabled {
updateLinkInText(attributedString: sanitizedString)
}
self.attributedText = sanitizedString
}
layoutTextView()
}
func updateLinkInText(attributedString: NSMutableAttributedString) {
self.linkRanges = LinkHandlerModel.appendLink(attributedString: attributedString)
}
// MARK: Container SetUp
func layoutTextView() {
updateTextContainerSize()
layoutView()
}
public func didTapAttributedText(_ gesture: UIGestureRecognizer) -> [LinkHandlerModel]? {
let indexOfCharacter = layoutManager.indexOfCharacter(self, touchLocation: gesture.location(in: self))
return self.linkRanges?.filter { $0.linkRange.contains(indexOfCharacter) }
}
// MARK: Text Sanitizing
func sanitizeAttributedString(attributedString: NSAttributedString) -> NSMutableAttributedString {
guard attributedString.length != 0 else { return attributedString.mutableString() }
var range = attributedString.nsRange()
guard let praStryle = attributedString.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? NSParagraphStyle,
let mutablePraStryle = praStryle.mutableCopy() as? NSMutableParagraphStyle else {
return attributedString.mutableString()
}
mutablePraStryle.lineBreakMode = .byWordWrapping
let restyledString = attributedString.mutableString()
restyledString.addParagraphStyle(style: mutablePraStryle)
return restyledString
}
}
extension NSLayoutManager {
func indexOfCharacter(_ label: UILabel, touchLocation: CGPoint) -> Int {
let textContainer = label.textContainer
let textStorage = NSTextStorage(attributedString: label.attributedText ?? NSAttributedString(string: ""))
textStorage.addLayoutManager(self)
let (labelSize, textBoundingBox) = (label.bounds.size, self.usedRect(for: textContainer))
let offsetX = (labelSize.width - textBoundingBox.size.width) * label.offsetXDivisor - textBoundingBox.origin.x
let offsetY = (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y
let locationOfTouch = CGPoint(x: touchLocation.x - offsetX, y: touchLocation.y - offsetY)
let indexOfCharacter = self.characterIndex(for: locationOfTouch, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return indexOfCharacter
}
}
| 29c2e65e659f78152fe85bd8413dfba8 | 39.766055 | 138 | 0.697873 | false | false | false | false |
zwaldowski/Attendant | refs/heads/master | Attendant/AssociationPolicy.swift | mit | 1 | //
// AssociationPolicy.swift
// Attendant
//
// Created by Zachary Waldowski on 4/16/15.
// Copyright © 2015-2016 Big Nerd Ranch. All rights reserved.
//
import ObjectiveC.runtime
public enum AssociationPolicy {
case Unowned
case Strong(atomic: Bool)
case Copying(atomic: Bool)
var runtimeValue: objc_AssociationPolicy {
switch self {
case .Strong(false): return .OBJC_ASSOCIATION_RETAIN_NONATOMIC
case .Strong(true): return .OBJC_ASSOCIATION_RETAIN
case .Copying(false): return .OBJC_ASSOCIATION_COPY_NONATOMIC
case .Copying(true): return .OBJC_ASSOCIATION_COPY
default: return .OBJC_ASSOCIATION_ASSIGN
}
}
}
extension AssociationPolicy: Hashable {
public var hashValue: Int {
return runtimeValue.hashValue
}
}
public func ==(lhs: AssociationPolicy, rhs: AssociationPolicy) -> Bool {
switch (lhs, rhs) {
case (.Unowned, .Unowned):
return true
case (.Strong(let latomic), .Strong(let ratomic)):
return latomic == ratomic
case (.Copying(let latomic), .Copying(let ratomic)):
return latomic == ratomic
default:
return false
}
}
| 8f73e6bc7669b96e559330afbb2af72a | 24.4375 | 72 | 0.63964 | false | false | false | false |
heoiu87/WalmartStoreLocator | refs/heads/master | Walmart Store Locator/Walmart Store Locator/ViewController.swift | mit | 1 | //
// ViewController.swift
// Walmart Store Locator
//
// Created by Brian Nguyen on 8/23/15.
// Copyright (c) 2015 Samoset & Squanto. All rights reserved.
//
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
@IBOutlet weak var CityNameTextBox: UITextField!
@IBOutlet weak var ZIPcodeTextBox: UITextField!
@IBOutlet weak var LocationsTextView: UITextView!
lazy var data = NSMutableData()
var locations = Array<NSDictionary>()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func SearchButton(sender: UIButton) {
var input = ZIPcodeTextBox.text
startConnection(input)
}
func startConnection(zipcode:String) {
let urlPath: String = "http://api.walmartlabs.com/v1/stores?apiKey=teeauzr2tm7867rfk6atybug&zip=\(zipcode)&format=json"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
// throwing an error on the line below (can't figure out where the error message is)
var jsonResult: Array<NSDictionary> = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Array<NSDictionary>
locations = jsonResult
println(locations)
}
}
| aa362246252e46ee0f6bafd3e9dfe223 | 33.890909 | 175 | 0.69359 | false | false | false | false |
roecrew/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Distortion/Bit Crusher/AKBitCrusher.swift | mit | 1 | //
// AKBitCrusher.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This will digitally degrade a signal.
///
/// - Parameters:
/// - input: Input node to process
/// - bitDepth: The bit depth of signal output. Typically in range (1-24). Non-integer values are OK.
/// - sampleRate: The sample rate of signal output.
///
public class AKBitCrusher: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKBitCrusherAudioUnit?
internal var token: AUParameterObserverToken?
private var bitDepthParameter: AUParameter?
private var sampleRateParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// The bit depth of signal output. Typically in range (1-24). Non-integer values are OK.
public var bitDepth: Double = 8 {
willSet {
if bitDepth != newValue {
if internalAU!.isSetUp() {
bitDepthParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.bitDepth = Float(newValue)
}
}
}
}
/// The sample rate of signal output.
public var sampleRate: Double = 10000 {
willSet {
if sampleRate != newValue {
if internalAU!.isSetUp() {
sampleRateParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.sampleRate = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this bitcrusher node
///
/// - Parameters:
/// - input: Input node to process
/// - bitDepth: The bit depth of signal output. Typically in range (1-24). Non-integer values are OK.
/// - sampleRate: The sample rate of signal output.
///
public init(
_ input: AKNode,
bitDepth: Double = 8,
sampleRate: Double = 10000) {
self.bitDepth = bitDepth
self.sampleRate = sampleRate
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = fourCC("btcr")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKBitCrusherAudioUnit.self,
asComponentDescription: description,
name: "Local AKBitCrusher",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKBitCrusherAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
bitDepthParameter = tree.valueForKey("bitDepth") as? AUParameter
sampleRateParameter = tree.valueForKey("sampleRate") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.bitDepthParameter!.address {
self.bitDepth = Double(value)
} else if address == self.sampleRateParameter!.address {
self.sampleRate = Double(value)
}
}
}
internalAU?.bitDepth = Float(bitDepth)
internalAU?.sampleRate = Float(sampleRate)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| f050275c45932244e99e3daffc7467c0 | 31.230769 | 107 | 0.600781 | false | false | false | false |
svbeemen/Eve | refs/heads/master | Eve/Eve/SavedDataManager.swift | mit | 1 | //
// SaveData.swift
// Eve
//
// Created by Sangeeta van Beemen on 24/06/15.
// Copyright (c) 2015 Sangeeta van Beemen. All rights reserved.
import Foundation
import UIKit
class SavedDataManager
{
class var sharedInstance : SavedDataManager
{
struct Static
{
static let instance : SavedDataManager = SavedDataManager()
}
return Static.instance
}
let defaults = NSUserDefaults.standardUserDefaults()
private let PAST_KEY = "pastCycleDates"
private let PREDICTED_KEY = "predictedCycleDates"
private let PASTMENSTRUATIONS_KEY = "pastMenstruationDates"
// Save predicted cycle dates
func savePredictedCycleDates(predictedCycleDates: [CycleDate])
{
let myData = NSKeyedArchiver.archivedDataWithRootObject(predictedCycleDates)
defaults.setObject(myData, forKey: PREDICTED_KEY)
}
// Retrieve saved predicted cycle dates or return empty array if their are no saved dates.
func getPredictedCycleDates() -> [CycleDate]
{
if (defaults.objectForKey(PREDICTED_KEY) as? NSData) != nil
{
let savedDated: NSData = defaults.objectForKey(PREDICTED_KEY) as! NSData
let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate]
return myData
}
return [CycleDate]()
}
// Save past cycle dates.
func savePastCycleDates(pastCycleDates: [CycleDate])
{
let myData = NSKeyedArchiver.archivedDataWithRootObject(pastCycleDates)
defaults.setObject(myData, forKey: PAST_KEY)
}
// Retrieve saved past cycle dates or return empty array if their are no saved dates.
func getPastCycleDates() -> [CycleDate]
{
if (defaults.objectForKey(PAST_KEY) as? NSData) != nil
{
let savedDated: NSData = defaults.objectForKey(PAST_KEY) as! NSData
let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate]
return myData
}
return [CycleDate]()
}
// Save past menstruation date
func savePastMenstruationDates(pastMenstruationDates: [CycleDate])
{
let myData = NSKeyedArchiver.archivedDataWithRootObject(pastMenstruationDates)
defaults.setObject(myData, forKey: PASTMENSTRUATIONS_KEY)
}
// Retrieve past menstruation dates or return empty array if their are no saved dates.
func getPastMenstruationDates() -> [CycleDate]
{
if (defaults.objectForKey(PASTMENSTRUATIONS_KEY) as? NSData) != nil
{
let savedDated: NSData = defaults.objectForKey(PASTMENSTRUATIONS_KEY) as! NSData
let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate]
return myData
}
return [CycleDate]()
}
}
| 81b8207cca8b3ce54f612ec7559ffc72 | 32.27907 | 94 | 0.665968 | false | false | false | false |
jduquennoy/Log4swift | refs/heads/master | Log4swift/Appenders/FileAppender.swift | apache-2.0 | 1 | //
// FileAppender.swift
// Log4swift
//
// Created by Jérôme Duquennoy on 16/06/2015.
// Copyright © 2015 Jérôme Duquennoy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
This appender will write logs to a file.
If file does not exist, it will be created on the first log, or re-created if deleted or moved (compatible with log rotate systems).
*/
public class FileAppender : Appender {
public enum DictionaryKey: String {
case FilePath = "FilePath"
case MaxFileAge = "MaxFileAge"
case MaxFileSize = "MaxFileSize"
}
@objc
public internal(set) var filePath : String {
didSet {
if let safeHandler = self.fileHandler {
safeHandler.closeFile()
self.fileHandler = nil
}
self.filePath = (self.filePath as NSString).expandingTildeInPath
didLogFailure = false
}
}
/// The rotation policies to apply. The file will be rotated if at least
/// one of the registered policies requests it.
/// If none are registered, the file will never be rotated.
public var rotationPolicies = [FileAppenderRotationPolicy]()
public var maxFileSize: UInt64?
/// The maximum number of rotated log files kept.
/// Files exceeding this limit will be deleted during rotation.
public var maxRotatedFiles: UInt?
private var fileHandler: FileHandle?
private var currentFileSize: UInt64?
private var didLogFailure = false
private var loggingMutex = PThreadMutex()
@objc
public init(identifier: String, filePath: String) {
self.fileHandler = nil
self.currentFileSize = nil
self.filePath = (filePath as NSString).expandingTildeInPath
super.init(identifier)
}
/// - Parameter identifier: the identifier of the appender.
/// - Parameter filePath: the path to the logfile. If possible and needed, the directory
/// structure will be created when creating the log file.
/// - Parameter maxFileSize: the maximum size of the file in octets before rotation is triggered.
/// Nil or zero disables the file size trigger for rotation. Default value is nil.
/// - Parameter maxFileAge: the maximum age of the file in seconds before rotation is triggered.
/// Nil or zero disables the file age trigger for rotation. Default value is nil.
public convenience init(identifier: String, filePath: String, rotationPolicies: [FileAppenderRotationPolicy]? = nil) {
self.init(identifier: identifier, filePath: filePath)
if let rotationPolicies = rotationPolicies {
self.rotationPolicies.append(contentsOf: rotationPolicies)
}
}
public required convenience init(_ identifier: String) {
self.init(identifier: identifier, filePath: "/dev/null")
}
public override func update(withDictionary dictionary: Dictionary<String, Any>, availableFormatters: Array<Formatter>) throws {
try super.update(withDictionary: dictionary, availableFormatters: availableFormatters)
if let safeFilePath = (dictionary[DictionaryKey.FilePath.rawValue] as? String) {
self.filePath = safeFilePath
} else {
self.filePath = "placeholder"
throw NSError.Log4swiftError(description: "Missing '\(DictionaryKey.FilePath.rawValue)' parameter for file appender '\(self.identifier)'")
}
if let maxFileAge = (dictionary[DictionaryKey.MaxFileAge.rawValue] as? Int) {
let existingRotationPolicy = self.rotationPolicies.find { ($0 as? DateRotationPolicy) != nil } as? DateRotationPolicy
if let existingRotationPolicy = existingRotationPolicy {
existingRotationPolicy.maxFileAge = TimeInterval(maxFileAge)
} else {
self.rotationPolicies.append(DateRotationPolicy(maxFileAge: TimeInterval(maxFileAge)))
}
}
if let maxFileSize = (dictionary[DictionaryKey.MaxFileSize.rawValue] as? Int) {
let existingRotationPolicy = self.rotationPolicies.find { ($0 as? SizeRotationPolicy) != nil } as? SizeRotationPolicy
if let existingRotationPolicy = existingRotationPolicy {
existingRotationPolicy.maxFileSize = UInt64(maxFileSize)
} else {
self.rotationPolicies.append(SizeRotationPolicy(maxFileSize: UInt64(maxFileSize)))
}
}
}
/// This is the only entry point to log.
/// It is thread safe, calling that method from multiple threads will not
// cause logs to interleave, or mess with the rotation mechanism.
public override func performLog(_ log: String, level: LogLevel, info: LogInfoDictionary) {
var normalizedLog = log
if(!normalizedLog.hasSuffix("\n")) {
normalizedLog = normalizedLog + "\n"
}
loggingMutex.sync {
try? rotateFileIfNeeded()
guard createFileHandlerIfNeeded() else {
return
}
if let dataToLog = normalizedLog.data(using: String.Encoding.utf8, allowLossyConversion: true) {
self.fileHandler?.write(dataToLog)
self.rotationPolicies.forEach { $0.appenderDidAppend(data: dataToLog)}
}
}
}
/// - returns: true if the file handler can be used, false if not.
private func createFileHandlerIfNeeded() -> Bool {
let fileManager = FileManager.default
do {
if !fileManager.fileExists(atPath: self.filePath) {
self.fileHandler = nil
let directoryPath = (filePath as NSString).deletingLastPathComponent
try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
fileManager.createFile(atPath: filePath, contents: nil, attributes: nil)
self.currentFileSize = 0
}
if self.fileHandler == nil {
self.fileHandler = FileHandle(forWritingAtPath: self.filePath)
self.fileHandler?.seekToEndOfFile()
}
self.rotationPolicies.forEach { $0.appenderDidOpenFile(atPath: self.filePath) }
didLogFailure = false
} catch (let error) {
if(!didLogFailure) {
NSLog("Appender \(self.identifier) failed to open log file \(self.filePath) : \(error)")
didLogFailure = true
self.fileHandler = nil
}
}
return self.fileHandler != nil
}
private func rotateFileIfNeeded() throws {
let shouldRotate = self.rotationPolicies.contains { $0.shouldRotate() }
guard shouldRotate else { return }
self.fileHandler?.closeFile()
self.fileHandler = nil
let fileManager = FileManager.default
let fileUrl = URL(fileURLWithPath: self.filePath)
let logFileName = fileUrl.lastPathComponent
let logFileDirectory = fileUrl.deletingLastPathComponent()
let files = try fileManager.contentsOfDirectory(atPath: logFileDirectory.path)
.filter { $0.hasPrefix(logFileName) }
.sorted {$0.localizedStandardCompare($1) == .orderedAscending }
.reversed()
var currentFileIndex = UInt(files.count)
try files.forEach { currentFileName in
let newFileName = logFileName.appending(".\(currentFileIndex)")
let currentFilePath = logFileDirectory.appendingPathComponent(currentFileName)
let rotatedFilePath = logFileDirectory.appendingPathComponent(newFileName)
if let maxRotatedFiles = self.maxRotatedFiles, currentFileIndex > maxRotatedFiles {
try fileManager.removeItem(at: currentFilePath)
} else {
try fileManager.moveItem(at: currentFilePath,
to: rotatedFilePath)
}
currentFileIndex -= 1
}
}
}
| ad5c689ce64674b968c375630d6841b7 | 38.293532 | 141 | 0.708154 | false | false | false | false |
yajeka/PS | refs/heads/master | PS/Master/CreatePostViewController.swift | lgpl-3.0 | 1 | //
// CreatePostViewController.swift
// PS
//
// Created by Andrew Rudsky on 3/20/16.
// Copyright © 2016 hackathon. All rights reserved.
//
import UIKit
class CreatePostViewController : UITableViewController {
var extendedSectionCell : Int = -1;
var tabC: UITabBarController?
override func viewDidLoad() {
super.viewDidLoad();
let backgroundView = UIImageView(frame: view.bounds)
backgroundView.image = UIImage(named: "background")
tableView.backgroundView = backgroundView
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.translucent = true
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
toggleDone()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
func doneActivated() {
tabC?.selectedIndex = 0
dismissViewControllerAnimated(true, completion: nil)
}
func toggleDone() {
if extendedSectionCell == -1 {
navigationItem.rightBarButtonItem = nil;
}
else {
navigationController?.navigationBarHidden = false
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Post", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneActivated"))
}
}
//MARK: TableView
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false);
if(extendedSectionCell == indexPath.section) {
}
else {
extendedSectionCell = indexPath.section
}
toggleDone()
tableView.reloadData()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var result : CGFloat = 120;
if indexPath.section == extendedSectionCell {
switch indexPath.row {
case 0:
break;
case 1:
result = 140.0;
break;
case 2:
result = 50.0;
break;
default:
break;
}
}
else {
switch indexPath.row {
case 0:
break;
case 1:
result = 0.0;
break;
case 2:
result = 0.0;
break;
default:
break;
}
}
return result;
}
} | 930a3e6c81e0b55d4ea1b34b87583a89 | 26.201923 | 161 | 0.56082 | false | false | false | false |
biohazardlover/ROer | refs/heads/master | Roer/Filter.swift | mit | 1 |
import Foundation
class Filter: NSObject {
var predicates: [String] {
var predicates = [String]()
for filterCategory in filterCategories {
if filterCategory.type == FilterCategoryType.More.rawValue {
for filterItem in filterCategory.filterItems ?? [] {
if let predicate = filterItem.predicate {
predicates.append(predicate)
}
}
} else {
if let predicate = filterCategory.selectedFilterItem?.predicate {
predicates.append(predicate)
}
}
}
return predicates
}
var sortDescriptors: [NSSortDescriptor] {
var sortDescriptors = [NSSortDescriptor]()
for filterCategory in filterCategories {
if let sortDescriptor = filterCategory.selectedFilterItem?.sortDescriptor {
sortDescriptors.append(sortDescriptor)
}
}
return sortDescriptors
}
var filterCategories = [FilterCategory]()
}
extension Filter {
convenience init(contentsOfURL url: URL) {
self.init()
if let dictionary = NSDictionary(contentsOf: url) as? [AnyHashable: Any] {
if let filterCategories = dictionary["FilterCategories"] as? [[AnyHashable: Any]] {
self.filterCategories = filterCategories.map({ (filterCategory) -> FilterCategory in
return FilterCategory(contents: filterCategory as [NSObject : AnyObject])
})
}
}
}
}
| d4b790b640c1072a410ce2760373cf6e | 28.803571 | 100 | 0.550629 | false | false | false | false |
wisonlin/HackingDesigner | refs/heads/master | HackingDesigner/Pages/FeedsViewController.swift | mit | 1 | //
// FeedsViewController.swift
// HackingDesigner
//
// Created by wison on 4/4/16.
// Copyright © 2016 HomeStudio. All rights reserved.
//
import UIKit
import Kingfisher
import GearRefreshControl
import ReachabilitySwift
import ImageViewer
class FeedsViewController: UITableViewController, ImageProvider, FeedCellDelegate {
var feeds = [Feed]()
var feedPage = 1
var gearRefreshControl : GearRefreshControl!
var fetchFeeds: ((Int, complete: ([Feed]) -> ()) -> ())!
var reachability: Reachability?
// MARK: - View Life Cycled
override func viewDidLoad() {
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
reachability = nil
}
gearRefreshControl = GearRefreshControl(frame: self.view.bounds)
gearRefreshControl.addTarget(self, action: #selector(onRefresh), forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl = gearRefreshControl
gearRefreshControl.beginRefreshing()
self.onRefresh()
}
// MARK: - Pull Refresh
func onRefresh() {
feedPage = 1
fetchFeeds(feedPage) { (feeds: [Feed]) in
self.feeds = feeds
self.gearRefreshControl.endRefreshing()
self.tableView.reloadData()
}
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
gearRefreshControl.scrollViewDidScroll(scrollView)
}
// MARK: - UITableViewDelegate & DataSource Methods
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feeds.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 340
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell") as! FeedCell
cell.indexPath = indexPath
cell.delegate = self
let feed = feeds[indexPath.row]
var imageUrl: NSURL!
if let imageURL = NSURL(string: feed.images.teaser) {
imageUrl = imageURL
}
if let reachability = reachability {
if (reachability.isReachableViaWiFi()) {
if let imageURL = NSURL(string: feed.images.normal) {
imageUrl = imageURL
}
}
}
cell.photoView.kf_setImageWithURL(imageUrl)
if let avatarURL = NSURL(string: feed.user.avatarUrl) {
cell.avatarView.kf_setImageWithURL(avatarURL)
}
cell.userNameLabel.text = feed.user.name
cell.titleLabel.text = feed.title
cell.viewsCountLabel.text = "\(feed.viewsCount) views"
cell.likesCountLabel.titleLabel?.text = "\(feed.likesCount) likes"
if feeds.count - 3 == indexPath.row {
feedPage += 1
fetchFeeds(feedPage) { (feeds: [Feed]) in
self.feeds.appendContentsOf(feeds)
self.tableView.reloadData()
}
}
return cell
}
var selectedIndexPath: NSIndexPath!
// MARK: - FeedCellDelegate Methods
func onFeedCellPhotoTapped(feedCell: FeedCell) {
self.selectedIndexPath = feedCell.indexPath
let imageProvider = self
let buttonAssets = CloseButtonAssets(normal: UIImage(named:"first")!, highlighted: UIImage(named: "second"))
let configuration = ImageViewerConfiguration(imageSize: CGSize(width: 10, height: 10), closeButtonAssets: buttonAssets)
let imageViewer = ImageViewer(imageProvider: imageProvider, configuration: configuration, displacedView: feedCell.photoView!)
self.presentImageViewer(imageViewer)
}
func onFeedCellLikeButtonTapped(feedCell: FeedCell) {
let feed = feeds[feedCell.indexPath!.row]
FeedManager().likeFeeds(feed) { (like: Like) in
}
}
// MARK: - ImageProvider Methods
func provideImage(completion: UIImage? -> Void) {
let feed = self.feeds[selectedIndexPath.row]
var imageUrl: NSURL!
if let imageURL = NSURL(string: feed.images.normal) {
imageUrl = imageURL
}
if let reachability = reachability {
if (reachability.isReachableViaWiFi()) {
if let imageURL = NSURL(string: feed.images.hidpi) {
imageUrl = imageURL
}
}
}
KingfisherManager.sharedManager.retrieveImageWithURL(imageUrl, optionsInfo: nil, progressBlock: nil) { (image, error, cacheType, imageURL) in
completion(image)
}
}
func provideImage(atIndex index: Int, completion: UIImage? -> Void) {
}
}
| 70d5438b568bb88063117b376b0d24c0 | 31.031646 | 149 | 0.609563 | false | false | false | false |
admkopec/BetaOS | refs/heads/x86_64 | Kernel/Swift Extensions/TextFile.swift | apache-2.0 | 1 | //
// TextFile.swift
// Kernel
//
// Created by Adam Kopeć on 3/29/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
import Loggable
class TextFile: File, Loggable {
let Name: String = "Text File"
var text: String {
get {
return String(utf8Characters: file.Data) ?? ""
}
set {
var buf = ContiguousArray<UInt8>(newValue.utf8)
file.Info.Size = newValue.utf8.count
file.Data.deallocate()
file.Data = MutableData(start: &buf[0], count: buf.count)
writeToDisk()
}
}
required init?(partition: Partition, path: String) {
super.init(partition: partition, path: path)
//MARK: Should I check extension for Plain Text or only for Rich and if fail then force Plain?
guard file.Info.Extension == "TXT" || file.Info.Extension == "PLI" || file.Info.Extension == "XML" else {
Log("File didn't pass Extension checks for plain text", level: .Error)
file.Data.deallocate()
return nil
}
}
}
| 13882ad651fdc187dd6c67871e412bc5 | 29.971429 | 113 | 0.581181 | false | false | false | false |
JonathanAhrenkiel-Frellsen/WorkWith-fitnes | refs/heads/master | KomITEksamen/KomITEksamen/CelenderViewController.swift | lgpl-3.0 | 1 | //
// CelenderViewController.swift
// KomITEksamen
//
// Created by Jonathans Macbook Pro on 26/04/2017.
// Copyright © 2017 skycode. All rights reserved.
//
import UIKit
import EventKit
import FirebaseAuth
import Firebase
class CelenderViewController: UIViewController {
var eventName = String()
var eventStartDate = String()
var eventEndDate = String()
var activeDays = [String] ()
override func viewDidLoad() {
super.viewDidLoad()
let userID = FIRAuth.auth()?.currentUser?.uid
// DataService.ds.REF_USER.child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// if let eventDict = snapshot.value as? Dictionary<String, AnyObject> {
// let user = UsersModel(userData: eventDict)
//
// self.eventName = user.category
//
// // reformats the string date stored in firebase and formats it as Date
// // alternativly i could have stored secundsSince 1970 in firebase af int, and format from there, but i'm lazy xd, this would also solve time zone problems
//// let dateFormatter = DateFormatter()
//// dateFormatter.dateFormat = "yyyy-MM-dd"
////
//// let dateStart = dateFormatter.date(from: user.startDate)
//// let dateEnd = dateFormatter.date(from: user.startDate)
//
// self.eventStartDate = user.startDate
// self.eventEndDate = user.endDate
//
// self.activeDays = user.acriveDays.components(separatedBy: [","])
//
// for day in self.activeDays {
// let date = Date()
// let formatter = DateFormatter()
//
// formatter.dateFormat = "dd.MM.yyyy"
//
// let currentDate = formatter.string(from: date)
//
// //self.getDayOfWeek(today: currentDate)
//
// print(currentDate)
// }
// }
// })
func getDayOfWeek(today:String)->Int {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.date(from: today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(.weekday, from: todayDate)
let weekDay = myComponents.weekday
return weekDay!
}
// let eventStore = EKEventStore();
//
// if let calendarForEvent = eventStore.calendarWithIdentifier(self.calendar.calendarIdentifier) {
// let newEvent = EKEvent(eventStore: eventStore)
//
// newEvent.calendar = calendarForEvent
// newEvent.title = "Some Event Name"
// newEvent.startDate = eventStartDate
// newEvent.endDate = eventEndDate
// }
//let event = EKEvent(eventStore: eventStore)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 3f6cf86487d397d31f1e82277ce35a0f | 36.2 | 172 | 0.548984 | false | false | false | false |
Sadmansamee/quran-ios | refs/heads/master | Quran/ConnectionsPool.swift | mit | 1 | //
// ConnectionsPool.swift
// Quran
//
// Created by Mohamed Afifi on 10/30/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
import SQLite
import CSQLite
final class ConnectionsPool {
static var `default`: ConnectionsPool = ConnectionsPool()
var pool: [String: (uses: Int, connection: Connection)] = [:]
func getConnection(filePath: String) throws -> Connection {
if let (uses, connection) = pool[filePath] {
pool[filePath] = (uses + 1, connection)
return connection
} else {
do {
let connection = try Connection(filePath, readonly: false)
pool[filePath] = (1, connection)
return connection
} catch {
Crash.recordError(error, reason: "Cannot open connection to sqlite file '\(filePath)'.")
throw PersistenceError.openDatabase(error)
}
}
}
func close(connection: Connection) {
let filePath = String(cString: sqlite3_db_filename(connection.handle, nil))
if let (uses, connection) = pool[filePath] {
if uses <= 1 {
pool[filePath] = nil // remove it
} else {
pool[filePath] = (uses - 1, connection)
}
} else {
CLog("Warning: Closing connection multiple times '\(filePath)'")
}
}
}
| a6d04f0034e4a9fe5a75861c62115f47 | 29.12766 | 104 | 0.565678 | false | false | false | false |
ozpopolam/TrivialAsia | refs/heads/master | TrivialAsia/TriviaViewAdapted.swift | mit | 1 | //
// TriviaAdapted.swift
// TrivialAsia
//
// Created by Anastasia Stepanova-Kolupakhina on 25.05.17.
// Copyright © 2017 Anastasia Kolupakhina. All rights reserved.
//
import Foundation
class TriviaViewAdapted {
var id = 0
var difficulty = ""
var question = ""
var answers = [String]()
init(fromTrivia trivia: Trivia) {
id = trivia.id
difficulty = trivia.difficulty
question = trivia.question
answers.append(trivia.correctAnswer)
answers.append(contentsOf: trivia.incorrectAnswers)
answers.shuffle(withStubbornnessLevel: 3)
}
}
| 2cb23397913492aea4929a682ea49c95 | 21.777778 | 64 | 0.660163 | false | false | false | false |
Zverik/omim | refs/heads/master | iphone/Maps/UI/Welcome/WelcomePageController.swift | apache-2.0 | 4 | import UIKit
@objc(MWMWelcomePageControllerProtocol)
protocol WelcomePageControllerProtocol {
var view: UIView! { get set }
func addChildViewController(_ childController: UIViewController)
func closePageController(_ pageController: WelcomePageController)
}
@objc(MWMWelcomePageController)
final class WelcomePageController: UIPageViewController {
fileprivate var controllers: [UIViewController] = []
private var parentController: WelcomePageControllerProtocol!
private var iPadBackgroundView: SolidTouchView?
private var isAnimatingTransition = true
fileprivate var currentController: UIViewController! {
get {
return viewControllers?.first
}
set {
guard let controller = newValue, let parentView = parentController.view else { return }
let animated = !isAnimatingTransition
parentView.isUserInteractionEnabled = isAnimatingTransition
setViewControllers([controller], direction: .forward, animated: animated) { [weak self] _ in
guard let s = self else { return }
s.isAnimatingTransition = false
parentView.isUserInteractionEnabled = true
}
isAnimatingTransition = animated
}
}
static func controller(parent: WelcomePageControllerProtocol) -> WelcomePageController? {
let isFirstSession = Alohalytics.isFirstSession()
let welcomeKey = isFirstSession ? FirstLaunchController.key : WhatsNewController.key
guard UserDefaults.standard.bool(forKey: welcomeKey) == false else { return nil }
let pagesCount = isFirstSession ? FirstLaunchController.pagesCount : WhatsNewController.pagesCount
let id = pagesCount == 1 ? "WelcomePageCurlController" : "WelcomePageScrollController"
let sb = UIStoryboard.instance(.welcome)
let vc = sb.instantiateViewController(withIdentifier: id) as! WelcomePageController
vc.config(parent)
vc.show()
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white()
iPadSpecific {
let parentView = parentController.view!
iPadBackgroundView = SolidTouchView(frame: parentView.bounds)
iPadBackgroundView!.backgroundColor = UIColor.fadeBackground()
iPadBackgroundView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
parentView.addSubview(iPadBackgroundView!)
view.layer.cornerRadius = 5
view.clipsToBounds = true
}
currentController = controllers.first
}
private func config(_ parent: WelcomePageControllerProtocol) {
parentController = parent
let isFirstSession = Alohalytics.isFirstSession()
let pagesCount = isFirstSession ? FirstLaunchController.pagesCount : WhatsNewController.pagesCount
let welcomeClass: WelcomeProtocolBase.Type = isFirstSession ? FirstLaunchController.self : WhatsNewController.self
(0..<pagesCount).forEach {
let vc = welcomeClass.controller($0)
(vc as! WelcomeProtocolBase).pageController = self
controllers.append(vc)
}
dataSource = self
}
func nextPage() {
let welcomeKey = Alohalytics.isFirstSession() ? FirstLaunchController.key : WhatsNewController.key
Statistics.logEvent(kStatEventName(kStatWhatsNew, welcomeKey),
withParameters: [kStatAction: kStatNext])
currentController = pageViewController(self, viewControllerAfter: currentController)
}
func close() {
UserDefaults.standard.set(true, forKey: FirstLaunchController.key)
UserDefaults.standard.set(true, forKey: WhatsNewController.key)
let welcomeKey = Alohalytics.isFirstSession() ? FirstLaunchController.key : WhatsNewController.key
Statistics.logEvent(kStatEventName(kStatWhatsNew, welcomeKey),
withParameters: [kStatAction: kStatClose])
iPadBackgroundView?.removeFromSuperview()
view.removeFromSuperview()
removeFromParentViewController()
parentController.closePageController(self)
}
func show() {
let welcomeKey = Alohalytics.isFirstSession() ? FirstLaunchController.key : WhatsNewController.key
Statistics.logEvent(kStatEventName(kStatWhatsNew, welcomeKey),
withParameters: [kStatAction: kStatOpen])
parentController.addChildViewController(self)
parentController.view.addSubview(view)
updateFrame()
}
private func updateFrame() {
let parentView = parentController.view!
view.frame = alternative(iPhone: CGRect(origin: CGPoint(), size: parentView.size),
iPad: CGRect(x: parentView.center.x - 260, y: parentView.center.y - 300, width: 520, height: 600))
(currentController as! WelcomeProtocolBase).updateSize()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [weak self] _ in self?.updateFrame() }, completion: nil)
}
}
extension WelcomePageController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard viewController != controllers.first else { return nil }
let index = controllers.index(before: controllers.index(of: viewController)!)
return controllers[index]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard viewController != controllers.last else { return nil }
let index = controllers.index(after: controllers.index(of: viewController)!)
return controllers[index]
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return controllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let vc = currentController else { return 0 }
return controllers.index(of: vc)!
}
}
| ac86af27ca0d5447e5870bad930df559 | 41.06383 | 147 | 0.747429 | false | false | false | false |
arvindhsukumar/PredicateEditor | refs/heads/master | Example/Pods/SeedStackViewController/StackViewController/AutoScrollView.swift | mit | 1 | //
// AutoScrollView.swift
// Seed
//
// Created by Indragie Karunaratne on 2016-03-10.
// Copyright © 2016 Seed Platform, Inc. All rights reserved.
//
import UIKit
/// A scroll view that automatically scrolls to a subview of its `contentView`
/// when the keyboard is shown. This replicates the behaviour implemented by
/// `UITableView`.
public class AutoScrollView: UIScrollView {
private struct Constants {
static let DefaultAnimationDuration: NSTimeInterval = 0.25
static let DefaultAnimationCurve = UIViewAnimationCurve.EaseInOut
static let ScrollAnimationID = "AutoscrollAnimation"
}
/// The content view to display inside the container view. Views can also
/// be added directly to this view without using the `contentView` property,
/// but it simply makes it more convenient for the common case where your
/// content fills the bounds of the scroll view.
public var contentView: UIView? {
willSet {
contentView?.removeFromSuperview()
}
didSet {
if let contentView = contentView {
addSubview(contentView)
updateContentViewConstraints()
}
}
}
private var contentViewConstraints: [NSLayoutConstraint]?
override public var contentInset: UIEdgeInsets {
didSet {
updateContentViewConstraints()
}
}
private func updateContentViewConstraints() {
if let constraints = contentViewConstraints {
NSLayoutConstraint.deactivateConstraints(constraints)
}
if let contentView = contentView {
contentViewConstraints = contentView.activateSuperviewHuggingConstraints(insets: contentInset)
} else {
contentViewConstraints = nil
}
}
private func commonInit() {
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Notifications
// Implementation based on code from Apple documentation
// https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
@objc private func keyboardWillShow(notification: NSNotification) {
let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue
guard var keyboardFrame = keyboardFrameValue?.CGRectValue() else { return }
keyboardFrame = convertRect(keyboardFrame, fromView: nil)
let bottomInset: CGFloat
let keyboardIntersectionRect = bounds.intersect(keyboardFrame)
if !keyboardIntersectionRect.isNull {
bottomInset = keyboardIntersectionRect.height
let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0)
super.contentInset = contentInset
scrollIndicatorInsets = contentInset
} else {
bottomInset = 0.0
}
guard let firstResponder = firstResponder else { return }
let firstResponderFrame = firstResponder.convertRect(firstResponder.bounds, toView: self)
var contentBounds = CGRect(origin: contentOffset, size: bounds.size)
contentBounds.size.height -= bottomInset
if !contentBounds.contains(firstResponderFrame.origin) {
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval ?? Constants.DefaultAnimationDuration
let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? UIViewAnimationCurve ?? Constants.DefaultAnimationCurve
// Dropping down to the old style UIView animation API because the new API
// does not support setting the curve directly. The other option is to take
// `curve` and shift it left by 16 bits to turn it into a `UIViewAnimationOptions`,
// but that seems uglier than just doing this.
UIView.beginAnimations(Constants.ScrollAnimationID, context: nil)
UIView.setAnimationCurve(curve)
UIView.setAnimationDuration(duration)
scrollRectToVisible(firstResponderFrame, animated: false)
UIView.commitAnimations()
}
}
@objc private func keyboardWillHide(notification: NSNotification) {
super.contentInset = UIEdgeInsetsZero
scrollIndicatorInsets = UIEdgeInsetsZero
}
}
private extension UIView {
var firstResponder: UIView? {
if isFirstResponder() {
return self
}
for subview in subviews {
if let responder = subview.firstResponder {
return responder
}
}
return nil
}
}
| c4e89abfb847851208f7771674fd6721 | 38.776119 | 150 | 0.669794 | false | false | false | false |
Malecks/PALette | refs/heads/master | Palette/NavigationTitleView.swift | mit | 1 | //
// NavigationTitleView.swift
// Palette
//
// Created by Alex Mathers on 2017-06-01.
// Copyright © 2017 Malecks. All rights reserved.
//
import UIKit
final class NavigationTitleView: UIView {
@IBOutlet private weak var containerView: UIView!
@IBOutlet private weak var leftIcon: UIImageView!
@IBOutlet private weak var centerIcon: UIImageView!
@IBOutlet private weak var rightIcon: UIImageView!
@IBOutlet private weak var horizontalConstraint: NSLayoutConstraint!
private lazy var icons: [UIImageView] = {
return [self.leftIcon, self.centerIcon, self.rightIcon]
}()
lazy var iconOffset: CGFloat = {
return (self.containerView.frame.width / 2.0) - (self.leftIcon.frame.width / 2.0)
}()
var tappedAtIndex: ((Int) -> ())?
override func awakeFromNib() {
super.awakeFromNib()
for (i, icon) in icons.enumerated() {
icon.image = icon.image?.withRenderingMode(.alwaysTemplate)
icon.tintColor = .lightGray
icon.tag = i
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapAtIndex(sender:)))
icon.addGestureRecognizer(tap)
}
highlightIcon(at: 1)
}
@objc func didTapAtIndex(sender: UITapGestureRecognizer) {
guard let view = sender.view else { return }
self.tappedAtIndex?(view.tag)
}
func scroll(to index: Int) {
guard index < icons.count else { return }
var offset: CGFloat
switch index {
case 0: offset = iconOffset
case 2: offset = -iconOffset
default: offset = 0
}
horizontalConstraint.constant = offset
UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseOut, animations: {
self.highlightIcon(at: index)
self.layoutIfNeeded()
}, completion: nil)
}
private func highlightIcon(at index: Int) {
guard index < icons.count else { return }
for (i, icon) in icons.enumerated() {
icon.tintColor = i == index ? .black : .lightGray
}
}
class func instanceFromNib() -> UIView? {
let nib = UINib(nibName: "NavigationTitleView", bundle: nil)
.instantiate(withOwner: nil, options: nil)
for view in nib {
if let view = view as? NavigationTitleView {
return view
}
}
return nil
}
}
| 24e82529745b856589614de614ac6535 | 29.130952 | 106 | 0.591861 | false | false | false | false |
KingMarney/SwiftTasksNotePad | refs/heads/master | TaskNotePad/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// TaskNotePad
//
// Created by Paul Marney on 8/14/14.
// Copyright (c) 2014 Exmaples. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
//AIzaSyAnRQLf7EiCP_Cehy2zF75F0nZWSon60JA
GMSServices.provideAPIKey("AIzaSyAnRQLf7EiCP_Cehy2zF75F0nZWSon60JA");
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("TaskNotePad", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TaskNotePad.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
| a023d7fb10cdc559aaea9b28580dba09 | 51.735294 | 285 | 0.703151 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournalTests/Metadata/ExperimentDataParserTest.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
class ExperimentDataParserTest: XCTestCase {
// MARK: - Properties
let trial = Trial()
var experimentDataParser: ExperimentDataParser!
var sensor1: Sensor!
var sensor2: Sensor!
let sensorTrialStat1Minimum = 5.0
let sensorTrialStat1Maximum = 6.0
let sensorTrialStat1Average = 5.5
let sensorTrialStat2Minimum = 7.0
let sensorTrialStat2Maximum = 9.0
let sensorTrialStat2Average = 8.0
// MARK: - XCTest
override func setUp() {
super.setUp()
let metadataManager = createMetadataManager()
experimentDataParser = ExperimentDataParser(experimentID: "TEST",
metadataManager: metadataManager,
sensorController: MockSensorController())
sensor1 = Sensor.mock(sensorId: "TestSensorID1",
name: "TestSensorName1",
textDescription: "Test description 1.",
iconName: "test icon 1",
unitDescription: "sin")
sensor2 = Sensor.mock(sensorId: "TestSensorID2",
name: "TestSensorName2",
textDescription: "Test description 2.",
iconName: "test icon 2")
setupTrial()
}
// MARK: - Test cases
func testParsedTrials() {
let trials = [Trial(), Trial(), Trial(), Trial()]
let parsedTrials = experimentDataParser.parsedTrials(trials)
XCTAssertEqual(parsedTrials.count, trials.count,
"The number of parsed trials should equal the number of trials.")
}
func testParsedTrialSensorCount() {
let displayTrial = experimentDataParser.parseTrial(trial)
let trialSensors = displayTrial.sensors
XCTAssertEqual(trialSensors.count, 2, "There should be a trial sensor for each sensor.")
}
func testParsedTrialSensorTitles() {
let experimentTrialData = experimentDataParser.parseTrial(trial)
let trialSensors = experimentTrialData.sensors
XCTAssertEqual(trialSensors[0].title, "\(sensor1.name) (\(sensor1.unitDescription!))",
"The trial sensor title should be the sensor name.")
XCTAssertEqual(trialSensors[1].title, sensor2.name,
"The trial sensor title should be the sensor name.")
}
func testParsedTrialSensorTimestamp() {
Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT")
let experimentTrialData = experimentDataParser.parseTrial(trial)
var expectedDateString: String
if #available(iOS 11.0, *) {
expectedDateString = "May 18, 2017 at 10:37 AM"
} else {
expectedDateString = "May 18, 2017, 10:37 AM"
}
XCTAssertEqual(expectedDateString, experimentTrialData.timestamp.string,
"The timestamp should be properly parsed.")
}
func testParsedTrialSensorDataStats() {
let experimentTrialData = experimentDataParser.parseTrial(trial)
let trialSensor1 = experimentTrialData.sensors[0]
XCTAssertEqual(trialSensor1.minValueString, sensor1.string(for: sensorTrialStat1Minimum),
"The `minValueString` should be the same as the sensor's string(for:) string " +
"for the minimum data point.")
XCTAssertEqual(trialSensor1.maxValueString, sensor1.string(for: sensorTrialStat1Maximum),
"The `maxValueString` should be the same as the sensor's string(for:) string " +
"for the maximum data point.")
XCTAssertEqual(trialSensor1.averageValueString, sensor1.string(for: sensorTrialStat1Average),
"The `averageValueString` should be the same as the sensor's string(for:) " +
"string for the maximum data point.")
let trialSensor2 = experimentTrialData.sensors[1]
XCTAssertEqual(trialSensor2.minValueString, sensor1.string(for: sensorTrialStat2Minimum),
"The `minValueString` should be the same as the sensor's string(for:) string " +
"for the minimum data point.")
XCTAssertEqual(trialSensor2.maxValueString, sensor1.string(for: sensorTrialStat2Maximum),
"The `maxValueString` should be the same as the sensor's string(for:) string " +
"for the maximum data point.")
XCTAssertEqual(trialSensor2.averageValueString, sensor1.string(for: sensorTrialStat2Average),
"The `averageValueString` should be the same as the sensor's string(for:) " +
"string for the maximum data point.")
}
func testParsedTrialNotesSortOrder() {
let note1 = TextNote(text: "First")
note1.timestamp = 1000
let note2 = TextNote(text: "Second")
note1.timestamp = 2000
let note3 = TextNote(text: "Third")
note1.timestamp = 3000
// Trial notes are added in non-chronological order.
trial.notes = [note2, note3, note1]
let displayTrial = experimentDataParser.parseTrial(trial)
XCTAssertEqual(3, displayTrial.notes.count)
XCTAssertEqual("First", (displayTrial.notes[0] as! DisplayTextNote).text)
XCTAssertEqual("Second", (displayTrial.notes[1] as! DisplayTextNote).text)
XCTAssertEqual("Third", (displayTrial.notes[2] as! DisplayTextNote).text)
}
func testParsedTextNote() {
Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT")
let textNote = TextNote(text: "A text note")
textNote.timestamp = 1496369345626
let experimentData = experimentDataParser.parseNote(textNote) as! DisplayTextNote
XCTAssertEqual("A text note", experimentData.text)
var expectedDateString: String
if #available(iOS 11.0, *) {
expectedDateString = "Jun 1, 2017 at 10:09 PM"
} else {
expectedDateString = "Jun 1, 2017, 10:09 PM"
}
XCTAssertEqual(expectedDateString, experimentData.timestamp.string)
}
func testParsedPictureNote() {
Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT")
let pictureNote = PictureNote()
pictureNote.timestamp = 1496369345626
pictureNote.filePath = "some_image_path"
let experimentData = experimentDataParser.parseNote(pictureNote) as! DisplayPictureNote
XCTAssertTrue(experimentData.imagePath!.hasSuffix(pictureNote.filePath!))
var expectedDateString: String
if #available(iOS 11.0, *) {
expectedDateString = "Jun 1, 2017 at 10:09 PM"
} else {
expectedDateString = "Jun 1, 2017, 10:09 PM"
}
XCTAssertEqual(expectedDateString, experimentData.timestamp.string)
}
func testParsedTrialNote() {
let trial = Trial()
let textNote = TextNote(text: "Some text here")
let displayTextNote = experimentDataParser.parseNote(textNote,
forTrial: trial) as! DisplayTextNote
XCTAssertEqual("Some text here", displayTextNote.text)
XCTAssertEqual(trial.ID, displayTextNote.trialID)
let textNote2 = TextNote(text: "Another note")
let displayTextNote2 = experimentDataParser.parseNote(textNote2,
forTrial: nil) as! DisplayTextNote
XCTAssertEqual("Another note", displayTextNote2.text)
XCTAssertNil(displayTextNote2.trialID)
}
func testUnknownNoteType() {
// Unknown subclass of Note.
class OtherNote: Note {}
let otherNote = OtherNote()
let experimentData = experimentDataParser.parseNote(otherNote)
XCTAssertNil(experimentData, "Unknown note types should return nil.")
}
func testAlternateTitle() {
let experimentTrialData = experimentDataParser.parseTrial(trial)
XCTAssertNil(experimentTrialData.title, "Trial title should be nil.")
XCTAssertEqual("\(String.runDefaultTitle) 5", experimentTrialData.alternateTitle,
"Alternate title should match default plus index+1.")
}
func testSnapshotTrialNoteTimestamp() {
// Create a snapshot note with a sensor snapshot that has a given timestamp.
let sensorSnapshot = SensorSnapshot()
sensorSnapshot.timestamp = 10000
let snapshotNote = SnapshotNote(snapshots: [sensorSnapshot])
// Create a trial without a crop.
let trial = Trial()
trial.recordingRange.min = 5000
// Parse it into a display note for the trial.
let displaySnapshotNote =
experimentDataParser.parseNote(snapshotNote, forTrial: trial) as! DisplaySnapshotNote
XCTAssertEqual(
"0:05",
displaySnapshotNote.snapshots[0].timestamp.string,
"The display note timestamp should be the duration after the min recording range.")
}
func testSnapshotTrialNoteTimestampWithCrop() {
// Create a snapshot note with a sensor snapshot that has a given timestamp.
let sensorSnapshot = SensorSnapshot()
sensorSnapshot.timestamp = 10000
let snapshotNote = SnapshotNote(snapshots: [sensorSnapshot])
// Create a trial with a crop.
let trial = Trial()
trial.recordingRange.min = 5000
trial.cropRange = ChartAxis(min: 7000, max: 15000)
// Parse it into a display note for the trial.
let displaySnapshotNote =
experimentDataParser.parseNote(snapshotNote, forTrial: trial) as! DisplaySnapshotNote
XCTAssertEqual(
"0:03",
displaySnapshotNote.snapshots[0].timestamp.string,
"The display note timestamp should be the duration after the min crop range.")
}
// MARK: - Setup trial
func setupTrial() {
// ID, experiment index, creation time, recording range.
trial.ID = "TrialId"
trial.trialNumberInExperiment = 5
trial.creationDate = Date(milliseconds: 1495118240287)
trial.recordingRange.min = 1234
trial.recordingRange.max = 5678
// Stats.
let statsCalculator1 = StatCalculator()
statsCalculator1.addDataPoint(DataPoint(x: 0, y: sensorTrialStat1Minimum))
statsCalculator1.addDataPoint(DataPoint(x: 1, y: sensorTrialStat1Maximum))
let sensorTrialStats1 = TrialStats(sensorID: sensor1.sensorId)
sensorTrialStats1.addStatsFromStatCalculator(statsCalculator1)
trial.trialStats.append(sensorTrialStats1)
let statsCalculator2 = StatCalculator()
statsCalculator2.addDataPoint(DataPoint(x: 0, y: sensorTrialStat2Minimum))
statsCalculator2.addDataPoint(DataPoint(x: 1, y: sensorTrialStat2Maximum))
let sensorTrialStats2 = TrialStats(sensorID: sensor2.sensorId)
sensorTrialStats2.addStatsFromStatCalculator(statsCalculator2)
trial.trialStats.append(sensorTrialStats2)
// Layouts.
let sensorLayout1 = SensorLayout(sensorID: sensor1.sensorId, colorPalette: .blue)
trial.sensorLayouts.append(sensorLayout1)
let sensorLayout2 = SensorLayout(sensorID: sensor2.sensorId, colorPalette: .blue)
trial.sensorLayouts.append(sensorLayout2)
// Appearance.
trial.addSensorAppearance(BasicSensorAppearance(sensor: sensor1), for: sensor1.sensorId)
trial.addSensorAppearance(BasicSensorAppearance(sensor: sensor2), for: sensor2.sensorId)
}
}
| 6aedbf2a94bb8684cfb1c5703b4c7875 | 39.775439 | 99 | 0.694949 | false | true | false | false |
recurly/recurly-client-ios | refs/heads/master | RecurlySDK-iOS/Models/REApplePaymentData.swift | mit | 1 | //
// REApplePaymentData.swift
// RecurlySDK-iOS
//
// Created by Carlos Landaverde on 21/6/22.
//
import Foundation
public struct REApplePaymentData: Codable {
let paymentData: REApplePaymentDataBody
public init(paymentData: REApplePaymentDataBody = REApplePaymentDataBody()) {
self.paymentData = paymentData
}
}
public struct REApplePaymentDataBody: Codable {
let version: String
let data: String
let signature: String
let header: REApplePaymentDataHeader
public init(version: String = String(),
data: String = String(),
signature: String = String(),
header: REApplePaymentDataHeader = REApplePaymentDataHeader()) {
self.version = version
self.data = data
self.signature = signature
self.header = header
}
}
public struct REApplePaymentDataHeader: Codable {
let ephemeralPublicKey: String
let publicKeyHash: String
let transactionId: String
public init(ephemeralPublicKey: String = String(),
publicKeyHash: String = String(),
transactionId: String = String()) {
self.ephemeralPublicKey = ephemeralPublicKey
self.publicKeyHash = publicKeyHash
self.transactionId = transactionId
}
}
| 47ddc855ac6f72e4bdcb5110088dfb61 | 26.021277 | 81 | 0.677953 | false | false | false | false |
luosheng/OpenSim | refs/heads/master | OpenSim/SimulatorResetMenuItem.swift | mit | 1 | //
// SimulatorResetMenuItem.swift
// OpenSim
//
// Created by Craig Peebles on 14/10/19.
// Copyright © 2019 Luo Sheng. All rights reserved.
//
import Cocoa
class SimulatorResetMenuItem: NSMenuItem {
var device: Device!
init(device:Device) {
self.device = device
let title = "\(UIConstants.strings.menuResetSimulatorButton) \(device.name)"
super.init(title: title, action: #selector(self.resetSimulator(_:)), keyEquivalent: "")
target = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func resetSimulator(_ sender: AnyObject) {
let alert: NSAlert = NSAlert()
alert.messageText = String(format: UIConstants.strings.actionFactoryResetAlertMessage, device.name)
alert.alertStyle = .critical
alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertConfirmButton)
alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertCancelButton)
let response = alert.runModal()
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
SimulatorController.factoryReset(device)
}
}
}
| 464cec6e184f754308a01af1044a1c4a | 29.525 | 107 | 0.68878 | false | false | false | false |
devcarlos/NSDateUtils.swift | refs/heads/master | NSDateUtilsDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// NSDateUtilsDemo
//
// Created by Carlos Alcala on 6/2/16.
// Copyright © 2016 Carlos Alcala. All rights reserved.
//
import UIKit
import NSDateUtils
class ViewController: UIViewController {
let date = NSDate().dateFromString("10/12/2013")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK : Actions
@IBAction func shortDate(sender: AnyObject) {
//using format: yyyy-MM-dd
let shortDate = date.convertToString()
self.showAlert(shortDate)
}
@IBAction func longDate(sender: AnyObject) {
//using format: EE, LLL d yyyy, HH:mm
let longDate = date.convertToLongString()
self.showAlert(longDate)
}
//MARK : Helper Functions
func showAlert(message:String) {
let alert = UIAlertController(title: "Date String", message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
| 230d76079ccc5459ee131df7323249e8 | 25.519231 | 101 | 0.638144 | false | false | false | false |
warnerbros/cpe-manifest-ios-experience | refs/heads/master | Source/In-Movie Experience/ShoppingSceneDetailCollectionViewCell.swift | apache-2.0 | 1 | //
// ShoppingSceneDetailCollectionViewCell.swift
//
import Foundation
import UIKit
import CPEData
enum ShoppingProductImageType {
case product
case scene
}
class ShoppingSceneDetailCollectionViewCell: SceneDetailCollectionViewCell {
static let NibName = "ShoppingSceneDetailCollectionViewCell"
static let ReuseIdentifier = "ShoppingSceneDetailCollectionViewCellReuseIdentifier"
@IBOutlet weak private var imageView: UIImageView!
@IBOutlet weak private var bullseyeImageView: UIImageView!
@IBOutlet weak private var extraDescriptionLabel: UILabel!
var productImageType = ShoppingProductImageType.product
private var extraDescription: String? {
set {
extraDescriptionLabel?.text = newValue
}
get {
return extraDescriptionLabel?.text
}
}
private var currentProduct: ProductItem? {
didSet {
if currentProduct != oldValue {
descriptionText = currentProduct?.brand
extraDescription = currentProduct?.name
if productImageType == .scene {
setImageURL(currentProduct?.sceneImageURL ?? currentProduct?.productImageURL)
} else {
setImageURL(currentProduct?.productImageURL)
}
}
if currentProduct == nil {
currentProductFrameTime = -1
}
}
}
private var currentProductFrameTime = -1.0
private var currentProductSessionDataTask: URLSessionDataTask?
var products: [ProductItem]? {
didSet {
currentProduct = products?.first
}
}
override func currentTimeDidChange() {
if let timedEvent = timedEvent, timedEvent.isType(.product) {
if let product = timedEvent.product {
products = [product]
} else {
DispatchQueue.global(qos: .userInteractive).async {
if let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil {
let newFrameTime = productAPIUtil.closestFrameTime(self.currentTime)
if newFrameTime != self.currentProductFrameTime {
self.currentProductFrameTime = newFrameTime
if let currentTask = self.currentProductSessionDataTask {
currentTask.cancel()
}
self.currentProductSessionDataTask = productAPIUtil.getFrameProducts(self.currentProductFrameTime, completion: { [weak self] (products) -> Void in
self?.currentProductSessionDataTask = nil
DispatchQueue.main.async {
self?.products = products
}
})
}
}
}
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
products = nil
bullseyeImageView.isHidden = true
if let task = currentProductSessionDataTask {
task.cancel()
currentProductSessionDataTask = nil
}
}
override func layoutSubviews() {
super.layoutSubviews()
if productImageType == .scene, let product = currentProduct, product.bullseyePoint != CGPoint.zero {
var bullseyeFrame = bullseyeImageView.frame
let bullseyePoint = CGPoint(x: imageView.frame.width * product.bullseyePoint.x, y: imageView.frame.height * product.bullseyePoint.y)
bullseyeFrame.origin = CGPoint(x: bullseyePoint.x + imageView.frame.minX - (bullseyeFrame.width / 2), y: bullseyePoint.y + imageView.frame.minY - (bullseyeFrame.height / 2))
bullseyeImageView.frame = bullseyeFrame
bullseyeImageView.layer.shadowColor = UIColor.black.cgColor
bullseyeImageView.layer.shadowOffset = CGSize(width: 1, height: 1)
bullseyeImageView.layer.shadowOpacity = 0.75
bullseyeImageView.layer.shadowRadius = 2
bullseyeImageView.clipsToBounds = false
bullseyeImageView.isHidden = false
} else {
bullseyeImageView.isHidden = true
}
}
private func setImageURL(_ imageURL: URL?) {
if let url = imageURL {
imageView.contentMode = .scaleAspectFit
imageView.sd_setImage(with: url)
} else {
imageView.sd_cancelCurrentImageLoad()
imageView.image = nil
}
}
}
| 74e4c4ee3e5a90fed1e77576a1c173d8 | 34.305344 | 185 | 0.594162 | false | false | false | false |
zhangchn/swelly | refs/heads/master | swelly/PTY.swift | gpl-2.0 | 1 | //
// PTY.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import Foundation
import Darwin
protocol PTYDelegate: NSObjectProtocol {
func ptyWillConnect(_ pty: PTY)
func ptyDidConnect(_ pty: PTY)
func pty(_ pty: PTY, didRecv data: Data)
func pty(_ pty: PTY, willSend data: Data)
func ptyDidClose(_ pty: PTY)
}
func ctrlKey(_ c: String) throws -> UInt8 {
if let c = c.unicodeScalars.first {
if !c.isASCII {
throw NSError(domain: "PTY", code: 1, userInfo: nil)
}
return UInt8(c.value) - UInt8("A".unicodeScalars.first!.value + 1)
} else {
throw NSError(domain: "PTY", code: 2, userInfo: nil)
}
}
func fdZero(_ set: inout fd_set) {
set.fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
}
func fdSet(_ fd: Int32, set: inout fd_set) {
let intOffset = Int(fd / 32)
let bitOffset = fd % 32
let mask: __int32_t = 1 << bitOffset
switch intOffset {
case 0: set.fds_bits.0 = set.fds_bits.0 | mask
case 1: set.fds_bits.1 = set.fds_bits.1 | mask
case 2: set.fds_bits.2 = set.fds_bits.2 | mask
case 3: set.fds_bits.3 = set.fds_bits.3 | mask
case 4: set.fds_bits.4 = set.fds_bits.4 | mask
case 5: set.fds_bits.5 = set.fds_bits.5 | mask
case 6: set.fds_bits.6 = set.fds_bits.6 | mask
case 7: set.fds_bits.7 = set.fds_bits.7 | mask
case 8: set.fds_bits.8 = set.fds_bits.8 | mask
case 9: set.fds_bits.9 = set.fds_bits.9 | mask
case 10: set.fds_bits.10 = set.fds_bits.10 | mask
case 11: set.fds_bits.11 = set.fds_bits.11 | mask
case 12: set.fds_bits.12 = set.fds_bits.12 | mask
case 13: set.fds_bits.13 = set.fds_bits.13 | mask
case 14: set.fds_bits.14 = set.fds_bits.14 | mask
case 15: set.fds_bits.15 = set.fds_bits.15 | mask
case 16: set.fds_bits.16 = set.fds_bits.16 | mask
case 17: set.fds_bits.17 = set.fds_bits.17 | mask
case 18: set.fds_bits.18 = set.fds_bits.18 | mask
case 19: set.fds_bits.19 = set.fds_bits.19 | mask
case 20: set.fds_bits.20 = set.fds_bits.20 | mask
case 21: set.fds_bits.21 = set.fds_bits.21 | mask
case 22: set.fds_bits.22 = set.fds_bits.22 | mask
case 23: set.fds_bits.23 = set.fds_bits.23 | mask
case 24: set.fds_bits.24 = set.fds_bits.24 | mask
case 25: set.fds_bits.25 = set.fds_bits.25 | mask
case 26: set.fds_bits.26 = set.fds_bits.26 | mask
case 27: set.fds_bits.27 = set.fds_bits.27 | mask
case 28: set.fds_bits.28 = set.fds_bits.28 | mask
case 29: set.fds_bits.29 = set.fds_bits.29 | mask
case 30: set.fds_bits.30 = set.fds_bits.30 | mask
case 31: set.fds_bits.31 = set.fds_bits.31 | mask
default: break
}
}
func fdIsset(_ fd: Int32, _ set: fd_set) -> Bool {
let a = fd / 32
let mask: Int32 = 1 << (fd % 32)
switch a {
case 0: return (set.fds_bits.0 & mask) != 0
case 1: return (set.fds_bits.1 & mask) != 0
case 2: return (set.fds_bits.2 & mask) != 0
case 3: return (set.fds_bits.3 & mask) != 0
case 4: return (set.fds_bits.4 & mask) != 0
case 5: return (set.fds_bits.5 & mask) != 0
case 6: return (set.fds_bits.6 & mask) != 0
case 7: return (set.fds_bits.7 & mask) != 0
case 8: return (set.fds_bits.8 & mask) != 0
case 9: return (set.fds_bits.9 & mask) != 0
case 10: return (set.fds_bits.10 & mask) != 0
case 11: return (set.fds_bits.11 & mask) != 0
case 12: return (set.fds_bits.12 & mask) != 0
case 13: return (set.fds_bits.13 & mask) != 0
case 14: return (set.fds_bits.14 & mask) != 0
case 15: return (set.fds_bits.15 & mask) != 0
case 16: return (set.fds_bits.16 & mask) != 0
case 17: return (set.fds_bits.17 & mask) != 0
case 18: return (set.fds_bits.18 & mask) != 0
case 19: return (set.fds_bits.19 & mask) != 0
case 20: return (set.fds_bits.20 & mask) != 0
case 21: return (set.fds_bits.21 & mask) != 0
case 22: return (set.fds_bits.22 & mask) != 0
case 23: return (set.fds_bits.23 & mask) != 0
case 24: return (set.fds_bits.24 & mask) != 0
case 25: return (set.fds_bits.25 & mask) != 0
case 26: return (set.fds_bits.26 & mask) != 0
case 27: return (set.fds_bits.27 & mask) != 0
case 28: return (set.fds_bits.28 & mask) != 0
case 29: return (set.fds_bits.29 & mask) != 0
case 30: return (set.fds_bits.30 & mask) != 0
case 31: return (set.fds_bits.31 & mask) != 0
default: break
}
return false
}
class PTY {
weak var delegate: PTYDelegate?
var proxyType: ProxyType
var proxyAddress: String
private var connecting = false
private var fd: Int32 = -1
private var pid: pid_t = 0
init(proxyAddress addr:String, proxyType type: ProxyType) {
proxyType = type
proxyAddress = addr
}
deinit {
close()
}
func close() {
if pid > 0 {
kill(pid, SIGKILL)
pid = 0
}
if fd >= 0 {
_ = Darwin.close(fd)
fd = -1
delegate?.ptyDidClose(self)
}
}
class func parse(addr: String) -> String {
var addr = addr.trimmingCharacters(in: CharacterSet.whitespaces)
if addr.contains(" ") {
return addr;
}
var ssh = false
var port: String? = nil
var fmt: String!
if addr.lowercased().hasPrefix("ssh://") {
ssh = true
let idx = addr.index(addr.startIndex, offsetBy: 6)
addr = String(addr[idx...])
} else {
if let range = addr.range(of: "://") {
addr = String(addr[range.upperBound...])
}
}
if let range = addr.range(of: ":") {
port = String(addr[range.upperBound...])
addr = String(addr[..<range.lowerBound])
}
if ssh {
if port == nil {
port = "22"
}
fmt = "ssh -o Protocol=2,1 -p %2$@ -x %1$@"
} else {
if port == nil {
port = "23"
}
if let range = addr.range(of: "@") {
addr = String(addr[range.upperBound...])
}
fmt = "/usr/bin/telnet -8 %@ -%@"
}
return String.init(format: fmt, addr, port!)
}
func connect(addr: String, connectionProtocol: ConnectionProtocol, userName: String!) -> Bool {
let slaveName = UnsafeMutablePointer<Int8>.allocate(capacity: Int(PATH_MAX))
let iflag = tcflag_t(bitPattern: Int(ICRNL | IXON | IXANY | IMAXBEL | BRKINT))
let oflag = tcflag_t(bitPattern: Int(OPOST | ONLCR))
let cflag = tcflag_t(bitPattern: Int(CREAD | CS8 | HUPCL))
let lflag = tcflag_t(bitPattern: Int(ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL))
let controlCharacters : (cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t) = try! (ctrlKey("D"), 0xff, 0xff, 0x7f, ctrlKey("W"), ctrlKey("U"), ctrlKey("R"), 0, ctrlKey("C"), 0x1c, ctrlKey("Z"), ctrlKey("Y"), ctrlKey("Q"), ctrlKey("S"), 0xff, 0xff, 1, 0, 0xff, 0)
var term = termios(c_iflag: iflag,
c_oflag: oflag,
c_cflag: cflag,
c_lflag: lflag,
c_cc: controlCharacters,
c_ispeed: speed_t(B38400),
c_ospeed: speed_t(B38400))
let ws_col = GlobalConfig.sharedInstance.column
let ws_row = GlobalConfig.sharedInstance.row
var size = winsize(ws_row: UInt16(ws_row), ws_col: UInt16(ws_col), ws_xpixel: 0, ws_ypixel: 0)
//var arguments = PTY.parse(addr: addr).components(separatedBy: " ")
pid = forkpty(&fd, slaveName, &term, &size)
if pid < 0 {
print("Error forking pty: \(errno)")
} else if pid == 0 {
// child process
//kill(0, SIGSTOP)
var arguments: [String]
var hostAndPort = addr.split(separator: ":")
switch connectionProtocol {
case .telnet:
if hostAndPort.count == 2, let _ = Int(hostAndPort[1]) {
arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0]), String(hostAndPort[1])]
} else {
arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0])]
}
case .ssh:
if hostAndPort.count == 2 {
if let _ = Int(hostAndPort[1]) {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", String(hostAndPort[1]), "-x", userName! + "@" + String(hostAndPort[0])]
} else {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])]
}
} else {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])]
}
if let proxyCommand = Proxy.proxyCommand(address: proxyAddress, type: proxyType) {
arguments.append("-o")
arguments.append(proxyCommand)
}
}
let argv = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: arguments.count + 1)
for (idx, arg) in arguments.enumerated() {
argv[idx] = arg.utf8CString.withUnsafeBytes({ (buf) -> UnsafeMutablePointer<Int8> in
let x = UnsafeMutablePointer<Int8>.allocate(capacity: buf.count + 1)
memcpy(x, buf.baseAddress, buf.count)
x[buf.count] = 0
return x
})
}
argv[arguments.count] = nil
execvp(argv[0], argv)
perror(argv[0])
sleep(UINT32_MAX)
} else {
// parent process
var one = 1
let result = ioctl(fd, TIOCPKT, &one)
if result == 0 {
Thread.detachNewThread {
self.readLoop()
}
} else {
print("ioctl failure: erron: \(errno)")
}
}
slaveName.deallocate()
connecting = true
delegate?.ptyWillConnect(self)
return true
}
func recv(data: Data) {
if connecting {
connecting = false
delegate?.ptyDidConnect(self)
}
delegate?.pty(self, didRecv: data)
}
func send(data: Data) {
guard fd >= 0 && !connecting else {
return
}
delegate?.pty(self, willSend: data)
var length = data.count
data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
var writefds = fd_set()
var errorfds = fd_set()
var timeout = timeval()
var chunkSize: Int
var msg = bytes.baseAddress!
while length > 0 {
// bzero(&writefds, MemoryLayout<fd_set>.size)
// bzero(&errorfds, MemoryLayout<fd_set>.size)
fdZero(&writefds)
fdZero(&errorfds)
fdSet(fd, set: &writefds)
fdSet(fd, set: &errorfds)
timeout.tv_sec = 0
timeout.tv_usec = 100000
let result = select(fd + 1, nil, &writefds, &errorfds, &timeout)
if result == 0 {
NSLog("timeout")
break
} else if result < 0 {
self.close()
break
}
if length > 4096 {
chunkSize = 4096
} else {
chunkSize = length
}
let size = write(fd, bytes.baseAddress!, chunkSize)
if size < 0 {
break
}
msg = msg.advanced(by: size)
length -= size
}
}
}
func readLoop() {
var readfds = fd_set()
var errorfds = fd_set()
var exit = false
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: 4096)
var iterationCount = 0
let result = autoreleasepool { () -> Int32 in
var result = Int32(0)
while !exit {
iterationCount += 1
fdZero(&readfds)
fdZero(&errorfds)
fdSet(fd, set: &readfds)
fdSet(fd, set: &errorfds)
result = select(fd.advanced(by: 1), &readfds, nil, &errorfds, nil)
if result < 0 {
print("")
break
} else if fdIsset(fd, errorfds) {
result = Int32(read(fd, buf, 1))
if result == 0 {
exit = true
}
} else if fdIsset(fd, readfds) {
result = Int32(read(fd, buf, 4096))
if result > 1 {
let d = Data(buffer: UnsafeBufferPointer<Int8>(start: buf.advanced(by: 1), count: Int(result)-1))
DispatchQueue.main.async {
self.recv(data: d)
}
} else if result == 0 {
exit = true
}
}
}
return result
}
if result >= 0 {
DispatchQueue.main.async {
self.close()
}
}
buf.deallocate()
}
}
| 6ab3e62ed175d7c0066d979e0c40f3ac | 36.415094 | 340 | 0.493048 | false | false | false | false |
hjudi/gelato-helpers | refs/heads/master | gelato-helpers.swift | mit | 1 | //
// gelato-helpers.swift
// Hazim Judi
// MIT license and all that metal \M/
//
import UIKit
//Quick access to the app delegate and system version.
let getAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let version = UIDevice.currentDevice().systemVersion
var isiPhone6 : Bool {
if UIScreen.mainScreen().bounds.size.height == 667.0 {
return true
}
return false
}
var isiPhone6Plus : Bool {
if UIScreen.mainScreen().bounds.size.height == 736.0 {
return true
}
return false
}
var isiOS9 : Bool {
if version.rangeOfString("9.") != nil { return true }
return false
}
//Lets you specify padding for the text + placeholder text in a UITextField.
class PaddingTextField : UITextField {
var xPadding = CGFloat(10)
var yPadding = CGFloat(1)
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2))
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2))
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2))
}
}
extension NSDate {
//Gives you a lean + modern elapsed time estimate string.
//Ex. "5m", "13d" ...
func getTimeElapsed() -> String {
let elapsed = abs(self.timeIntervalSinceNow)
if elapsed > 0 && elapsed < 120 {
return "Now"
}
else if elapsed > 120 && elapsed < 3600 {
let r = NSString(format: "%.f", elapsed/120)
return "\(r)m"
}
else if elapsed > 3600 && elapsed < 86400 {
let r = NSString(format: "%.f", elapsed/3600)
return "\(r)h"
}
else if elapsed > 86400 && elapsed < 604800 {
let r = NSString(format: "%.f", elapsed/86400)
return "\(r)d"
}
else if elapsed > 604800 && elapsed < 2419200 {
let r = NSString(format: "%.f", elapsed/604800)
return "\(r)w"
}
else if elapsed > 2419200 && elapsed < 29030400 {
let r = NSString(format: "%.f", elapsed/2419200)
return "\(r)mo"
}
else {
let r = NSString(format: "%.f", elapsed/29030400)
return "\(r)y"
}
}
}
extension UIViewController {
var x : CGFloat {
get {
return self.view.frame.origin.x
}
set(newX) {
self.view.frame.origin.x = newX
}
}
var y : CGFloat {
get {
return self.view.frame.origin.y
}
set(newY) {
self.view.frame.origin.y = newY
}
}
var width : CGFloat {
get {
return self.view.frame.width
}
set(newW) {
self.view.frame.size.width = newW
}
}
var height : CGFloat {
get {
return self.view.frame.height
}
set(newH) {
self.view.frame.size.height = newH
}
}
}
extension UIView {
//Removes all subviews.
func removeAllSubviews() {
for subview in self.subviews {
subview.removeFromSuperview()
}
}
//Quick access to get/set frame values without "frame.origin" or "frame.size"
var x : CGFloat {
get {
return self.frame.origin.x
}
set(newX) {
self.frame.origin.x = newX
}
}
var y : CGFloat {
get {
return self.frame.origin.y
}
set(newY) {
self.frame.origin.y = newY
}
}
var width : CGFloat {
get {
return self.frame.width
}
set(newWidth) {
self.frame.size.width = newWidth
}
}
var height : CGFloat {
get {
return self.frame.height
}
set(newHeight) {
self.frame.size.height = newHeight
}
}
}
//Self explanatory: turn a 6-character hex value into a UIColor.
func hexToColor(hex: String) -> UIColor? {
if let hexIntValue = UInt(hex, radix: 16) {
return UIColor(
red: CGFloat((hexIntValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hexIntValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hexIntValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
return nil
}
//Vice versa.
func colorToHex(color: UIColor) -> String {
let values = color.getRGBA()
return String(format: "%02x%02x%02x", Int(values[0]*255), Int(values[1]*255), Int(values[2]*255))
}
//If you use NSAttributedString, this is your lucky day.
//paragraphStyleWithLineHeight() gives you a quick paragraph style with specified settings.
func paragraphStyleWithLineHeight(lineHeight: CGFloat?, alignment: NSTextAlignment?) -> NSParagraphStyle {
let paragraphStyle = NSMutableParagraphStyle()
if lineHeight != nil { paragraphStyle.lineSpacing = lineHeight! }
if alignment != nil { paragraphStyle.alignment = alignment! }
return paragraphStyle as NSParagraphStyle
}
extension Array {
// No more nil subscript returns!!
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
extension String {
//Saved you an extra property
var length: Int { return self.characters.count }
//We've all had to deal with value inconsistency + REST APIs before
func toBool() -> Bool? {
switch self {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}
//Gives you a simple array of username-valid strings that appear after '@'
//"We @all live in the yellow @submarine" -> ["all", "submarine"]
func toMentionsArray() -> Array<String> {
var arrayOfMentions : Array<String> = []
if self.length > 0 {
var string = self
var containsMore = true
while containsMore == true && string.length > 0 {
if let r = string.rangeOfString("@") {
if arrayOfMentions.count == 0 && r.endIndex == string.endIndex { containsMore = false; break }
var finalMentionRange = r
finalMentionRange.startIndex++
var hitAnObstacle = false
while hitAnObstacle == false {
if finalMentionRange.endIndex == string.endIndex {
hitAnObstacle = true
break
}
if String(string[finalMentionRange.endIndex]).rangeOfCharacterFromSet(NSCharacterSet(charactersInString: " .@:!$%^&*()+=?\"\'[]\n")) != nil {
hitAnObstacle = true
break
}
finalMentionRange.endIndex++
}
if string.substringWithRange(finalMentionRange) != "" {
arrayOfMentions.append(string.substringWithRange(finalMentionRange))
}
string = string.substringFromIndex(finalMentionRange.endIndex)
}
else {
containsMore = false
}
}
}
return arrayOfMentions
}
//Shortens URL strings down to their 'roots'
func minifiedLink(link: String) -> String {
var minified = self.lowercaseString.stringByReplacingOccurrencesOfString("http://", withString: "", options: [], range: nil).stringByReplacingOccurrencesOfString("https://", withString: "", options: [], range: nil).stringByReplacingOccurrencesOfString("www.", withString: "", options: [], range: nil)
if let r = minified.rangeOfString("/") {
let range = r.startIndex..<minified.endIndex
minified = minified.stringByReplacingCharactersInRange(range, withString: link)
}
else {
minified += link
}
return minified
}
}
extension UIImage {
//Returns a version of the image with the specified alpha. No more selected state assets!
func dimWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
self.drawInRect(CGRect(origin: CGPointZero, size: self.size), blendMode: .Normal, alpha: alpha)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//Fills the opaque parts of an image with the specified color.
func fillWithColor(color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let c = UIGraphicsGetCurrentContext()
self.drawInRect(CGRect(origin: CGPointZero, size: self.size), blendMode: .Normal, alpha: 1)
CGContextSetBlendMode(c, CGBlendMode.SourceIn)
CGContextSetFillColorWithColor(c, color.CGColor)
CGContextFillRect(c, CGRect(origin: CGPointZero, size: self.size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
extension UIColor {
//Gives a single-pt image representation of the color, for use as a lazy BG sprite.
func toImage() -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, self.CGColor);
CGContextFillRect(context, rect);
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//Makes the image darker/brighter by the specified percentage.
//<White>.darkerByPercentage(percentage: 1.0) -> <Black>
func darkerByPercentage(percentage: CGFloat) -> UIColor {
var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var a = CGFloat()
self.getRed(&red, green: &green, blue: &blue, alpha: &a)
return UIColor(red: red-percentage, green: green-percentage, blue: blue-percentage, alpha: a)
}
func lighterByPercentage(percentage: CGFloat) -> UIColor {
var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var a = CGFloat()
self.getRed(&red, green: &green, blue: &blue, alpha: &a)
return UIColor(red: red+percentage, green: green+percentage, blue: blue+percentage, alpha: a)
}
//Gives a 4-value collection of a color's RGBA values. <Red>.getRGBA()[0] -> 1.0
func getRGBA() -> [CGFloat] {
var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var alpha = CGFloat()
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return [red,green,blue,alpha]
}
}
| 783e7c9de97d283d75b94b1eff1bb3c9 | 26.81733 | 308 | 0.549419 | false | false | false | false |
waterskier2007/NVActivityIndicatorView | refs/heads/master | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineScalePulseOutRapid.swift | mit | 1 | //
// NVActivityIndicatorAnimationLineScalePulseOutRapid.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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
class NVActivityIndicatorAnimationLineScalePulseOutRapid: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.width - size.width) / 2
let y = (layer.bounds.height - size.height) / 2
let duration: CFTimeInterval = 0.9
let beginTime = CACurrentMediaTime()
let beginTimes = [0.5, 0.25, 0, 0.25, 0.5]
let timingFunction = CAMediaTimingFunction(controlPoints: 0.11, 0.49, 0.38, 0.78)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.8, 0.9]
animation.timingFunctions = [timingFunction, timingFunction]
animation.beginTime = beginTime
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw lines
for i in 0 ..< 5 {
let line = NVActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i),
y: y,
width: lineSize,
height: size.height)
animation.beginTime = beginTime + beginTimes[i]
line.frame = frame
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
| 9f7c7c17abda8750bc6d049a68f13a04 | 41.227273 | 128 | 0.672408 | false | false | false | false |
adamnemecek/WebMIDIKit | refs/heads/master | Sources/WebMIDIKit/MIDIOutput.swift | mit | 1 | import CoreMIDI
// extension MIDIPacket {
//// public typealias ArrayLiteralElement = UInt8
// public init(data: UInt8..., timestamp: MIDITimeStamp = 0) {
// assert(data.count < 256)
// self.init()
// self.timeStamp = timestamp
//
//// var elements = elements
//// with
// data.withUnsafeBufferPointer { _ in
//
// }
// fatalError()
// }
// }
func MIDISend(port: MIDIPortRef, endpoint: MIDIEndpointRef, list: UnsafePointer<MIDIPacketList>) {
OSAssert(MIDISend(port, endpoint, list))
/// this let's us propagate the events to everyone subscribed to this
/// endpoint not just this port, i'm not sure if we actually want this
/// but for now, it let's us create multiple ports from different MIDIAccess
/// objects and have them all receive the same messages
OSAssert(MIDIReceived(endpoint, list))
}
public class MIDIOutput: MIDIPort {
// @discardableResult
// public final func send<S: Sequence>(_ data: S, offset: Double? = nil) -> Self where S.Iterator.Element == UInt8 {
// open()
// var lst = MIDIPacketList(data)
// lst.send(to: self, offset: offset)
//
// return self
// }
//
// @discardableResult
// public final func send(_ list: UnsafePointer<MIDIPacketList>) -> Self {
//// packet.send(to: self, offset: 0)
//// return self
//// fatalError()
// MIDISend(port: self.ref, endpoint: self.endpoint.ref, list: list)
// return self
// }
@discardableResult
public final func send(_ list: MIDIPacketListBuilder) -> Self {
MIDISend(port: self.ref, endpoint: self.endpoint.ref, list: list.list)
return self
}
public final func clear() {
endpoint.flush()
}
// internal convenience init(virtual client: MIDIClient, block: @escaping MIDIReadBlock) {
// self.init(client: client, endpoint: VirtualMIDIDestination(client: client, block: block))
// }
}
//
// fileprivate final class VirtualMIDIDestination: VirtualMIDIEndpoint {
// init(client: MIDIClient, block: @escaping MIDIReadBlock) {
// super.init(ref: MIDIDestinationCreate(ref: client.ref, block: block))
// }
//// ths needs to use midi received
// http://stackoverflow.com/questions/10572747/why-doesnt-this-simple-coremidi-program-produce-midi-output
// func send(lst: UnsafePointer<MIDIPacketList>) {
// fatalError()
//// MIDISend(ref, endpoint.ref, lst)
// }
// }
//
//
// fileprivate func MIDIDestinationCreate(ref: MIDIClientRef, block: @escaping MIDIReadBlock) -> MIDIEndpointRef {
// var endpoint: MIDIEndpointRef = 0
// MIDIDestinationCreateWithBlock(ref, "Virtual MIDI destination endpoint" as CFString, &endpoint, block)
// return endpoint
// }
//
| 26abc59ef77281e54adeb16283295df7 | 33.148148 | 119 | 0.655459 | false | false | false | false |
contentful/contentful.swift | refs/heads/master | Sources/Contentful/Util.swift | mit | 1 | //
// Util.swift
// Contentful
//
// Created by JP Wright on 07.03.18.
// Copyright © 2018 Contentful GmbH. All rights reserved.
//
import Foundation
/// Utility method to add two dictionaries of the same time.
public func +=<K, V> (left: [K: V], right: [K: V]) -> [K: V] {
var result = left
right.forEach { key, value in result[key] = value }
return result
}
/// Utility method to add two dictionaries of the same time.
public func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] {
return left += right
}
/// Convenience methods for reading from dictionaries without conditional casts.
public extension Dictionary where Key: ExpressibleByStringLiteral {
/// Extract the String at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `String` from.
/// - Returns: The `String` value, or `nil` if data contained is not convertible to a `String`.
func string(at key: Key) -> String? {
return self[key] as? String
}
/// Extracts the array of `String` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `[String]` from
/// - Returns: The `[String]`, or nil if data contained is not convertible to an `[String]`.
func strings(at key: Key) -> [String]? {
return self[key] as? [String]
}
/// Extracts the `Int` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Int` value from.
/// - Returns: The `Int` value, or `nil` if data contained is not convertible to an `Int`.
func int(at key: Key) -> Int? {
return self[key] as? Int
}
/// Extracts the `Date` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Date` value from.
/// - Returns: The `Date` value, or `nil` if data contained is not convertible to a `Date`.
func int(at key: Key) -> Date? {
let dateString = self[key] as? String
let date = dateString?.iso8601StringDate
return date
}
/// Extracts the `Entry` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Entry` from.
/// - Returns: The `Entry` value, or `nil` if data contained does not have contain a Link referencing an `Entry`.
func linkedEntry(at key: Key) -> Entry? {
let link = self[key] as? Link
let entry = link?.entry
return entry
}
/// Extracts the `Asset` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Asset` from.
/// - Returns: The `Asset` value, or `nil` if data contained does not have contain a Link referencing an `Asset`.
func linkedAsset(at key: Key) -> Asset? {
let link = self[key] as? Link
let asset = link?.asset
return asset
}
/// Extracts the `[Entry]` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `[Entry]` from.
/// - Returns: The `[Entry]` value, or `nil` if data contained does not have contain a Link referencing an `Entry`.
func linkedEntries(at key: Key) -> [Entry]? {
let links = self[key] as? [Link]
let entries = links?.compactMap { $0.entry }
return entries
}
/// Extracts the `[Asset]` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `[Asset]` from.
/// - Returns: The `[Asset]` value, or `nil` if data contained does not have contain a Link referencing an `[Asset]`.
func linkedAssets(at key: Key) -> [Asset]? {
let links = self[key] as? [Link]
let assets = links?.compactMap { $0.asset }
return assets
}
/// Extracts the `Bool` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Bool` value from.
/// - Returns: The `Bool` value, or `nil` if data contained is not convertible to a `Bool`.
func bool(at key: Key) -> Bool? {
return self[key] as? Bool
}
/// Extracts the `Contentful.Location` at the specified fieldName.
///
/// - Parameter key: The name of the field to extract the `Contentful.Location` value from.
/// - Returns: The `Contentful.Location` value, or `nil` if data contained is not convertible to a `Contentful.Location`.
func location(at key: Key) -> Location? {
let coordinateJSON = self[key] as? [String: Any]
guard let longitude = coordinateJSON?["lon"] as? Double else { return nil }
guard let latitude = coordinateJSON?["lat"] as? Double else { return nil }
let location = Location(latitude: latitude, longitude: longitude)
return location
}
}
// Convenience protocol and accompanying extension for extracting the type of data wrapped in an Optional.
internal protocol OptionalProtocol {
static func wrappedType() -> Any.Type
}
extension Optional: OptionalProtocol {
internal static func wrappedType() -> Any.Type {
return Wrapped.self
}
}
| f100863a7ae18e9b84a02b60a1902386 | 37.610687 | 125 | 0.629893 | false | false | false | false |
coolsamson7/inject | refs/heads/master | InjectTests/BeanFactoryTest.swift | mit | 1 | //
// BeanFactoryTests.swift
// Inject
//
// Created by Andreas Ernst on 18.07.16.
// Copyright © 2016 Andreas Ernst. All rights reserved.
//
import XCTest
import Foundation
@testable import Inject
class BarFactoryBean: NSObject, FactoryBean {
func create() throws -> AnyObject {
let result = BarBean()
result.name = "factory"
result.age = 4711
return result
}
}
class BarBean: NSObject {
var name : String = "andi"
var age : Int = 51
var weight : Int = 87
}
class Data : NSObject, Bean, BeanDescriptorInitializer {
// instance data
var string : String = ""
var int : Int = 0
var float : Float = 0.0
var double : Double = 0.0
var character : Character = Character(" ")
var int8 : Int8 = 0
var foo : FooBase?
var bar : BarBean?
// ClassInitializer
func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) {
beanDescriptor["foo"].inject(InjectBean())
}
// Bean
func postConstruct() -> Void {
//print("post construct \(self)");
}
// CustomStringConvertible
override var description : String {
return "data[string: \(string) foo: \(String(describing: foo))]"
}
}
class FooBase : NSObject, Bean {
// Bean
func postConstruct() -> Void {
//print("post construct \(self)");
}
// CustomStringConvertible
override var description : String {
return "foobase[]"
}
}
class FooBean: FooBase {
var name : String?
var age : Int = 0
// Bean
override func postConstruct() -> Void {
//print("post construct \(self)");.auto
}
// CustomStringConvertible
override var description : String {
return "foo[name: \(String(describing: name)) age: \(age)]"
}
}
class BeanFactoryTests: XCTestCase {
override class func setUp() {
Classes.setDefaultBundle(BeanFactoryTests.self)
try! BeanDescriptor.forClass(Data.self) // force creation
// set tracing
Tracer.setTraceLevel("inject", level: .off)
// set logging
LogManager()
.registerLogger("", level : .off, logs: [QueuedLog(name: "async-console", delegate: ConsoleLog(name: "console", synchronize: false))])
}
// tests
func testXML() {
ConfigurationNamespaceHandler(namespace: "configuration")
// load parent xml
let parentData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "parent", withExtension: "xml")!)
let childData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "application", withExtension: "xml")!)
var environment = try! Environment(name: "parent")
try! environment.loadXML(parentData)
// load child
environment = try! Environment(name: "parent", parent: environment)
try! environment.loadXML(childData)
// check
let bean : Data = try! environment.getBean(Data.self, byId: "b1")
XCTAssert(bean.string == "b1")
let lazy = try! environment.getBean(Data.self, byId: "lazy")
XCTAssert(lazy.string == "lazy")
let proto1 = try! environment.getBean(Data.self, byId: "prototype")
let proto2 = try! environment.getBean(Data.self, byId: "prototype")
XCTAssert(proto1 !== proto2)
let bar = try! environment.getBean(BarBean.self)
XCTAssert(bar.age == 4711)
// Measure
if false {
try! Timer.measure({
var environment = try! Environment(name: "parent")
try! environment.loadXML(parentData)
// load child
environment = try! Environment(name: "child", parent: environment)
try! environment.loadXML(childData)
// force load!
try! environment.getBean(BarBean.self)
return true
}, times: 1000)
}
}
func testFluent() throws {
let parent = try Environment(name: "parent")
try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource())
try parent.getConfigurationManager().addSource(PlistConfigurationSource(name: "Info", forClass: type(of: self)))
try parent
.define(parent.settings()
.setValue(key: "key", value: "key_value"))
//.define(parent.bean(ProcessInfoConfigurationSource.self)
// .id("x1"))
.define(parent.bean(Data.self, id: "b0")
.property("string", value: "b0")
.property("int", value: 1)
.property("float", value: Float(-1.1))
.property("double", value: -2.2))
.define(parent.bean(FooBean.self, id: "foo")
.property("name", resolve: "${andi=Andreas?}")
.property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}"))
/*.define(parent.bean(Bar.self)
.id("bar")
.abstract()
.property("name", resolve: "${andi=Andreas?}"))
*/
//print(parent.getConfigurationManager().report())
let child = try! Environment(name: "child", parent: parent)
try! child
.define(child.bean(Data.self)
.id("b1")
.dependsOn("b0")
.property("foo", inject: InjectBean(id: "foo"))
.property("string", value: "b1")
.property("int", value: 1)
.property("int8", value: Int8(1))
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("lazy")
.lazy()
.property("bar", bean: child.bean(BarBean.self)
.property("name", value: "name")
.property("age", value: 0)
)
.property("string", value: "lazy")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("prototype")
.scope(child.scope("prototype"))
.property("string", value: "b1")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
//.define(child.bean(BarFactory.self)
// .target("Bar"))
//print(parent.getConfigurationManager().report())
// check
let bean : Data = try! child.getBean(Data.self, byId: "b1")
XCTAssert(bean.string == "b1")
let lazy = try! child.getBean(Data.self, byId: "lazy")
XCTAssert(lazy.string == "lazy")
let proto1 = try! child.getBean(Data.self, byId: "prototype")
let proto2 = try! child.getBean(Data.self, byId: "prototype")
XCTAssert(proto1 !== proto2)
let bar = try! child.getBean(BarBean.self)
XCTAssert(bar.age == 0)
_ = try! child.getBean(FooBean.self, byId: "foo")
//XCTAssert(bar.age == 4711)
try! Timer.measure({
let parent = try Environment(name: "parent")
try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource())
try parent
.define(parent.settings()
.setValue(key: "key", value: "key_value"))
//.define(parent.bean(ProcessInfoConfigurationSource.self)
// .id("x1"))
.define(parent.bean(Data.self, id: "b0")
.property("string", value: "b0")
.property("int", value: 1)
.property("float", value: Float(-1.1))
.property("double", value: -2.2))
.define(parent.bean(FooBean.self, id: "foo")
.property("name", resolve: "${andi=Andreas?}")
.property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}")).startup() // TODO?
/*.define(parent.bean(Bar.self)
.id("bar")
.abstract()
.property("name", resolve: "${andi=Andreas?}"))
*/
let child = try! Environment(name: "child", parent: parent)
try! child
.define(child.bean(Data.self)
.id("b1")
.dependsOn("b0")
.property("foo", inject: InjectBean(id: "foo"))
.property("string", value: "b1")
.property("int", value: 1)
.property("int8", value: Int8(1))
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("lazy")
.lazy()
.property("bar", bean: child.bean(BarBean.self)
.property("name", value: "name")
.property("age", value: 0)
)
.property("string", value: "lazy")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2))
.define(child.bean(Data.self)
.id("prototype")
.scope(child.scope("prototype"))
.property("string", value: "b1")
.property("int", value: 1)
.property("float", value: Float(1.1))
.property("double", value: 2.2)).startup()
return true
}, times: 1000)
}
}
| 389f61a2752cd0d62c8e51a866f86a7d | 29.490854 | 148 | 0.514549 | false | false | false | false |
JudoPay/JudoKit | refs/heads/master | Carthage/Checkouts/flickrpickr-sdk/Carthage/Checkouts/judokit/Source/Theme.swift | mit | 3 | //
// JudoPayViewController.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// 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
/// A class which can be used to easily customize the SDKs view
public struct Theme {
/// A tint color that is used to generate a theme for the judo payment form
public var tintColor: UIColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42)
public var tintActiveColor: UIColor = UIColor(red: 30/255, green: 120/255, blue: 160/255, alpha: 1.0)
/// Set the address verification service to true to prompt the user to input his country and post code information
public var avsEnabled: Bool = false
/// a boolean indicating whether a security message should be shown below the input
public var showSecurityMessage: Bool = false
/// An array of accepted card configurations (card network and card number length)
public var acceptedCardNetworks: [Card.Configuration] = [Card.Configuration(.amex, 15), Card.Configuration(.visa, 16), Card.Configuration(.masterCard, 16), Card.Configuration(.maestro, 16)]
// MARK: Buttons
/// the title for the payment button
public var paymentButtonTitle = "Pay"
/// the title for the button when registering a card
public var registerCardButtonTitle = "Add card"
/// the title for the back button of the navigation controller
public var registerCardNavBarButtonTitle = "Add"
/// the title for the back button
public var backButtonTitle = "< Back"
// MARK: Titles
/// the title for a payment
public var paymentTitle = "Payment"
/// the title for a card registration
public var registerCardTitle = "Add card"
/// the title for a refund
public var refundTitle = "Refund"
/// the title for an authentication
public var authenticationTitle = "Authentication"
// MARK: Loading
/// when a register card transaction is currently running
public var loadingIndicatorRegisterCardTitle = "Adding card..."
/// the title of the loading indicator during a transaction
public var loadingIndicatorProcessingTitle = "Processing payment..."
/// the title of the loading indicator during a redirect to a 3DS webview
public var redirecting3DSTitle = "Redirecting..."
/// the title of the loading indicator during the verification of the transaction
public var verifying3DSPaymentTitle = "Verifying payment"
/// the title of the loading indicator during the verification of the card registration
public var verifying3DSRegisterCardTitle = "Verifying card"
// MARK: Input fields
/// the height of the input fields
public var inputFieldHeight: CGFloat = 68
// MARK: Security message
/// the message that is shown below the input fields the ensure safety when entering card information
public var securityMessageString = "Your card details are encrypted using SSL before transmission to our secure payment service provider."
/// the text size of the security message
public var securityMessageTextSize: CGFloat = 12
// MARK: Colors
/**
Helper method to identifiy whether to use a dark or light theme
- returns: A boolean indicating to use dark or light mode
*/
public func colorMode() -> Bool {
return self.tintColor.greyScale() < 0.5
}
/// The default text color
public var judoTextColor: UIColor?
/// The default navigation bar title color
public var judoNavigationBarTitleColor: UIColor?
/// The default navigation bar bottom color
public var judoNavigationBarBottomColor: UIColor?
/// The default navigation bar background color
public var judoNavigationBarBackgroundColor: UIColor?
/// The color that is used for active input fields
public var judoInputFieldTextColor: UIColor?
/// The color that is used for active input fields
public var judoInputFieldHintTextColor: UIColor?
/// The color that is used for the placeholders of the input fields
public var judoPlaceholderTextColor: UIColor?
/// The color that is used for the border color of the input fields
public var judoInputFieldBorderColor: UIColor?
/// The background color of the contentView
public var judoContentViewBackgroundColor: UIColor?
/// The button color
public var judoButtonColor: UIColor?
/// The title color of the button
public var judoButtonTitleColor: UIColor?
/// The background color of the loadingView
public var judoLoadingBackgroundColor: UIColor?
/// The color that is used when an error occurs during entry
public var judoErrorColor: UIColor?
/// The color of the block that is shown when something is loading
public var judoLoadingBlockViewColor: UIColor?
/// Input field background color
public var judoInputFieldBackgroundColor: UIColor?
/**
The default text color
- returns: A UIColor object
*/
public func getTextColor() -> UIColor {
if self.judoTextColor != nil {
return self.judoTextColor!
}
let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87)
if self.colorMode() {
return dgc
} else {
return dgc.inverseColor()
}
}
/**
The default text color
- returns: A UIColor object
*/
public func getNavigationBarTitleColor() -> UIColor {
if self.judoNavigationBarTitleColor != nil {
return self.judoNavigationBarTitleColor!
}
let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87)
if self.colorMode() {
return dgc
} else {
return dgc.inverseColor()
}
}
/**
The default text color
- returns: A UIColor object
*/
public func getNavigationBarBottomColor() -> UIColor {
if self.judoNavigationBarBottomColor != nil {
return self.judoNavigationBarBottomColor!
}
let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42)
if self.colorMode() {
return dgc
} else {
return dgc.inverseColor()
}
}
/**
The default text color
- returns: A UIColor object
*/
public func getNavigationBarBackgroundColor() -> UIColor {
if self.judoNavigationBarBackgroundColor != nil {
return self.judoNavigationBarBackgroundColor!
}
let dgc = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0)
if self.colorMode() {
return dgc
} else {
return dgc.inverseColor()
}
}
/**
The color that is used for active input fields
- returns: A UIColor object
*/
public func getInputFieldTextColor() -> UIColor {
return self.judoInputFieldTextColor ?? UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87)
}
/**
The color that is used for active input fields
- returns: A UIColor object
*/
public func getInputFieldHintTextColor() -> UIColor {
return self.judoInputFieldHintTextColor ?? UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87)
}
/**
The color that is used for the placeholders of the input fields
- returns: A UIColor object
*/
public func getPlaceholderTextColor() -> UIColor {
if self.judoPlaceholderTextColor != nil {
return self.judoPlaceholderTextColor!
}
let lgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42)
if self.colorMode() {
return lgc
} else {
return lgc.inverseColor()
}
}
/**
The color that is used for the border color of the input fields
- returns: A UIColor object
*/
public func getInputFieldBorderColor() -> UIColor {
return self.judoInputFieldBorderColor ?? UIColor(red: 180/255, green: 180/255, blue: 180/255, alpha: 1.0)
}
/**
The background color of the contentView
- returns: A UIColor object
*/
public func getContentViewBackgroundColor() -> UIColor {
if self.judoContentViewBackgroundColor != nil {
return self.judoContentViewBackgroundColor!
}
let gc = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
if self.colorMode() {
return gc
} else {
return UIColor(red: 75/255, green: 75/255, blue: 75/255, alpha: 1)
}
}
/**
The button color
- returns: A UIColor object
*/
public func getButtonColor() -> UIColor {
return self.judoButtonColor ?? self.tintActiveColor
}
/**
The title color of the button
- returns: A UIColor object
*/
public func getButtonTitleColor() -> UIColor {
if self.judoButtonTitleColor != nil {
return self.judoButtonTitleColor!
}
if self.colorMode() {
return .white
} else {
return .black
}
}
/**
The background color of the loadingView
- returns: A UIColor object
*/
public func getLoadingBackgroundColor() -> UIColor {
if self.judoLoadingBackgroundColor != nil {
return self.judoLoadingBackgroundColor!
}
let lbc = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 0.8)
if self.colorMode() {
return lbc
} else {
return lbc.inverseColor()
}
}
/**
The color that is used when an error occurs during entry
- returns: A UIColor object
*/
public func getErrorColor() -> UIColor {
return self.judoErrorColor ?? UIColor(red: 235/255, green: 55/255, blue: 45/255, alpha: 1.0)
}
/**
The color of the block that is shown when something is loading
- returns: A UIColor object
*/
public func getLoadingBlockViewColor() -> UIColor {
if self.judoLoadingBlockViewColor != nil {
return self.judoLoadingBlockViewColor!
}
if self.colorMode() {
return .white
} else {
return .black
}
}
/**
Input field background color
- returns: A UIColor object
*/
public func getInputFieldBackgroundColor() -> UIColor {
return self.judoInputFieldBackgroundColor ?? self.getContentViewBackgroundColor()
}
}
| d533e0f39c0931817ecb69327742b64b | 31.075676 | 193 | 0.634311 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | refs/heads/master | GeekSpeak Show Timer/AppDelegate.swift | mit | 2 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
struct Constants {
static let CurrentTimerFileName = "Current Timer"
static let TimerId = "timerViewControllerTimerId"
static let TimerNotificationKey = "com.geekspeak.timerNotificationKey"
static let TimerDataPath = "TimerData.plist"
}
var window: UIWindow?
var timer: Timer {
get {
if let timer = _timer {
return timer
}
if let timer = readCurrentTimer() {
_timer = timer
return timer
} else {
let timer = Timer()
_timer = timer
return timer
}
}
set(timer) {
_timer = timer
}
}
fileprivate var _timer: Timer?
// Convenience property to make intentions clear what is gonig on.
var allowDeviceToSleepDisplay: Bool {
get {
return !UIApplication.shared.isIdleTimerDisabled
}
set(allowed) {
UIApplication.shared.isIdleTimerDisabled = !allowed
}
}
// MARK: App Delegate
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
-> Bool {
registerUserDefaults()
Appearance.apply()
resetTimerIfShowTimeIsZero()
registerForTimerNotifications()
return true
}
func application(_ application: UIApplication,
willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
-> Bool {
self.window?.makeKeyAndVisible()
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
resetTimerIfShowTimeIsZero()
// setAllowDeviceToSleepDisplayForTimer(timer)
}
func applicationDidBecomeActive(_ application: UIApplication) {
timerChangedCountingStatus()
}
func applicationWillResignActive(_ application: UIApplication) {
writeCurrentTimer()
}
func applicationDidEnterBackground(_ application: UIApplication) {
allowDeviceToSleepDisplay = true
}
func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
writeCurrentTimer()
}
func applicationWillTerminate(_ application: UIApplication) {
}
func application(_ application: UIApplication, shouldSaveApplicationState
coder: NSCoder) -> Bool {
unregisterForTimerNotifications()
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState
coder: NSCoder) -> Bool {
registerForTimerNotifications()
return true
}
// MARK: -
// MARK: Timer Persistance
var applicationDocumentsDirectory: URL {
return FileManager.default
.urls( for: .documentDirectory,
in: .userDomainMask)
.last!
}
var savedTimer: URL {
return applicationDocumentsDirectory
.appendingPathComponent(Constants.CurrentTimerFileName)
}
func writeCurrentTimer() {
writeCurrentTimer(timer)
}
func writeCurrentTimer(_ timer: Timer) {
let name = savedTimer.lastPathComponent
let directory = savedTimer.deletingLastPathComponent()
let backupName = "\(name) Backup"
let backupURL = directory.appendingPathComponent(backupName)
let path = savedTimer.path
let backupPath = backupURL.path
let fileManager = FileManager.default
do {
if fileManager.fileExists(atPath: backupPath) {
try fileManager.removeItem(atPath: backupPath)
}
if fileManager.fileExists(atPath: path) {
try fileManager.moveItem(atPath: path, toPath: backupPath)
}
if !NSKeyedArchiver.archiveRootObject(timer, toFile: path) {
print("Warning: Timer could not be archived to the disk.")
}
} catch let error as NSError {
print("Timer not writen: \(error.localizedDescription)")
}
}
func readCurrentTimer() -> Timer? {
var timer: Timer? = .none
let fileManager = FileManager.default
let path = savedTimer.path
if fileManager.fileExists(atPath: path) {
let readTimer = NSKeyedUnarchiver.unarchiveObject(withFile: path)
if let readTimer = readTimer as? Timer {
timer = readTimer
}
}
return timer
}
func restoreAnySavedTimer() {
if let restoredTimer = readCurrentTimer() {
timer = restoredTimer
}
}
}
// MARK: Additional
extension AppDelegate {
func registerForTimerNotifications() {
let notifyCenter = NotificationCenter.default
notifyCenter.addObserver( self,
selector: #selector(AppDelegate.timerChangedCountingStatus),
name: NSNotification.Name(rawValue: Timer.Constants.CountingStatusChanged),
object: timer)
}
func unregisterForTimerNotifications() {
let notifyCenter = NotificationCenter.default
// TODO: When I explicitly remove each observer it throws an execption. why?
// notifyCenter.removeObserver( self,
// forKeyPath: Timer.Constants.CountingStatusChanged)
notifyCenter.removeObserver(self)
}
@objc func timerChangedCountingStatus() {
setAllowDeviceToSleepDisplayForTimer(timer)
}
func setAllowDeviceToSleepDisplayForTimer(_ timer: Timer) {
writeCurrentTimer()
switch timer.state {
case .Ready,
.Paused,
.PausedAfterComplete:
allowDeviceToSleepDisplay = true
case .Counting,
.CountingAfterComplete:
allowDeviceToSleepDisplay = false
}
}
func resetTimerIfShowTimeIsZero() {
// reset the timer if it hasn't started, so that it uses the UserDefaults
// to set which timing to use (demo or show)
let useDemoDurations = UserDefaults.standard
.bool(forKey: Timer.Constants.UseDemoDurations)
if timer.totalShowTimeElapsed == 0 {
if useDemoDurations {
timer.reset(usingDemoTiming: true)
} else {
timer.reset(usingDemoTiming: false)
}
}
}
// Setup the default defaults in app memory
func registerUserDefaults() {
let useDebugTimings: Bool
#if DEBUG
useDebugTimings = true
#else
useDebugTimings = false
#endif
let defaults: [String:AnyObject] = [
Timer.Constants.UseDemoDurations: useDebugTimings as AnyObject
]
UserDefaults.standard.register(defaults: defaults)
}
}
| f589cd5b903a1899681e7986ee902b8c | 25.264822 | 99 | 0.646652 | false | false | false | false |
AnthonyMDev/ImageValet | refs/heads/develop | DemoClass/RxSwiftProject/Pods/Alamofire/Source/Request.swift | gpl-3.0 | 16 | //
// Request.swift
//
// Copyright (c) 2014-2018 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 Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
///
/// - parameter urlRequest: The URL request to adapt.
///
/// - throws: An `Error` if the adaptation encounters an error.
///
/// - returns: The adapted `URLRequest`.
func adapt(_ urlRequest: URLRequest) throws -> URLRequest
}
// MARK: -
/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - parameter manager: The session manager the request was executed on.
/// - parameter request: The request that failed due to the encountered error.
/// - parameter error: The error encountered when executing the request.
/// - parameter completion: The completion closure to be executed when retry decision has been determined.
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
}
// MARK: -
protocol TaskConvertible {
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
}
/// A dictionary of headers to apply to a `URLRequest`.
public typealias HTTPHeaders = [String: String]
// MARK: -
/// Responsible for sending a request and receiving the response and associated data from the server, as well as
/// managing its underlying `URLSessionTask`.
open class Request {
// MARK: Helper Types
/// A closure executed when monitoring upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
enum RequestTask {
case data(TaskConvertible?, URLSessionTask?)
case download(TaskConvertible?, URLSessionTask?)
case upload(TaskConvertible?, URLSessionTask?)
case stream(TaskConvertible?, URLSessionTask?)
}
// MARK: Properties
/// The delegate for the underlying task.
open internal(set) var delegate: TaskDelegate {
get {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
return taskDelegate
}
set {
taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
taskDelegate = newValue
}
}
/// The underlying task.
open var task: URLSessionTask? { return delegate.task }
/// The session belonging to the underlying task.
public let session: URLSession
/// The request sent or to be sent to the server.
open var request: URLRequest? { return task?.originalRequest }
/// The response received from the server, if any.
open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
/// The number of times the request has been retried.
open internal(set) var retryCount: UInt = 0
let originalTask: TaskConvertible?
var startTime: CFAbsoluteTime?
var endTime: CFAbsoluteTime?
var validations: [() -> Void] = []
private var taskDelegate: TaskDelegate
private var taskDelegateLock = NSLock()
// MARK: Lifecycle
init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
self.session = session
switch requestTask {
case .data(let originalTask, let task):
taskDelegate = DataTaskDelegate(task: task)
self.originalTask = originalTask
case .download(let originalTask, let task):
taskDelegate = DownloadTaskDelegate(task: task)
self.originalTask = originalTask
case .upload(let originalTask, let task):
taskDelegate = UploadTaskDelegate(task: task)
self.originalTask = originalTask
case .stream(let originalTask, let task):
taskDelegate = TaskDelegate(task: task)
self.originalTask = originalTask
}
delegate.error = error
delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
}
// MARK: Authentication
/// Associates an HTTP Basic credential with the request.
///
/// - parameter user: The user.
/// - parameter password: The password.
/// - parameter persistence: The URL credential persistence. `.ForSession` by default.
///
/// - returns: The request.
@discardableResult
open func authenticate(
user: String,
password: String,
persistence: URLCredential.Persistence = .forSession)
-> Self
{
let credential = URLCredential(user: user, password: password, persistence: persistence)
return authenticate(usingCredential: credential)
}
/// Associates a specified credential with the request.
///
/// - parameter credential: The credential.
///
/// - returns: The request.
@discardableResult
open func authenticate(usingCredential credential: URLCredential) -> Self {
delegate.credential = credential
return self
}
/// Returns a base64 encoded basic authentication credential as an authorization header tuple.
///
/// - parameter user: The user.
/// - parameter password: The password.
///
/// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
let credential = data.base64EncodedString(options: [])
return (key: "Authorization", value: "Basic \(credential)")
}
// MARK: State
/// Resumes the request.
open func resume() {
guard let task = task else { delegate.queue.isSuspended = false ; return }
if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
task.resume()
NotificationCenter.default.post(
name: Notification.Name.Task.DidResume,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Suspends the request.
open func suspend() {
guard let task = task else { return }
task.suspend()
NotificationCenter.default.post(
name: Notification.Name.Task.DidSuspend,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
/// Cancels the request.
open func cancel() {
guard let task = task else { return }
task.cancel()
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task]
)
}
}
// MARK: - CustomStringConvertible
extension Request: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
/// well as the response status code if a response has been received.
open var description: String {
var components: [String] = []
if let HTTPMethod = request?.httpMethod {
components.append(HTTPMethod)
}
if let urlString = request?.url?.absoluteString {
components.append(urlString)
}
if let response = response {
components.append("(\(response.statusCode))")
}
return components.joined(separator: " ")
}
}
// MARK: - CustomDebugStringConvertible
extension Request: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, in the form of a cURL command.
open var debugDescription: String {
return cURLRepresentation()
}
func cURLRepresentation() -> String {
var components = ["$ curl -v"]
guard let request = self.request,
let url = request.url,
let host = url.host
else {
return "$ curl command could not be created"
}
if let httpMethod = request.httpMethod, httpMethod != "GET" {
components.append("-X \(httpMethod)")
}
if let credentialStorage = self.session.configuration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(
host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = delegate.credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if session.configuration.httpShouldSetCookies {
if
let cookieStorage = session.configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
{
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
#if swift(>=3.2)
components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
#else
components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
#endif
}
}
var headers: [AnyHashable: Any] = [:]
if let additionalHeaders = session.configuration.httpAdditionalHeaders {
for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
headers[field] = value
}
}
if let headerFields = request.allHTTPHeaderFields {
for (field, value) in headerFields where field != "Cookie" {
headers[field] = value
}
}
for (field, value) in headers {
let escapedValue = String(describing: value).replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
open class DataRequest: Request {
// MARK: Helper Types
struct Requestable: TaskConvertible {
let urlRequest: URLRequest
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let urlRequest = try self.urlRequest.adapt(using: adapter)
return queue.sync { session.dataTask(with: urlRequest) }
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let requestable = originalTask as? Requestable { return requestable.urlRequest }
return nil
}
/// The progress of fetching the response data from the server for the request.
open var progress: Progress { return dataDelegate.progress }
var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
// MARK: Stream
/// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
///
/// This closure returns the bytes most recently received from the server, not including data from previous calls.
/// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
/// also important to note that the server data in any `Response` object will be `nil`.
///
/// - parameter closure: The code to be executed periodically during the lifecycle of the request.
///
/// - returns: The request.
@discardableResult
open func stream(closure: ((Data) -> Void)? = nil) -> Self {
dataDelegate.dataStream = closure
return self
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
dataDelegate.progressHandler = (closure, queue)
return self
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
open class DownloadRequest: Request {
// MARK: Helper Types
/// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
/// destination URL.
public struct DownloadOptions: OptionSet {
/// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
public let rawValue: UInt
/// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
/// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
/// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
///
/// - parameter rawValue: The raw bitmask value for the option.
///
/// - returns: A new log level instance.
public init(rawValue: UInt) {
self.rawValue = rawValue
}
}
/// A closure executed once a download request has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
public typealias DownloadFileDestination = (
_ temporaryURL: URL,
_ response: HTTPURLResponse)
-> (destinationURL: URL, options: DownloadOptions)
enum Downloadable: TaskConvertible {
case request(URLRequest)
case resumeData(Data)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .request(urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.downloadTask(with: urlRequest) }
case let .resumeData(resumeData):
task = queue.sync { session.downloadTask(withResumeData: resumeData) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
return urlRequest
}
return nil
}
/// The resume data of the underlying download task if available after a failure.
open var resumeData: Data? { return downloadDelegate.resumeData }
/// The progress of downloading the response data from the server for the request.
open var progress: Progress { return downloadDelegate.progress }
var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
// MARK: State
/// Cancels the request.
open override func cancel() {
downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
NotificationCenter.default.post(
name: Notification.Name.Task.DidCancel,
object: self,
userInfo: [Notification.Key.Task: task as Any]
)
}
// MARK: Progress
/// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is read from the server.
///
/// - returns: The request.
@discardableResult
open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
downloadDelegate.progressHandler = (closure, queue)
return self
}
// MARK: Destination
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - parameter directory: The search path directory. `.DocumentDirectory` by default.
/// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
///
/// - returns: A download file destination closure.
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
if !directoryURLs.isEmpty {
return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
}
return (temporaryURL, [])
}
}
}
// MARK: -
/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
open class UploadRequest: DataRequest {
// MARK: Helper Types
enum Uploadable: TaskConvertible {
case data(Data, URLRequest)
case file(URL, URLRequest)
case stream(InputStream, URLRequest)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
do {
let task: URLSessionTask
switch self {
case let .data(data, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
case let .file(url, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
case let .stream(_, urlRequest):
let urlRequest = try urlRequest.adapt(using: adapter)
task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
}
return task
} catch {
throw AdaptError(error: error)
}
}
}
// MARK: Properties
/// The request sent or to be sent to the server.
open override var request: URLRequest? {
if let request = super.request { return request }
guard let uploadable = originalTask as? Uploadable else { return nil }
switch uploadable {
case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
return urlRequest
}
}
/// The progress of uploading the payload to the server for the upload request.
open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
// MARK: Upload Progress
/// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
/// the server.
///
/// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
/// of data being read from the server.
///
/// - parameter queue: The dispatch queue to execute the closure on.
/// - parameter closure: The code to be executed periodically as data is sent to the server.
///
/// - returns: The request.
@discardableResult
open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
uploadDelegate.uploadProgressHandler = (closure, queue)
return self
}
}
// MARK: -
#if !os(watchOS)
/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open class StreamRequest: Request {
enum Streamable: TaskConvertible {
case stream(hostName: String, port: Int)
case netService(NetService)
func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
let task: URLSessionTask
switch self {
case let .stream(hostName, port):
task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
case let .netService(netService):
task = queue.sync { session.streamTask(with: netService) }
}
return task
}
}
}
#endif
| f3ffdb516b6728c18e3d760e1ea81a8b | 36.204893 | 131 | 0.641994 | false | false | false | false |
mo3bius/My-Simple-Instagram | refs/heads/master | My-Simple-Instagram/Database/Image/Image.swift | mit | 1 | //
// Image.swift
// My-Simple-Instagram
//
// Created by Luigi Aiello on 31/10/17.
// Copyright © 2017 Luigi Aiello. All rights reserved.
//
import Foundation
import RealmSwift
class Image: Object {
// MARK: - Properties
@objc dynamic var imageId = ""
@objc dynamic var userId = ""
@objc dynamic var instaLink: String = ""
@objc dynamic var creationTime: Date?
@objc dynamic var commentsNumber: Int = 0
@objc dynamic var likesNumber: Int = 0
@objc dynamic var userHasLike: Bool = false
@objc dynamic var attribution: String?
@objc dynamic var highResolution: String = ""
@objc dynamic var standardResolution: String = ""
@objc dynamic var thumbnailResolution: String = ""
@objc dynamic var locationName: String = ""
@objc dynamic var coordinate: String = ""
var tags = List<String>()
var filters = List<String>()
var fileTpe: FileType = .image
override static func primaryKey() -> String? {
return "imageId"
}
// MARK: - Constructors
convenience init(imageId: String,
userId: String,
instaLink: String,
creationTime: Date?,
commentsNumber cn: Int,
likesNumber ln: Int,
userHasLike: Bool,
attribution: String?,
highResolution: String,
standardResolution: String,
thumbnailResolution: String,
locationName: String?) {
self.init()
self.imageId = imageId
self.userId = userId
self.instaLink = instaLink
self.creationTime = creationTime
self.commentsNumber = cn
self.likesNumber = ln
self.userHasLike = userHasLike
self.attribution = attribution ?? ""
self.highResolution = highResolution
self.standardResolution = standardResolution
self.thumbnailResolution = thumbnailResolution
self.locationName = locationName ?? ""
}
class func getImage(withId id: String) -> Image? {
let predicate = NSPredicate(format: "imageId == %@", id)
return Database.shared.query(entitiesOfType: Image.self, where: predicate)?.first
}
class func getAllImages(withUserID id: String) -> [Image] {
let predicate = NSPredicate(format: "userId == %@", id)
return Object.all(where: predicate)
}
}
| 3061f5f86ef577bb3901b3df1e7bb937 | 32.093333 | 89 | 0.59589 | false | false | false | false |
diegosanchezr/Chatto | refs/heads/master | ChattoAdditions/Source/Chat Items/PhotoMessages/PhotoMessagePresenterBuilder.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 Chatto
public class PhotoMessagePresenterBuilder<ViewModelBuilderT, InteractionHandlerT where
ViewModelBuilderT: ViewModelBuilderProtocol,
ViewModelBuilderT.ModelT: PhotoMessageModelProtocol,
ViewModelBuilderT.ViewModelT: PhotoMessageViewModelProtocol,
InteractionHandlerT: BaseMessageInteractionHandlerProtocol,
InteractionHandlerT.ViewModelT == ViewModelBuilderT.ViewModelT
>: ChatItemPresenterBuilderProtocol {
public typealias ModelT = ViewModelBuilderT.ModelT
public typealias ViewModelT = ViewModelBuilderT.ViewModelT
public init(
viewModelBuilder: ViewModelBuilderT,
interactionHandler: InteractionHandlerT?) {
self.viewModelBuilder = viewModelBuilder
self.interactionHandler = interactionHandler
}
let viewModelBuilder: ViewModelBuilderT
let interactionHandler: InteractionHandlerT?
public lazy var sizingCell: PhotoMessageCollectionViewCell = PhotoMessageCollectionViewCell.sizingCell()
public lazy var photoCellStyle: PhotoMessageCollectionViewCellStyleProtocol = PhotoMessageCollectionViewCellDefaultStyle()
public lazy var baseCellStyle: BaseMessageCollectionViewCellStyleProtocol = BaseMessageCollectionViewCellDefaultSyle()
public func canHandleChatItem(chatItem: ChatItemProtocol) -> Bool {
return chatItem is PhotoMessageModelProtocol ? true : false
}
public func createPresenterWithChatItem(chatItem: ChatItemProtocol) -> ChatItemPresenterProtocol {
assert(self.canHandleChatItem(chatItem))
return PhotoMessagePresenter<ViewModelBuilderT, InteractionHandlerT>(
messageModel: chatItem as! ModelT,
viewModelBuilder: self.viewModelBuilder,
interactionHandler: self.interactionHandler,
sizingCell: sizingCell,
baseCellStyle: self.baseCellStyle,
photoCellStyle: self.photoCellStyle
)
}
public var presenterType: ChatItemPresenterProtocol.Type {
return PhotoMessagePresenter<ViewModelBuilderT, InteractionHandlerT>.self
}
}
| 158651b817d3c69fbbce26d12792d724 | 44.985714 | 126 | 0.780677 | false | false | false | false |
mmick66/KDDragAndDropCollectionView | refs/heads/master | Classes/KDDragAndDropCollectionView.swift | mit | 1 | /*
* KDDragAndDropCollectionView.swift
* Created by Michael Michailidis on 10/04/2015.
*
* 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
public protocol KDDragAndDropCollectionViewDataSource : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath?
func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject
func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void
func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void
func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) -> Void
/* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool
/* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool
/* optional */ func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView?
}
extension KDDragAndDropCollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView? {
return nil
}
func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool {
return true
}
}
open class KDDragAndDropCollectionView: UICollectionView, KDDraggable, KDDroppable {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public var draggingPathOfCellBeingDragged : IndexPath?
var iDataSource : UICollectionViewDataSource?
var iDelegate : UICollectionViewDelegate?
override open func awakeFromNib() {
super.awakeFromNib()
}
override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
}
// MARK : KDDraggable
public func canDragAtPoint(_ point : CGPoint) -> Bool {
if let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource,
let indexPathOfPoint = self.indexPathForItem(at: point) {
return dataSource.collectionView(self, cellIsDraggableAtIndexPath: indexPathOfPoint)
}
return false
}
public func representationImageAtPoint(_ point : CGPoint) -> UIView? {
guard let indexPath = self.indexPathForItem(at: point) else {
return nil
}
guard let cell = self.cellForItem(at: indexPath) else {
return nil
}
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageView = UIImageView(image: image)
imageView.frame = cell.frame
return imageView
}
public func stylingRepresentationView(_ view: UIView) -> UIView? {
guard let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else {
return nil
}
return dataSource.collectionView(self, stylingRepresentationView: view)
}
public func dataItemAtPoint(_ point : CGPoint) -> AnyObject? {
guard let indexPath = self.indexPathForItem(at: point) else {
return nil
}
guard let dragDropDS = self.dataSource as? KDDragAndDropCollectionViewDataSource else {
return nil
}
return dragDropDS.collectionView(self, dataItemForIndexPath: indexPath)
}
public func startDraggingAtPoint(_ point : CGPoint) -> Void {
self.draggingPathOfCellBeingDragged = self.indexPathForItem(at: point)
self.reloadData()
}
public func stopDragging() -> Void {
if let idx = self.draggingPathOfCellBeingDragged {
if let cell = self.cellForItem(at: idx) {
cell.isHidden = false
}
}
self.draggingPathOfCellBeingDragged = nil
self.reloadData()
}
public func dragDataItem(_ item : AnyObject) -> Void {
guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else {
return
}
guard let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else {
return
}
dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath)
if self.animating {
self.deleteItems(at: [existngIndexPath])
}
else {
self.animating = true
self.performBatchUpdates({ () -> Void in
self.deleteItems(at: [existngIndexPath])
}, completion: { complete -> Void in
self.animating = false
self.reloadData()
})
}
}
// MARK : KDDroppable
public func canDropAtRect(_ rect : CGRect) -> Bool {
return (self.indexPathForCellOverlappingRect(rect) != nil)
}
public func indexPathForCellOverlappingRect( _ rect : CGRect) -> IndexPath? {
var overlappingArea : CGFloat = 0.0
var cellCandidate : UICollectionViewCell?
let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource
let visibleCells = self.visibleCells
if visibleCells.count == 0 {
return IndexPath(row: 0, section: 0)
}
if isHorizontal && rect.origin.x > self.contentSize.width ||
!isHorizontal && rect.origin.y > self.contentSize.height {
if dataSource?.collectionView(self, cellIsDroppableAtIndexPath: IndexPath(row: visibleCells.count - 1, section: 0)) == true {
return IndexPath(row: visibleCells.count - 1, section: 0)
}
return nil
}
for visible in visibleCells {
let intersection = visible.frame.intersection(rect)
if (intersection.width * intersection.height) > overlappingArea {
overlappingArea = intersection.width * intersection.height
cellCandidate = visible
}
}
if let cellRetrieved = cellCandidate, let indexPath = self.indexPath(for: cellRetrieved), dataSource?.collectionView(self, cellIsDroppableAtIndexPath: indexPath) == true {
return self.indexPath(for: cellRetrieved)
}
return nil
}
fileprivate var currentInRect : CGRect?
public func willMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void {
let dragDropDataSource = self.dataSource as! KDDragAndDropCollectionViewDataSource // its guaranteed to have a data source
if let _ = dragDropDataSource.collectionView(self, indexPathForDataItem: item) { // if data item exists
return
}
if let indexPath = self.indexPathForCellOverlappingRect(rect) {
dragDropDataSource.collectionView(self, insertDataItem: item, atIndexPath: indexPath)
self.draggingPathOfCellBeingDragged = indexPath
self.animating = true
self.performBatchUpdates({ () -> Void in
self.insertItems(at: [indexPath])
}, completion: { complete -> Void in
self.animating = false
// if in the meantime we have let go
if self.draggingPathOfCellBeingDragged == nil {
self.reloadData()
}
})
}
currentInRect = rect
}
public var isHorizontal : Bool {
return (self.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .horizontal
}
public var animating: Bool = false
public var paging : Bool = false
func checkForEdgesAndScroll(_ rect : CGRect) -> Void {
if paging == true {
return
}
let currentRect : CGRect = CGRect(x: self.contentOffset.x, y: self.contentOffset.y, width: self.bounds.size.width, height: self.bounds.size.height)
var rectForNextScroll : CGRect = currentRect
if isHorizontal {
let leftBoundary = CGRect(x: -30.0, y: 0.0, width: 30.0, height: self.frame.size.height)
let rightBoundary = CGRect(x: self.frame.size.width, y: 0.0, width: 30.0, height: self.frame.size.height)
if rect.intersects(leftBoundary) == true {
rectForNextScroll.origin.x -= self.bounds.size.width * 0.5
if rectForNextScroll.origin.x < 0 {
rectForNextScroll.origin.x = 0
}
}
else if rect.intersects(rightBoundary) == true {
rectForNextScroll.origin.x += self.bounds.size.width * 0.5
if rectForNextScroll.origin.x > self.contentSize.width - self.bounds.size.width {
rectForNextScroll.origin.x = self.contentSize.width - self.bounds.size.width
}
}
} else { // is vertical
let topBoundary = CGRect(x: 0.0, y: -30.0, width: self.frame.size.width, height: 30.0)
let bottomBoundary = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: 30.0)
if rect.intersects(topBoundary) == true {
rectForNextScroll.origin.y -= self.bounds.size.height * 0.5
if rectForNextScroll.origin.y < 0 {
rectForNextScroll.origin.y = 0
}
}
else if rect.intersects(bottomBoundary) == true {
rectForNextScroll.origin.y += self.bounds.size.height * 0.5
if rectForNextScroll.origin.y > self.contentSize.height - self.bounds.size.height {
rectForNextScroll.origin.y = self.contentSize.height - self.bounds.size.height
}
}
}
// check to see if a change in rectForNextScroll has been made
if currentRect.equalTo(rectForNextScroll) == false {
self.paging = true
self.scrollRectToVisible(rectForNextScroll, animated: true)
let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.paging = false
}
}
}
public func didMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void {
let dragDropDS = self.dataSource as! KDDragAndDropCollectionViewDataSource // guaranteed to have a ds
if let existingIndexPath = dragDropDS.collectionView(self, indexPathForDataItem: item),
let indexPath = self.indexPathForCellOverlappingRect(rect) {
if indexPath.item != existingIndexPath.item {
dragDropDS.collectionView(self, moveDataItemFromIndexPath: existingIndexPath, toIndexPath: indexPath)
self.animating = true
self.performBatchUpdates({ () -> Void in
self.moveItem(at: existingIndexPath, to: indexPath)
}, completion: { (finished) -> Void in
self.animating = false
self.reloadData()
})
self.draggingPathOfCellBeingDragged = indexPath
}
}
// Check Paging
var normalizedRect = rect
normalizedRect.origin.x -= self.contentOffset.x
normalizedRect.origin.y -= self.contentOffset.y
currentInRect = normalizedRect
self.checkForEdgesAndScroll(normalizedRect)
}
public func didMoveOutItem(_ item : AnyObject) -> Void {
guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource,
let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else {
return
}
dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath)
if self.animating {
self.deleteItems(at: [existngIndexPath])
}
else {
self.animating = true
self.performBatchUpdates({ () -> Void in
self.deleteItems(at: [existngIndexPath])
}, completion: { (finished) -> Void in
self.animating = false;
self.reloadData()
})
}
if let idx = self.draggingPathOfCellBeingDragged {
if let cell = self.cellForItem(at: idx) {
cell.isHidden = false
}
}
self.draggingPathOfCellBeingDragged = nil
currentInRect = nil
}
public func dropDataItem(_ item : AnyObject, atRect : CGRect) -> Void {
// show hidden cell
if let index = draggingPathOfCellBeingDragged,
let cell = self.cellForItem(at: index), cell.isHidden == true {
cell.alpha = 1
cell.isHidden = false
}
currentInRect = nil
self.draggingPathOfCellBeingDragged = nil
self.reloadData()
}
}
| 2fac70d9177dca39cc5029b824f566c6 | 35.339492 | 179 | 0.594789 | false | false | false | false |
ZB0106/MCSXY | refs/heads/master | MCSXY/MCSXY/Macro/UtilsMacro.swift | mit | 1 | //
// UtilsMacro.swift
// MCSXY
//
// Created by 瞄财网 on 2017/6/16.
// Copyright © 2017年 瞄财网. All rights reserved.
//
import UIKit
//弹框显示时间
let ALertTimeInterval = 2.0
/****** 宏 ******/
let Screen_Width = UIScreen.main.bounds.size.width
let Screen_Height = UIScreen.main.bounds.size.height
let Home_Btn_Width = (Screen_Width - 160) / 5
let Home_Btn_Height = Home_Btn_Width + 30
//宽 高
//字体
let H22 = UIFont.systemFont(ofSize: 22)
let H20 = UIFont.systemFont(ofSize: 20)
let H18 = UIFont.systemFont(ofSize: 18)
let H16 = UIFont.systemFont(ofSize: 16)
let H15 = UIFont.systemFont(ofSize: 15)
let H14 = UIFont.systemFont(ofSize: 14)
let H13 = UIFont.systemFont(ofSize: 13)
let H12 = UIFont.systemFont(ofSize: 12)
let H11 = UIFont.systemFont(ofSize: 11)
let H10 = UIFont.systemFont(ofSize: 10)
let HB20 = UIFont.boldSystemFont(ofSize: 20)
let HB18 = UIFont.boldSystemFont(ofSize:18)
let HB16 = UIFont.boldSystemFont(ofSize:16)
let HB15 = UIFont.boldSystemFont(ofSize:15)
//颜色
func Color_RGB(r:CGFloat,g:CGFloat,b:CGFloat) -> UIColor{
return UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha:1.0);
}
func Color_RGB_Alpha(r:CGFloat,g:CGFloat,b:CGFloat,f:CGFloat) -> UIColor{
return UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: f)
}
func Color_Random() -> UIColor{
return UIColor(red: CGFloat(arc4random()%256) / 255.0 , green: CGFloat(arc4random()%256) / 255.0 , blue: CGFloat(arc4random()%256) / 255.0 , alpha: 1.0)
}
let Color_BG = Color_RGB(r: 245, g: 245, b: 245)
let Color_Cell_BG = Color_RGB(r: 80, g: 80, b: 80)
let Color_Nav = Color_RGB(r: 255, g: 130, b: 86)
let Color_TabBar = Color_RGB(r: 255, g: 255, b: 255)
let Color_TabBarNormal = Color_RGB(r: 153, g: 153, b: 153)
let Color_TabBarSelected = Color_RGB(r: 255, g: 130, b: 86)
let Color_StatusBG = Color_RGB(r: 207, g: 52, b: 3)
let Color_H1 = Color_RGB(r: 77, g: 77, b: 77)
let Color_H2 = Color_RGB(r: 153, g: 153, b: 153)
let Color_H3 = Color_RGB(r: 186, g: 149, b: 99)
let Color_Line = Color_RGB(r: 245, g: 245, b: 245)
let Color_Holder = Color_RGB(r: 210, g: 210, b: 214)
let Color_Free = Color_RGB(r: 239, g: 85, b: 34)
let Color_VIP = Color_RGB(r: 155, g: 206, b: 120)
let Color_White = UIColor.white
let Color_Gray = UIColor.gray
let Color_LightGray = UIColor.lightGray
let Color_Black = UIColor.black
let Color_Red = UIColor.red
let Color_Clear = UIColor.clear
let Color_Green = UIColor.green
let Color_Blue = UIColor.blue
let Color_Orange = UIColor.orange
let Color_Yellow = UIColor.orange
// MARK: -Cell相关
let cellHeight = "cellHeight"
let headerHeight = "headerHeight"
let footerHeight = "footerHeight"
let cellDataArray = "cellDataArray"
| 2b99abdd1cfb946cb825a672520b0815 | 34.837209 | 156 | 0.601233 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/existential_erasure.swift | apache-2.0 | 1 |
// RUN: %target-swift-frontend -module-name existential_erasure -emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol P {
func downgrade(_ m68k: Bool) -> Self
func upgrade() throws -> Self
}
protocol Q {}
struct X: P, Q {
func downgrade(_ m68k: Bool) -> X {
return self
}
func upgrade() throws -> X {
return self
}
}
func makePQ() -> P & Q { return X() }
func useP(_ x: P) { }
func throwingFunc() throws -> Bool { return true }
// CHECK-LABEL: sil hidden @$S19existential_erasure5PQtoPyyF : $@convention(thin) () -> () {
func PQtoP() {
// CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr immutable_access [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]]
// CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]]
// CHECK: copy_addr [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]]
// CHECK: destroy_addr [[PQ]]
// CHECK-NOT: destroy_addr [[P]]
// CHECK-NOT: destroy_addr [[P_PAYLOAD]]
// CHECK-NOT: deinit_existential_addr [[PQ]]
// CHECK-NOT: destroy_addr [[PQ_PAYLOAD]]
useP(makePQ())
}
// Make sure uninitialized existentials are properly deallocated when we
// have an early return.
// CHECK-LABEL: sil hidden @$S19existential_erasure19openExistentialToP1yyAA1P_pKF
func openExistentialToP1(_ p: P) throws {
// CHECK: bb0(%0 : @trivial $*P):
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]]
// CHECK: [[RESULT:%.*]] = alloc_stack $P
// CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]]
// CHECK: [[FUNC:%.*]] = function_ref @$S19existential_erasure12throwingFuncSbyKF
// CHECK: try_apply [[FUNC]]()
//
// CHECK: bb1([[SUCCESS:%.*]] : @trivial $Bool):
// CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1 : {{.*}}, [[OPEN]]
// CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]])
// CHECK: dealloc_stack [[RESULT]]
// CHECK: return
//
// CHECK: bb2([[FAILURE:%.*]] : @owned $Error):
// CHECK: deinit_existential_addr [[RESULT]]
// CHECK: dealloc_stack [[RESULT]]
// CHECK: throw [[FAILURE]]
//
try useP(p.downgrade(throwingFunc()))
}
// CHECK-LABEL: sil hidden @$S19existential_erasure19openExistentialToP2yyAA1P_pKF
func openExistentialToP2(_ p: P) throws {
// CHECK: bb0(%0 : @trivial $*P):
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]]
// CHECK: [[RESULT:%.*]] = alloc_stack $P
// CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1 : {{.*}}, [[OPEN]]
// CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]])
//
// CHECK: bb1
// CHECK: dealloc_stack [[RESULT]]
// CHECK: return
//
// CHECK: bb2([[FAILURE:%.*]]: @owned $Error):
// CHECK: deinit_existential_addr [[RESULT]]
// CHECK: dealloc_stack [[RESULT]]
// CHECK: throw [[FAILURE]]
//
try useP(p.upgrade())
}
// Same as above but for boxed existentials
extension Error {
func returnOrThrowSelf() throws -> Self {
throw self
}
}
// CHECK-LABEL: sil hidden @$S19existential_erasure12errorHandlerys5Error_psAC_pKF
func errorHandler(_ e: Error) throws -> Error {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Error):
// CHECK: debug_value [[ARG]] : $Error
// CHECK: [[OPEN:%.*]] = open_existential_box [[ARG]] : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]]
// CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]]
// CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error
// CHECK: [[FUNC:%.*]] = function_ref @$Ss5ErrorP19existential_erasureE17returnOrThrowSelf{{[_0-9a-zA-Z]*}}F
// CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]])
//
// CHECK: bb1
// CHECK: return [[RESULT]] : $Error
//
// CHECK: bb2([[FAILURE:%.*]] : @owned $Error):
// CHECK: dealloc_existential_box [[RESULT]]
// CHECK: throw [[FAILURE]] : $Error
//
return try e.returnOrThrowSelf()
}
// rdar://problem/22003864 -- SIL verifier crash when init_existential_addr
// references dynamic Self type
class EraseDynamicSelf {
required init() {}
// CHECK-LABEL: sil hidden @$S19existential_erasure16EraseDynamicSelfC7factoryACXDyFZ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf
// CHECK: [[ANY:%.*]] = alloc_stack $Any
// CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf
//
class func factory() -> Self {
let instance = self.init()
let _: Any = instance
return instance
}
}
| a80b14cedc13102db6f67d3b22d30425 | 34.782946 | 166 | 0.619801 | false | false | false | false |
jwfriese/FrequentFlyer | refs/heads/master | FrequentFlyer/Authentication/AuthMethod.swift | apache-2.0 | 1 | import ObjectMapper
struct AuthMethod {
let type: AuthType
let displayName: String
let url: String
class DisplayNames {
static let basic = "Basic Auth"
static let gitHub = "GitHub"
static let uaa = "UAA"
}
init(type: AuthType, displayName: String, url: String) {
self.type = type
self.displayName = displayName
self.url = url
}
}
extension AuthMethod: Equatable {}
func ==(lhs: AuthMethod, rhs: AuthMethod) -> Bool {
return lhs.type == rhs.type &&
lhs.displayName == rhs.displayName &&
lhs.url == rhs.url
}
extension AuthMethod: ImmutableMappable {
init(map: Map) throws {
let typeString: String = try map.value("type")
let displayNameString: String = try map.value("display_name")
var type = AuthType.basic
if typeString == "basic" && displayNameString == AuthMethod.DisplayNames.basic {
type = .basic
} else if typeString == "oauth" && displayNameString == AuthMethod.DisplayNames.gitHub {
type = .gitHub
} else if typeString == "oauth" && displayNameString == AuthMethod.DisplayNames.uaa {
type = .uaa
} else {
throw MapError(key: "type", currentValue: "", reason: "Failed to map `AuthMethod` with `type` == `\(typeString)` and `display_name` == \(displayNameString)")
}
self.type = type
self.displayName = displayNameString
self.url = try map.value("auth_url")
}
}
| cc00997d0fd6540f71b56354b5fc1f65 | 30.583333 | 169 | 0.60686 | false | false | false | false |
rgkobashi/PhotoSearcher | refs/heads/master | PhotoViewer/Utilities.swift | mit | 1 | //
// Utilities.swift
// PhotoViewer
//
// Created by Rogelio Martinez Kobashi on 2/27/17.
// Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved.
//
import Foundation
import UIKit
typealias VoidCompletionHandler = () -> ()
typealias SuceedCompletionHandler = (AnyObject?) -> ()
typealias ErrorCompletionHandler = (NSError) -> ()
class Utilities
{
class func downloadImageFrom(_ urlString: String, suceedHandler: @escaping SuceedCompletionHandler, failedHandler: @escaping ErrorCompletionHandler)
{
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
let url = URL(string: urlString)
if let url = url
{
let data = try? Data(contentsOf: url)
if let data = data
{
let image = UIImage(data: data)
if let image = image
{
DispatchQueue.main.async(execute: { () -> Void in
suceedHandler(image)
})
}
else
{
DispatchQueue.main.async(execute: { () -> Void in
let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "Image could not be initialized from the specified data."])
failedHandler(error)
})
}
}
else
{
DispatchQueue.main.async(execute: { () -> Void in
let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "No data returned from the server."])
failedHandler(error)
})
}
}
else
{
DispatchQueue.main.async(execute: { () -> Void in
let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "URL string malformed."])
failedHandler(error)
})
}
}
}
class func displayAlertWithTitle(_ title: String?, message: String?, buttonTitle: String, buttonHandler: VoidCompletionHandler?)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: buttonTitle, style: .default) { (alertAction) in
buttonHandler?()
}
alert.addAction(action)
UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil)
}
class func displayAlertWithTitle(_ title: String?, message: String?, buttonTitle: String, buttonHandler: VoidCompletionHandler?, destructiveTitle: String, destructiveHandler: @escaping VoidCompletionHandler)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let destructiveAction = UIAlertAction(title: destructiveTitle, style: .destructive) { (alertAction) in
destructiveHandler()
}
alert.addAction(destructiveAction)
let action = UIAlertAction(title: buttonTitle, style: .default) { (alertAction) in
buttonHandler?()
}
alert.addAction(action)
UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil)
}
class func openURLWithString(_ string: String)
{
if let url = URL(string: string)
{
UIApplication.shared.openURL(url)
}
}
class func stringDifferenceFromTimeStamp(_ timeStamp: Int) -> String
{
let before = Date(timeIntervalSince1970: TimeInterval(NSNumber(value: timeStamp as Int)))
let today = Date()
let unitFlags: NSCalendar.Unit = [.hour, .day, .month, .year]
let dateComponents = (Calendar.current as NSCalendar).components(unitFlags, from: before, to: today, options: [])
if dateComponents.year! > 0
{
return "\(dateComponents.year) years ago"
}
else if dateComponents.month! > 0
{
return "\(dateComponents.month) months ago"
}
else
{
let days = dateComponents.day
if days! > 7
{
let weeks = days! / 7
if weeks > 0
{
return "\(weeks) weeks ago"
}
else
{
return "\(days) days ago"
}
}
else if days == 0
{
return "Today"
}
else
{
return "\(days) days ago"
}
}
}
}
| 0e21fe25de399b94fb08eaaa05d9ba9f | 36.122137 | 211 | 0.537323 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKFormMessageView.swift | apache-2.0 | 3 | //
// EKFormMessageView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 5/15/18.
//
import UIKit
public class EKFormMessageView: UIView {
private let scrollViewVerticalOffset: CGFloat = 20
// MARK: Props
private let titleLabel = UILabel()
private let scrollView = UIScrollView()
private let textFieldsContent: [EKProperty.TextFieldContent]
private var textFieldViews: [EKTextField] = []
private var buttonBarView: EKButtonBarView!
// MARK: Setup
public init(with title: EKProperty.LabelContent, textFieldsContent: [EKProperty.TextFieldContent], buttonContent: EKProperty.ButtonContent) {
self.textFieldsContent = textFieldsContent
super.init(frame: UIScreen.main.bounds)
setupScrollView()
setupTitleLabel(with: title)
setupTextFields(with: textFieldsContent)
setupButton(with: buttonContent)
setupTapGestureRecognizer()
scrollView.layoutIfNeeded()
set(.height, of: scrollView.contentSize.height + scrollViewVerticalOffset * 2, priority: .defaultHigh)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTextFields(with textFieldsContent: [EKProperty.TextFieldContent]) {
var textFieldIndex = 0
textFieldViews = textFieldsContent.map { content -> EKTextField in
let textField = EKTextField(with: content)
scrollView.addSubview(textField)
textField.tag = textFieldIndex
textFieldIndex += 1
return textField
}
textFieldViews.first!.layout(.top, to: .bottom, of: titleLabel, offset: 20)
textFieldViews.spread(.vertically, offset: 5)
textFieldViews.layoutToSuperview(axis: .horizontally)
}
// Setup tap gesture
private func setupTapGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
}
private func setupScrollView() {
addSubview(scrollView)
scrollView.layoutToSuperview(axis: .horizontally, offset: 20)
scrollView.layoutToSuperview(axis: .vertically, offset: scrollViewVerticalOffset)
scrollView.layoutToSuperview(.width, .height, offset: -scrollViewVerticalOffset * 2)
}
private func setupTitleLabel(with content: EKProperty.LabelContent) {
scrollView.addSubview(titleLabel)
titleLabel.layoutToSuperview(.top, .width)
titleLabel.layoutToSuperview(axis: .horizontally)
titleLabel.forceContentWrap(.vertically)
titleLabel.content = content
}
private func setupButton(with buttonContent: EKProperty.ButtonContent) {
var buttonContent = buttonContent
let action = buttonContent.action
buttonContent.action = { [weak self] in
self?.extractTextFieldsContent()
action?()
}
let buttonsBarContent = EKProperty.ButtonBarContent(with: buttonContent, separatorColor: .clear, expandAnimatedly: true)
buttonBarView = EKButtonBarView(with: buttonsBarContent)
buttonBarView.clipsToBounds = true
scrollView.addSubview(buttonBarView)
buttonBarView.expand()
buttonBarView.layout(.top, to: .bottom, of: textFieldViews.last!, offset: 20)
buttonBarView.layoutToSuperview(.centerX)
buttonBarView.layoutToSuperview(.width, offset: -40)
buttonBarView.layoutToSuperview(.bottom)
buttonBarView.layer.cornerRadius = 5
}
private func extractTextFieldsContent() {
for (content, textField) in zip(textFieldsContent, textFieldViews) {
content.contentWrapper.text = textField.text
}
}
/** Makes a specific text field the first responder */
public func becomeFirstResponder(with textFieldIndex: Int) {
textFieldViews[textFieldIndex].makeFirstResponder()
}
// Tap Gesture
@objc func tapGestureRecognized() {
endEditing(true)
}
}
| f674e7805824a445638731e6a049bf29 | 36.882883 | 145 | 0.684899 | false | false | false | false |
mateuszfidosBLStream/MFCircleMenu | refs/heads/master | Example/ViewController.swift | mit | 1 | //
// ViewController.swift
// MFCircleMenu
//
// Created by Mateusz Fidos on 03.05.2016.
// Copyright © 2016 mateusz.fidos. All rights reserved.
//
import UIKit
import Foundation
import MFCircleMenu
class ViewController: UIViewController
{
var menuController:MFCircleMenu!
override func viewDidLoad()
{
super.viewDidLoad()
let mainAction: MainItemActionClosure = {
if (self.menuController.menuState == .Closed)
{
self.menuController.openMenu()
}
else
{
self.menuController.closeMenu()
}
}
let itemOneAction: ItemActionClosure = {
print("Item One tapped")
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("nextViewController")
self.presentViewController(controller, animated: true, completion: nil)
}
let itemTwoAction: ItemActionClosure = {
print("Item Two tapped")
}
let mainCircle = MFCircleMenuMainItem(action: mainAction, closedStateImage: UIImage(named: "settings")!, openedStateImage: UIImage(named: "soundon")!, text: nil, backgroundColor: UIColor.redColor())
let itemOne = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil)
let itemTwo = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor())
let itemThree = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil)
let itemFour = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor())
let itemFive = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil)
let itemSix = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor())
self.menuController = MFCircleMenu(mainItem: mainCircle, otherItems: [itemOne, itemTwo, itemThree, itemFour, itemFive, itemSix], parent: self.view, adjustToOrientation: false)
self.menuController.showAtPosition(MFCircleMenuPosition.TopRight)
}
@IBAction func showMenu(sender: AnyObject)
{
self.menuController.showMenu()
}
@IBAction func hideMenu(sender: AnyObject)
{
self.menuController.hideMenu()
}
}
| 3b9d7569c7c4fa3986445e3a0afd45ff | 39.71875 | 206 | 0.679969 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01351-swift-inflightdiagnostic-fixitreplacechars.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A : NSManagedObject {
class func b<T: b = g() -> {
assert(array: a : a {
}
var f = c<c) {
return x }
class B : A {
class a(f(mx : l) {
return b: b(array: e : NSObject {
enum a("], g = [unowned self.d
}
let a {
}
class B : l.c {
protocol b {
var _ = {
return {
class A {
typealias f == b)
| 51aa2e250bee5f26bb7b7d98bcaec0df | 24.62963 | 79 | 0.671965 | false | false | false | false |
bhajian/raspi-remote | refs/heads/master | Carthage/Checkouts/ios-sdk/Source/PersonalityInsightsV2/Models/Profile.swift | mit | 1 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** A personality profile generated by the Personality Insights service. */
public struct Profile: JSONDecodable {
/// Detailed results for a specific characteristic of the input text.
public let tree: TraitTreeNode
/// The unique identifier for which these characteristics were computed,
/// from the "userid" field of the input ContentItems.
public let id: String
/// The source for which these characteristics were computed,
/// from the "sourceid" field of the input ContentItems.
public let source: String
/// The number of words found in the input.
public let wordCount: Int
/// A message indicating the number of words found and where the value falls
/// in the range of required or suggested number of words when guidance is
/// available.
public let wordCountMessage: String?
/// The language model that was used to process the input.
public let processedLanguage: String
/// Used internally to initialize a `Profile` model from JSON.
public init(json: JSON) throws {
tree = try json.decode("tree")
id = try json.string("id")
source = try json.string("source")
wordCount = try json.int("word_count")
wordCountMessage = try? json.string("word_count_message")
processedLanguage = try json.string("processed_lang")
}
}
| 784ef6e1af3e6c5ce0fe102e5c90293d | 35.796296 | 80 | 0.708103 | false | false | false | false |
castial/HYAlertController | refs/heads/master | HYAlertController/HYShareCollectionCell.swift | mit | 2 | //
// HYShareCollectionCell.swift
// Quick-Start-iOS
//
// Created by work on 2016/11/2.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
class HYShareCollectionCell: UICollectionViewCell {
fileprivate lazy var shareImageView: UIImageView = {
let imageView = UIImageView (frame: CGRect (x: 15, y: 0, width: self.bounds.size.width - 30, height: self.bounds.size.width - 30))
imageView.contentMode = .scaleAspectFit
return imageView
}()
fileprivate lazy var shareTitleLabel: UILabel = {
let label = UILabel (frame: CGRect (x: 0, y: self.shareImageView.frame.maxY + 5, width: self.bounds.size.width, height: 20))
label.textColor = UIColor.lightGray
label.font = UIFont.systemFont(ofSize: 12.0)
label.textAlignment = .center
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(shareImageView)
contentView.addSubview(shareTitleLabel)
}
var action: HYAlertAction? {
didSet {
self.shareImageView.image = action?.image
self.shareTitleLabel.text = action?.title
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Class Methods
extension HYShareCollectionCell {
class var ID: String {
return "HYShareCollectionCell"
}
class var cellSize: CGSize {
return CGSize(width: HYConstants.shareItemWidth, height: HYConstants.shareItemHeight)
}
class var cellInset: UIEdgeInsets {
return UIEdgeInsets(top: HYConstants.shareItemPadding, left: HYConstants.shareItemPadding, bottom: HYConstants.shareItemPadding, right: HYConstants.shareItemPadding)
}
}
// MARK: - Layout Methods
extension HYShareCollectionCell {
fileprivate func initLayout(title: String?, image: UIImage?) {
}
}
| 15ab488c734bc8dceebdaf8a8f496bde | 28.393939 | 173 | 0.669588 | false | false | false | false |
gecko655/Swifter | refs/heads/master | Sources/SwifterTimelines.swift | mit | 2 | //
// SwifterTimelines.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 extension Swifter {
// Convenience method
private func getTimeline(at path: String, parameters: Dictionary<String, Any>, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
var params = parameters
params["count"] ??= count
params["since_id"] ??= sinceID
params["max_id"] ??= maxID
params["trim_user"] ??= trimUser
params["contributor_details"] ??= contributorDetails
params["include_entities"] ??= includeEntities
self.getJSON(path: path, baseURL: .api, parameters: params, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET statuses/mentions_timeline
Returns Tweets (*: mentions for the user)
Returns the 20 most recent mentions (tweets containing a users's @screen_name) for the authenticating user.
The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com.
This method can only return up to 800 tweets.
*/
public func getMentionsTimlineTweets(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler?) {
self.getTimeline(at: "statuses/mentions_timeline.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/**
GET statuses/user_timeline
Returns Tweets (*: tweets for the user)
Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.
User timelines belonging to protected users may only be requested when the authenticated user either "owns" the timeline or is an approved follower of the owner.
The timeline returned is the equivalent of the one seen when you view a user's profile on twitter.com.
This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource.
*/
public func getTimeline(for userID: String, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let parameters: Dictionary<String, Any> = ["user_id": userID]
self.getTimeline(at: "statuses/user_timeline.json", parameters: parameters, count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/**
GET statuses/home_timeline
Returns Tweets (*: tweets from people the user follows)
Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. The home timeline is central to how most users interact with the Twitter service.
Up to 800 Tweets are obtainable on the home timeline. It is more volatile for users that follow many users or follow users who tweet frequently.
*/
public func getHomeTimeline(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
self.getTimeline(at: "statuses/home_timeline.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
/**
GET statuses/retweets_of_me
Returns the most recent tweets authored by the authenticating user that have been retweeted by others. This timeline is a subset of the user's GET statuses/user_timeline. See Working with Timelines for instructions on traversing timelines.
*/
public func getRetweetsOfMe(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, trimUser: Bool? = nil, contributorDetails: Bool? = nil, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
self.getTimeline(at: "statuses/retweets_of_me.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
}
| efaa30c1764ea2b0870a1b734650f495 | 58.9 | 299 | 0.724541 | false | false | false | false |
tschob/ContainerController | refs/heads/main | Example/Core/ViewController/TabContainerViewController.swift | mit | 1 | //
// TabContainerViewController.swift
// Example
//
// Created by Hans Seiffert on 06.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import UIKit
import ContainerController
class TabContainerViewController: UIViewController {
@IBAction private func didPressContentAButton(_ sender: AnyObject) {
self.cc_ContainerViewController?.display(segue: "showContentA")
}
@IBAction private func didPressContentBButton(_ sender: AnyObject) {
self.cc_ContainerViewController?.display(segue: "showContentB")
}
@IBAction private func didPressContentCButton(_ sender: AnyObject) {
self.cc_ContainerViewController?.display(segue: "showContentC")
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
self.cc_setupContainerViewControllerIfNeeded(segue, default: "showContentA", didSetup: {
self.cc_ContainerViewController?.delegate = self
})
}
}
extension TabContainerViewController: ContainerViewControllerDelegate {
func containerViewController(_ containerViewController: ContainerViewController, willDisplay contentController: UIViewController, isReused: Bool) {
guard !isReused else {
return
}
if
let navigationController = contentController as? UINavigationController,
let contentController = navigationController.viewControllers.first as? ContentViewController {
contentController.bottomText = "Text set from the calling UIViewController"
} else if let contentController = contentController as? ContentViewController {
contentController.bottomText = "Text set from the calling UIViewController"
}
}
}
| 1e8d48d907f3a1c9d74319e79a1645fa | 31.22 | 148 | 0.783364 | false | false | false | false |
google/iosched-ios | refs/heads/master | Source/IOsched/Screens/Schedule/ViewModel/SessionListViewModel.swift | apache-2.0 | 1 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MaterialComponents
import FirebaseFirestore
/// A type responsible for transforming a list of sessions into conference days and maintaining
/// accessory state so the sessions can be displayed.
/// - SeeAlso: DefaultScheduleViewModel
protocol SessionListViewModel {
/// A boolean indicating whether or not the viewmodel should only show saved items (reservations
/// and bookmarks). Defaults to false.
var shouldShowOnlySavedItems: Bool { get set }
/// The filter view model for the schedule maintained by this instance. The filterViewModel
/// can be modified to filter the schedule.
var filterViewModel: ScheduleFilterViewModel { get }
/// A list of days that are further broken down into time slots.
/// - SeeAlso: ConferenceDayViewModel, ConferenceTimeSlotViewModel, SessionViewModel
var conferenceDays: [ConferenceDayViewModel] { get }
/// The slots within a given day, where each slot is a time period roughly one session long.
/// Since Google I/O is a multi-track event, slots may contain multiple sessions.
func slots(forDayWithIndex index: Int) -> [ConferenceTimeSlotViewModel]
/// The sessions in a slot in a given day.
/// - SeeAlso: SessionViewModel
func events(forDayWithIndex dayIndex: Int, andSlotIndex slotIndex: Int) -> [SessionViewModel]
/// Assigns a callback that will be invoked each time the view model updates its data in
/// a way that would cause a UI change. The closure is retained by the receiver.
func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void)
/// Called by the consumer of this class to indicate an update request, i.e. when the user swipes
/// down to refresh data.
func updateModel()
/// Called by other classes to force a view refresh.
func updateView()
/// This method should be called when changing the status of a bookmark (star). Classes
/// implementing this method should use it to write the changes somewhere and call any update
/// methods that may be affected by the changes.
func toggleBookmark(sessionID: String)
/// This method should be called by the consumer of this type whenever a session is selected.
/// Types that implement this protocol are then responsible for triggering the appropriate UI
/// updates.
func didSelectSession(_ session: SessionViewModel)
/// This method takes a given session and returns a view controller showing that session's
/// details.
func detailsViewController(for session: SessionViewModel) -> UIViewController
/// This method should be called when the user taps the filter button.
func didSelectFilter()
/// This method should be called when the account button is tapped.
func didSelectAccount()
}
private enum Formatters {
static let dateFormatter: DateFormatter = {
let formatter = TimeZoneAwareDateFormatter()
formatter.setLocalizedDateFormatFromTemplate("MMMd")
return formatter
}()
static let timeSlotFormatter: DateFormatter = {
let formatter = TimeZoneAwareDateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
formatter.timeZone = TimeZone.userTimeZone()
return formatter
}()
static let dateIntervalFormatter: DateIntervalFormatter = {
let formatter = DateIntervalFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
formatter.timeZone = TimeZone.userTimeZone()
return formatter
}()
}
class DefaultSessionListViewModel: SessionListViewModel {
init(sessionsDataSource: LazyReadonlySessionsDataSource,
bookmarkDataSource: RemoteBookmarkDataSource,
reservationDataSource: RemoteReservationDataSource,
navigator: ScheduleNavigator) {
self.sessionsDataSource = sessionsDataSource
self.bookmarkDataSource = bookmarkDataSource
self.reservationDataSource = reservationDataSource
self.navigator = navigator
filterViewModel = ScheduleFilterViewModel()
conferenceDays = []
registerForTimezoneUpdates()
registerForBookmarkUpdates()
registerForReservationsUpdates()
updateModel()
}
lazy private var clashDetector = ReservationClashDetector(sessions: sessionsDataSource,
reservations: reservationDataSource)
// MARK: - View updates
var viewUpdateCallback: ((_ indexPath: IndexPath?) -> Void)?
func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void) {
self.viewUpdateCallback = viewUpdateCallback
updateModel()
}
func updateView() {
viewUpdateCallback?(nil)
}
deinit {
timezoneObserver = nil
bookmarkObserver = nil
reservationsObserver = nil
}
// MARK: - Dependencies
fileprivate let sessionsDataSource: LazyReadonlySessionsDataSource
internal let bookmarkDataSource: RemoteBookmarkDataSource
internal let reservationDataSource: RemoteReservationDataSource
internal let navigator: ScheduleNavigator
// MARK: - Output
private lazy var savedItemsViewModel: SavedItemsViewModel = {
return SavedItemsViewModel(reservations: reservationDataSource,
bookmarks: bookmarkDataSource)
}()
var filterViewModel: ScheduleFilterViewModel
private(set) var conferenceDays: [ConferenceDayViewModel]
var shouldShowOnlySavedItems: Bool {
get {
return savedItemsViewModel.shouldShowOnlySavedItems
}
set {
savedItemsViewModel.shouldShowOnlySavedItems = newValue
}
}
func slots(forDayWithIndex index: Int) -> [ConferenceTimeSlotViewModel] {
return conferenceDays.count > 0 ? conferenceDays[index].slots : []
}
func events(forDayWithIndex dayIndex: Int, andSlotIndex slotIndex: Int) -> [SessionViewModel] {
let unfilteredEvents = slots(forDayWithIndex: dayIndex)[slotIndex].events
if filterViewModel.isEmpty && !savedItemsViewModel.shouldShowOnlySavedItems {
return unfilteredEvents
} else {
return unfilteredEvents.filter { event -> Bool in
return filterViewModel.shouldShow(topics: event.topics,
levels: event.levels,
types: event.types) &&
savedItemsViewModel.shouldShow(event.session)
}
}
}
func updateModel() {
populateConferenceDays()
updateView()
}
// MARK: - Timezone observing
private func timeZoneUpdated() {
updateFormatters()
updateModel()
}
private func updateFormatters() {
Formatters.dateFormatter.timeZone = TimeZone.userTimeZone()
Formatters.timeSlotFormatter.timeZone = TimeZone.userTimeZone()
Formatters.dateIntervalFormatter.timeZone = TimeZone.userTimeZone()
}
private var timezoneObserver: Any? {
willSet {
if let observer = timezoneObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForTimezoneUpdates() {
timezoneObserver = NotificationCenter.default.addObserver(forName: .timezoneUpdate,
object: nil,
queue: nil) { [weak self] _ in
self?.timeZoneUpdated()
}
}
// MARK: - Data update observing
func bookmarksUpdated() {
updateModel()
}
private var bookmarkObserver: Any? {
willSet {
if let observer = bookmarkObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForBookmarkUpdates() {
bookmarkObserver = NotificationCenter.default.addObserver(forName: .bookmarkUpdate,
object: nil,
queue: nil) { [weak self] _ in
guard let self = self else { return }
self.bookmarksUpdated()
}
}
func reservationsUpdated() {
updateModel()
}
private var reservationsObserver: Any? {
willSet {
if let observer = reservationsObserver {
NotificationCenter.default.removeObserver(observer)
}
}
}
private func registerForReservationsUpdates() {
reservationsObserver = NotificationCenter.default.addObserver(forName: .reservationUpdate,
object: nil,
queue: nil) { [weak self] _ in
self?.reservationsUpdated()
}
}
}
// MARK: - Actions
extension DefaultSessionListViewModel {
func didSelectSession(_ viewModel: SessionViewModel) {
navigator.navigate(to: viewModel.session, popToRoot: false)
}
func detailsViewController(for viewModel: SessionViewModel) -> UIViewController {
return navigator.detailsViewController(for: viewModel.session)
}
func toggleBookmark(sessionID: String) {
bookmarkDataSource.toggleBookmark(sessionID: sessionID)
}
func didSelectFilter() {
navigator.navigateToFilter(viewModel: filterViewModel, callback: {
self.updateView()
})
}
func didSelectAccount() {
navigator.navigateToAccount()
}
}
// MARK: - Transformer
extension DefaultSessionListViewModel {
/// This method transforms all inputs into the correct output
func conferenceDays(from allSessions: [Session]) -> [ConferenceDayViewModel] {
var calendar = Calendar.autoupdatingCurrent
calendar.timeZone = TimeZone.userTimeZone()
let allDates = allSessions.map { event -> Date in
return calendar.startOfDay(for: event.startTimestamp)
}
let uniqueDates = Set(allDates)
// create view models for the individual days
return uniqueDates.map { date -> ConferenceDayViewModel in
let eventsInThisDay = allSessions.filter { event -> Bool in
return calendar.isDate(event.startTimestamp, inSameDayAs: date)
}
let hours = eventsInThisDay.map { $0.startTimestamp }
let uniqueHours = Set(hours)
let slots = uniqueHours.map { time -> ConferenceTimeSlotViewModel in
let eventsInThisTimeSlot = eventsInThisDay.filter { $0.startTimestamp == time }
let eventsViewModels = eventsInThisTimeSlot.map { timedDetailedEvent -> SessionViewModel in
return SessionViewModel(session: timedDetailedEvent,
bookmarkDataSource: bookmarkDataSource,
reservationDataSource: reservationDataSource,
clashDetector: clashDetector,
scheduleNavigator: navigator)
}.sorted(by: <)
return ConferenceTimeSlotViewModel(time: time, events: eventsViewModels)
}.sorted(by: < )
return ConferenceDayViewModel(day: date, slots: slots)
}
.sorted(by: < )
}
/// Generates a list of conference days from sessions in the sessions data source.
func populateConferenceDays() {
conferenceDays = conferenceDays(from: sessionsDataSource.sessions)
}
}
// MARK: - View Models
/// A type responsible for aggregating events by day.
struct ConferenceDayViewModel {
let day: Date
let slots: [ConferenceTimeSlotViewModel]
init(day: Date, slots: [ConferenceTimeSlotViewModel]) {
self.day = day
self.slots = slots
}
}
extension ConferenceDayViewModel {
var dayString: String {
return Formatters.dateFormatter.string(from: day)
}
}
extension ConferenceDayViewModel: Comparable { }
func == (lhs: ConferenceDayViewModel, rhs: ConferenceDayViewModel) -> Bool {
return lhs.day == rhs.day
}
func < (lhs: ConferenceDayViewModel, rhs: ConferenceDayViewModel) -> Bool {
return lhs.day < rhs.day
}
/// A struct responsible for aggregating events that occur at the same time. In the
/// schedule UI, this struct is also responsible for displaying the section header
/// titles (which are times).
struct ConferenceTimeSlotViewModel {
let time: Date
var timeSlotString: String
let events: [SessionViewModel]
init(time: Date, events: [SessionViewModel]) {
self.time = time
self.events = events
self.timeSlotString = Formatters.timeSlotFormatter.string(from: time)
}
}
extension ConferenceTimeSlotViewModel: Comparable { }
func == (lhs: ConferenceTimeSlotViewModel, rhs: ConferenceTimeSlotViewModel) -> Bool {
return lhs.time == rhs.time
&& lhs.events == rhs.events
}
func < (lhs: ConferenceTimeSlotViewModel, rhs: ConferenceTimeSlotViewModel) -> Bool {
return lhs.time < rhs.time
}
/// A type responsible for connecting sessions and session state (like reservation/star status).
/// This type is also responsible for transforming struct data into more UI-friendly types.
class SessionViewModel {
private enum Constants {
static let sessionBookmarkedImage = UIImage(named: "ic_session_bookmarked")!
static let sessionBookmarkImage = UIImage(named: "ic_session_bookmark-dark")!
static let sessionReservedImage = UIImage(named: "ic_session_reserved")!
static let sessionWaitlistedImage = UIImage(named: "ic_waitlisted")!
static let sessionNotReservedImage = UIImage(named: "ic_session_reserve-dark")!
}
// Dependencies
let session: Session
let formattedDateInterval: String
let location: String
let signIn: SignInInterface
let reservationService: FirebaseReservationServiceInterface
var timeAndLocation: String {
let separator = location.isEmpty ? "" : " / "
return[formattedDateInterval, location].joined(separator: separator)
}
private let reservationDataSource: RemoteReservationDataSource
private let bookmarkDataSource: RemoteBookmarkDataSource
private let clashDetector: ReservationClashDetector
private let navigator: ScheduleNavigator
/// Returns the user's reservation status for this session.
var reservationStatus: ReservationStatus {
return reservationDataSource.reservationStatus(for: session.id)
}
var bookmarkButtonImage: UIImage {
return isBookmarked
? Constants.sessionBookmarkedImage
: Constants.sessionBookmarkImage
}
var bookmarkButtonAccessibilityLabel: String {
return isBookmarked
? NSLocalizedString("Session is bookmarked. Tap to remove bookmark.",
comment: "Accessibility hint for bookmark button, bookmarked state")
: NSLocalizedString("Session is not bookmarked. Tap to add bookmark.",
comment: "Accessibility hint for bookmark button, non-bookmarked state.")
}
var isReservable: Bool {
return signIn.currentUser != nil && session.isReservable
}
var reserveButtonImage: UIImage? {
switch reservationStatus {
case .reserved:
return Constants.sessionReservedImage
case .waitlisted:
return Constants.sessionWaitlistedImage
case .none:
return Constants.sessionNotReservedImage
}
}
var reserveButtonAccessibilityLabel: String {
switch reservationStatus {
case .reserved:
return NSLocalizedString("This session is reserved. Double-tap to cancel reservation.",
comment: "Icon accessibility label for reserved session button")
case .waitlisted:
return NSLocalizedString("This session is waitlisted. Double-tap to cancel whitelisting.",
comment: "Icon accessibility label for waitlisted session button")
case .none:
return NSLocalizedString("This session is not reserved. Double-tap to reserve.",
comment: "Button icon accessibility label for no session reservation")
}
}
init(session: Session,
bookmarkDataSource: RemoteBookmarkDataSource,
reservationDataSource: RemoteReservationDataSource,
clashDetector: ReservationClashDetector,
scheduleNavigator: ScheduleNavigator,
signIn: SignInInterface = SignIn.sharedInstance) {
self.session = session
self.bookmarkDataSource = bookmarkDataSource
self.signIn = signIn
self.reservationDataSource = reservationDataSource
self.reservationService = FirestoreReservationService(sessionID: session.id)
navigator = scheduleNavigator
formattedDateInterval = Formatters.dateIntervalFormatter.string(from: session.startTimestamp,
to: session.endTimestamp)
location = session.roomName
self.clashDetector = clashDetector
}
var startTimeStamp: Date {
return session.startTimestamp
}
var title: String {
return session.title
}
var tags: [EventTag] {
return session.tags
}
var topics: [EventTag] {
return tags.filter { $0.type == .topic }
}
var levels: [EventTag] {
return tags.filter { $0.type == .level }
}
var types: [EventTag] {
return tags.filter { $0.type == .type }
}
var isBookmarked: Bool {
return bookmarkDataSource.isBookmarked(sessionID: id)
}
var id: String {
return session.id
}
func reserve() {
reservationService.attemptReservation()
}
func cancelReservation() {
reservationService.attemptCancellation()
}
func attemptReservationAction() {
startObservingReservationResult()
reservationService.attemptReservation()
}
private func startObservingReservationResult() {
_ = reservationService.onReservationResultUpdate { reservationResult in
switch reservationResult {
case .clash, .swapClash:
self.handleClash()
case .cancelled, .cancelCutoff, .cancelUnknown:
print("Reservation removed reservation with result: \(reservationResult)")
case .reserved:
print("Reservation successful")
case .waitlisted:
print("Waitlist successful")
case .swapped, .swapCutoff, .swapWaitlisted, .swapUnknown:
print("Swap: \(reservationResult.rawValue)")
case .unknown:
print("Reservation request returned unknown result")
case .cutoff:
// Display cutoff error
print("Reservation errored with cutoff")
}
self.stopObservingReservationResults()
}
}
private func stopObservingReservationResults() {
reservationService.removeUpdateListeners()
}
private func handleClash() {
let clashes = clashDetector.clashes(for: session)
switch clashes.count {
case 0:
break
case 1:
guard let clash = clashes.first else { return }
navigator.showReservationClashDialog {
self.reservationService.attemptSwap(withConflictingSessionID: clash.id)
}
case _:
navigator.showMultiClashDialog()
}
}
}
extension SessionViewModel: Comparable { }
func == (lhs: SessionViewModel, rhs: SessionViewModel) -> Bool {
return lhs.id == rhs.id &&
lhs.timeAndLocation == rhs.timeAndLocation &&
lhs.tags == rhs.tags &&
lhs.reservationStatus == rhs.reservationStatus
}
func < (lhs: SessionViewModel, rhs: SessionViewModel) -> Bool {
return lhs.title < rhs.title
}
extension SessionViewModel: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(title)
hasher.combine(timeAndLocation)
}
}
| 7b815102d4d2679b4b858b2afab8c60a | 31.824121 | 101 | 0.698102 | false | false | false | false |
hmx101607/mhweibo | refs/heads/master | weibo/weibo/App/viewcontrollers/main/WBTabbarViewController.swift | mit | 1 | //
// WBTabbarViewController.swift
// weibo
//
// Created by mason on 2017/7/29.
// Copyright © 2017年 mason. All rights reserved.
//
import UIKit
class WBTabbarViewController: UITabBarController {
private lazy var publicBtn = UIButton(type: UIButtonType.custom)
override func viewDidLoad() {
super.viewDidLoad()
//添加控制器页面
addChildViewController(childVCName: "WBHomeViewController", title: "首页", imageName: "tabbar_home")
addChildViewController(childVCName: "WBMessageViewController", title: "消息", imageName: "tabbar_message_center")
addChildViewController(childVCName: "WBNullViewController", title: "", imageName: "")
addChildViewController(childVCName: "WBDiscoverViewController", title: "发现", imageName: "tabbar_discover")
addChildViewController(childVCName: "WBMeViewController", title: "我的", imageName: "tabbar_profile")
//添加中间位置tabbarItem
tabBar.addSubview(publicBtn)
publicBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
publicBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
publicBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
publicBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
publicBtn.sizeToFit()
publicBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.frame.size.height * 0.5)
publicBtn.addTarget(self, action: #selector(buttonTap(button:)), for: .touchUpInside)
//1.读取json文件
/*
guard let jsonPath = Bundle.main.path(forResource: "MainVCSettings", ofType: "json") else {
MLog(message: "json文件不存在")
return
}
//2.从文件中读取数据
guard let data = NSData(contentsOfFile: jsonPath) else {
MLog(message: "json文件中午数据")
return
}
//3.解析json文件中的数据
guard let anyObject = try? JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) else {
MLog(message: "解析失败")
return
}
guard let dicArray = anyObject as? [[String : AnyObject]] else {
return
}
for dic in dicArray {
guard let chileVCName = dic["vcName"] as? String else {
continue
}
guard let title = dic["title"] as? String else {
continue
}
guard let imageName = dic["imageName"] as? String else {
continue
}
addChildViewController(childVCName: chileVCName, title: title, imageName: imageName)
}*/
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let count = tabBar.items?.count else {
MLog(message: "items为空")
return
}
for i in 0..<count{
let item = tabBar.items![i]
// 3.如果是下标值为2,则该item不可以和用户交互
if i == 2 {
item.isEnabled = false
break
}
}
}
private func addChildViewController(childVCName: String, title : String, imageName : String) {
// 1. 获取命名空间
guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
MLog(message: "命名空间不存在")
return
}
//2. 根据命名空间和类名确定类是否存在
guard let childVCClass = NSClassFromString(nameSpace + "." + childVCName) else {
MLog(message: "该类不存在")
return
}
//3. 获取具体的类的类型
guard let childType = childVCClass as? UIViewController.Type else {
MLog(message: "类型不存在")
return;
}
let childVC = childType.init()
childVC.title = title
childVC.tabBarItem.image = UIImage(named: imageName)
childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
let nav = UINavigationController(rootViewController: childVC)
addChildViewController(nav)
}
func buttonTap(button : UIButton) {
let publicVC = WBPublicViewController()
let nav = UINavigationController(rootViewController: publicVC)
present(nav, animated: true, completion: nil)
}
}
| e87dac6d6ca864603460e1944cd823c3 | 35.330579 | 119 | 0.601228 | false | false | false | false |
CalvinChina/Demo | refs/heads/master | Swift3Demo/Swift3Demo/CoreLocation/CoreLocationViewController.swift | mit | 1 | //
// CoreLocationViewController.swift
// Swift3Demo
//
// Created by pisen on 16/10/12.
// Copyright © 2016年 丁文凯. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class CoreLocationViewController: UIViewController ,CLLocationManagerDelegate ,MKMapViewDelegate{
@IBOutlet weak var CLMKMapView: MKMapView!
let locationManager = CLLocationManager()
var myLatitude:CLLocationDegrees!
var myLongitude:CLLocationDegrees!
var finalLatitude:CLLocationDegrees!
var finalLongitude:CLLocationDegrees!
var distance:CLLocationDistance!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let tap = UITapGestureRecognizer(target:self ,action:#selector(action(_ :)))
CLMKMapView.addGestureRecognizer(tap)
// Do any additional setup after loading the view.
}
func action(_ tap:UITapGestureRecognizer){
let touchPoint = tap.location(in: self.CLMKMapView)
let newCoord = CLMKMapView.convert(touchPoint, toCoordinateFrom: self.CLMKMapView)
let getLat:CLLocationDegrees = newCoord.latitude
let getLon = newCoord.longitude
let newCoord2 = CLLocation(latitude:getLat ,longitude:getLon)
let newCoord3 = CLLocation(latitude:myLatitude , longitude:myLongitude)
finalLatitude = newCoord2.coordinate.longitude
finalLongitude = newCoord2.coordinate.longitude
print("Original Latitude: \(myLatitude)")
print("Original Longitude: \(myLongitude)")
print("Final Latitude: \(finalLatitude)")
print("Final Longitude: \(finalLongitude)")
let distance = newCoord2.distance(from: newCoord3)
print("Distance between two points: \(distance)")
let newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoord
newAnnotation.title = "ABC"
newAnnotation.subtitle = "abc"
CLMKMapView.addAnnotation(newAnnotation)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in
if(error != nil){
print("reverseGeocodeLocation error:" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
}else{
print("Problem with the data received from geocoder")
}
}
}
// 地址信息解析
func displayLocationInfo(_ placemark:CLPlacemark?){
if let containsPlacemark = placemark{
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.country : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
myLongitude = (containsPlacemark.location!.coordinate.longitude)
myLatitude = (containsPlacemark.location!.coordinate.latitude)
print("Locality: \(locality)")
print("PostalCode: \(postalCode)")
print("Area: \(administrativeArea)")
print("Country: \(country)")
print(myLatitude)
print(myLongitude)
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1)
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:myLatitude,longitude:myLongitude)
let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location,theSpan)
CLMKMapView.setRegion(theRegion, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
print("Error while updating location " + error.localizedDescription)
}
func degreesToRadians(_ degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(_ radians: Double) -> Double { return radians * 180.0 / M_PI }
func getBearingBetweenTwoPoints1(_ point1:CLLocation , point2:CLLocation) -> Double {
let lat1 = degreesToRadians(point1.coordinate.latitude)
let lon1 = degreesToRadians(point1.coordinate.longitude)
let lat2 = degreesToRadians(point2.coordinate.latitude);
let lon2 = degreesToRadians(point2.coordinate.longitude);
print("Start latitude: \(point1.coordinate.latitude)")
print("Start longitude: \(point1.coordinate.longitude)")
print("Final latitude: \(point2.coordinate.latitude)")
print("Final longitude: \(point2.coordinate.longitude)")
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let radiansBearing = atan2(y ,x)
return radiansToDegrees(radiansBearing)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 6506d5926cd57b2e8e200a3b6fbdc67a | 39.540541 | 116 | 0.653833 | false | false | false | false |
venmo/DVR | refs/heads/master | Sources/DVR/SessionDataTask.swift | mit | 1 | import Foundation
final class SessionDataTask: URLSessionDataTask {
// MARK: - Types
typealias Completion = (Data?, Foundation.URLResponse?, NSError?) -> Void
// MARK: - Properties
weak var session: Session!
let request: URLRequest
let headersToCheck: [String]
let completion: Completion?
private let queue = DispatchQueue(label: "com.venmo.DVR.sessionDataTaskQueue", attributes: [])
private var interaction: Interaction?
override var response: Foundation.URLResponse? {
return interaction?.response
}
override var currentRequest: URLRequest? {
return request
}
// MARK: - Initializers
init(session: Session, request: URLRequest, headersToCheck: [String] = [], completion: (Completion)? = nil) {
self.session = session
self.request = request
self.headersToCheck = headersToCheck
self.completion = completion
}
// MARK: - URLSessionTask
override func cancel() {
// Don't do anything
}
override func resume() {
let cassette = session.cassette
// Find interaction
if let interaction = session.cassette?.interactionForRequest(request, headersToCheck: headersToCheck) {
self.interaction = interaction
// Forward completion
if let completion = completion {
queue.async {
completion(interaction.responseData, interaction.response, nil)
}
}
session.finishTask(self, interaction: interaction, playback: true)
return
}
if cassette != nil {
fatalError("[DVR] Invalid request. The request was not found in the cassette.")
}
// Cassette is missing. Record.
if session.recordingEnabled == false {
fatalError("[DVR] Recording is disabled.")
}
let task = session.backingSession.dataTask(with: request, completionHandler: { [weak self] data, response, error in
//Ensure we have a response
guard let response = response else {
fatalError("[DVR] Failed to record because the task returned a nil response.")
}
guard let this = self else {
fatalError("[DVR] Something has gone horribly wrong.")
}
// Still call the completion block so the user can chain requests while recording.
this.queue.async {
this.completion?(data, response, nil)
}
// Create interaction
this.interaction = Interaction(request: this.request, response: response, responseData: data)
this.session.finishTask(this, interaction: this.interaction!, playback: false)
})
task.resume()
}
}
| 491e7bafbbbdfbd57125cf976a39a5c2 | 30 | 123 | 0.608649 | false | false | false | false |
mkrd/Swift-Big-Integer | refs/heads/master | Benchmarks/Benchmarks.swift | mit | 1 | /*
* ————————————————————————————————————————————————————————————————————————————
* Benchmarks.swift
* ————————————————————————————————————————————————————————————————————————————
* Created by Marcel Kröker on 05.09.17.
* Copyright © 2017 Marcel Kröker. All rights reserved.
*/
import Foundation
public class Benchmarks
{
static func Matrix1()
{
let A = Matrix<BDouble>(
[[2,5,-2],
[3,5,6],
[-55,4,3]]
)
let G12 = Matrix<BDouble>([
[0.8, -0.6, 0.0],
[0.6, 0.8, 0.0],
[0.0, 0.0, 1.0]
])
let al = Matrix<BDouble>([4, -3, 1])
print(G12 * al)
let (L, R, P, D) = LRDecompPivEquil(A)
print(solveGauss(A, [2.0, -4.0, 15.0]))
print(solveLR(A, [2.0, -4.0, 15.0]))
print(solveLRPD(A, [2.0, -4.0, 15.0]))
print("P L R")
print(P)
print(L)
print(R)
print("LR == PDA")
print(L * R)
print(P * D * A)
benchmarkAndPrint(title: "Matix ^ 100")
{
var R = A
for _ in 0...100
{
R = R * A
}
}
}
static func BDoubleConverging()
{
benchmarkAndPrint(title: "BDouble converging to 2")
{
// BDouble converging to 2 Debug Mode
// 06.02.16: 3351ms
var res: BDouble = 0
var den: BInt = 1
for _ in 0..<1000
{
res = res + BDouble(BInt(1), over: den)
den *= 2
}
}
}
static func factorial()
{
let n = 25_000
benchmarkAndPrint(title: "Factorial of 25000")
{
// Fkt 1000 Debug Mode
// 27.01.16: 2548ms
// 30.01.16: 1707ms
// 01.02.16: 398ms
// Fkt 2000 Debug Mode
// 01.02.16: 2452ms
// 04.02.16: 2708ms
// 06.02.16: 328ms
// Factorial 4000 Debug Mode
// 06.02.16: 2669ms
// 10.02.16: 571ms
// 28.02.16: 550ms
// 01.03.16: 56ms
// Factorial 25000 Debug Mode
// 01.03.16: 2871ms
// 07.03.16: 2221ms
// 16.08.16: 1759ms
// 20.08.16: 1367ms
// 23.08.19: 1075ms
_ = BInt(n).factorial()
}
}
static func exponentiation()
{
let n = 10
let pow = 120_000
benchmarkAndPrint(title: "10^120_000")
{
// 10^14000 Debug Mode
// 06.02.16: 2668ms
// 10.02.16: 372ms
// 20.02.16: 320ms
// 28.02.16: 209ms
// 01.03.16: 39ms
// 10^120_000 Debug Mode
// 01.03.16: 2417ms
// 07.03.16: 1626ms
// 16.08.16: 1154ms
// 20.08.16: 922ms
// 23.08.19: 710ms
_ = BInt(n) ** pow
}
}
static func fibonacci()
{
let n = 100_000
benchmarkAndPrint(title: "Fib \(n)")
{
// Fib 35.000 Debug Mode
// 27.01.16: 2488ms
// 30.01.16: 1458ms
// 01.02.16: 357ms
// Fib 100.000 Debug Mode
// 01.02.16: 2733ms
// 04.02.16: 2949ms
// 10.02.16: 1919ms
// 28.02.16: 1786ms
// 07.03.16: 1716ms
// 23.08.19: 1124ms
_ = BIntMath.fib(n)
}
}
static func mersennes()
{
let n = 256
benchmarkAndPrint(title: "\nMersennes to 2^\(n)")
{
// Mersenne to exp 256 Debug Mode
// 02.10.16: 1814ms
for i in 1...n
{
if math.isPrime(i) && BIntMath.isMersenne(i)
{
print(i, terminator: ",")
}
}
}
}
static func BIntToString()
{
let factorialBase = 15_000
let n = BInt(factorialBase).factorial()
benchmarkAndPrint(title: "Get \(factorialBase)! as String")
{
// Get 300! (615 decimal digits) as String Debug Mode
// 30.01.16: 2635ms
// 01.02.16: 3723ms
// 04.02.16: 2492m
// 06.02.16: 2326ms
// 07.02.16: 53ms
// Get 1000! (2568 decimal digits) as String Debug Mode
// 07.02.16: 2386ms
// 10.02.16: 343ms
// 20.02.16: 338ms
// 22.02.16: 159ms
// Get 3000! (9131 decimal digits) as String Debug Mode
// 22.02.16: 2061ms
// 28.02.16: 1891ms
// 01.03.16: 343ms
// Get 7500! (25809 decimal digits) as String Debug Mode
// 01.03.16: 2558ms
// 07.03.16: 1604ms
// 07.03.16: 1562ms
// 16.08.16: 455ms
// Get 15000! (56130 decimal digits) as String Debug Mode
// 07.09.17: 2701ms
_ = n.description
}
}
static func StringToBInt()
{
let factorialBase = 16_000
let asStr = BInt(factorialBase).factorial().description
var res: BInt = 0
benchmarkAndPrint(title: "BInt from String, \(asStr.count) digits (\(factorialBase)!)")
{
// BInt from String, 3026 digits (1151!) Debug Mode
// 07.02.16: 2780ms
// 10.02.16: 1135ms
// 28.02.16: 1078ms
// 01.03.16: 430ms
// BInt from String, 9131 digits (3000!) Debug Mode
// 01.03.16: 3469ms
// 07.03.16: 2305ms
// 07.03.16: 1972ms
// 26.06.16: 644ms
// BInt from String, 20066 digits (6000!) Debug Mode
// 26.06.16: 3040ms
// 16.08.16: 2684ms
// 20.08.16: 2338ms
// BInt from String, 60320 digits (16000!) Debug Mode
// 07.09.17: 2857ms
// 26.04.18: 1081ms
res = BInt(asStr)!
}
assert(asStr == res.description)
}
static func permutationsAndCombinations()
{
benchmarkAndPrint(title: "Perm and Comb")
{
// Perm and Comb (2000, 1000) Debug Mode
// 04.02.16: 2561ms
// 06.02.16: 2098ms
// 07.02.16: 1083ms
// 10.02.16: 350ms
// 28.02.16: 337ms
// 01.03.16: 138ms
// Perm and Comb (8000, 4000) Debug Mode
// 07.03.16: 905ms
// 07.03.16: 483ms
_ = BIntMath.permutations(8000, 4000)
_ = BIntMath.combinations(8000, 4000)
}
}
static func multiplicationBalanced()
{
let b1 = BIntMath.randomBInt(bits: 270_000)
let b2 = BIntMath.randomBInt(bits: 270_000)
benchmarkAndPrint(title: "Multiply two random BInts with size of 270_000 and 270_000 bits")
{
// Multiply two random BInts with size of 270_000 and 270_000 bits
// 26.04.18: 2427ms
_ = b1 * b2
}
}
static func multiplicationUnbalanced()
{
let b1 = BIntMath.randomBInt(bits: 70_000_000)
let b2 = BIntMath.randomBInt(bits: 1_000)
benchmarkAndPrint(title: "Multiply two random BInts with size of 70_000_000 and 1_000 bits")
{
// Multiply two random BInts with size of 70_000_000 and 1_000 bits
// 26.04.18: 2467ms
_ = b1 * b2
}
}
}
| d4ef09087e391110a14d8741f0259c7a | 18.692568 | 94 | 0.567507 | false | false | false | false |
tlax/looper | refs/heads/master | looper/View/Camera/Rotate/VCameraRotateImage.swift | mit | 1 | import UIKit
class VCameraRotateImage:UIView
{
private weak var controller:CCameraRotate!
private weak var imageView:UIImageView!
private weak var border:VBorder!
private weak var layoutBorderTop:NSLayoutConstraint!
private weak var layoutBorderLeft:NSLayoutConstraint!
private weak var layoutBorderBottom:NSLayoutConstraint!
private weak var layoutBorderRight:NSLayoutConstraint!
private var borderMargin:CGFloat
private let kImageMargin:CGFloat = 120
private let kImageBorder:CGFloat = 2
init(controller:CCameraRotate)
{
borderMargin = kImageMargin - kImageBorder
super.init(frame:CGRect.zero)
clipsToBounds = true
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor.black)
self.border = border
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.image = controller.record.items.first?.image
self.imageView = imageView
addSubview(border)
addSubview(imageView)
NSLayoutConstraint.equals(
view:imageView,
toView:self,
margin:kImageMargin)
layoutBorderTop = NSLayoutConstraint.topToTop(
view:border,
toView:self)
layoutBorderBottom = NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
layoutBorderLeft = NSLayoutConstraint.leftToLeft(
view:border,
toView:self)
layoutBorderRight = NSLayoutConstraint.rightToRight(
view:border,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let hrMargin:CGFloat
let vrMargin:CGFloat
if width <= height
{
let deltaHeightWidth:CGFloat = height - width
let deltaHeightWidth_2:CGFloat = deltaHeightWidth / 2.0
hrMargin = borderMargin
vrMargin = borderMargin + deltaHeightWidth_2
}
else
{
let deltaWidthHeight:CGFloat = width - height
let deltaWidthHeight_2:CGFloat = deltaWidthHeight / 2.0
vrMargin = borderMargin
hrMargin = borderMargin + deltaWidthHeight_2
}
layoutBorderTop.constant = vrMargin
layoutBorderBottom.constant = -vrMargin
layoutBorderLeft.constant = hrMargin
layoutBorderRight.constant = -hrMargin
super.layoutSubviews()
}
}
| d433297695c394edf71dac1bdcdd7e26 | 30.642105 | 67 | 0.633733 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Shared/NotificationConstants.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
extension Notification.Name {
// add a property to allow the observation of firefox accounts
public static let FirefoxAccountChanged = Notification.Name("FirefoxAccountChanged")
public static let FirefoxAccountStateChange = Notification.Name("FirefoxAccountStateChange")
public static let RegisterForPushNotifications = Notification.Name("RegisterForPushNotifications")
public static let FirefoxAccountProfileChanged = Notification.Name("FirefoxAccountProfileChanged")
public static let FirefoxAccountDeviceRegistrationUpdated = Notification.Name("FirefoxAccountDeviceRegistrationUpdated")
public static let PrivateDataClearedHistory = Notification.Name("PrivateDataClearedHistory")
public static let PrivateDataClearedDownloadedFiles = Notification.Name("PrivateDataClearedDownloadedFiles")
// Fired when the user finishes navigating to a page and the location has changed
public static let OnLocationChange = Notification.Name("OnLocationChange")
// MARK: Notification UserInfo Keys
public static let UserInfoKeyHasSyncableAccount = Notification.Name("UserInfoKeyHasSyncableAccount")
// Fired when the login synchronizer has finished applying remote changes
public static let DataRemoteLoginChangesWereApplied = Notification.Name("DataRemoteLoginChangesWereApplied")
// Fired when a the page metadata extraction script has completed and is being passed back to the native client
public static let OnPageMetadataFetched = Notification.Name("OnPageMetadataFetched")
public static let ProfileDidStartSyncing = Notification.Name("ProfileDidStartSyncing")
public static let ProfileDidFinishSyncing = Notification.Name("ProfileDidFinishSyncing")
public static let DatabaseWasRecreated = Notification.Name("DatabaseWasRecreated")
public static let DatabaseWasClosed = Notification.Name("DatabaseWasClosed")
public static let DatabaseWasReopened = Notification.Name("DatabaseWasReopened")
public static let RustPlacesOpened = Notification.Name("RustPlacesOpened")
public static let PasscodeDidChange = Notification.Name("PasscodeDidChange")
public static let PasscodeDidCreate = Notification.Name("PasscodeDidCreate")
public static let PasscodeDidRemove = Notification.Name("PasscodeDidRemove")
public static let DynamicFontChanged = Notification.Name("DynamicFontChanged")
public static let UserInitiatedSyncManually = Notification.Name("UserInitiatedSyncManually")
public static let FaviconDidLoad = Notification.Name("FaviconDidLoad")
public static let ReachabilityStatusChanged = Notification.Name("ReachabilityStatusChanged")
public static let HomePanelPrefsChanged = Notification.Name("HomePanelPrefsChanged")
public static let FileDidDownload = Notification.Name("FileDidDownload")
public static let DisplayThemeChanged = Notification.Name("DisplayThemeChanged")
// This will eventually replace DisplayThemeChanged
public static let ThemeDidChange = Notification.Name("ThemeDidChange")
public static let SearchBarPositionDidChange = Notification.Name("SearchBarPositionDidChange")
public static let WallpaperDidChange = Notification.Name("WallpaperDidChange")
public static let UpdateLabelOnTabClosed = Notification.Name("UpdateLabelOnTabClosed")
public static let TopTabsTabClosed = Notification.Name("TopTabsTabClosed")
public static let ShowHomepage = Notification.Name("ShowHomepage")
public static let TabsTrayDidClose = Notification.Name("TabsTrayDidClose")
public static let TabsTrayDidSelectHomeTab = Notification.Name("TabsTrayDidSelectHomeTab")
public static let TabsPrivacyModeChanged = Notification.Name("TabsPrivacyModeChanged")
public static let OpenClearRecentHistory = Notification.Name("OpenClearRecentHistory")
public static let LibraryPanelStateDidChange = Notification.Name("LibraryPanelStateDidChange")
public static let SearchSettingsChanged = Notification.Name("SearchSettingsChanged")
// MARK: Tab manager
// Tab manager creates a toast for undo recently closed tabs and a notification is
// fired when user taps on undo button on Toast
public static let DidTapUndoCloseAllTabToast = Notification.Name("DidTapUndoCloseAllTabToast")
// MARK: Settings
public static let BookmarksUpdated = Notification.Name("BookmarksUpdated")
public static let ReadingListUpdated = Notification.Name("ReadingListUpdated")
public static let TopSitesUpdated = Notification.Name("TopSitesUpdated")
public static let HistoryUpdated = Notification.Name("HistoryUpdated")
}
| 2c11ddc52b4ded9f42727e5606315396 | 47.79798 | 124 | 0.79942 | false | false | false | false |
CoderJackyHuang/iOSLoadWebViewImage | refs/heads/develop | Example/Pods/AlamofireImage/Source/ImageCache.swift | apache-2.0 | 23 | // 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
}
}
| b132555a0e052a76f183c9761d9d6596 | 37.377709 | 126 | 0.666989 | false | false | false | false |
stormpath/stormpath-swift-example | refs/heads/master | Pods/Stormpath/Stormpath/Networking/APIRequest.swift | mit | 1 | //
// APIRequest.swift
// Stormpath
//
// Created by Edward Jiang on 12/15/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import UIKit
struct APIRequest {
let url: URL
var method: APIRequestMethod
var headers = [String: String]()
var body: [String: Any]?
var contentType = ContentType.json
init(method: APIRequestMethod, url: URL) {
self.method = method
self.url = url
}
func send(callback: APIRequestCallback? = nil) {
APIClient().execute(request: self, callback: callback)
}
var asURLRequest: URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
// Set headers
request.setValue(ContentType.json.rawValue, forHTTPHeaderField: "Accept") // Default to accept json
headers.forEach { (name, value) in
request.setValue(value, forHTTPHeaderField: name)
}
// Encode body
if let body = body {
request.setValue(contentType.rawValue, forHTTPHeaderField: "Content-Type")
switch(contentType) {
case .json:
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
case .urlEncoded:
request.httpBody = body.map { (key, value) -> String in
var formUrlEncodedCharacters = CharacterSet.urlQueryAllowed
formUrlEncodedCharacters.remove(charactersIn: "+&")
let key = key.addingPercentEncoding(withAllowedCharacters: formUrlEncodedCharacters) ?? ""
let value = "\(value)".addingPercentEncoding(withAllowedCharacters: formUrlEncodedCharacters) ?? ""
return "\(key)=\(value)"
}
.joined(separator: "&")
.data(using: .utf8)
}
}
return request
}
}
| 4afca92562740b8155d32fbecbd18bbb | 31.639344 | 119 | 0.567052 | false | false | false | false |
evgenyneu/Auk | refs/heads/master | Auk/Utils/iiAutolayoutConstraints.swift | mit | 1 | //
// Collection of shortcuts to create autolayout constraints.
//
import UIKit
class iiAutolayoutConstraints {
class func fillParent(_ view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) {
var marginFormat = ""
if margin != 0 {
marginFormat = "-(\(margin))-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
}
@discardableResult
class func alignSameAttributes(_ item: AnyObject, toItem: AnyObject,
constraintContainer: UIView, attribute: NSLayoutConstraint.Attribute, margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: item,
attribute: attribute,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: toItem,
attribute: attribute,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func equalWidth(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] {
return equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: false)
}
// MARK: - Equal height and width
class func equalHeight(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] {
return equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: true)
}
@discardableResult
class func equalSize(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] {
var constraints = equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: false)
constraints += equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: true)
return constraints
}
class func equalWidthOrHeight(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView,
isHeight: Bool) -> [NSLayoutConstraint] {
var prefix = ""
if isHeight { prefix = "V:" }
let constraints = NSLayoutConstraint.constraints(withVisualFormat: "\(prefix)[viewOne(==viewTwo)]",
options: [], metrics: nil,
views: ["viewOne": viewOne, "viewTwo": viewTwo])
constraintContainer.addConstraints(constraints)
return constraints
}
// MARK: - Align view next to each other
@discardableResult
class func viewsNextToEachOther(_ views: [UIView],
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
if views.count < 2 { return [] }
var constraints = [NSLayoutConstraint]()
for (index, view) in views.enumerated() {
if index >= views.count - 1 { break }
let viewTwo = views[index + 1]
constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo,
constraintContainer: constraintContainer, margin: margin, vertically: vertically)
}
return constraints
}
class func twoViewsNextToEachOther(_ viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "[viewOne]\(marginFormat)[viewTwo]"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: [ "viewOne": viewOne, "viewTwo": viewTwo ])
constraintContainer.addConstraints(constraints)
return constraints
}
@discardableResult
class func height(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isHeight: true)
}
@discardableResult
class func width(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isHeight: false)
}
class func widthOrHeight(_ view: UIView, value: CGFloat, isHeight: Bool) -> [NSLayoutConstraint] {
let layoutAttribute = isHeight ? NSLayoutConstraint.Attribute.height : NSLayoutConstraint.Attribute.width
let constraint = NSLayoutConstraint(
item: view,
attribute: layoutAttribute,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1,
constant: value)
view.addConstraint(constraint)
return [constraint]
}
}
| e642a66c4d43a8fe18c56d169dec79b6 | 29.559748 | 126 | 0.675242 | false | false | false | false |
p0dee/PDAlertView | refs/heads/master | PDAlertView/AlertBodyView.swift | gpl-2.0 | 1 | //
// BodyView.swift
// AlertViewMock
//
// Created by Takeshi Tanaka on 12/23/15.
// Copyright © 2015 Takeshi Tanaka. All rights reserved.
//
import UIKit
internal func actionButtonLineWidth() -> Double {
let scale = Double(UIScreen.main.scale)
return (scale > 2.0 ? 2.0 : 1.0) / scale
}
fileprivate extension AlertSelectionControl {
fileprivate var selectedView: AlertSelectionComponentView? {
if let selIdx = self.selectedIndex, selIdx < self.components.count {
return self.components[selIdx]
} else {
return nil
}
}
}
internal protocol AlertBodyViewDelegate: class {
func bodyView(_ bodyView: AlertBodyView, didSelectedItemAtIndex index: Int)
}
internal class AlertBodyView: UIView {
private let vibracyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: UIBlurEffect(style: .dark)))
private let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
private let bgView = UIView()
private var bodyMaskView: MaskView?
private let contentView = UIStackView()
private let titleLabel = UILabel()
private let messageLabel = UILabel()
private let selectionView = AlertSelectionControl()
let accessoryContentView = AccessoryContentView() as UIView
var delegate: AlertBodyViewDelegate?
var button = UITableViewCell()
var title: String? {
set {
titleLabel.text = newValue
}
get {
return titleLabel.text
}
}
var message: String? {
set {
messageLabel.text = newValue
}
get {
return messageLabel.text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
bodyMaskView = MaskView(bodyView: self)
self.clipsToBounds = true
self.layer.cornerRadius = 7.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal override var intrinsicContentSize: CGSize {
return CGSize(width: 270, height: UIViewNoIntrinsicMetric)
}
internal override func willMove(toSuperview newSuperview: UIView?) {
setupViews()
setupConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
bodyMaskView?.sizeToFit()
}
//MARK:
func addAction(_ action: AlertAction) {
selectionView.addButton(with: action.title, style: action.style)
bodyMaskView?.setNeedsDisplay()
}
//MARK:
private func setupViews() {
vibracyView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(vibracyView)
let mask = UIView(frame: vibracyView.bounds)
mask.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mask.backgroundColor = UIColor.black.withAlphaComponent(0.5)
vibracyView.contentView.addSubview(mask)
blurView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(blurView)
bgView.translatesAutoresizingMaskIntoConstraints = false
bgView.backgroundColor = UIColor(white: 1.0, alpha: 0.7)
self.addSubview(bgView)
bgView.mask = bodyMaskView
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.layoutMargins = UIEdgeInsetsMake(20, 18, 12, 18)
contentView.axis = .vertical
contentView.spacing = 8.0
self.addSubview(contentView)
titleLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
titleLabel.textAlignment = .center
titleLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal)
contentView.addArrangedSubview(titleLabel)
messageLabel.numberOfLines = 0
messageLabel.font = UIFont.systemFont(ofSize: 13.0)
messageLabel.textAlignment = .center
messageLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal)
contentView.addArrangedSubview(messageLabel)
selectionView.translatesAutoresizingMaskIntoConstraints = false
selectionView.addTarget(bodyMaskView, action: #selector(MaskView.selectionViewDidChange(_:)), for: .valueChanged)
selectionView.addTarget(self, action: #selector(selectionViewDidTouchUpInside(_:)), for: .touchUpInside)
self.addSubview(selectionView)
}
private func setupConstraints() {
var cstrs = [NSLayoutConstraint]()
cstrs += NSLayoutConstraint.constraintsToFillSuperview(vibracyView)
cstrs += NSLayoutConstraint.constraintsToFillSuperview(blurView)
cstrs += NSLayoutConstraint.constraintsToFillSuperview(bgView)
let lineWidth = NSNumber(value: actionButtonLineWidth())
let metrics = ["lineWidth" : lineWidth]
let views = ["contentView" : contentView, "selectionView" : selectionView]
let formatHorizG = "H:|[contentView]|"
cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatHorizG, options: .directionLeadingToTrailing, metrics: metrics, views: views)
let formatVertG = "V:|-(20)-[contentView]-(20)-[selectionView]|"
cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatVertG, options: [.alignAllLeading, .alignAllTrailing], metrics: metrics, views: views)
NSLayoutConstraint.activate(cstrs)
}
@objc private func selectionViewDidTouchUpInside(_ sender: AlertSelectionControl) {
if let selIdx = selectionView.selectedIndex {
delegate?.bodyView(self, didSelectedItemAtIndex: selIdx)
}
}
private class AccessoryContentView: UIView {
override func addSubview(_ view: UIView) {
super.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = true
view.autoresizingMask = [view.autoresizingMask, .flexibleLeftMargin, .flexibleRightMargin]
}
override func layoutSubviews() {
super.layoutSubviews()
for v in self.subviews {
var frame = v.frame
frame.size.width = min(self.bounds.size.width, frame.size.width)
frame.origin.x = (self.bounds.size.width - frame.size.width) * 0.5
frame.origin.y = 0
v.frame = frame
}
}
override var intrinsicContentSize: CGSize {
var maxY: CGFloat = 0
for v in subviews {
maxY = max(maxY, v.frame.maxY)
}
return CGSize(width: UIViewNoIntrinsicMetric, height: maxY)
}
func hasContent() -> Bool {
return self.subviews.count > 0
}
}
private class MaskView: UIView {
weak private var bodyView: AlertBodyView?
private static let PixelWidth = CGFloat(actionButtonLineWidth())
convenience init(bodyView: AlertBodyView) {
self.init()
self.backgroundColor = UIColor.clear
self.bodyView = bodyView
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
guard let bodyView = bodyView else {
return size
}
return bodyView.bounds.size
}
override func draw(_ rect: CGRect) {
guard let bodyView = bodyView else {
return
}
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.addRect(bodyView.contentView.frame.insetBy(dx: 0, dy: -20)) //FIXME:
for view in bodyView.selectionView.components {
if view.isEqual(bodyView.selectionView.selectedView) {
continue
}
context.addRect(CGRect(x: view.frame.origin.x + bodyView.selectionView.frame.origin.x, y: view.frame.origin.y + bodyView.selectionView.frame.origin.y + MaskView.PixelWidth, width: view.frame.size.width, height: view.frame.size.height))
}
UIColor.black.setFill()
context.fillPath()
if let view = bodyView.selectionView.selectedView {
let rect = CGRect(x: view.frame.origin.x + bodyView.selectionView.frame.origin.x, y: view.frame.origin.y + bodyView.selectionView.frame.origin.y + MaskView.PixelWidth, width: view.frame.size.width, height: view.frame.size.height)
if bodyView.selectionView.axis == .horizontal {
context.addRect(rect.insetBy(dx: -MaskView.PixelWidth, dy: 0))
} else {
context.addRect(rect.insetBy(dx: 0, dy: -MaskView.PixelWidth))
}
UIColor.black.withAlphaComponent(0.5).setFill()
context.fillPath()
}
}
@objc func selectionViewDidChange(_ sender: AlertSelectionControl) {
setNeedsDisplay()
}
}
}
| cb7860524330033986c29ae1af405704 | 37.313559 | 251 | 0.633378 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/CollectionKit-master/Sources/Layout/InsetLayout.swift | mit | 1 | //
// InsetLayout.swift
// CollectionKit
//
// Created by Luke Zhao on 2017-09-08.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
open class InsetLayout<Data>: WrapperLayout<Data> {
public var insets: UIEdgeInsets
public var insetProvider: ((CGSize) -> UIEdgeInsets)?
public init(_ rootLayout: CollectionLayout<Data>, insets: UIEdgeInsets = .zero) {
self.insets = insets
super.init(rootLayout)
}
public init(_ rootLayout: CollectionLayout<Data>, insetProvider: @escaping ((CGSize) -> UIEdgeInsets)) {
self.insets = .zero
self.insetProvider = insetProvider
super.init(rootLayout)
}
open override var contentSize: CGSize {
return rootLayout.contentSize.insets(by: -insets)
}
open override func layout(collectionSize: CGSize,
dataProvider: CollectionDataProvider<Data>,
sizeProvider: @escaping (Int, Data, CGSize) -> CGSize) {
if let insetProvider = insetProvider {
insets = insetProvider(collectionSize)
}
rootLayout.layout(collectionSize: collectionSize.insets(by: insets),
dataProvider: dataProvider, sizeProvider: sizeProvider)
}
open override func visibleIndexes(activeFrame: CGRect) -> [Int] {
return rootLayout.visibleIndexes(activeFrame: activeFrame.inset(by: -insets))
}
open override func frame(at: Int) -> CGRect {
return rootLayout.frame(at: at) + CGPoint(x: insets.left, y: insets.top)
}
}
| 78cc14801af4c8d6352bc158d81fd608 | 30.617021 | 106 | 0.681023 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Services/Settings/EmailVerification/EmailVerificationService.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import RxRelay
import RxSwift
public final class EmailVerificationService: EmailVerificationServiceAPI {
// MARK: - Types
private enum ServiceError: Error {
case emailNotVerified
case pollCancelled
}
// MARK: - Properties
private let syncService: WalletNabuSynchronizerServiceAPI
private let settingsService: SettingsServiceAPI & EmailSettingsServiceAPI
private let isActiveRelay = BehaviorRelay<Bool>(value: false)
// MARK: - Setup
init(
syncService: WalletNabuSynchronizerServiceAPI = resolve(),
settingsService: CompleteSettingsServiceAPI = resolve()
) {
self.syncService = syncService
self.settingsService = settingsService
}
public func cancel() -> Completable {
Completable
.create { [weak self] observer -> Disposable in
self?.isActiveRelay.accept(false)
observer(.completed)
return Disposables.create()
}
}
public func verifyEmail() -> Completable {
start()
.flatMapCompletable(weak: self) { (self, _) -> Completable in
self.syncService.sync().asSingle().asCompletable()
}
}
public func requestVerificationEmail(to email: String, context: FlowContext?) -> Completable {
settingsService
.update(email: email, context: context)
.andThen(syncService.sync().asSingle().asCompletable())
}
/// Start polling by triggering the wallet settings fetch
private func start() -> Single<Void> {
Single
.create(weak: self) { (self, observer) -> Disposable in
self.isActiveRelay.accept(true)
observer(.success(()))
return Disposables.create()
}
.flatMap(waitForVerification)
}
/// Continues the polling only if it has not been cancelled
private func `continue`() -> Single<Void> {
isActiveRelay
.take(1)
.asSingle()
.map { isActive in
guard isActive else {
throw ServiceError.pollCancelled
}
return ()
}
.flatMap(weak: self) { (self, _: ()) -> Single<Void> in
self.settingsService.fetch(force: true).mapToVoid()
}
}
/// Returns a Single that upon subscription waits until the email is verified.
/// Only when it streams a value (`Void`) the email is considered `verified`.
private func waitForVerification() -> Single<Void> {
self.continue()
.flatMap(weak: self) { (self, _) -> Single<Void> in
self.settingsService
/// Get the first value and make sure the stream terminates
/// by converting it to a `Single`
.valueSingle
/// Make sure the email is verified, if not throw an error
.map(weak: self) { _, settings -> Void in
guard settings.isEmailVerified else {
throw ServiceError.emailNotVerified
}
return ()
}
/// If email is not verified try again
.catch { error -> Single<Void> in
switch error {
case ServiceError.emailNotVerified:
return Single<Int>
.timer(
.seconds(1),
scheduler: ConcurrentDispatchQueueScheduler(qos: .background)
)
.flatMap(weak: self) { (self, _) -> Single<Void> in
self.waitForVerification()
}
default:
return self.cancel().andThen(Single.error(ServiceError.pollCancelled))
}
}
}
}
}
| 7c4751efec98a9360d78ae54fc283395 | 35.356522 | 98 | 0.522363 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Compositions/Standart/QTitleButtonComposition.swift | mit | 1 | //
// Quickly
//
open class QTitleButtonComposable : QComposable {
public typealias Closure = (_ composable: QTitleButtonComposable) -> Void
public var titleStyle: QLabelStyleSheet
public var buttonStyle: QButtonStyleSheet
public var buttonIsHidden: Bool
public var buttonHeight: CGFloat
public var buttonSpacing: CGFloat
public var buttonIsSpinnerAnimating: Bool
public var buttonPressed: Closure
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
titleStyle: QLabelStyleSheet,
buttonStyle: QButtonStyleSheet,
buttonIsHidden: Bool = false,
buttonHeight: CGFloat = 44,
buttonSpacing: CGFloat = 4,
buttonPressed: @escaping Closure
) {
self.titleStyle = titleStyle
self.buttonStyle = buttonStyle
self.buttonIsHidden = buttonIsHidden
self.buttonHeight = buttonHeight
self.buttonSpacing = buttonSpacing
self.buttonIsSpinnerAnimating = false
self.buttonPressed = buttonPressed
super.init(edgeInsets: edgeInsets)
}
}
open class QTitleButtonComposition< Composable: QTitleButtonComposable > : QComposition< Composable > {
public private(set) lazy var titleView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var buttonView: QButton = {
let view = QButton(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(
horizontal: UILayoutPriority(rawValue: 252),
vertical: UILayoutPriority(rawValue: 252)
)
view.onPressed = { [weak self] _ in
guard let self = self, let composable = self.composable else { return }
composable.buttonPressed(composable)
}
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _buttonIsHidden: Bool?
private var _buttonSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let textSize = composable.titleStyle.size(width: availableWidth)
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(textSize.height, composable.buttonHeight) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._buttonIsHidden != composable.buttonIsHidden || self._buttonSpacing != composable.buttonSpacing {
self._edgeInsets = composable.edgeInsets
self._buttonIsHidden = composable.buttonIsHidden
self._buttonSpacing = composable.buttonSpacing
var constraints: [NSLayoutConstraint] = [
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.buttonView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.buttonView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.buttonView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right)
]
if composable.buttonIsHidden == false {
constraints.append(contentsOf: [
self.titleView.trailingLayout == self.buttonView.leadingLayout.offset(-composable.buttonSpacing)
])
} else {
constraints.append(contentsOf: [
self.titleView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right)
])
}
self._constraints = constraints
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.titleView.apply(composable.titleStyle)
self.buttonView.apply(composable.buttonStyle)
}
open override func postLayout(composable: Composable, spec: IQContainerSpec) {
self.buttonView.alpha = (composable.buttonIsHidden == false) ? 1 : 0
if composable.buttonIsSpinnerAnimating == true {
self.buttonView.startSpinner()
} else {
self.buttonView.stopSpinner()
}
}
public func isSpinnerAnimating() -> Bool {
return self.buttonView.isSpinnerAnimating()
}
public func startSpinner() {
if let composable = self.composable {
composable.buttonIsSpinnerAnimating = true
self.buttonView.startSpinner()
}
}
public func stopSpinner() {
if let composable = self.composable {
composable.buttonIsSpinnerAnimating = false
self.buttonView.stopSpinner()
}
}
}
| afd1f8a03af8d26b409be528c2984374 | 39.485507 | 158 | 0.665652 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwallet/src/ViewControllers/HomeScreenViewController.swift | mit | 1 | //
// HomeScreenViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-11-27.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class HomeScreenViewController: UIViewController, Subscriber, Trackable {
private let walletAuthenticator: WalletAuthenticator
private let widgetDataShareService: WidgetDataShareService
private let assetList = AssetListTableView()
private let subHeaderView = UIView()
private let logo = UIImageView(image: UIImage(named: "LogoGradientSmall"))
private let total = UILabel(font: Theme.h1Title, color: Theme.primaryText)
private let totalAssetsLabel = UILabel(font: Theme.caption, color: Theme.tertiaryText)
private let debugLabel = UILabel(font: .customBody(size: 12.0), color: .transparentWhiteText) // debug info
private let prompt = UIView()
private var promptHiddenConstraint: NSLayoutConstraint!
private let toolbar = UIToolbar()
private var toolbarButtons = [UIButton]()
private let notificationHandler = NotificationHandler()
private var shouldShowBuyAndSell: Bool {
return (Store.state.experimentWithName(.buyAndSell)?.active ?? false) && (Store.state.defaultCurrencyCode == C.usdCurrencyCode)
}
private var buyButtonTitle: String {
return shouldShowBuyAndSell ? S.HomeScreen.buyAndSell : S.HomeScreen.buy
}
private let buyButtonIndex = 0
private let tradeButtonIndex = 1
private let menuButtonIndex = 2
private var buyButton: UIButton? {
guard toolbarButtons.count == 3 else { return nil }
return toolbarButtons[buyButtonIndex]
}
private var tradeButton: UIButton? {
guard toolbarButtons.count == 3 else { return nil }
return toolbarButtons[tradeButtonIndex]
}
var didSelectCurrency: ((Currency) -> Void)?
var didTapManageWallets: (() -> Void)?
var didTapBuy: (() -> Void)?
var didTapTrade: (() -> Void)?
var didTapMenu: (() -> Void)?
var okToShowPrompts: Bool {
//Don't show any prompts on the first couple launches
guard UserDefaults.appLaunchCount > 2 else { return false }
// On the initial display we need to load the wallets in the asset list table view first.
// There's already a lot going on, so don't show the home-screen prompts right away.
return !Store.state.wallets.isEmpty
}
private lazy var totalAssetsNumberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.isLenient = true
formatter.numberStyle = .currency
formatter.generatesDecimalNumbers = true
return formatter
}()
// MARK: -
init(walletAuthenticator: WalletAuthenticator, widgetDataShareService: WidgetDataShareService) {
self.walletAuthenticator = walletAuthenticator
self.widgetDataShareService = widgetDataShareService
super.init(nibName: nil, bundle: nil)
}
deinit {
Store.unsubscribe(self)
}
func reload() {
setInitialData()
setupSubscriptions()
assetList.reload()
attemptShowPrompt()
}
override func viewDidLoad() {
assetList.didSelectCurrency = didSelectCurrency
assetList.didTapAddWallet = didTapManageWallets
addSubviews()
addConstraints()
setInitialData()
setupSubscriptions()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + promptDelay) { [unowned self] in
self.attemptShowPrompt()
if !Store.state.isLoginRequired {
NotificationAuthorizer().showNotificationsOptInAlert(from: self, callback: { _ in
self.notificationHandler.checkForInAppNotifications()
})
}
}
updateTotalAssets()
}
// MARK: Setup
private func addSubviews() {
view.addSubview(subHeaderView)
subHeaderView.addSubview(logo)
subHeaderView.addSubview(totalAssetsLabel)
subHeaderView.addSubview(total)
subHeaderView.addSubview(debugLabel)
view.addSubview(prompt)
view.addSubview(toolbar)
}
private func addConstraints() {
let headerHeight: CGFloat = 30.0
let toolbarHeight: CGFloat = 74.0
subHeaderView.constrain([
subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subHeaderView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0),
subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subHeaderView.heightAnchor.constraint(equalToConstant: headerHeight) ])
total.constrain([
total.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]),
total.centerYAnchor.constraint(equalTo: subHeaderView.topAnchor, constant: C.padding[1])])
totalAssetsLabel.constrain([
totalAssetsLabel.trailingAnchor.constraint(equalTo: total.trailingAnchor),
totalAssetsLabel.bottomAnchor.constraint(equalTo: total.topAnchor)])
logo.constrain([
logo.leadingAnchor.constraint(equalTo: subHeaderView.leadingAnchor, constant: C.padding[2]),
logo.centerYAnchor.constraint(equalTo: total.centerYAnchor)])
debugLabel.constrain([
debugLabel.leadingAnchor.constraint(equalTo: logo.leadingAnchor),
debugLabel.bottomAnchor.constraint(equalTo: logo.topAnchor, constant: -4.0)])
promptHiddenConstraint = prompt.heightAnchor.constraint(equalToConstant: 0.0)
prompt.constrain([
prompt.leadingAnchor.constraint(equalTo: view.leadingAnchor),
prompt.trailingAnchor.constraint(equalTo: view.trailingAnchor),
prompt.topAnchor.constraint(equalTo: subHeaderView.bottomAnchor),
promptHiddenConstraint])
addChildViewController(assetList, layout: {
assetList.view.constrain([
assetList.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
assetList.view.topAnchor.constraint(equalTo: prompt.bottomAnchor),
assetList.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
assetList.view.bottomAnchor.constraint(equalTo: toolbar.topAnchor)])
})
toolbar.constrain([
toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: -C.padding[1]),
toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: C.padding[1]),
toolbar.heightAnchor.constraint(equalToConstant: toolbarHeight) ])
}
private func setInitialData() {
view.backgroundColor = .darkBackground
subHeaderView.backgroundColor = .darkBackground
subHeaderView.clipsToBounds = false
navigationItem.titleView = UIView()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.shadowImage = #imageLiteral(resourceName: "TransparentPixel")
navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "TransparentPixel"), for: .default)
logo.contentMode = .center
total.textAlignment = .right
total.text = "0"
title = ""
if E.isTestnet && !E.isScreenshots {
debugLabel.text = "(Testnet)"
debugLabel.isHidden = false
} else if (E.isTestFlight || E.isDebug), let debugHost = UserDefaults.debugBackendHost {
debugLabel.text = "[\(debugHost)]"
debugLabel.isHidden = false
} else {
debugLabel.isHidden = true
}
totalAssetsLabel.text = S.HomeScreen.totalAssets
setupToolbar()
updateTotalAssets()
}
//Returns the added image view so that it can be kept track of for removing later
private func addNotificationIndicatorToButton(button: UIButton) -> UIImageView? {
guard (button.subviews.last as? UIImageView) == nil else { return nil } // make sure we didn't already add the bell
guard let buttonImageView = button.imageView else { return nil }
let buyImageFrame = buttonImageView
let bellImage = UIImage(named: "notification-bell")
let bellImageView = UIImageView(image: bellImage)
bellImageView.contentMode = .center
let bellWidth = bellImage?.size.width ?? 0
let bellHeight = bellImage?.size.height ?? 0
let bellXOffset = buyImageFrame.center.x + 4
let bellYOffset = buyImageFrame.center.y - bellHeight + 2.0
bellImageView.frame = CGRect(x: bellXOffset, y: bellYOffset, width: bellWidth, height: bellHeight)
button.addSubview(bellImageView)
return bellImageView
}
private func setupToolbar() {
let buttons = [(buyButtonTitle, #imageLiteral(resourceName: "buy"), #selector(buy)),
(S.HomeScreen.trade, #imageLiteral(resourceName: "trade"), #selector(trade)),
(S.HomeScreen.menu, #imageLiteral(resourceName: "menu"), #selector(menu))].map { (title, image, selector) -> UIBarButtonItem in
let button = UIButton.vertical(title: title, image: image)
button.tintColor = .navigationTint
button.addTarget(self, action: selector, for: .touchUpInside)
return UIBarButtonItem(customView: button)
}
let paddingWidth = C.padding[2]
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [
flexibleSpace,
buttons[0],
flexibleSpace,
buttons[1],
flexibleSpace,
buttons[2],
flexibleSpace
]
let buttonWidth = (view.bounds.width - (paddingWidth * CGFloat(buttons.count+1))) / CGFloat(buttons.count)
let buttonHeight = CGFloat(44.0)
buttons.forEach {
$0.customView?.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight)
}
// Stash the UIButton's wrapped by the toolbar items in case we need add a badge later.
buttons.forEach { (toolbarButtonItem) in
if let button = toolbarButtonItem.customView as? UIButton {
self.toolbarButtons.append(button)
}
}
toolbar.isTranslucent = false
toolbar.barTintColor = Theme.secondaryBackground
}
private func setupSubscriptions() {
Store.unsubscribe(self)
Store.subscribe(self, selector: {
var result = false
let oldState = $0
let newState = $1
$0.wallets.values.map { $0.currency }.forEach { currency in
result = result || oldState[currency]?.balance != newState[currency]?.balance
result = result || oldState[currency]?.currentRate?.rate != newState[currency]?.currentRate?.rate
}
return result
},
callback: { _ in
self.updateTotalAssets()
self.updateAmountsForWidgets()
})
// prompts
Store.subscribe(self, name: .didUpgradePin, callback: { _ in
if self.currentPromptView?.type == .upgradePin {
self.currentPromptView = nil
}
})
Store.subscribe(self, name: .didWritePaperKey, callback: { _ in
if self.currentPromptView?.type == .paperKey {
self.currentPromptView = nil
}
})
Store.subscribe(self, selector: {
return ($0.experiments ?? nil) != ($1.experiments ?? nil)
}, callback: { _ in
// Do a full reload of the toolbar so it's laid out correctly with updated button titles.
self.setupToolbar()
self.saveEvent("experiment.buySellMenuButton", attributes: ["show": self.shouldShowBuyAndSell ? "true" : "false"])
})
Store.subscribe(self, selector: {
$0.wallets.count != $1.wallets.count
}, callback: { _ in
self.updateTotalAssets()
self.updateAmountsForWidgets()
})
}
private func updateTotalAssets() {
let fiatTotal: Decimal = Store.state.wallets.values.map {
guard let balance = $0.balance,
let rate = $0.currentRate else { return 0.0 }
let amount = Amount(amount: balance,
rate: rate)
return amount.fiatValue
}.reduce(0.0, +)
totalAssetsNumberFormatter.currencySymbol = Store.state.orderedWallets.first?.currentRate?.currencySymbol ?? ""
self.total.text = totalAssetsNumberFormatter.string(from: fiatTotal as NSDecimalNumber)
}
private func updateAmountsForWidgets() {
let info: [CurrencyId: Double] = Store.state.wallets
.map { ($0, $1) }
.reduce(into: [CurrencyId: Double]()) {
if let balance = $1.1.balance {
let unit = $1.1.currency.defaultUnit
$0[$1.0] = balance.cryptoAmount.double(as: unit) ?? 0
}
}
widgetDataShareService.updatePortfolio(info: info)
widgetDataShareService.quoteCurrencyCode = Store.state.defaultCurrencyCode
}
// MARK: Actions
@objc private func buy() {
saveEvent("currency.didTapBuyBitcoin", attributes: [ "buyAndSell": shouldShowBuyAndSell ? "true" : "false" ])
didTapBuy?()
}
@objc private func trade() {
saveEvent("currency.didTapTrade", attributes: [:])
didTapTrade?()
}
@objc private func menu() { didTapMenu?() }
// MARK: - Prompt
private let promptDelay: TimeInterval = 0.6
private let inAppNotificationDelay: TimeInterval = 3.0
private var currentPromptView: PromptView? {
didSet {
if currentPromptView != oldValue {
var afterFadeOut: TimeInterval = 0.0
if let oldPrompt = oldValue {
afterFadeOut = 0.15
UIView.animate(withDuration: 0.2, animations: {
oldValue?.alpha = 0.0
}, completion: { _ in
oldPrompt.removeFromSuperview()
})
}
if let newPrompt = currentPromptView {
newPrompt.alpha = 0.0
prompt.addSubview(newPrompt)
newPrompt.constrain(toSuperviewEdges: .zero)
prompt.layoutIfNeeded()
promptHiddenConstraint.isActive = false
// fade-in after fade-out and layout
UIView.animate(withDuration: 0.2, delay: afterFadeOut + 0.15, options: .curveEaseInOut, animations: {
newPrompt.alpha = 1.0
})
} else {
promptHiddenConstraint.isActive = true
}
// layout after fade-out
UIView.animate(withDuration: 0.2, delay: afterFadeOut, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
})
}
}
}
private func attemptShowPrompt() {
guard okToShowPrompts else { return }
guard currentPromptView == nil else { return }
if let nextPrompt = PromptFactory.nextPrompt(walletAuthenticator: walletAuthenticator) {
self.saveEvent("prompt.\(nextPrompt.name).displayed")
// didSet {} for 'currentPromptView' will display the prompt view
currentPromptView = PromptFactory.createPromptView(prompt: nextPrompt, presenter: self)
nextPrompt.didPrompt()
guard let prompt = currentPromptView else { return }
prompt.dismissButton.tap = { [unowned self] in
self.saveEvent("prompt.\(nextPrompt.name).dismissed")
self.currentPromptView = nil
}
if !prompt.shouldHandleTap {
prompt.continueButton.tap = { [unowned self] in
if let trigger = nextPrompt.trigger {
Store.trigger(name: trigger)
}
self.saveEvent("prompt.\(nextPrompt.name).trigger")
self.currentPromptView = nil
}
}
} else {
currentPromptView = nil
}
}
// MARK: -
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 1eb351af45bc89ad489d77e49d6320c5 | 38.642369 | 150 | 0.604091 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | playgrounds/swift/SwiftBasics.playground/Pages/BasicSyntax.xcplaygroundpage/Contents.swift | mit | 2 | //: ## Basic Syntax
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)//: ****
//: ### Constants and Variables
let constant = "Constants are declared with 'let'"
// constant = "You can not change a constant!"
//: _It is considered a good practice to declare any value as a constant until you have a need to change it to a variable._
var variable = "Variables are declared with 'var'"
variable = "You can assign a new value to a variable"
//: You can declare multiple constants or variables in one line if you separate them with a comma:
let a = 0, b = 0, c = 0
//:### Basic Types
let boolean: Bool = true
let long: Int = Int.max // Int64 for x64 systems
let integer: Int32 = Int32.max
let short: Int16 = Int16.max
let byte: Int8 = Int8.max
let ubyte: UInt8 = UInt8.max // there are also UInt16, UInt32, UInt62
let pi: Double = 3.141592653589793
let e: Float = 2.71828182
//: Type of a value can be inferred from the declaration
let i = 0x2a
"i is inferred as \(type(of: i))"
let π = 3.14
"π is inferred as \(type(of: π))"
let star = "⭐️"
"star is inferred as \(type(of: star))"
//:### Type Casting
//: There is no implicit type conversions in Swift.
let intPi = Int(pi)
let doubleE = Double(e)
//: But literals has no type, so the following is not a type conversion.
let fire: Character = "🔥"
let four: Double = 2 * 2
//:### Operators
let arithmetics = 1 + (2 * 3) - (5 / 4) % 2
let comparision = ((1 > 2) == (2 < 3)) != ((2 >= 3) == (3<=4))
let logic = (true && !false) || (!true && false)
let range = 1...3
let interval = 1..<10
//:### Control Flow
//: In Swift curved braces are required for control flow.
if comparision {
"Comparision result is True"
} else {
"Comparision result is False"
}
let signedValue = -1
if signedValue > 0 {
"signedValue > 0"
} else if signedValue < 0 {
"signedValue < 0"
} else {
"signedValue == 0"
}
switch signedValue {
case Int.min..<0:
"signedValue < 0"
case 0:
"signedValue == 0"
default:
"signedValue > 0"
}
//: _There is no implicit fallthrough in switch. Switch clausures must be exauhstive and every case should contain an action._
let switchValue = 34
switch switchValue {
case Int.min..<0:
"switchValue is a negative number"
case 0:
"switchValue is a zero"
case 1, 2, 3, 5, 8, 13, 21, 34, 55, 89:
"\(switchValue) is one of the first 10 Fibonachi numbers"
default:
break
}
//:_there are the basic loops in Swift_
for i in 1...10 {
i % 2
}
var whileCondition = true
while whileCondition {
whileCondition
whileCondition = false
}
var repeatCondition = false
repeat {
repeatCondition
} while repeatCondition
//: ****
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
| d6d5fdbbbe1cd07518cb643d1e57c559 | 26.168317 | 126 | 0.66035 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | refs/heads/master | Source/Phone/WebSocketService.swift | mit | 1 | // Copyright 2016 Cisco Systems Inc
//
// 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 Starscream
import SwiftyJSON
class WebSocketService: WebSocketDelegate {
static let sharedInstance = WebSocketService()
private var socket: WebSocket?
private let MessageBatchingIntervalInSec = 0.5
private let ConnectionTimeoutIntervalInSec = 60.0
private var connectionTimeoutTimer: Timer?
private var messageBatchingTimer: Timer?
private var connectionRetryCounter: ExponentialBackOffCounter
private var pendingMessages: [JSON]
init() {
connectionRetryCounter = ExponentialBackOffCounter(minimum: 0.5, maximum: 32, multiplier: 2)
pendingMessages = [JSON]()
}
deinit {
cancelConnectionTimeOutTimer()
cancelMessageBatchingTimer()
}
func connect(_ webSocketUrl: URL) {
if socket == nil {
socket = createWebSocket(webSocketUrl)
guard socket != nil else {
Logger.error("Skip connection due to failure of creating socket")
return
}
}
if socket!.isConnected {
Logger.warn("Web socket is already connected")
return
}
Logger.info("Web socket is being connected")
socket?.connect()
scheduleConnectionTimeoutTimer()
}
func disconnect() {
guard socket != nil else {
Logger.warn("Web socket has not been connected")
return
}
guard socket!.isConnected else {
Logger.warn("Web socket is already disconnected")
return
}
Logger.info("Web socket is being disconnected")
socket?.disconnect()
socket = nil
}
private func reconnect() {
guard socket != nil else {
Logger.warn("Web socket has not been connected")
return
}
guard !socket!.isConnected else {
Logger.warn("Web socket has already connected")
return
}
Logger.info("Web socket is being reconnected")
socket?.connect()
}
private func createWebSocket(_ webSocketUrl: URL) -> WebSocket? {
// Need to check authorization, avoid crash when logout as soon as login
guard let authorization = AuthManager.sharedInstance.getAuthorization() else {
Logger.error("Failed to create web socket due to no authorization")
return nil
}
socket = WebSocket(url: webSocketUrl)
if socket == nil {
Logger.error("Failed to create web socket")
return nil
}
socket?.headers.unionInPlace(authorization)
socket?.voipEnabled = true
socket?.disableSSLCertValidation = true
socket?.delegate = self
return socket
}
private func despatch_main_after(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
execute: closure
)
}
// MARK: - Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
Logger.info("Websocket is connected")
connectionRetryCounter.reset()
scheduleMessageBatchingTimer()
cancelConnectionTimeOutTimer()
ReachabilityService.sharedInstance.fetch()
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
cancelMessageBatchingTimer()
cancelConnectionTimeOutTimer()
guard let code = error?.code, let discription = error?.localizedDescription else {
return
}
Logger.info("Websocket is disconnected: \(code), \(discription)")
guard self.socket != nil else {
Logger.info("Websocket is disconnected on purpose")
return
}
let backoffTime = connectionRetryCounter.next()
if code > Int(WebSocket.CloseCode.normal.rawValue) {
// Abnormal disconnection, re-register device.
self.socket = nil
Logger.error("Abnormal disconnection, re-register device in \(backoffTime) seconds")
despatch_main_after(backoffTime) {
Spark.phone.register(nil)
}
} else {
// Unexpected disconnection, reconnect socket.
Logger.warn("Unexpected disconnection, websocket will reconnect in \(backoffTime) seconds")
despatch_main_after(backoffTime) {
self.reconnect()
}
}
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
Logger.info("Websocket got some text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
let json = JSON(data: data)
ackMessage(socket, messageId: json["id"].string!)
pendingMessages.append(json)
}
// MARK: - Websocket Event Handler
private func ackMessage(_ socket: WebSocket, messageId: String) {
let ack = JSON(["type": "ack", "messageId": messageId])
do {
let ackData: Data = try ack.rawData(options: .prettyPrinted)
socket.write(data: ackData)
} catch {
Logger.error("Failed to acknowledge message")
}
}
private func processMessages() {
for message in pendingMessages {
let eventData = message["data"]
if let eventType = eventData["eventType"].string {
if eventType.hasPrefix("locus") {
Logger.info("locus event: \(eventData.object)")
CallManager.sharedInstance.handle(callEventJson: eventData.object)
}
}
}
pendingMessages.removeAll()
}
// MARK: - Web Socket Timers
private func scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, selector: Selector, repeats: Bool) -> Timer {
return Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: selector, userInfo: nil, repeats: repeats)
}
private func scheduleMessageBatchingTimer() {
messageBatchingTimer = scheduledTimerWithTimeInterval(MessageBatchingIntervalInSec, selector: #selector(onMessagesBatchingTimerFired), repeats: true)
}
private func cancelMessageBatchingTimer() {
messageBatchingTimer?.invalidate()
messageBatchingTimer = nil
}
private func scheduleConnectionTimeoutTimer() {
connectionTimeoutTimer = scheduledTimerWithTimeInterval(ConnectionTimeoutIntervalInSec, selector: #selector(onConnectionTimeOutTimerFired), repeats: false)
}
private func cancelConnectionTimeOutTimer() {
connectionTimeoutTimer?.invalidate()
connectionTimeoutTimer = nil
}
@objc private func onMessagesBatchingTimerFired() {
processMessages()
}
@objc private func onConnectionTimeOutTimerFired() {
Logger.info("Connect timed out, try to reconnect")
reconnect()
}
}
| 49235964cfb0f722c653a121a5d87e12 | 33.6625 | 163 | 0.629883 | false | false | false | false |
hq7781/MoneyBook | refs/heads/master | MoneyBook/Model/Payment/ProductManager.swift | mit | 1 | //
// ProductManager.swift
// MoneyBook
//
// Created by HongQuan on 2017/08/15.
// Copyright © 2017年 Roan.Hong. All rights reserved.
//
import Foundation
import StoreKit
fileprivate var productManagers : Set<ProductManager> = Set()
class ProductManager: NSObject, SKProductsRequestDelegate {
static var subscriptionProduct : SKProduct? = nil
fileprivate var completion : (([SKProduct]?,NSError?) -> Void)?
static func getProducts(withProductIdentifiers productIdentifiers :
[String],completion:(([SKProduct]?,NSError?) -> Void)?){
let productManager = ProductManager()
productManager.completion = completion
let request = SKProductsRequest(productIdentifiers: Set(productIdentifiers))
request.delegate = productManager
request.start()
productManagers.insert(productManager)
}
static func getSubscriptionProduct(completion:(() -> Void)? = nil) {
guard ProductManager.subscriptionProduct == nil else {
if let completion = completion {
completion()
}
return
}
let productIdentifier = "xxx.xxx.xxx.xxx"
ProductManager.getProducts(withProductIdentifiers:
[productIdentifier], completion: { (_products, error) -> Void in
if let product = _products?.first {
ProductManager.subscriptionProduct = product
}
if let completion = completion {
completion()
}
})
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
var error : NSError? = nil
if response.products.count == 0 {
error = NSError(domain: "ProductsRequestErrorDomain",
code: 0, userInfo: [NSLocalizedDescriptionKey:"プロダクトを取得できませんでした。"])
}
completion?(response.products, error)
}
func request(_ request: SKRequest, didFailWithError error: Error) {
let error = NSError(domain: "ProductsRequestErrorDomain",
code: 0, userInfo: [NSLocalizedDescriptionKey:"プロダクトを取得できませんでした。"])
completion?(nil,error)
productManagers.remove(self)
}
func requestDidFinish(_ request: SKRequest) {
productManagers.remove(self)
}
}
| 094c1033ddd9ff68e134a77a3c1c368e | 32.676056 | 97 | 0.619406 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Character/Skills/Skills.swift | lgpl-2.1 | 2 | //
// Skills.swift
// Neocom
//
// Created by Artem Shimanski on 1/22/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import Alamofire
import Expressible
import Combine
struct Skills: View {
var editMode: Bool
@Environment(\.managedObjectContext) private var managedObjectContext
private func getSkills() -> FetchedResultsController<SDEInvType> {
let controller = managedObjectContext
.from(SDEInvType.self)
.filter(/\SDEInvType.published == true && /\SDEInvType.group?.category?.categoryID == SDECategoryID.skill.rawValue)
.sort(by: \SDEInvType.group?.groupName, ascending: true)
.sort(by: \SDEInvType.typeName, ascending: true)
.fetchedResultsController(sectionName: /\SDEInvType.group?.groupName, cacheName: nil)
return FetchedResultsController(controller)
}
private let skills: Lazy<FetchedResultsController<SDEInvType>, Never> = Lazy()
var body: some View {
let skills = self.skills.get(initial: getSkills())
return SkillsContent(skills: skills, editMode: editMode).navigationBarTitle(Text("Skills"))
}
}
struct SkillsContent: View {
var skills: FetchedResultsController<SDEInvType>
var editMode: Bool
@Environment(\.backgroundManagedObjectContext) private var backgroundManagedObjectContext
@EnvironmentObject private var sharedState: SharedState
@State private var filter = SkillsFilter.Filter.my
@ObservedObject private var pilot = Lazy<DataLoader<Pilot, AFError>, Account>()
private func loadPilot(account: Account) -> DataLoader<Pilot, AFError> {
DataLoader(Pilot.load(sharedState.esi.characters.characterID(Int(account.characterID)), in: self.backgroundManagedObjectContext).receive(on: RunLoop.main))
}
private func subtitle(for skills: [SDEInvType], pilot: Pilot) -> Text {
let items = skills.compactMap { type -> (skill: Pilot.Skill, type: SDEInvType, trained: ESI.Skill?, queued: Pilot.SkillQueueItem?)? in
guard let skill = Pilot.Skill(type: type) else {return nil}
let typeID = Int(type.typeID)
let trainedSkill = pilot.trainedSkills[Int(typeID)]
let queuedSkill = pilot.skillQueue.filter{$0.queuedSkill.skillID == typeID}.min{$0.queuedSkill.finishedLevel < $1.queuedSkill.finishedLevel}
return (skill, type, trainedSkill, queuedSkill)
}
switch filter {
case .my:
let skills = items.compactMap{$0.trained}
let sp = skills.map{$0.skillpointsInSkill}.reduce(0, +)
return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))")
case .canTrain:
let skills = items.filter{($0.trained?.trainedSkillLevel ?? 0) < 5}
let mySP = items.compactMap{$0.trained?.skillpointsInSkill}.map{Int64($0)}.reduce(0, +)
let totalSP = items.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +)
return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: totalSP - mySP, unit: .skillPoints, style: .long))")
case .notKnown:
let skills = items.filter{$0.trained == nil}
let sp = skills.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +)
return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))")
case .all:
let sp = items.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +)
return Text("\(items.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))")
}
}
var body: some View {
let pilot = sharedState.account.map{account in self.pilot.get(account, initial: self.loadPilot(account: account))}?.result?.value// ?? .some(.empty)
return List {
Section(header: SkillsFilter(filter: $filter)) {
ForEach(skills.sections, id: \.name) { section in
NavigationLink(destination: SkillsPage(skills: section, filter: self.$filter, pilot: pilot, editMode: self.editMode)) {
VStack(alignment: .leading) {
Text(section.name)
pilot.map { pilot in
self.subtitle(for: section.objects, pilot: pilot).modifier(SecondaryLabelModifier())
}
}
}
}
}
}.listStyle(GroupedListStyle())
}
}
struct SkillsFilter: View {
@Binding var filter: Filter
enum Filter {
case my
case canTrain
case notKnown
case all
}
var body: some View {
Picker("Filter", selection: $filter) {
Text("My", comment: "Skill Borwser. My skills.").tag(Filter.my)
Text("Can Train", comment: "Skill Borwser").tag(Filter.canTrain)
Text("Not Known", comment: "Skill Borwser").tag(Filter.notKnown)
Text("All", comment: "Skill Borwser. All skills.").tag(Filter.all)
}.pickerStyle(SegmentedPickerStyle())
}
}
#if DEBUG
struct Skills_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
Skills(editMode: false)
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| 3419ead973832cfce57e9e0dcca0005b | 42.523438 | 163 | 0.624843 | false | false | false | false |
qingpengchen2011/PageMenu | refs/heads/master | Classes/CAPSPageMenu.swift | bsd-3-clause | 1 | // CAPSPageMenu.swift
//
// Niklas Fahl
//
// Copyright (c) 2014 The Board of Trustees of The University of Alabama All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of the University nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import UIKit
@objc public protocol CAPSPageMenuDelegate {
// MARK: - Delegate functions
optional func willMoveToPage(controller: UIViewController, index: Int)
optional func didMoveToPage(controller: UIViewController, index: Int)
}
class MenuItemView: UIView {
// MARK: - Menu item view
var titleLabel : UILabel?
var menuItemSeparator : UIView?
func setUpMenuItemView(menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) {
titleLabel = UILabel(frame: CGRectMake(0.0, 0.0, menuItemWidth, menuScrollViewHeight - indicatorHeight))
menuItemSeparator = UIView(frame: CGRectMake(menuItemWidth - (separatorWidth / 2), floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), separatorWidth, floor(menuScrollViewHeight * separatorPercentageHeight)))
menuItemSeparator!.backgroundColor = menuItemSeparatorColor
if separatorRoundEdges {
menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2
}
menuItemSeparator!.hidden = true
self.addSubview(menuItemSeparator!)
self.addSubview(titleLabel!)
}
func setTitleText(text: NSString) {
if titleLabel != nil {
titleLabel!.text = text as String
titleLabel!.numberOfLines = 0
titleLabel!.sizeToFit()
}
}
}
public class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
let menuScrollView = UIScrollView()
let controllerScrollView = UIScrollView()
var controllerArray : [AnyObject] = []
var menuItems : [MenuItemView] = []
var menuItemWidths : [CGFloat] = []
public var menuHeight : CGFloat = 34.0
public var menuMargin : CGFloat = 15.0
public var menuItemWidth : CGFloat = 111.0
public var selectionIndicatorHeight : CGFloat = 3.0
var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0
public var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons
var startingMenuMargin : CGFloat = 0.0
var selectionIndicatorView : UIView = UIView()
var currentPageIndex : Int = 0
var lastPageIndex : Int = 0
public var selectionIndicatorColor : UIColor = UIColor.whiteColor()
public var selectedMenuItemLabelColor : UIColor = UIColor.whiteColor()
public var unselectedMenuItemLabelColor : UIColor = UIColor.lightGrayColor()
public var scrollMenuBackgroundColor : UIColor = UIColor.blackColor()
public var viewBackgroundColor : UIColor = UIColor.whiteColor()
public var bottomMenuHairlineColor : UIColor = UIColor.whiteColor()
public var menuItemSeparatorColor : UIColor = UIColor.lightGrayColor()
public var menuItemFont : UIFont = UIFont(name: "HelveticaNeue", size: 15.0)!
public var menuItemSeparatorPercentageHeight : CGFloat = 0.2
public var menuItemSeparatorWidth : CGFloat = 0.5
public var menuItemSeparatorRoundEdges : Bool = false
public var addBottomMenuHairline : Bool = true
public var menuItemWidthBasedOnTitleTextWidth : Bool = false
public var useMenuLikeSegmentedControl : Bool = false
public var centerMenuItems : Bool = false
public var enableHorizontalBounce : Bool = true
public var hideTopMenuBar : Bool = false
var currentOrientationIsPortrait : Bool = true
var pageIndexForOrientationChange : Int = 0
var didLayoutSubviewsAfterRotation : Bool = false
var didScrollAlready : Bool = false
var lastControllerScrollViewContentOffset : CGFloat = 0.0
var lastScrollDirection : CAPSPageMenuScrollDirection = .Other
var startingPageForScroll : Int = 0
var didTapMenuItemToScroll : Bool = false
var pagesAddedDictionary : [Int : Int] = [:]
public weak var delegate : CAPSPageMenuDelegate?
var tapTimer : NSTimer?
var enableControllerScrollViewScroll: Bool!
enum CAPSPageMenuScrollDirection : Int {
case Left
case Right
case Other
}
// MARK: - View life cycle
/**
Initialize PageMenu with view controllers
:param: viewControllers List of view controllers that must be subclasses of UIViewController
:param: frame Frame for page menu view
:param: options Dictionary holding any customization options user might want to set
*/
public init(viewControllers: [AnyObject], frame: CGRect, options: [String: AnyObject]?, enableControllerScrollViewScroll: Bool = true) {
super.init(nibName: nil, bundle: nil)
self.enableControllerScrollViewScroll = enableControllerScrollViewScroll
controllerArray = viewControllers
self.view.frame = frame
if options != nil {
for key : String in options!.keys {
if key == "selectionIndicatorHeight" {
selectionIndicatorHeight = options![key] as! CGFloat
} else if key == "menuItemSeparatorWidth" {
menuItemSeparatorWidth = options![key] as! CGFloat
} else if key == "scrollMenuBackgroundColor" {
scrollMenuBackgroundColor = options![key] as! UIColor
} else if key == "viewBackgroundColor" {
viewBackgroundColor = options![key] as! UIColor
} else if key == "bottomMenuHairlineColor" {
bottomMenuHairlineColor = options![key] as! UIColor
} else if key == "selectionIndicatorColor" {
selectionIndicatorColor = options![key] as! UIColor
} else if key == "menuItemSeparatorColor" {
menuItemSeparatorColor = options![key] as! UIColor
} else if key == "menuMargin" {
menuMargin = options![key] as! CGFloat
} else if key == "menuHeight" {
menuHeight = options![key] as! CGFloat
} else if key == "selectedMenuItemLabelColor" {
selectedMenuItemLabelColor = options![key] as! UIColor
} else if key == "unselectedMenuItemLabelColor" {
unselectedMenuItemLabelColor = options![key] as! UIColor
} else if key == "useMenuLikeSegmentedControl" {
useMenuLikeSegmentedControl = options![key] as! Bool
} else if key == "menuItemSeparatorRoundEdges" {
menuItemSeparatorRoundEdges = options![key] as! Bool
} else if key == "menuItemFont" {
menuItemFont = options![key] as! UIFont
} else if key == "menuItemSeparatorPercentageHeight" {
menuItemSeparatorPercentageHeight = options![key] as! CGFloat
} else if key == "menuItemWidth" {
menuItemWidth = options![key] as! CGFloat
} else if key == "enableHorizontalBounce" {
enableHorizontalBounce = options![key] as! Bool
} else if key == "addBottomMenuHairline" {
addBottomMenuHairline = options![key] as! Bool
} else if key == "menuItemWidthBasedOnTitleTextWidth" {
menuItemWidthBasedOnTitleTextWidth = options![key] as! Bool
} else if key == "scrollAnimationDurationOnMenuItemTap" {
scrollAnimationDurationOnMenuItemTap = options![key] as! Int
} else if key == "centerMenuItems" {
centerMenuItems = options![key] as! Bool
} else if key == "hideTopMenuBar" {
hideTopMenuBar = options![key] as! Bool
}
}
if hideTopMenuBar {
addBottomMenuHairline = false
menuHeight = 0.0
}
}
setUpUserInterface()
if menuScrollView.subviews.count == 0 {
configureUserInterface()
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - UI Setup
func setUpUserInterface() {
let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView]
// Set up controller scroll view
controllerScrollView.pagingEnabled = true
controllerScrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce
controllerScrollView.bounces = enableHorizontalBounce
controllerScrollView.frame = CGRectMake(0.0, menuHeight, self.view.frame.width, self.view.frame.height)
self.view.addSubview(controllerScrollView)
let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[controllerScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|[controllerScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(controllerScrollView_constraint_H)
self.view.addConstraints(controllerScrollView_constraint_V)
// Set up menu scroll view
menuScrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
menuScrollView.frame = CGRectMake(0.0, 0.0, self.view.frame.width, menuHeight)
self.view.addSubview(menuScrollView)
let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuScrollView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(menuScrollView_constraint_H)
self.view.addConstraints(menuScrollView_constraint_V)
// Add hairline to menu scroll view
if addBottomMenuHairline {
var menuBottomHairline : UIView = UIView()
menuBottomHairline.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(menuBottomHairline)
let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
self.view.addConstraints(menuBottomHairline_constraint_H)
self.view.addConstraints(menuBottomHairline_constraint_V)
menuBottomHairline.backgroundColor = bottomMenuHairlineColor
}
// Disable scroll bars
menuScrollView.showsHorizontalScrollIndicator = false
menuScrollView.showsVerticalScrollIndicator = false
controllerScrollView.showsHorizontalScrollIndicator = false
controllerScrollView.showsVerticalScrollIndicator = false
controllerScrollView.scrollEnabled = enableControllerScrollViewScroll
// Set background color behind scroll views and for menu scroll view
self.view.backgroundColor = viewBackgroundColor
menuScrollView.backgroundColor = scrollMenuBackgroundColor
}
func configureUserInterface() {
// Add tap gesture recognizer to controller scroll view to recognize menu item selection
let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleMenuItemTap:"))
menuItemTapGestureRecognizer.numberOfTapsRequired = 1
menuItemTapGestureRecognizer.numberOfTouchesRequired = 1
menuItemTapGestureRecognizer.delegate = self
menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer)
// Set delegate for controller scroll view
controllerScrollView.delegate = self
// When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top,
// but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top.
// If more than one scroll view is found, none will be scrolled.
// Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture.
menuScrollView.scrollsToTop = false;
controllerScrollView.scrollsToTop = false;
// Configure menu scroll view
if useMenuLikeSegmentedControl {
menuScrollView.scrollEnabled = false
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
menuMargin = 0.0
} else {
menuScrollView.contentSize = CGSizeMake((menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, menuHeight)
}
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), 0.0)
var index : CGFloat = 0.0
for controller in controllerArray {
if controller.isKindOfClass(UIViewController) {
if index == 0.0 {
// Add first two controllers to scrollview and as child view controller
(controller as! UIViewController).viewWillAppear(true)
addPageAtIndex(0)
(controller as! UIViewController).viewDidAppear(true)
}
// Set up menu item for menu scroll view
var menuItemFrame : CGRect = CGRect()
//add by qky
if useMenuLikeSegmentedControl && menuItemWidthBasedOnTitleTextWidth {
var controllerTitle : String? = (controller as! UIViewController).title
var titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
var itemWidthRect : CGRect = (titleText as NSString).boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
}
//add end
else if useMenuLikeSegmentedControl {
menuItemFrame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, menuItemWidth, menuHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
var controllerTitle : String? = (controller as! UIViewController).title
var titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
var itemWidthRect : CGRect = (titleText as NSString).boundingRectWithSize(CGSizeMake(1000, 1000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRectMake(totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), 0.0, menuItemWidth, menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
} else {
if centerMenuItems && index == 0.0 {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
menuItemFrame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
menuItemFrame = CGRectMake(menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
}
var menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame)
if useMenuLikeSegmentedControl {
menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
} else {
menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
}
// Configure menu item label font if font is set by user
menuItemView.titleLabel!.font = menuItemFont
menuItemView.titleLabel!.textAlignment = NSTextAlignment.Center
menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor
// Set title depending on if controller has a title set
if (controller as! UIViewController).title != nil {
menuItemView.titleLabel!.text = controller.title!
} else {
menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)"
}
// Add separator between menu items when using as segmented control
if useMenuLikeSegmentedControl {
if Int(index) < controllerArray.count - 1 {
menuItemView.menuItemSeparator!.hidden = false
}
}
// Add menu item view to menu scroll view
menuScrollView.addSubview(menuItemView)
menuItems.append(menuItemView)
index++
}
}
// Set new content size for menu scroll view if needed
if menuItemWidthBasedOnTitleTextWidth {
//removed by qky
// menuScrollView.contentSize = CGSizeMake((totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, menuHeight)
}
// Set selected color for title label of selected menu item
if menuItems.count > 0 {
if menuItems[currentPageIndex].titleLabel != nil {
menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor
}
}
// Configure selection indicator view
var selectionIndicatorFrame : CGRect = CGRect()
//add by qky
if useMenuLikeSegmentedControl && menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRectMake(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count) / 2 - menuItemWidths[0]/2, menuHeight - selectionIndicatorHeight - 10, menuItemWidths[0], selectionIndicatorHeight)
}
//add end
else if useMenuLikeSegmentedControl {
selectionIndicatorFrame = CGRectMake(0.0, menuHeight - selectionIndicatorHeight, self.view.frame.width / CGFloat(controllerArray.count), selectionIndicatorHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidths[0], selectionIndicatorHeight)
} else {
if centerMenuItems {
selectionIndicatorFrame = CGRectMake(startingMenuMargin + menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
} else {
selectionIndicatorFrame = CGRectMake(menuMargin, menuHeight - selectionIndicatorHeight, menuItemWidth, selectionIndicatorHeight)
}
}
selectionIndicatorView = UIView(frame: selectionIndicatorFrame)
selectionIndicatorView.backgroundColor = selectionIndicatorColor
menuScrollView.addSubview(selectionIndicatorView)
}
// MARK: - Scroll view delegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
if !didLayoutSubviewsAfterRotation {
if scrollView.isEqual(controllerScrollView) {
if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) {
if (currentOrientationIsPortrait && self.interfaceOrientation.isPortrait) || (!currentOrientationIsPortrait && self.interfaceOrientation.isLandscape) {
// Check if scroll direction changed
if !didTapMenuItemToScroll {
if didScrollAlready {
var newScrollDirection : CAPSPageMenuScrollDirection = .Other
if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) {
newScrollDirection = .Right
} else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) {
newScrollDirection = .Left
}
if newScrollDirection != .Other {
if lastScrollDirection != newScrollDirection {
var index : Int = newScrollDirection == .Left ? currentPageIndex + 1 : currentPageIndex - 1
if index >= 0 && index < controllerArray.count {
// Check dictionary if page was already added
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
}
lastScrollDirection = newScrollDirection
}
if !didScrollAlready {
if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) {
if currentPageIndex != controllerArray.count - 1 {
// Add page to the left of current page
var index : Int = currentPageIndex - 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Right
}
} else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) {
if currentPageIndex != 0 {
// Add page to the right of current page
var index : Int = currentPageIndex + 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .Left
}
}
didScrollAlready = true
}
lastControllerScrollViewContentOffset = scrollView.contentOffset.x
}
var ratio : CGFloat = 1.0
// Calculate ratio between scroll views
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
// Calculate current page
var width : CGFloat = controllerScrollView.frame.size.width;
var page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width)
// Update page if changed
if page != currentPageIndex {
lastPageIndex = currentPageIndex
currentPageIndex = page
if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 {
addPageAtIndex(page)
pagesAddedDictionary[page] = page
}
if !didTapMenuItemToScroll {
// Add last page to pages dictionary to make sure it gets removed after scrolling
if pagesAddedDictionary[lastPageIndex] != lastPageIndex {
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory
var indexLeftTwo : Int = page - 2
if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo {
pagesAddedDictionary.removeValueForKey(indexLeftTwo)
removePageAtIndex(indexLeftTwo)
}
var indexRightTwo : Int = page + 2
if pagesAddedDictionary[indexRightTwo] == indexRightTwo {
pagesAddedDictionary.removeValueForKey(indexRightTwo)
removePageAtIndex(indexRightTwo)
}
}
}
// Move selection indicator view when swiping
moveSelectionIndicator(page)
}
} else {
var ratio : CGFloat = 1.0
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
}
} else {
didLayoutSubviewsAfterRotation = false
// Move selection indicator view when swiping
moveSelectionIndicator(currentPageIndex)
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if scrollView.isEqual(controllerScrollView) {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[currentPageIndex] as! UIViewController
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
didScrollAlready = false
startingPageForScroll = currentPageIndex
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
}
func scrollViewDidEndTapScrollingAnimation() {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[currentPageIndex] as! UIViewController
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
startingPageForScroll = currentPageIndex
didTapMenuItemToScroll = false
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepCapacity: false)
}
// MARK: - Handle Selection Indicator
func moveSelectionIndicator(pageIndex: Int) {
if pageIndex >= 0 && pageIndex < controllerArray.count {
UIView.animateWithDuration(0.15, animations: { () -> Void in
var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width
var selectionIndicatorX : CGFloat = 0.0
//add by qky
if self.useMenuLikeSegmentedControl && self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) + (self.view.frame.width / CGFloat(self.controllerArray.count))/2 - self.menuItemWidths[pageIndex]/2
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
}
//add end
else if self.useMenuLikeSegmentedControl {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count)
} else if self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
selectionIndicatorX += self.menuMargin
if pageIndex > 0 {
for i in 0...(pageIndex - 1) {
selectionIndicatorX += (self.menuMargin + self.menuItemWidths[i])
}
}
} else {
if self.centerMenuItems && pageIndex == 0 {
selectionIndicatorX = self.startingMenuMargin + self.menuMargin
} else {
selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin
}
}
self.selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Switch newly selected menu item title label to selected color and old one to unselected color
if self.menuItems.count > 0 {
if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil {
self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor
self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor
}
}
})
}
}
// MARK: - Tap gesture recognizer selector
func handleMenuItemTap(gestureRecognizer : UITapGestureRecognizer) {
var tappedPoint : CGPoint = gestureRecognizer.locationInView(menuScrollView)
if tappedPoint.y < menuScrollView.frame.height {
// Calculate tapped page
var itemIndex : Int = 0
if useMenuLikeSegmentedControl {
itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count)))
} else if menuItemWidthBasedOnTitleTextWidth {
// Base case being first item
var menuItemLeftBound : CGFloat = 0.0
var menuItemRightBound : CGFloat = menuItemWidths[0] + menuMargin + (menuMargin / 2)
if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for i in 1...controllerArray.count - 1 {
menuItemLeftBound = menuItemRightBound + 1.0
menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = i
break
}
}
}
} else {
var rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth)
// Prevent moving to first item when tapping left to first item
if rawItemIndex < 0 {
itemIndex = -1
} else {
itemIndex = Int(rawItemIndex)
}
}
if itemIndex >= 0 && itemIndex < controllerArray.count {
// Update page if changed
if itemIndex != currentPageIndex {
startingPageForScroll = itemIndex
lastPageIndex = currentPageIndex
currentPageIndex = itemIndex
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
var smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
var largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for index in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
addPageAtIndex(itemIndex)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
var duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
var xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
if tapTimer != nil {
tapTimer!.invalidate()
}
var timerInterval : NSTimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001
tapTimer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "scrollViewDidEndTapScrollingAnimation", userInfo: nil, repeats: false)
}
}
}
// MARK: - Remove/Add Page
func addPageAtIndex(index : Int) {
// Call didMoveToPage delegate function
var currentController : UIViewController = controllerArray[index] as! UIViewController
delegate?.willMoveToPage?(currentController, index: index)
var newVC : UIViewController = controllerArray[index] as! UIViewController
newVC.willMoveToParentViewController(self)
newVC.view.frame = CGRectMake(self.view.frame.width * CGFloat(index), menuHeight, self.view.frame.width, self.view.frame.height - menuHeight)
self.addChildViewController(newVC)
self.controllerScrollView.addSubview(newVC.view)
newVC.didMoveToParentViewController(self)
}
func removePageAtIndex(index : Int) {
var oldVC : UIViewController = controllerArray[index] as! UIViewController
oldVC.willMoveToParentViewController(nil)
oldVC.view.removeFromSuperview()
oldVC.removeFromParentViewController()
oldVC.didMoveToParentViewController(nil)
}
// MARK: - Orientation Change
override public func viewDidLayoutSubviews() {
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSizeMake(self.view.frame.width * CGFloat(controllerArray.count), self.view.frame.height - menuHeight)
var oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait
currentOrientationIsPortrait = self.interfaceOrientation.isPortrait
if (oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.currentDevice().orientation.isPortrait) {
didLayoutSubviewsAfterRotation = true
//Resize menu items if using as segmented control
if useMenuLikeSegmentedControl {
menuScrollView.contentSize = CGSizeMake(self.view.frame.width, menuHeight)
// Resize selectionIndicator bar
var selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
var selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count)
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, selectionIndicatorWidth, self.selectionIndicatorView.frame.height)
// Resize menu items
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
item.frame = CGRectMake(self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.titleLabel!.frame = CGRectMake(0.0, 0.0, self.view.frame.width / CGFloat(controllerArray.count), menuHeight)
item.menuItemSeparator!.frame = CGRectMake(item.frame.width - (menuItemSeparatorWidth / 2), item.menuItemSeparator!.frame.origin.y, item.menuItemSeparator!.frame.width, item.menuItemSeparator!.frame.height)
index++
}
} else if centerMenuItems {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
var selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin
selectionIndicatorView.frame = CGRectMake(selectionIndicatorX, self.selectionIndicatorView.frame.origin.y, self.selectionIndicatorView.frame.width, self.selectionIndicatorView.frame.height)
// Recalculate frame for menu items if centered
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
if index == 0 {
item.frame = CGRectMake(startingMenuMargin + menuMargin, 0.0, menuItemWidth, menuHeight)
} else {
item.frame = CGRectMake(menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, 0.0, menuItemWidth, menuHeight)
}
index++
}
}
for view : UIView in controllerScrollView.subviews as! [UIView] {
view.frame = CGRectMake(self.view.frame.width * CGFloat(currentPageIndex), menuHeight, controllerScrollView.frame.width, self.view.frame.height - menuHeight)
}
var xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width
controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false)
var ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
// Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout
// still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation
// needs to send -layoutSubviews to the view to invoke auto layout.'"
//
// http://stackoverflow.com/questions/15490140/auto-layout-error
//
// Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead.
self.view.layoutIfNeeded()
}
// MARK: - Move to page index
/**
Move to page at index
:param: index Index of the page to move to
*/
public func moveToPage(index: Int) {
if index >= 0 && index < controllerArray.count {
// Update page if changed
if index != currentPageIndex {
startingPageForScroll = index
lastPageIndex = currentPageIndex
currentPageIndex = index
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
var smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
var largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for i in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[i] != i {
addPageAtIndex(i)
pagesAddedDictionary[i] = i
}
}
}
addPageAtIndex(index)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
var duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animateWithDuration(duration, animations: { () -> Void in
var xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
}
}
}
| 3ae8951bf9a91632c83c9dec049be29e | 53.048835 | 392 | 0.588833 | false | false | false | false |
massimoksi/Gaston | refs/heads/master | Source/UIFont.swift | mit | 1 | // Copyright (c) 2016 Massimo Peri (@massimoksi)
//
// 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
public extension UIFont {
/**
A version of the font with monospaced numbers.
*/
public var monospacedDigitFont: UIFont {
if #available(iOS 9, *) {
let oldFontDescriptor = fontDescriptor()
let newFontDescriptor = oldFontDescriptor.monospacedDigitFontDescriptor
return UIFont(descriptor: newFontDescriptor, size: 0.0)
} else {
return self
}
}
}
// MARK: -
private extension UIFontDescriptor {
var monospacedDigitFontDescriptor: UIFontDescriptor {
let fontDescriptorFeatures = [
[
UIFontFeatureTypeIdentifierKey: kNumberSpacingType,
UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
]
]
let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatures]
let fontDescriptor = self.fontDescriptorByAddingAttributes(fontDescriptorAttributes)
return fontDescriptor
}
}
| 9c4a1f39c19535e0a8d8703020913a3e | 36.719298 | 105 | 0.717209 | false | false | false | false |
ztmdsbt/tw-ios-training | refs/heads/master | storyboard-and-autolayout/json-data/json-data/AppDelegate.swift | gpl-2.0 | 1 | //
// AppDelegate.swift
// json-data
//
// Created by Kaihang An on 6/23/15.
// Copyright (c) 2015 Thoughtworks. inc. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| d0bac98d87cf4ecea47b91048fe518f9 | 52.190476 | 285 | 0.750224 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | refs/heads/master | Pods/Former/Former/Cells/FormTextViewCell.swift | mit | 1 | //
// FormTextViewCell.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/28/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public class FormTextViewCell: FormCell, TextViewFormableRow {
// MARK: Public
public private(set) weak var textView: UITextView!
public private(set) weak var titleLabel: UILabel!
public func formTextView() -> UITextView {
return textView
}
public func formTitleLabel() -> UILabel? {
return titleLabel
}
public override func updateWithRowFormer(rowFormer: RowFormer) {
super.updateWithRowFormer(rowFormer)
leftConst.constant = titleLabel.text?.isEmpty ?? true ? 5 : 15
}
public override func setup() {
super.setup()
let titleLabel = UILabel()
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(titleLabel, atIndex: 0)
self.titleLabel = titleLabel
let textView = UITextView()
textView.backgroundColor = .clearColor()
textView.font = .systemFontOfSize(17)
textView.translatesAutoresizingMaskIntoConstraints = false
contentView.insertSubview(textView, atIndex: 0)
self.textView = textView
let constraints = [
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-10-[label(>=0)]",
options: [],
metrics: nil,
views: ["label": titleLabel]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[text]-0-|",
options: [],
metrics: nil,
views: ["text": textView]
),
NSLayoutConstraint.constraintsWithVisualFormat(
"H:[label]-5-[text]-10-|",
options: [],
metrics: nil,
views: ["label": titleLabel, "text": textView]
)
].flatMap { $0 }
let leftConst = NSLayoutConstraint(
item: titleLabel,
attribute: .Leading,
relatedBy: .Equal,
toItem: contentView,
attribute: .Leading,
multiplier: 1,
constant: 15
)
contentView.addConstraints(constraints + [leftConst])
self.leftConst = leftConst
}
// MARK: Private
private weak var leftConst: NSLayoutConstraint!
private weak var rightConst: NSLayoutConstraint!
} | 927b3717e110222211e37452b9873b81 | 29.988095 | 71 | 0.57648 | false | false | false | false |
crazypoo/PTools | refs/heads/master | Pods/FluentDarkModeKit/Sources/FluentDarkModeKit/Extensions/UITextField+DarkModeKit.swift | mit | 1 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
extension UITextField {
override open func dmTraitCollectionDidChange(_ previousTraitCollection: DMTraitCollection?) {
super.dmTraitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
return
}
else {
dm_updateDynamicColors()
if let dynamicTextColor = textColor?.copy() as? DynamicColor {
textColor = dynamicTextColor
}
keyboardAppearance = {
if DMTraitCollection.override.userInterfaceStyle == .dark {
return .dark
}
else {
return .default
}
}()
}
}
}
extension UITextField {
/// `UITextField` will not call `super.willMove(toWindow:)` in its implementation, so we need to swizzle it separately.
static let swizzleTextFieldWillMoveToWindowOnce: Void = {
let selector = #selector(willMove(toWindow:))
guard let method = class_getInstanceMethod(UITextField.self, selector) else {
assertionFailure(DarkModeManager.messageForSwizzlingFailed(class: UITextField.self, selector: selector))
return
}
let imp = method_getImplementation(method)
class_replaceMethod(UITextField.self, selector, imp_implementationWithBlock({ (self: UITextField, window: UIWindow?) -> Void in
let oldIMP = unsafeBitCast(imp, to: (@convention(c) (UITextField, Selector, UIWindow?) -> Void).self)
oldIMP(self, selector, window)
self.dmTraitCollectionDidChange(nil)
} as @convention(block) (UITextField, UIWindow?) -> Void), method_getTypeEncoding(method))
}()
}
| 62722e4cc087c7630ab185001e084006 | 32.530612 | 131 | 0.690201 | false | false | false | false |
nissivm/DemoShop | refs/heads/master | Demo Shop/Objects/Device.swift | mit | 2 | //
// Device.swift
// Demo Shop
//
// Created by Nissi Vieira Miranda on 1/13/16.
// Copyright © 2016 Nissi Vieira Miranda. All rights reserved.
//
import Foundation
class Device
{
static var IS_IPHONE: Bool {
get {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone
{
return true
}
else
{
return false
}
}
}
static var IS_IPHONE_4: Bool {
get {
if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 480.0
{
return true
}
else
{
return false
}
}
}
static var IS_IPHONE_5: Bool {
get {
if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 568.0
{
return true
}
else
{
return false
}
}
}
static var IS_IPHONE_6: Bool {
get {
if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 667.0
{
return true
}
else
{
return false
}
}
}
static var IS_IPHONE_6_PLUS: Bool {
get {
if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 736.0
{
return true
}
else
{
return false
}
}
}
} | bcd031b28a3da5bf01ba384d502beadf | 19.363636 | 77 | 0.395022 | false | false | false | false |
jopamer/swift | refs/heads/master | test/IRGen/class_field_other_module.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/other_class.swiftmodule %S/Inputs/other_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -O %s | %FileCheck %s -DINT=i%target-ptrsize
import other_class
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$S24class_field_other_module12getSubclassXys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly)
// CHECK-NEXT: entry:
// CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 1, i32 0
// CHECK-NEXT: %1 = load i32, i32* %._value
// CHECK-NEXT: ret i32 %1
public func getSubclassX(_ o: Subclass) -> Int32 {
return o.x
}
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$S24class_field_other_module12getSubclassYys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly)
// CHECK-NEXT: entry:
// CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 2, i32 0
// CHECK-NEXT: %1 = load i32, i32* %._value
// CHECK-NEXT: ret i32 %1
public func getSubclassY(_ o: Subclass) -> Int32 {
return o.y
}
| 5620101d071e5b5a2e472a501fb07a4b | 49.083333 | 181 | 0.708819 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/MarkRule.swift | mit | 1 | import Foundation
import SourceKittenFramework
private let nonSpace = "[^ ]"
private let twoOrMoreSpace = " {2,}"
private let mark = "MARK:"
private let nonSpaceOrTwoOrMoreSpace = "(?:\(nonSpace)|\(twoOrMoreSpace))"
private let nonSpaceOrTwoOrMoreSpaceOrNewline = "(?:[^ \n]|\(twoOrMoreSpace))"
public struct MarkRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "mark",
name: "Mark",
description: "MARK comment should be in valid format. e.g. '// MARK: ...' or '// MARK: - ...'",
kind: .lint,
nonTriggeringExamples: [
"// MARK: good\n",
"// MARK: - good\n",
"// MARK: -\n",
"// BOOKMARK",
"//BOOKMARK",
"// BOOKMARKS"
],
triggeringExamples: [
"↓//MARK: bad",
"↓// MARK:bad",
"↓//MARK:bad",
"↓// MARK: bad",
"↓// MARK: bad",
"↓// MARK: -bad",
"↓// MARK:- bad",
"↓// MARK:-bad",
"↓//MARK: - bad",
"↓//MARK:- bad",
"↓//MARK: -bad",
"↓//MARK:-bad",
"↓//Mark: bad",
"↓// Mark: bad",
"↓// MARK bad",
"↓//MARK bad",
"↓// MARK - bad",
issue1029Example
],
corrections: [
"↓//MARK: comment": "// MARK: comment",
"↓// MARK: comment": "// MARK: comment",
"↓// MARK:comment": "// MARK: comment",
"↓// MARK: comment": "// MARK: comment",
"↓//MARK: - comment": "// MARK: - comment",
"↓// MARK:- comment": "// MARK: - comment",
"↓// MARK: -comment": "// MARK: - comment",
issue1029Example: issue1029Correction
]
)
private let spaceStartPattern = "(?:\(nonSpaceOrTwoOrMoreSpace)\(mark))"
private let endNonSpacePattern = "(?:\(mark)\(nonSpace))"
private let endTwoOrMoreSpacePattern = "(?:\(mark)\(twoOrMoreSpace))"
private let invalidEndSpacesPattern = "(?:\(mark)\(nonSpaceOrTwoOrMoreSpace))"
private let twoOrMoreSpacesAfterHyphenPattern = "(?:\(mark) -\(twoOrMoreSpace))"
private let nonSpaceOrNewlineAfterHyphenPattern = "(?:\(mark) -[^ \n])"
private let invalidSpacesAfterHyphenPattern = "(?:\(mark) -\(nonSpaceOrTwoOrMoreSpaceOrNewline))"
private let invalidLowercasePattern = "(?:// ?[Mm]ark:)"
private let missingColonPattern = "(?:// ?MARK[^:])"
private var pattern: String {
return [
spaceStartPattern,
invalidEndSpacesPattern,
invalidSpacesAfterHyphenPattern,
invalidLowercasePattern,
missingColonPattern
].joined(separator: "|")
}
public func validate(file: File) -> [StyleViolation] {
return violationRanges(in: file, matching: pattern).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
var result = [Correction]()
result.append(contentsOf: correct(file: file,
pattern: spaceStartPattern,
replaceString: "// MARK:"))
result.append(contentsOf: correct(file: file,
pattern: endNonSpacePattern,
replaceString: "// MARK: ",
keepLastChar: true))
result.append(contentsOf: correct(file: file,
pattern: endTwoOrMoreSpacePattern,
replaceString: "// MARK: "))
result.append(contentsOf: correct(file: file,
pattern: twoOrMoreSpacesAfterHyphenPattern,
replaceString: "// MARK: - "))
result.append(contentsOf: correct(file: file,
pattern: nonSpaceOrNewlineAfterHyphenPattern,
replaceString: "// MARK: - ",
keepLastChar: true))
return result.unique
}
private func correct(file: File,
pattern: String,
replaceString: String,
keepLastChar: Bool = false) -> [Correction] {
let violations = violationRanges(in: file, matching: pattern)
let matches = file.ruleEnabled(violatingRanges: violations, for: self)
if matches.isEmpty { return [] }
var nsstring = file.contents.bridge()
let description = type(of: self).description
var corrections = [Correction]()
for var range in matches.reversed() {
if keepLastChar {
range.length -= 1
}
let location = Location(file: file, characterOffset: range.location)
nsstring = nsstring.replacingCharacters(in: range, with: replaceString).bridge()
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(nsstring.bridge())
return corrections
}
private func violationRanges(in file: File, matching pattern: String) -> [NSRange] {
let nsstring = file.contents.bridge()
return file.rangesAndTokens(matching: pattern).filter { _, syntaxTokens in
return !syntaxTokens.isEmpty && SyntaxKind(rawValue: syntaxTokens[0].type) == .comment
}.compactMap { range, syntaxTokens in
let identifierRange = nsstring
.byteRangeToNSRange(start: syntaxTokens[0].offset, length: 0)
return identifierRange.map { NSUnionRange($0, range) }
}
}
}
private let issue1029Example = "↓//MARK:- Top-Level bad mark\n" +
"↓//MARK:- Another bad mark\n" +
"struct MarkTest {}\n" +
"↓// MARK:- Bad mark\n" +
"extension MarkTest {}\n"
private let issue1029Correction = "// MARK: - Top-Level bad mark\n" +
"// MARK: - Another bad mark\n" +
"struct MarkTest {}\n" +
"// MARK: - Bad mark\n" +
"extension MarkTest {}\n"
| 4e9d7c84e509407640ed71672abb8ccc | 38.940476 | 103 | 0.512072 | false | false | false | false |
achiwhane/ReadHN | refs/heads/master | ReadHN/AskHNStoriesTableViewController.swift | mit | 1 | //
// AskHNStoriesTableViewController.swift
// ReadHN
//
// Created by Akshay Chiwhane on 8/8/15.
// Copyright (c) 2015 Akshay Chiwhane. All rights reserved.
//
import UIKit
class AskHNStoriesTableViewContoller: StoriesTableViewController{
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
private func updateUI() {
super.categoryUrl = "https://hacker-news.firebaseio.com/v0/askstories.json"
super.brain.delegate = self
super.refresh()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "View AskHN Content":
if let wvc = segue.destinationViewController as? WebViewController {
if let cell = sender as? UITableViewCell {
wvc.pageTitle = cell.textLabel?.text
if let cellIndexPath = self.tableView.indexPathForCell(cell) {
let data = Submission.loadSaved(storyTableCellData[cellIndexPath.row] ?? 0)
wvc.pageUrl = data?.url
print(wvc.pageUrl)
}
}
}
default: break
}
}
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("View AskHN Content", sender: self)
}
}
| d3d55b1924c13aed4dc8b9d957cecf49 | 31.489796 | 118 | 0.584799 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK | refs/heads/master | OpenTimeSDK/Classes/OTAPIRawResponse.swift | mit | 1 | //
// APIRawResponse.swift
// OpenTime
//
// Created by Josh Woodcock on 5/10/15.
// Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved.
//
public class OTAPIRawResponse {
// Whether or not the request logically succeeded or logically failed.
// @SerializedName("success")
private var _success: Bool;
// The message associated with the success or failed response.
// @SerializedName("message")
private var _message: String;
// String representation of data object.
// @SerializedName("data")
private var _rawData: AnyObject?;
/**
Designated constructor.
*/
public init() {
self._success = false;
self._message = "Error: Message not parsed from server response";
}
/**
Gets the success or failure from the response body from the server.
- returns: Whether or not the request to the server succeeded.
*/
public func isSuccessful() -> Bool {
return self._success;
}
/**
Gets the message about why the response failed or succeeded.
- returns: A message explaining why the request to the server failed or succeeded.
*/
public func getMessage() -> String {
return self._message;
}
/**
Gets a parsed object usually a dictionairy or an array.
- returns: nil, an array of dictionaries, or a dictionary with data in it.
*/
public func getRawData() -> AnyObject? {
return self._rawData;
}
/**
Tries to parse data elements from the first level of JSON elements.
- parameter responseObject: The object given by AFNetworking by parsing a JSON string.
- returns: A raw response object with the values of the first level of the JSON object.
*/
public static func deserialize(_ responseObject: AnyObject!) -> OTAPIRawResponse {
// Setup the raw response object.
let rawResponse: OTAPIRawResponse = OTAPIRawResponse();
if(responseObject != nil)
{
// Try to get the success from the response object.
if(OTSerialHelper.keyExists(responseObject, key: "success") == true) {
rawResponse._success = responseObject.object(forKey: "success") as! Bool;
}
// Try to get the message from the response object.
if(OTSerialHelper.keyExists(responseObject, key: "message") == true) {
rawResponse._message = responseObject.object(forKey: "message") as! String;
}
// Try to get the data from the response object.
if (rawResponse._success == true && OTSerialHelper.keyExists(responseObject, key: "data") == true) {
rawResponse._rawData = self._getData(responseObject);
}
}
if(responseObject != nil && rawResponse._success == false) {
// Print the response object.
print(responseObject, terminator: "");
}
return rawResponse;
}
/**
Gets the data element from the response object.
- returns: The data element of the response object.
*/
private static func _getData(_ responseObject: AnyObject) -> AnyObject!
{
// Try to get the data object.
let data: AnyObject! = responseObject["data"]! as AnyObject!;
// Set data property of the OTAPIResponse as a typed object.
if(data is NSDictionary)
{
// Its a dictionary. Cast it as a dictionary.
return data as! NSDictionary;
}else if(data is NSArray){
// Its an array. Cast it as an array.
return data as! NSArray;
}else{
// Its either empty or something besides an array or dictionary.
return data;
}
}
}
| db58042066c9a44846d34e85a776981f | 31.841667 | 112 | 0.587922 | false | false | false | false |
huonw/swift | refs/heads/master | test/SILGen/enum_resilience.swift | apache-2.0 | 3 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-emit-silgen -module-name enum_resilience -I %t -enable-sil-ownership -enable-resilience %s | %FileCheck %s
import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden @$S15enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]
// CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: destroy_value [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick Medium.Type, [[BOX]] : $*Medium
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$Ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<Medium>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NOT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(_ m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
// CHECK-LABEL: sil hidden @$S15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchDefault(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.Int2048, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.Int2048, 1
case .Canvas: return 1
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.Int2048, -1
default: return -1
}
} // CHECK: end sil function '$S15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF'
// CHECK-LABEL: sil hidden @$S15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchUnknownCase(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.Int2048, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.Int2048, 1
case .Canvas: return 1
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.Int2048, -1
@unknown case _: return -1
}
} // CHECK: end sil function '$S15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF'
// CHECK-LABEL: sil hidden @$S15enum_resilience36resilientSwitchUnknownCaseExhaustiveys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchUnknownCaseExhaustive(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], case #Medium.Pamphlet!enumelt.1: [[PAMPHLET:[^ ]+]], case #Medium.Postcard!enumelt.1: [[POSTCARD:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.Int2048, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.Int2048, 1
case .Canvas: return 1
// CHECK: [[PAMPHLET]]:
// CHECK: integer_literal $Builtin.Int2048, 2
case .Pamphlet: return 2
// CHECK: [[POSTCARD]]:
// CHECK: integer_literal $Builtin.Int2048, 3
case .Postcard: return 3
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.Int2048, -1
@unknown case _: return -1
}
}
// Indirect enums are still address-only, because the discriminator is stored
// as part of the value, so we cannot resiliently make assumptions about the
// enum's size
// CHECK-LABEL: sil hidden @$S15enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in_guaranteed IndirectApproach) -> ()
func indirectResilientEnum(_ ia: IndirectApproach) {}
public enum MyResilientEnum {
case kevin
case loki
}
// CHECK-LABEL: sil @$S15enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> ()
// CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 //
// CHECK: return
public func resilientSwitch(_ e: MyResilientEnum) {
switch e {
case .kevin: ()
case .loki: ()
}
}
// Inlinable functions must lower the switch as if it came from outside the module
// CHECK-LABEL: sil [serialized] @$S15enum_resilience15inlinableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> ()
// CHECK: switch_enum_addr %2 : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3
// CHECK: return
@inlinable public func inlinableSwitch(_ e: MyResilientEnum) {
switch e {
case .kevin: ()
case .loki: ()
}
}
| d39b7d99480c77f2e94a4db23ccc243e | 44.964286 | 267 | 0.67568 | false | false | false | false |
deyton/swift | refs/heads/master | test/SILGen/dynamic.swift | apache-2.0 | 4 | // RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify
// REQUIRES: objc_interop
import Foundation
import gizmo
class Foo: Proto {
// Not objc or dynamic, so only a vtable entry
init(native: Int) {}
func nativeMethod() {}
var nativeProp: Int = 0
subscript(native native: Int) -> Int {
get { return native }
set {}
}
// @objc, so it has an ObjC entry point but can also be dispatched
// by vtable
@objc init(objc: Int) {}
@objc func objcMethod() {}
@objc var objcProp: Int = 0
@objc subscript(objc objc: AnyObject) -> Int {
get { return 0 }
set {}
}
// dynamic, so it has only an ObjC entry point
dynamic init(dynamic: Int) {}
dynamic func dynamicMethod() {}
dynamic var dynamicProp: Int = 0
dynamic subscript(dynamic dynamic: Int) -> Int {
get { return dynamic }
set {}
}
func overriddenByDynamic() {}
@NSManaged var managedProp: Int
}
protocol Proto {
func nativeMethod()
var nativeProp: Int { get set }
subscript(native native: Int) -> Int { get set }
func objcMethod()
var objcProp: Int { get set }
subscript(objc objc: AnyObject) -> Int { get set }
func dynamicMethod()
var dynamicProp: Int { get set }
subscript(dynamic dynamic: Int) -> Int { get set }
}
// ObjC entry points for @objc and dynamic entry points
// normal and @objc initializing ctors can be statically dispatched
// CHECK-LABEL: sil hidden @_T07dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @_T07dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden @_T07dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @_T07dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSifgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC8objcPropSifsTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptSiyXl4objc_tcfgTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptSiyXl4objc_tcfsTo
// TODO: dynamic initializing ctor must be objc dispatched
// CHECK-LABEL: sil hidden @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign :
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSifgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T07dynamic3FooC0A4PropSifsTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfgTo
// CHECK-LABEL: sil hidden [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfsTo
// Protocol witnesses use best appropriate dispatch
// Native witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP12nativeMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10nativePropSifgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10nativePropSifsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2i6native_tcfgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2i6native_tcfsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// @objc witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP10objcMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP8objcPropSifgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP8objcPropSifsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptSiyXl4objc_tcfgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptSiyXl4objc_tcfsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// Dynamic witnesses use objc dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A6Method{{[_0-9a-zA-Z]*}}FTW
// CHECK: function_ref @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A4PropSifgTW
// CHECK: function_ref @_T07dynamic3FooC0A4PropSifgTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A4PropSifgTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP0A4PropSifsTW
// CHECK: function_ref @_T07dynamic3FooC0A4PropSifsTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC0A4PropSifsTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2iAA_tcfgTW
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2iAA_tcfgTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfgTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @_T07dynamic3FooCAA5ProtoA2aDP9subscriptS2iAA_tcfsTW
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2iAA_tcfsTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T07dynamic3FooC9subscriptS2iAA_tcfsTD
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign :
// Superclass dispatch
class Subclass: Foo {
// Native and objc methods can directly reference super members
override init(native: Int) {
super.init(native: native)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
override func nativeMethod() {
super.nativeMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC12nativeMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T07dynamic3FooC12nativeMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var nativeProp: Int {
get { return super.nativeProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10nativePropSifg
// CHECK: function_ref @_T07dynamic3FooC10nativePropSifg : $@convention(method) (@guaranteed Foo) -> Int
set { super.nativeProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10nativePropSifs
// CHECK: function_ref @_T07dynamic3FooC10nativePropSifs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(native native: Int) -> Int {
get { return super[native: native] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2i6native_tcfg
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2i6native_tcfg : $@convention(method) (Int, @guaranteed Foo) -> Int
set { super[native: native] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2i6native_tcfs
// CHECK: function_ref @_T07dynamic3FooC9subscriptS2i6native_tcfs : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
}
override init(objc: Int) {
super.init(objc: objc)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassCACSi4objc_tcfc
// CHECK: function_ref @_T07dynamic3FooCACSi4objc_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
override func objcMethod() {
super.objcMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC10objcMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @_T07dynamic3FooC10objcMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var objcProp: Int {
get { return super.objcProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC8objcPropSifg
// CHECK: function_ref @_T07dynamic3FooC8objcPropSifg : $@convention(method) (@guaranteed Foo) -> Int
set { super.objcProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC8objcPropSifs
// CHECK: function_ref @_T07dynamic3FooC8objcPropSifs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(objc objc: AnyObject) -> Int {
get { return super[objc: objc] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptSiyXl4objc_tcfg
// CHECK: function_ref @_T07dynamic3FooC9subscriptSiyXl4objc_tcfg : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int
set { super[objc: objc] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptSiyXl4objc_tcfs
// CHECK: function_ref @_T07dynamic3FooC9subscriptSiyXl4objc_tcfs : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
}
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign :
override func dynamicMethod() {
super.dynamicMethod()
}
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A6Method{{[_0-9a-zA-Z]*}}F
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign :
override var dynamicProp: Int {
get { return super.dynamicProp }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A4PropSifg
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign :
set { super.dynamicProp = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC0A4PropSifs
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign :
}
override subscript(dynamic dynamic: Int) -> Int {
get { return super[dynamic: dynamic] }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2iAA_tcfg
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign :
set { super[dynamic: dynamic] = newValue }
// CHECK-LABEL: sil hidden @_T07dynamic8SubclassC9subscriptS2iAA_tcfs
// CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign :
}
dynamic override func overriddenByDynamic() {}
}
class SubclassWithInheritedInits: Foo {
// CHECK-LABEL: sil hidden @_T07dynamic26SubclassWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $SubclassWithInheritedInits, #Foo.init!initializer.1.foreign :
}
class GrandchildWithInheritedInits: SubclassWithInheritedInits {
// CHECK-LABEL: sil hidden @_T07dynamic28GrandchildWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $GrandchildWithInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
class GrandchildOfInheritedInits: SubclassWithInheritedInits {
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @_T07dynamic26GrandchildOfInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: super_method [volatile] {{%.*}} : $GrandchildOfInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
// CHECK-LABEL: sil hidden @_T07dynamic20nativeMethodDispatchyyF : $@convention(thin) () -> ()
func nativeMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(native: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic18objcMethodDispatchyyF : $@convention(thin) () -> ()
func objcMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(objc: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[objc: 0 as NSNumber]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[objc: 0 as NSNumber] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic0A14MethodDispatchyyF : $@convention(thin) () -> ()
func dynamicMethodDispatch() {
// CHECK: function_ref @_T07dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic15managedDispatchyAA3FooCF
func managedDispatch(_ c: Foo) {
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_T07dynamic21foreignMethodDispatchyyF
func foreignMethodDispatch() {
// CHECK: function_ref @_T0So9GuisemeauC{{[_0-9a-zA-Z]*}}fC
let g = Guisemeau()!
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign
g.frob()
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign
let x = g.count
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign
g.count = x
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign
let y: Any! = g[0]
// CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign
g[0] = y
// CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign
_ = g.description
}
extension Gizmo {
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fc
// CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign
convenience init(convenienceInExtension: Int) {
self.init(bellsOn: convenienceInExtension)
}
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassFactory x: Int) {
self.init(stuff: x)
}
// CHECK-LABEL: sil hidden @_T0So5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassExactFactory x: Int) {
self.init(exactlyStuff: x)
}
@objc func foreignObjCExtension() { }
dynamic func foreignDynamicExtension() { }
}
// CHECK-LABEL: sil hidden @_T07dynamic24foreignExtensionDispatchySo5GizmoCF
// CHECK: bb0([[ARG:%.*]] : $Gizmo):
func foreignExtensionDispatch(_ g: Gizmo) {
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo)
g.foreignObjCExtension()
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [volatile] [[BORROWED_ARG]] : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign
g.foreignDynamicExtension()
}
// CHECK-LABEL: sil hidden @_T07dynamic33nativeMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func nativeMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(native: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic31objcMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func objcMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(objc: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[objc: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[objc: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic0A27MethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func dynamicMethodDispatchFromOtherFile() {
// CHECK: function_ref @_T07dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(dynamic: 0)
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @_T07dynamic28managedDispatchFromOtherFileyAA0deF0CF
func managedDispatchFromOtherFile(_ c: FromOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @_T07dynamic0A16ExtensionMethodsyAA13ObjCOtherFileCF
func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign
obj.extensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign
_ = obj.extensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).extensionClassProp
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign
obj.dynExtensionMethod()
// CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign
_ = obj.dynExtensionProp
// CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign
// CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
_ = type(of: obj).dynExtensionClassProp
}
public class Base {
dynamic var x: Bool { return false }
}
public class Sub : Base {
// CHECK-LABEL: sil hidden @_T07dynamic3SubC1xSbfg : $@convention(method) (@guaranteed Sub) -> Bool {
// CHECK: bb0([[SELF:%.*]] : $Sub):
// CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_T07dynamic3SubC1xSbfgSbyKXKfu_ : $@convention(thin) (@owned Sub) -> (Bool, @error Error)
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: = partial_apply [[AUTOCLOSURE]]([[SELF_COPY]])
// CHECK: return {{%.*}} : $Bool
// CHECK: } // end sil function '_T07dynamic3SubC1xSbfg'
// CHECK-LABEL: sil private [transparent] @_T07dynamic3SubC1xSbfgSbyKXKfu_ : $@convention(thin) (@owned Sub) -> (Bool, @error Error) {
// CHECK: bb0([[VALUE:%.*]] : $Sub):
// CHECK: [[BORROWED_VALUE:%.*]] = begin_borrow [[VALUE]]
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[BORROWED_VALUE]]
// CHECK: [[CASTED_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]]
// CHECK: [[BORROWED_CASTED_VALUE_COPY:%.*]] = begin_borrow [[CASTED_VALUE_COPY]]
// CHECK: [[DOWNCAST_FOR_SUPERMETHOD:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_VALUE_COPY]]
// CHECK: [[SUPER:%.*]] = super_method [volatile] [[DOWNCAST_FOR_SUPERMETHOD]] : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool, $@convention(objc_method) (Base) -> ObjCBool
// CHECK: end_borrow [[BORROWED_CASTED_VALUE_COPY]] from [[CASTED_VALUE_COPY]]
// CHECK: = apply [[SUPER]]([[CASTED_VALUE_COPY]])
// CHECK: destroy_value [[VALUE_COPY]]
// CHECK: end_borrow [[BORROWED_VALUE]] from [[VALUE]]
// CHECK: destroy_value [[VALUE]]
// CHECK: } // end sil function '_T07dynamic3SubC1xSbfgSbyKXKfu_'
override var x: Bool { return false || super.x }
}
public class BaseExt : NSObject {}
extension BaseExt {
@objc public var count: Int {
return 0
}
}
public class SubExt : BaseExt {
public override var count: Int {
return 1
}
}
public class GenericBase<T> {
public func method(_: T) {}
}
public class ConcreteDerived : GenericBase<Int> {
public override dynamic func method(_: Int) {}
}
// The dynamic override has a different calling convention than the base,
// so after re-abstracting the signature we must dispatch to the dynamic
// thunk.
// CHECK-LABEL: sil private @_T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV : $@convention(method) (@in Int, @guaranteed ConcreteDerived) -> ()
// CHECK: bb0(%0 : $*Int, %1 : $ConcreteDerived):
// CHECK-NEXT: [[VALUE:%.*]] = load [trivial] %0 : $*Int
// CHECK: [[DYNAMIC_THUNK:%.*]] = function_ref @_T07dynamic15ConcreteDerivedC6methodySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK-NEXT: apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK: return
// Vtable contains entries for native and @objc methods, but not dynamic ones
// CHECK-LABEL: sil_vtable Foo {
// CHECK-NEXT: #Foo.init!initializer.1: {{.*}} : _T07dynamic3FooCACSi6native_tcfc
// CHECK-NEXT: #Foo.nativeMethod!1: {{.*}} : _T07dynamic3FooC12nativeMethodyyF
// CHECK-NEXT: #Foo.nativeProp!getter.1: {{.*}} : _T07dynamic3FooC10nativePropSifg // dynamic.Foo.nativeProp.getter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!setter.1: {{.*}} : _T07dynamic3FooC10nativePropSifs // dynamic.Foo.nativeProp.setter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!materializeForSet.1
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooC9subscriptS2i6native_tcfg // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooC9subscriptS2i6native_tcfs // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!materializeForSet.1
// CHECK-NEXT: #Foo.init!initializer.1: {{.*}} : _T07dynamic3FooCACSi4objc_tcfc
// CHECK-NEXT: #Foo.objcMethod!1: {{.*}} : _T07dynamic3FooC10objcMethodyyF
// CHECK-NEXT: #Foo.objcProp!getter.1: {{.*}} : _T07dynamic3FooC8objcPropSifg // dynamic.Foo.objcProp.getter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!setter.1: {{.*}} : _T07dynamic3FooC8objcPropSifs // dynamic.Foo.objcProp.setter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!materializeForSet.1
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : _T07dynamic3FooC9subscriptSiyXl4objc_tcfg // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : _T07dynamic3FooC9subscriptSiyXl4objc_tcfs // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!materializeForSet
// CHECK-NEXT: #Foo.overriddenByDynamic!1: {{.*}} : _T07dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}}
// CHECK-NEXT: #Foo.deinit!deallocator: {{.*}}
// CHECK-NEXT: }
// Vtable uses a dynamic thunk for dynamic overrides
// CHECK-LABEL: sil_vtable Subclass {
// CHECK: #Foo.overriddenByDynamic!1: {{.*}} : public _T07dynamic8SubclassC19overriddenByDynamic{{[_0-9a-zA-Z]*}}FTD
// CHECK: }
// Check vtables for implicitly-inherited initializers
// CHECK-LABEL: sil_vtable SubclassWithInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26SubclassWithInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildWithInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic28GrandchildWithInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildOfInheritedInits {
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi6native_tcfc
// CHECK: #Foo.init!initializer.1: (Foo.Type) -> (Int) -> Foo : _T07dynamic26GrandchildOfInheritedInitsCACSi4objc_tcfc
// CHECK-NOT: .init!
// CHECK: }
// No vtable entry for override of @objc extension property
// CHECK-LABEL: sil_vtable SubExt {
// CHECK-NEXT: #BaseExt.init!initializer.1: (BaseExt.Type) -> () -> BaseExt : _T07dynamic6SubExtCACycfc // dynamic.SubExt.init() -> dynamic.SubExt
// CHECK-NEXT: #SubExt.deinit!deallocator: _T07dynamic6SubExtCfD // dynamic.SubExt.__deallocating_deinit
// CHECK-NEXT: }
// Dynamic thunk + vtable re-abstraction
// CHECK-LABEL: sil_vtable ConcreteDerived {
// CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public _T07dynamic15ConcreteDerivedC6methodySiFAA11GenericBaseCADyxFTV // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
// CHECK-NEXT: #GenericBase.init!initializer.1: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : _T07dynamic15ConcreteDerivedCACycfc // dynamic.ConcreteDerived.init() -> dynamic.ConcreteDerived
// CHECK-NEXT: #ConcreteDerived.deinit!deallocator: _T07dynamic15ConcreteDerivedCfD // dynamic.ConcreteDerived.__deallocating_deinit
// CHECK-NEXT: }
| 6c82313c2874a22214bf79bf7599d236 | 50.083779 | 267 | 0.684765 | false | false | false | false |
spacedrabbit/100-days | refs/heads/master | One00Days/One00Days/Day36Playground.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
// Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
import UIKit
func numbersInArray(var num: Int) -> [Int] {
var numArray: [Int] = []
while num % 10 > 0 {
numArray.append(num % 10)
num = num / 10
}
return numArray
}
func sumNumbers(numbers: [Int]) -> Int {
var total: Int = 0
for num in numbers {
total += num
}
return total
}
func doTheThingFor(num: Int) {
var new = numbersInArray(num)
var newTotal: Int
var newTotalCount: Int = 0
if new.count < 2 {
print("final: \(num)")
return
}
repeat {
newTotal = sumNumbers(new)
newTotalCount = numbersInArray(newTotal).count
new = numbersInArray(newTotal)
} while newTotalCount > 1
print("final: \(new)")
}
//doTheThingFor(99999999)
doTheThingFor(0)
//doTheThingFor(10)
doTheThingFor(2)
doTheThingFor(1)
doTheThingFor(1111111111)
| e779094a0677d41989935590ed0bebf2 | 18.26 | 101 | 0.638629 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Revolution Tool CL/objects/PBRConstant.swift | gpl-2.0 | 1 | //
// XDSConstant.swift
// Revolution Tool CL
//
// Created by The Steez on 26/12/2018.
//
import Foundation
enum XDSConstantTypes {
// same as classes in script class info
case void
case integer
case float
case string
case vector
case array
case codePointer
case unknown(Int)
var string : String {
get {
switch self {
case .void : return "Void"
case .integer : return "Int"
case .float : return "Float"
case .string : return "String"
case .vector : return "Vector"
case .array : return "Array"
case .codePointer : return "Pointer"
case .unknown(let val) : return "Class\(val)"
}
}
}
var index : Int {
switch self {
case .void : return 0
case .integer : return 1
case .float : return 2
case .string : return 3
case .vector : return 4
case .array : return 7
case .codePointer : return 8
case .unknown(let val) : return val
}
}
static func typeWithIndex(_ id: Int) -> XDSConstantTypes {
switch id {
case 0 : return .void
case 1 : return .integer
case 2 : return .float
case 3 : return .string
case 4 : return .vector
case 7 : return .array
case 8 : return .codePointer
default : return .unknown(id)
}
}
static func typeWithName(_ name: String) -> XDSConstantTypes? {
// not sure of actual number of types but should be fewer than 100
for i in 0 ..< 100 {
let type = XDSConstantTypes.typeWithIndex(i)
if type.string == name {
return type
}
}
return nil
}
}
class XDSConstant: NSObject {
var type: XDSConstantTypes = .void
var value: UInt32 = 0
override var description: String {
return self.rawValueString
}
var asFloat: Float {
return value.hexToSignedFloat()
}
var asInt: Int {
return value.int32
}
var rawValueString: String {
switch self.type {
case .float:
var text = String(format: "%.4f", self.asFloat)
if !text.contains(".") {
text += ".0"
}
while text.last == "0" {
text.removeLast()
}
if text.last == "." {
text += "0"
}
return text
case .string:
return "String(\(self.asInt))"
case .vector:
return "vector_" + String(format: "%02d", self.asInt)
case .integer:
return self.asInt >= 0x200 ? self.asInt.hexString() : "\(self.asInt)"
case .void:
return "Null"
case .array:
return "array_" + String(format: "%02d", self.asInt)
case .codePointer:
return XDSExpr.locationIndex(self.asInt).text[0]
case .unknown(let i):
return XGScriptClass.classes(i).name + "(\(self.asInt))"
}
}
init(type: Int, rawValue: UInt32) {
super.init()
self.type = XDSConstantTypes.typeWithIndex(type)
self.value = rawValue
}
convenience init(type: XDSConstantTypes, rawValue: Int) {
self.init(type: type.index, rawValue: rawValue.unsigned)
}
class var null: XDSConstant {
return XDSConstant(type: 0, rawValue: 0)
}
class func integer(_ val: Int) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val.unsigned)
}
class func integer(_ val: UInt32) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val)
}
class func float(_ val: Float) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.float.index, rawValue: val.floatToHex())
}
}
| f702ee1160e8f4c8c12bbc1860b3d865 | 20.697368 | 84 | 0.649788 | false | false | false | false |
knehez/edx-app-ios | refs/heads/master | Source/DiscussionTopicsViewController.swift | apache-2.0 | 2 | //
// DiscussionTopicsViewController.swift
// edX
//
// Created by Jianfeng Qiu on 11/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import UIKit
public class DiscussionTopicsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
public class Environment {
private let config: OEXConfig?
private let courseDataManager : CourseDataManager
private let networkManager : NetworkManager?
private weak var router: OEXRouter?
private let styles : OEXStyles
public init(config: OEXConfig,
courseDataManager : CourseDataManager,
networkManager: NetworkManager?,
router: OEXRouter?,
styles: OEXStyles)
{
self.config = config
self.courseDataManager = courseDataManager
self.networkManager = networkManager
self.router = router
self.styles = styles
}
}
private let topics = BackedStream<[DiscussionTopic]>()
private let environment: Environment
private let courseID : String
private let searchBar = UISearchBar()
private let loadController : LoadStateViewController
private var searchBarTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .Normal, size: .XSmall, color: self.environment.styles.neutralBlack())
}
private let contentView = UIView()
private let tableView = UITableView()
public init(environment: Environment, courseID: String) {
self.environment = environment
self.courseID = courseID
self.loadController = LoadStateViewController(styles : environment.styles)
super.init(nibName: nil, bundle: nil)
let stream = environment.courseDataManager.discussionManagerForCourseWithID(courseID).topics
topics.backWithStream(stream.map {
return DiscussionTopic.linearizeTopics($0)
}
)
}
public required init(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = OEXLocalizedString("DISCUSSION_TOPICS", nil)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
view.backgroundColor = self.environment.styles.standardBackgroundColor()
self.view.addSubview(contentView)
// Set up tableView
tableView.dataSource = self
tableView.delegate = self
tableView.applyStandardSeparatorInsets()
self.contentView.addSubview(tableView)
searchBar.placeholder = OEXLocalizedString("SEARCH_ALL_POSTS", nil)
searchBar.delegate = self
searchBar.showsCancelButton = false
searchBar.searchBarStyle = .Minimal
searchBar.sizeToFit()
tableView.tableHeaderView = searchBar
contentView.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
tableView.snp_makeConstraints { make -> Void in
make.edges.equalTo(self.contentView)
}
// Register tableViewCell
tableView.registerClass(DiscussionTopicsCell.self, forCellReuseIdentifier: DiscussionTopicsCell.identifier)
loadController.setupInController(self, contentView: contentView)
topics.listen(self, success : {[weak self]_ in
self?.loadedData()
}, failure : {[weak self] error in
self?.loadController.state = LoadState.failed(error: error)
})
}
func loadedData() {
self.loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : OEXLocalizedString("UNABLE_TO_LOAD_COURSE_CONTENT", nil)) : .Loaded
self.tableView.reloadData()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow() {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
public func searchBarSearchButtonClicked(searchBar: UISearchBar) {
if searchBar.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty {
return
}
// TODO: Move this inside the search screen and add a failure + empty cases
let apiRequest = DiscussionAPI.searchThreads(courseID: self.courseID, searchText: searchBar.text)
environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in
if let threads: [DiscussionThread] = result.data, owner = self {
owner.environment.router?.showPostsFromController(owner, courseID: owner.courseID, searchResults: threads)
}
}
}
public func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
public func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
self.view.endEditing(true)
searchBar.setShowsCancelButton(false, animated: true)
}
// MARK: - TableView Data and Delegate
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.topics.value?.count ?? 0
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50.0
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(DiscussionTopicsCell.identifier, forIndexPath: indexPath) as! DiscussionTopicsCell
if let topic = self.topics.value?[indexPath.row] {
cell.topic = topic
}
return cell
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.view.endEditing(true)
if let topic = self.topics.value?[indexPath.row] {
environment.router?.showPostsFromController(self, courseID: courseID, topic: topic)
}
}
}
extension DiscussionTopicsViewController {
public func t_topicsLoaded() -> Stream<[DiscussionTopic]> {
return topics
}
} | 2a5fc42416b246e88c9858906e5fcaee | 35.340426 | 173 | 0.660079 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureWalletConnect/Sources/FeatureWalletConnectData/Handlers/TransactionRequestHandler.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BigInt
import Combine
import DIKit
import EthereumKit
import FeatureWalletConnectDomain
import Foundation
import MoneyKit
import PlatformKit
import ToolKit
import WalletConnectSwift
final class TransactionRequestHandler: RequestHandler {
private let accountProvider: WalletConnectAccountProviderAPI
private let analyticsEventRecorder: AnalyticsEventRecorderAPI
private let enabledCurrenciesService: EnabledCurrenciesServiceAPI
private let getSession: (WCURL) -> Session?
private let responseEvent: (WalletConnectResponseEvent) -> Void
private let userEvent: (WalletConnectUserEvent) -> Void
private var cancellables: Set<AnyCancellable> = []
init(
accountProvider: WalletConnectAccountProviderAPI = resolve(),
analyticsEventRecorder: AnalyticsEventRecorderAPI = resolve(),
enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve(),
getSession: @escaping (WCURL) -> Session?,
responseEvent: @escaping (WalletConnectResponseEvent) -> Void,
userEvent: @escaping (WalletConnectUserEvent) -> Void
) {
self.accountProvider = accountProvider
self.analyticsEventRecorder = analyticsEventRecorder
self.enabledCurrenciesService = enabledCurrenciesService
self.getSession = getSession
self.responseEvent = responseEvent
self.userEvent = userEvent
}
func canHandle(request: Request) -> Bool {
Method(rawValue: request.method) != nil
}
func handle(request: Request) {
guard let session = getSession(request.url) else {
responseEvent(.invalid(request))
return
}
guard let chainID = session.walletInfo?.chainId else {
// No chain ID
responseEvent(.invalid(request))
return
}
guard let network: EVMNetwork = EVMNetwork(int: chainID) else {
// Chain not recognised.
responseEvent(.invalid(request))
return
}
guard enabledCurrenciesService.allEnabledCryptoCurrencies.contains(network.cryptoCurrency) else {
// Chain recognised, but currently disabled.
responseEvent(.invalid(request))
return
}
accountProvider
.defaultAccount(network: network)
.map { [responseEvent, analyticsEventRecorder] defaultAccount -> WalletConnectUserEvent? in
Self.createEvent(
analytics: analyticsEventRecorder,
defaultAccount: defaultAccount,
network: network,
request: request,
responseEvent: responseEvent,
session: session
)
}
.sink(
receiveValue: { [userEvent, responseEvent] event in
guard let event = event else {
responseEvent(.invalid(request))
return
}
userEvent(event)
}
)
.store(in: &cancellables)
}
/// Creates a `WalletConnectUserEvent.sendTransaction(,)` or `WalletConnectUserEvent.signTransaction(,)`
/// from input data.
private static func createEvent(
analytics: AnalyticsEventRecorderAPI,
defaultAccount: SingleAccount,
network: EVMNetwork,
request: Request,
responseEvent: @escaping (WalletConnectResponseEvent) -> Void,
session: Session
) -> WalletConnectUserEvent? {
guard let method = Method(rawValue: request.method) else {
return nil
}
guard let transaction = try? request.parameter(of: EthereumJsonRpcTransaction.self, at: 0) else {
return nil
}
let dAppName = session.dAppInfo.peerMeta.name
let dAppAddress = session.dAppInfo.peerMeta.url.host ?? ""
let dAppLogoURL = session.dAppInfo.peerMeta.icons.first?.absoluteString ?? ""
let onTxCompleted: TransactionTarget.TxCompleted = { [analytics] transactionResult in
analytics.record(
event: method.analyticsEvent(
appName: dAppName,
action: .confirm
)
)
switch transactionResult {
case .signed(let string):
responseEvent(.signature(string, request))
case .hashed(let txHash, _):
responseEvent(.transactionHash(txHash, request))
case .unHashed:
break
}
return .empty()
}
let onTransactionRejected: () -> AnyPublisher<Void, Never> = {
responseEvent(.rejected(request))
return .just(())
}
let target = EthereumSendTransactionTarget(
dAppAddress: dAppAddress,
dAppLogoURL: dAppLogoURL,
dAppName: dAppName,
method: method.targetMethod,
network: network,
onTransactionRejected: onTransactionRejected,
onTxCompleted: onTxCompleted,
transaction: transaction
)
return method.userEvent(
account: defaultAccount,
target: target
)
}
}
extension TransactionRequestHandler {
private enum Method: String {
case sendTransaction = "eth_sendTransaction"
case signTransaction = "eth_signTransaction"
var targetMethod: EthereumSendTransactionTarget.Method {
switch self {
case .sendTransaction:
return .send
case .signTransaction:
return .sign
}
}
func userEvent(
account: SingleAccount,
target: EthereumSendTransactionTarget
) -> WalletConnectUserEvent {
switch self {
case .sendTransaction:
return .sendTransaction(account, target)
case .signTransaction:
return .signTransaction(account, target)
}
}
func analyticsEvent(
appName: String,
action: AnalyticsEvents.New.WalletConnect.Action
) -> AnalyticsEvent {
switch self {
case .sendTransaction:
return AnalyticsEvents.New.WalletConnect
.dappRequestActioned(
action: action,
appName: appName,
method: .sendTransaction
)
case .signTransaction:
return AnalyticsEvents.New.WalletConnect
.dappRequestActioned(
action: action,
appName: appName,
method: .signTransaction
)
}
}
}
}
| 658fdf01eada6652ccf78d5b1ffd000e | 34.299492 | 108 | 0.58585 | false | false | false | false |
AlbertXYZ/HDCP | refs/heads/master | HDCP/Pods/SnapKit/Source/LayoutConstraint.swift | mit | 3 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
open class LayoutConstraint: NSLayoutConstraint {
open var label: String? {
get {
return self.identifier
}
set {
self.identifier = newValue
}
}
internal weak var constraint: Constraint? = nil
}
internal func ==(lhs: LayoutConstraint, rhs: LayoutConstraint) -> Bool {
guard lhs.firstItem === rhs.firstItem &&
lhs.secondItem === rhs.secondItem &&
lhs.firstAttribute == rhs.firstAttribute &&
lhs.secondAttribute == rhs.secondAttribute &&
lhs.relation == rhs.relation &&
lhs.priority == rhs.priority &&
lhs.multiplier == rhs.multiplier else {
return false
}
return true
}
| 487ffa9b5607cbbd89069534d08439e0 | 33.877193 | 81 | 0.68008 | false | false | false | false |
TorIsHere/SwiftyProgressBar | refs/heads/master | SwiftyProgressBar/CircleView.swift | apache-2.0 | 1 | //
// CircleView.swift
// SwiftyProgressBar
//
// Created by Kittikorn Ariyasuk on 6/11/16.
// Copyright © 2016 TorIsHere. All rights reserved.
//
import UIKit
@IBDesignable open class CircleView: UIView {
@IBInspectable open var primaryColor: UIColor = UIColor.blue
@IBInspectable open var secondaryColor: UIColor = UIColor.gray
@IBInspectable open var bgColor: UIColor = UIColor.gray
@IBInspectable open var lineWidth:CGFloat = 6
@IBInspectable open var bgLineWidth:CGFloat = 6
@IBInspectable open var startAngle:CGFloat = -90
@IBInspectable open var endAngle:CGFloat = -90
@IBInspectable open var willDraw:Bool = true
var gradientLayer:CAGradientLayer!
var pathLayer:CAShapeLayer!
var path:UIBezierPath!
var bgPath:UIBezierPath!
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override open func draw(_ rect: CGRect) {
// Drawing code
super.draw(rect)
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
let radius: CGFloat = max(bounds.width, bounds.height)
path = UIBezierPath(arcCenter: center,
radius: radius/2 - lineWidth/2,
startAngle: self.startAngle.degreesToRadians,
endAngle: self.endAngle.degreesToRadians,
clockwise: true)
path.lineWidth = lineWidth
path.lineCapStyle = CGLineCap.round
bgPath = UIBezierPath(arcCenter: center,
radius: radius/2 - lineWidth/2,
startAngle: -90,
endAngle: 90,
clockwise: true)
bgPath.lineWidth = bgLineWidth
if willDraw {
bgColor.setStroke()
bgPath.stroke()
//self.drawCircle()
}
}
override public init (frame : CGRect) {
super.init(frame : frame)
}
convenience public init () {
self.init(frame:CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
}
}
| 04484fe9c0a6237b0c6d99f26af8913d | 31.027027 | 78 | 0.584388 | false | false | false | false |
julienbodet/wikipedia-ios | refs/heads/develop | WMF Framework/NSFileManager+DirectorySize.swift | mit | 1 | import Foundation
@objc extension FileManager {
@objc func sizeOfDirectory(at url: URL) -> Int64 {
var size: Int64 = 0
let prefetchedProperties: [URLResourceKey] = [.isRegularFileKey, .fileAllocatedSizeKey, .totalFileAllocatedSizeKey]
if let enumerator = self.enumerator(at: url, includingPropertiesForKeys: prefetchedProperties) {
for item in enumerator {
guard let itemURL = item as? NSURL else {
continue
}
let resourceValueForKey: (URLResourceKey) throws -> NSNumber? = { key in
var value: AnyObject?
try itemURL.getResourceValue(&value, forKey: key)
return value as? NSNumber
}
guard let value = try? resourceValueForKey(URLResourceKey.isRegularFileKey), let isRegularFile = value?.boolValue else {
continue
}
guard isRegularFile else {
continue
}
var fileSize = try? resourceValueForKey(URLResourceKey.totalFileAllocatedSizeKey)
fileSize = try? fileSize ?? resourceValueForKey(URLResourceKey.fileAllocatedSizeKey)
guard let allocatedSize = fileSize??.int64Value else {
assertionFailure("URLResourceKey.fileAllocatedSizeKey should always return a value")
return size
}
size += allocatedSize
}
}
return size
}
}
| 3a0b141375c6791d9fcd206f37edd2e5 | 42.459459 | 136 | 0.554726 | false | false | false | false |
criticalmaps/criticalmaps-ios | refs/heads/main | CriticalMapsKit/Sources/NextRideFeature/NextRideCore.swift | mit | 1 | import Combine
import ComposableArchitecture
import ComposableCoreLocation
import Foundation
import Logger
import SharedDependencies
import SharedModels
// MARK: State
public struct NextRideFeature: ReducerProtocol {
public init() {}
@Dependency(\.nextRideService) public var service
@Dependency(\.userDefaultsClient) public var userDefaultsClient
@Dependency(\.date) public var date
@Dependency(\.mainQueue) public var mainQueue
@Dependency(\.coordinateObfuscator) public var coordinateObfuscator
@Dependency(\.isNetworkAvailable) public var isNetworkAvailable
public struct State: Equatable {
public init(nextRide: Ride? = nil) {
self.nextRide = nextRide
}
public var nextRide: Ride?
public var rideEvents: [Ride] = []
public var userLocation: Coordinate?
}
// MARK: Actions
public enum Action: Equatable {
case getNextRide(Coordinate)
case nextRideResponse(TaskResult<[Ride]>)
case setNextRide(Ride)
}
// MARK: Reducer
/// Reducer handling next ride feature actions
public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> {
switch action {
case let .getNextRide(coordinate):
guard userDefaultsClient.rideEventSettings.isEnabled else {
logger.debug("NextRide featue is disabled")
return .none
}
guard isNetworkAvailable else {
logger.debug("Not fetching next ride. No connectivity")
return .none
}
let obfuscatedCoordinate = coordinateObfuscator.obfuscate(
coordinate,
.thirdDecimal
)
let requestRidesInMonth: Int = queryMonth(for: date.callAsFunction)
return .task {
await .nextRideResponse(
TaskResult {
try await service.nextRide(
obfuscatedCoordinate,
userDefaultsClient.rideEventSettings.eventDistance.rawValue,
requestRidesInMonth
)
}
)
}
case let .nextRideResponse(.failure(error)):
logger.error("Get next ride failed 🛑 with error: \(error)")
return .none
case let .nextRideResponse(.success(rides)):
guard !rides.isEmpty else {
logger.info("Rides array is empty")
return .none
}
guard !rides.map(\.rideType).isEmpty else {
logger.info("No upcoming events for filter selection rideType")
return .none
}
state.rideEvents = rides.sortByDateAndFilterBeforeDate(date.callAsFunction)
// Sort rides by date and pick the first one with a date greater than now
let ride = rides // swiftlint:disable:this sorted_first_last
.lazy
.filter {
guard let type = $0.rideType else { return true }
return userDefaultsClient.rideEventSettings.typeSettings
.lazy
.filter(\.isEnabled)
.map(\.type)
.contains(type)
}
.filter(\.enabled)
.sorted { lhs, rhs in
let byDate = lhs.dateTime < rhs.dateTime
guard
let userLocation = state.userLocation,
let lhsCoordinate = lhs.coordinate,
let rhsCoordinate = rhs.coordinate
else {
return byDate
}
if Calendar.current.isDate(lhs.dateTime, inSameDayAs: rhs.dateTime) {
return lhsCoordinate.distance(from: userLocation) < rhsCoordinate.distance(from: userLocation)
} else {
return byDate
}
}
.first { ride in ride.dateTime > date() }
guard let filteredRide = ride else {
logger.info("No upcoming events after filter")
return .none
}
return Effect(value: .setNextRide(filteredRide))
case let .setNextRide(ride):
state.nextRide = ride
return .none
}
}
}
// MARK: Helper
enum EventError: Error, LocalizedError {
case eventsAreNotEnabled
case invalidDateError
case rideIsOutOfRangeError
case noUpcomingRides
case rideTypeIsFiltered
case rideDisabled
}
private func queryMonth(for date: () -> Date = Date.init, calendar: Calendar = .current) -> Int {
let currentMonthOfFallback = calendar.dateComponents([.month], from: date()).month ?? 0
guard !calendar.isDateInWeekend(date()) else { // current date is on a weekend
return currentMonthOfFallback
}
guard let startDateOfNextWeekend = calendar.nextWeekend(startingAfter: date())?.start else {
return currentMonthOfFallback
}
guard let month = calendar.dateComponents([.month], from: startDateOfNextWeekend).month else {
return currentMonthOfFallback
}
return max(currentMonthOfFallback, month)
}
public extension Array where Element == Ride {
func sortByDateAndFilterBeforeDate(_ now: () -> Date) -> Self {
lazy
.sorted(by: \.dateTime)
.filter { $0.dateTime > now() }
}
}
extension SharedModels.Coordinate {
init(_ location: ComposableCoreLocation.Location) {
self = .init(
latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude
)
}
}
| 48c586717676f5a51f7d61e67334d6e3 | 27.649718 | 106 | 0.659436 | false | false | false | false |
aulas-lab/ads-mobile | refs/heads/master | swift/Funcoes/Funcoes/main.swift | mit | 1 | //
// main.swift
// Funcoes
//
// Created by Mobitec on 19/04/16.
// Copyright (c) 2016 Unopar. All rights reserved.
//
import Foundation
func nomeFuncao(param1: String, param2: Int, param3: Float) -> Float {
return Float(param2) * param3
}
let resultado = nomeFuncao("Teste", 10, 10.1)
println("Resultado: \(resultado)")
func funcaoSemRetorno1() {
println("Chamada da funcao sem retorno 1")
}
func funcaoSemRetorno2() -> Void {
println("Chamada da funcao sem retorno 2")
}
func contaPositivosNegativos(numeros: [Int])
-> (contaP: Int, contaN: Int) {
var cp = 0
var cn = 0
for n in numeros {
if n < 0 {
cn++;
} else {
cp++;
}
}
return (cp, cn)
}
let numeros = [-1, 10, -45, 39, 900];
let contagem = contaPositivosNegativos(numeros)
println(
"Positivos: \(contagem.contaP) Negativos: \(contagem.contaN)")
| 73439333ac3a71c1ef02c95233d8d013 | 19.083333 | 70 | 0.572614 | false | false | false | false |
mali1488/Bluefruit_LE_Connect | refs/heads/master | BLE Test/ColorPickerViewController.swift | bsd-3-clause | 1 | //
// ColorPickerViewController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 1/23/15.
// Copyright (c) 2015 Adafruit Industries. All rights reserved.
//
import UIKit
protocol ColorPickerViewControllerDelegate: HelpViewControllerDelegate {
func sendColor(red:UInt8, green:UInt8, blue:UInt8)
}
class ColorPickerViewController: UIViewController, UITextFieldDelegate, ISColorWheelDelegate {
var delegate:ColorPickerViewControllerDelegate!
@IBOutlet var helpViewController:HelpViewController!
@IBOutlet var infoButton:UIButton!
private var infoBarButton:UIBarButtonItem?
var helpPopoverController:UIPopoverController?
// @IBOutlet var redSlider:UISlider!
// @IBOutlet var greenSlider:UISlider!
// @IBOutlet var blueSlider:UISlider!
// @IBOutlet var redField:UITextField!
// @IBOutlet var greenField:UITextField!
// @IBOutlet var blueField:UITextField!
// @IBOutlet var swatchView:UIView!
@IBOutlet var valueLable:UILabel!
@IBOutlet var sendButton:UIButton!
@IBOutlet var wheelView:UIView!
@IBOutlet var wellView:UIView!
@IBOutlet var wheelHorzConstraint:NSLayoutConstraint!
@IBOutlet var wellVertConstraint:NSLayoutConstraint! //34 for 3.5"
@IBOutlet var wellHeightConstraint:NSLayoutConstraint! //64 for 3.5"
@IBOutlet var sendVertConstraint:NSLayoutConstraint! //46 for 3.5"
@IBOutlet var brightnessSlider: UISlider!
@IBOutlet var sliderGradientView: GradientView!
var colorWheel:ISColorWheel!
convenience init(aDelegate:ColorPickerViewControllerDelegate){
//Separate NIBs for iPhone & iPad
var nibName:NSString
if IS_IPHONE {
nibName = "ColorPickerViewController_iPhone"
}
else{ //IPAD
nibName = "ColorPickerViewController_iPad"
}
self.init(nibName: nibName as String, bundle: NSBundle.mainBundle())
self.delegate = aDelegate
self.title = "Color Picker"
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Color Picker"
//setup help view
self.helpViewController.title = "Color Picker Help"
self.helpViewController.delegate = delegate
//add info bar button
let archivedData = NSKeyedArchiver.archivedDataWithRootObject(infoButton)
let buttonCopy = NSKeyedUnarchiver.unarchiveObjectWithData(archivedData) as! UIButton
buttonCopy.addTarget(self, action: Selector("showInfo:"), forControlEvents: UIControlEvents.TouchUpInside)
infoBarButton = UIBarButtonItem(customView: buttonCopy)
self.navigationItem.rightBarButtonItem = infoBarButton
sendButton.layer.cornerRadius = 4.0
sendButton.layer.borderColor = sendButton.currentTitleColor?.CGColor
sendButton.layer.borderWidth = 1.0;
wellView.backgroundColor = UIColor.whiteColor()
wellView.layer.borderColor = UIColor.blackColor().CGColor
wellView.layer.borderWidth = 1.0
wheelView.backgroundColor = UIColor.clearColor()
//customize brightness slider
let sliderTrackImage = UIImage(named: "clearPixel.png")
brightnessSlider.setMinimumTrackImage(sliderTrackImage, forState: UIControlState.Normal)
brightnessSlider.setMaximumTrackImage(sliderTrackImage, forState: UIControlState.Normal)
sliderGradientView.endColor = wellView.backgroundColor!
//adjust layout for 3.5" displays
if (IS_IPHONE_4) {
wellVertConstraint.constant = 34
wellHeightConstraint.constant = 64
sendVertConstraint.constant = 46
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Add color wheel
if wheelView.subviews.count == 0 {
// let size = wheelView.bounds.size
// let wheelSize = CGSizeMake(size.width * 0.9, size.width * 0.9)
// let rect = CGRectMake(size.width / 2 - wheelSize.width / 2,
//// 0.0,
// size.height * 0.1,
// wheelSize.width,
// wheelSize.height)
let rect = CGRectMake(
0.0,
0.0,
wheelView.bounds.size.width,
wheelView.bounds.size.height)
colorWheel = ISColorWheel(frame: rect)
colorWheel.delegate = self
colorWheel.continuous = true
wheelView.addSubview(colorWheel)
}
}
// @IBAction func sliderValueChanged(sender:UISlider) {
//
// var textField:UITextField
//
// switch sender.tag {
// case 0: //red
// textField = redField
// case 1: //green
// textField = greenField
// case 2: //blue
// textField = blueField
// default:
// printLog(self, "\(__FUNCTION__)", "slider returned invalid tag")
// return
// }
//
// //Dismiss any text field
//
// //Update textfield
// textField.text = "\(Int(sender.value))"
//
// //Update value label
// updateValueLabel()
//
// }
func updateValueLabel() {
//RGB method
// valueLable.text = "R:\(redField.text) G:\(greenField.text) B:\(blueField.text)"
//
// //Update color swatch
// let color = UIColor(red: CGFloat(redSlider.value / 255.0), green: CGFloat(greenSlider.value / 255.0), blue: CGFloat(blueSlider.value / 255.0), alpha: 1.0)
// swatchView.backgroundColor = color
}
// func textFieldDidEndEditing(textField: UITextField) {
//
// var slider:UISlider
//
// switch textField.tag {
// case 0: //red
// slider = redSlider
// case 1: //green
// slider = greenSlider
// case 2: //blue
// slider = blueSlider
// default:
// printLog(self, "\(__FUNCTION__)", "textField returned with invalid tag")
// return
// }
//
// //Update slider
// var intVal = textField.text.toInt()?
// if (intVal != nil) {
// slider.value = Float(intVal!)
// }
// else {
// printLog(self, "\(__FUNCTION__)", "textField returned non-integer value")
// return
// }
//
// //Update value label
// updateValueLabel()
//
// }
@IBAction func showInfo(sender:AnyObject) {
// Show help info view on iPhone via flip transition, called via "i" button in navbar
if (IS_IPHONE) {
presentViewController(helpViewController, animated: true, completion: nil)
}
//iPad
else if (IS_IPAD) {
//show popover if it isn't shown
helpPopoverController?.dismissPopoverAnimated(true)
helpPopoverController = UIPopoverController(contentViewController: helpViewController)
helpPopoverController?.backgroundColor = UIColor.darkGrayColor()
let rightBBI:UIBarButtonItem! = self.navigationController?.navigationBar.items.last!.rightBarButtonItem
let aFrame:CGRect = rightBBI!.customView!.frame
helpPopoverController?.presentPopoverFromRect(aFrame,
inView: rightBBI.customView!.superview!,
permittedArrowDirections: UIPopoverArrowDirection.Any,
animated: true)
}
}
@IBAction func brightnessSliderChanged(sender: UISlider) {
colorWheelDidChangeColor(colorWheel)
}
@IBAction func sendColor() {
//Send color bytes thru UART
var r:CGFloat = 0.0
var g:CGFloat = 0.0
var b:CGFloat = 0.0
wellView.backgroundColor!.getRed(&r, green: &g, blue: &b, alpha: nil)
delegate.sendColor((UInt8(255.0 * Float(r))), green: (UInt8(255.0 * Float(g))), blue: (UInt8(255.0 * Float(b))))
}
func colorWheelDidChangeColor(colorWheel:ISColorWheel) {
let colorWheelColor = colorWheel.currentColor()
// sliderTintView.backgroundColor = colorWheelColor
sliderGradientView.endColor = colorWheelColor!
let brightness = CGFloat(brightnessSlider.value)
var red:CGFloat = 0.0
var green:CGFloat = 0.0
var blue:CGFloat = 0.0
colorWheelColor.getRed(&red, green: &green, blue: &blue, alpha: nil)
red *= brightness; green *= brightness; blue *= brightness
let color = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
wellView.backgroundColor = color
// var r:CGFloat = 0.0
// var g:CGFloat = 0.0
// var b:CGFloat = 0.0
//// var a:UnsafeMutablePointer<CGFloat>
// color.getRed(&r, green: &g, blue: &b, alpha: nil)
valueLable.text = "R:\(Int(255.0 * Float(red))) G:\(Int(255.0 * Float(green))) B:\(Int(255.0 * Float(blue)))"
}
}
| 88d423780cb4b1ca385857488e276b17 | 31.475248 | 166 | 0.580285 | false | false | false | false |
Motsai/neblina-motiondemo-swift | refs/heads/master | NebCtrlPanel/iOS/NebCtrlPanel/DetailViewController.swift | mit | 2 | //
// DetailViewController.swift
// Nebblina Control Panel
//
// Created by Hoan Hoang on 2015-10-22.
// Copyright © 2015 Hoan Hoang. All rights reserved.
//
import UIKit
import CoreBluetooth
import QuartzCore
import SceneKit
let MotionDataStream = Int32(1)
let Heading = Int32(2)
let LuggageDataLog = Int32(3)
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 : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_UART.rawValue),
Name: "UART Data Port", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, ActiveStatus: 0,
Name: "Change Device Name", Actuator : ACTUATOR_TYPE_TEXT_FIELD_BUTTON, Text: "Change"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM, ActiveStatus: 0,
Name: "Shock Segment Stream", Actuator : ACTUATOR_TYPE_TEXT_FIELD_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, ActiveStatus: 0,
Name: "Calibrate Forward Pos", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Calib Fwrd"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, ActiveStatus: 0,
Name: "Calibrate Down Pos", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Calib Dwn"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, ActiveStatus: 0,
Name: "Reset timestamp", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Reset"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_FUSION_TYPE, ActiveStatus: 0,
Name: "Fusion 9 axis", Actuator : ACTUATOR_TYPE_SWITCH, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_QUATERNION.rawValue),
Name: "Quaternion Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_PEDOMETER.rawValue),
Name: "Pedometer Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_ROTATION_INFO.rawValue),
Name: "Rotation info Stream", Actuator : ACTUATOR_TYPE_TEXT_FIELD_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER.rawValue),
Name: "Accelerometer Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_GYROSCOPE.rawValue),
Name: "Gyroscope Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_MAGNETOMETER.rawValue),
Name: "Magnetometer Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, 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 : ACTUATOR_TYPE_SWITCH, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_HUMIDITY.rawValue),
Name: "Humidity Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_TEMPERATURE.rawValue),
Name: "Temperature Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, ActiveStatus: 0,
Name: "Lock Heading Ref.", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: UInt32(NEBLINA_RECORDER_STATUS_RECORD.rawValue),
Name: "Flash Record", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: 0,
Name: "Flash Record", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Stop"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK, ActiveStatus: 0,
Name: "Flash Playback", Actuator : ACTUATOR_TYPE_TEXT_FIELD_BUTTON, Text: "Play"),
// NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, ActiveStatus: 0,
// Name: "Flash Download", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED0 level", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED1 level", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED2", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_EEPROM, CmdId: NEBLINA_COMMAND_EEPROM_READ, ActiveStatus: 0,
Name: "EEPROM Read", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Read"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_POWER, CmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, ActiveStatus: 0,
Name: "Charge Current in mA", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: MotionDataStream, ActiveStatus: 0,
Name: "Motion data stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: Heading, ActiveStatus: 0,
Name: "Heading", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: LuggageDataLog, ActiveStatus: 0,
Name: "Luggage data logging", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_ERASE_ALL, ActiveStatus: 0,
Name: "Flash Erase All", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Erase"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, ActiveStatus: 0,
Name: "Firmware Update", Actuator : ACTUATOR_TYPE_BUTTON, Text: "DFU"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN, ActiveStatus: 0,
Name: "Shutdown", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Shutdown")
)
//let CtrlName = [String](arrayLiteral:"Heading")//, "Test1", "Test2")
class DetailViewController: UIViewController, UITextFieldDelegate, NeblinaDelegate, SCNSceneRendererDelegate, UITableViewDataSource {
var nebdev : Neblina? {
didSet {
nebdev!.delegate = self
}
}
//let scene = SCNScene(named: "art.scnassets/Millennium_Falcon/Millennium_Falcon.dae") as SCNScene!
//let scene = SCNScene(named: "art.scnassets/SchoolBus/schoolBus.obj")!
let sceneShip = SCNScene(named: "art.scnassets/ship.scn")!
//let scene = SCNScene(named: "art.scnassets/AstonMartinRapide/rapide.scn")!
//let scene = SCNScene(named: "art.scnassets/E-TIE-I/E-TIE-I.3ds.obj")!
let sceneCube = SCNScene(named: "art.scnassets/neblina_calibration.dae")!
var scene : SCNScene?
//let scene = SCNScene(named: "art.scnassets/Neblina_Cube.dae")!
//var textview = UITextView()
//@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var accelGraph : GraphView!
@IBOutlet weak var gyroGraph : GraphView!
@IBOutlet weak var magGraph : GraphView!
@IBOutlet weak var cmdView: UITableView!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var flashLabel: UILabel!
@IBOutlet weak var dumpLabel: UILabel!
@IBOutlet weak var planeCubeSwitch : UISegmentedControl!
//var eulerAngles = SCNVector3(x: 0,y:0,z:0)
var ship : SCNNode! //= scene.rootNode.childNodeWithName("ship", recursively: true)!
let max_count = Int16(15)
var prevTimeStamp = 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(0)
var dropCnt = UInt32(0)
// var curDownloadSession = UInt16(0xFFFF)
// var curDownloadOffset = UInt32(0)
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 badTimestampCnt = Int(0)
var dubTimestampCnt = Int(0)
var prevPacket = NeblinaFusionPacket_t();
/* var detailItem: Neblina? {
didSet {
// Update the view.
//self.configureView()
//detailItem!.delegate = self
nebdev = detailItem
nebdev.setPeripheral(detailItem!.id, peripheral : detailItem!.peripheral)
nebdev.delegate = self
}
}*/
func configureView() {
// Update the user interface for the detail item.
if self.nebdev != nil {
//if let label = self.consoleTextView {
//label.text = detail.description
// }
}
}
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()
cnt = max_count
scene = sceneShip
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
sceneCube.rootNode.addChildNode(cameraNode)
let cameraNode1 = SCNNode()
sceneShip.rootNode.addChildNode(cameraNode1)
//scene?.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z:20)
cameraNode1.position = SCNVector3(x: 0, y: 0, z:20)
//cameraNode.position = SCNVector3(x: 0, y: 15, z: 0)
//cameraNode.rotation = SCNVector4(0, 0, 1, GLKMathDegreesToRadians(180))
//cameraNode.rotation = SCNVector4(1, 0, 0, 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)
sceneCube.rootNode.addChildNode(lightNode)
let lightNode1 = SCNNode()
lightNode1.light = SCNLight()
lightNode1.light!.type = SCNLight.LightType.omni
lightNode1.position = SCNVector3(x: 0, y: 10, z: 50)
sceneShip.rootNode.addChildNode(lightNode1)
// 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
sceneCube.rootNode.addChildNode(ambientLightNode)
let ambientLightNode1 = SCNNode()
ambientLightNode1.light = SCNLight()
ambientLightNode1.light!.type = SCNLight.LightType.ambient
ambientLightNode1.light!.color = UIColor.darkGray
sceneShip.rootNode.addChildNode(ambientLightNode1)
// retrieve the ship node
// ship = scene.rootNode.childNodeWithName("MillenniumFalconTop", recursively: true)!
// ship = scene.rootNode.childNodeWithName("ARC_170_LEE_RAY_polySurface1394376_2_2", recursively: true)!
ship = scene?.rootNode.childNode(withName: "ship", recursively: true)!
//ship = scene.rootNode.childNode(withName: "Mesh258_SCHOOL_BUS2_Group2_Group1_Model", recursively: true)!
ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180))
// Cube view
//ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(-90), GLKMathDegreesToRadians(0), GLKMathDegreesToRadians(0))
//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))
// 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(DetailViewController.handleTap(_:)))
scnView.addGestureRecognizer(tapGesture)
//scnView.preferredFramesPerSecond = 60
magGraph.valueRanges = [-16000.0...16000.0, -16000.0...16000.0, -16000.0...16000.0]
}
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)
nebdev!.setLed(UInt8(row - i), Value: UInt8(value!))
break
case NEBLINA_SUBSYSTEM_POWER:
nebdev!.setBatteryChargeCurrent(value!)
break
default:
break
}
return true;
}
@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()
}
}
override var shouldAutorotate : Bool {
return true
}
override var prefersStatusBarHidden : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func switch3DView(_ sender:UISwitch)
{
if (sender.isOn) {
cmdView.isHidden = true
let scnView = self.view.subviews[0] as! SCNView
scnView.isHidden = false
accelGraph.isHidden = false
gyroGraph.isHidden = false
magGraph.isHidden = false
planeCubeSwitch.isHidden = false
}
else {
cmdView.isHidden = false
let scnView = self.view.subviews[0] as! SCNView
scnView.isHidden = true
accelGraph.isHidden = true
gyroGraph.isHidden = true
magGraph.isHidden = true
planeCubeSwitch.isHidden = true
}
}
@IBAction func switch3DObject(_ sender:UISegmentedControl)
{
if sender.selectedSegmentIndex == 0 {
scene = sceneShip
ship = scene?.rootNode.childNode(withName: "ship", recursively: true)!
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
}
else {
scene = sceneCube
ship = scene?.rootNode.childNode(withName: "node", recursively: true)!
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
}
}
@IBAction func buttonAction(_ sender:UIButton)
{
let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if (nebdev == nil) {
return
}
if (row < NebCmdList.count) {
switch (NebCmdList[row].SubSysId)
{
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE:
nebdev!.firmwareUpdate()
print("DFU Command")
break
case NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP:
nebdev!.resetTimeStamp(Delayed: true)
print("Reset timestamp")
break
case NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET:
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(4) as! UITextField
nebdev!.setDeviceName(name: control.text!);
// nebdev?.device = nil
}
break
case NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN:
nebdev!.shutdown()
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_EEPROM:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_EEPROM_READ:
nebdev!.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:
nebdev!.calibrateForwardPosition()
break
case NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION:
nebdev!.calibrateDownPosition()
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
if flashEraseProgress == false {
//print("Send Command erase")
flashEraseProgress = true;
flashLabel.text = "Erasing ..."
nebdev!.eraseStorage(false)
}
case NEBLINA_COMMAND_RECORDER_RECORD:
if NebCmdList[row].ActiveStatus == 0 {
nebdev?.sessionRecord(false, info: "")
}
else {
nebdev!.sessionRecord(true, info: "")
}
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 !(tf.text!.isEmpty) {
n = (UInt16((tf.text!)))!
}
nebdev?.sessionPlayback(true, sessionId : n)
PaketCnt = 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 (nebdev == nil) {
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:
nebdev!.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:
nebdev!.streamMotionState(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_FUSION_FUSION_TYPE:
nebdev!.setFusionType(UInt8(sender.selectedSegmentIndex))
break
//case IMU_Data:
// nebdev!.streamIMU(sender.selectedSegmentIndex == 1)
// break
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
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_PEDOMETER_STREAM:
nebdev!.streamPedometer(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM:
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
var type = UInt8(0)
if cell != nil {
let tf = cell?.viewWithTag(4) as! UITextField
if !(tf.text!.isEmpty) {
type = (UInt8((tf.text!)))!
}
}
nebdev!.streamRotationInfo(sender.selectedSegmentIndex == 1, Type:type)
break
case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM:
nebdev!.streamQuaternion(false)
nebdev!.streamEulerAngle(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM:
nebdev!.streamExternalForce(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD:
nebdev!.recordTrajectory(sender.selectedSegmentIndex == 1)
break;
case NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM:
nebdev!.streamTrajectoryInfo(sender.selectedSegmentIndex == 1)
break;
// case NEBLINA_COMMAND_FUSION_MAG_STATE:
// nebdev!.streamMAG(sender.selectedSegmentIndex == 1)
// break;
case NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE:
nebdev!.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
case NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM:
var thresh = UInt8(0)
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if cell != nil {
let tf = cell?.viewWithTag(4) as! UITextField
thresh = UInt8(tf.text!)!
}
nebdev!.streamShockSegment(sender.selectedSegmentIndex == 1, threshold: thresh)
default:
break
}
case NEBLINA_SUBSYSTEM_LED:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE)
nebdev!.setLed(UInt8(row - i), Value: UInt8(sender.selectedSegmentIndex))
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
if (sender.selectedSegmentIndex == 1) {
flashEraseProgress = true;
}
nebdev!.eraseStorage(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_RECORDER_RECORD:
nebdev!.sessionRecord(sender.selectedSegmentIndex == 1, info: "")
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
nebdev!.sessionPlayback(sender.selectedSegmentIndex == 1, sessionId : 0xffff)
if (sender.selectedSegmentIndex == 1) {
PaketCnt = 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:
nebdev!.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:
nebdev!.sensorStreamAccelData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM:
nebdev?.sensorStreamGyroData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
nebdev?.sensorStreamHumidityData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM:
nebdev?.sensorStreamMagData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM:
nebdev?.sensorStreamPressureData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM:
nebdev?.sensorStreamTemperatureData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
nebdev?.sensorStreamAccelGyroData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
nebdev?.sensorStreamAccelMagData(sender.selectedSegmentIndex == 1)
break
default:
break
}
break
case 0xf:
switch (NebCmdList[row].CmdId) {
case Heading:
nebdev!.streamQuaternion(false)
nebdev!.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: MotionDataStream)
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: LuggageDataLog)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
case MotionDataStream:
if sender.selectedSegmentIndex == 0 {
nebdev?.disableStreaming()
break
}
nebdev!.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
}
// nebdev!.streamIMU(sender.selectedSegmentIndex == 1)
// i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_IMU_STATE)
// cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
// if (cell != nil) {
// let control = cell!.viewWithTag(1) as! UISegmentedControl
// control.selectedSegmentIndex = sender.selectedSegmentIndex
// }
nebdev!.sensorStreamMagData(sender.selectedSegmentIndex == 1)
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, 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
}
nebdev!.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
}
nebdev!.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
}
nebdev!.streamRotationInfo(sender.selectedSegmentIndex == 1, Type : 1)
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: Heading)
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: LuggageDataLog)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
case LuggageDataLog:
if sender.selectedSegmentIndex == 0 {
nebdev!.disableStreaming()
nebdev!.sessionRecord(false, info: "")
break
}
else {
nebdev!.sensorStreamAccelGyroData(true)
nebdev!.sensorStreamMagData(true)
nebdev!.sensorStreamPressureData(true)
nebdev!.sensorStreamTemperatureData(true)
nebdev!.sessionRecord(true, info: "")
}
var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
i = getCmdIdx(0xF, cmdId: Heading)
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: MotionDataStream)
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 renderer(renderer: SCNSceneRenderer,
// updateAtTime time: NSTimeInterval) {
// let ship = renderer.scene!.rootNode.childNodeWithName("ship", recursively: true)!
//
//
// }
// func didReceiveFusionData(type : UInt8, data : FusionPacket) {
// print("\(data)")
// }
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:
//print("\(NebCmdList[idx])")
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].CmdId == NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM {
if NebCmdList[idx].ActiveStatus == UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.rawValue) {
print("Accel_Gyro button \(status.sensor) ")
}
}
if (NebCmdList[idx].ActiveStatus & UInt32(status.sensor)) == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
default:
break
}
}
}
// MARK: Neblina
func didConnectNeblina(sender : Neblina) {
// Switch to BLE interface
prevTimeStamp = 0;
nebdev!.getSystemStatus()
nebdev!.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
)
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 = "Flash erased"
flashEraseProgress = false
break
case NEBLINA_COMMAND_RECORDER_RECORD:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
flashLabel.text = String(format: "Recording session %d", session)
}
else {
flashLabel.text = String(format: "Recorded session %d", session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
flashLabel.text = String(format: "Playing session %d", session)
}
else {
flashLabel.text = String(format: "Playback sess %d finished %u packets", session, nebdev!.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) {
}
//
// General data
//
func didReceiveGeneralData(sender : Neblina, respType: Int32, cmdRspId : Int32, data : UnsafeRawPointer, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
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
//dumpLabel.text = String(format: "Total packet %u @ %0.2f pps, drop \(dropCnt)", nebdev!.getPacketCount(), nebdev!.getDataRate())
switch (cmdRspId) {
case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM:
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 (heading) {
ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot))
}
else {
ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot))
}
label.text = String("Euler - Yaw:\(xrot), Pitch:\(yrot), Roll:\(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)//w
let xq = Float(x) / 32768.0
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)//x
let yq = Float(y) / 32768.0
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)//y
let zq = Float(z) / 32768.0
let w = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8)//z
let wq = Float(w) / 32768.0
ship.orientation = SCNQuaternion(-zq, xq, yq, wq)// ship
//ship.orientation = SCNQuaternion(-yq, wq, xq, zq)// ship
//ship.orientation = SCNQuaternion(xq, yq, zq, wq)
//ship.orientation = SCNQuaternion(yq, -xq, -zq, wq)// cube
label.text = String("Quat - w:\(xq), x:\(yq), y:\(zq), z:\(wq)")
if (prevTimeStamp == data.timestamp)
{
var diff = Bool(false)
if prevPacket.data.0 != data.data.0 {
diff = true
}
else if prevPacket.data.1 != data.data.1 {
diff = true
}
else if prevPacket.data.2 != data.data.2 {
diff = true
}
else if prevPacket.data.3 != data.data.3 {
diff = true
}
else if prevPacket.data.4 != data.data.4 {
diff = true
}
else if prevPacket.data.5 != data.data.5 {
diff = true
}
else if prevPacket.data.6 != data.data.6 {
diff = true
}
else if prevPacket.data.7 != data.data.7 {
diff = true
}
else if prevPacket.data.8 != data.data.8 {
diff = true
}
else if prevPacket.data.9 != data.data.9 {
diff = true
}
else if prevPacket.data.10 != data.data.10 {
diff = true
}
else if prevPacket.data.11 != data.data.11 {
diff = true
}
if diff == true {
badTimestampCnt += 1
}
else {
dubTimestampCnt += 1
}
}
//print("\(badTimestampCnt), \(dubTimestampCnt)")
if (prevTimeStamp == 0 || data.timestamp <= prevTimeStamp)
{
prevTimeStamp = data.timestamp;
prevPacket = data;
}
else
{
let tdiff = data.timestamp - prevTimeStamp;
if (tdiff > 49000)
{
dropCnt += 1
//dumpLabel.text = String("\(dropCnt) Drop : \(tdiff), \(badTimestampCnt)")
}
prevTimeStamp = data.timestamp
prevPacket = data
}
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.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
//}
}
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_STATE:
//
// 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
label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)")
//ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90))
break
*/
case NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM:
let stridelen = data.data.9;
let totaldistance = UInt16(data.data.10) + (UInt16(data.data.11) << 8)
label.text = String("Stride = \(stridelen), dist = \(totaldistance)")
break
case NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM:
let ax = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let ay = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let az = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
// label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)")
accelGraph.add(double3(Double(ax), Double(ay), Double(az)))
let gx = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8)
let gy = (Int16(data.data.8) & 0xff) | (Int16(data.data.9) << 8)
let gz = (Int16(data.data.10) & 0xff) | (Int16(data.data.11) << 8)
gyroGraph.add(double3(Double(gx), Double(gy), Double(gz)))
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)
{
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) {
switch (cmdRspId) {
case NEBLINA_COMMAND_LED_STATUS:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATUS)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let tf = cell!.viewWithTag(3) as! UITextField
tf.text = String(data[0])
}
cell = cmdView.cellForRow( at: IndexPath(row: i + 1, section: 0))
if (cell != nil) {
let tf = cell!.viewWithTag(3) as! UITextField
tf.text = String(data[1])
}
cell = cmdView.cellForRow( at: IndexPath(row: i + 2, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
if (data[2] != 0) {
sw.selectedSegmentIndex = 1
}
else {
sw.selectedSegmentIndex = 0
}
}
break
default:
break
}
}
//
// Debug
//
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:
dumpLabel.text = String(format: "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
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:
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) {
flashLabel.text = String(format: "Recording session %d", session)
}
else {
flashLabel.text = String(format: "Recorded session %d", session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
flashLabel.text = String(format: "Playing session %d", session)
}
else {
flashLabel.text = String(format: "End session %d, %u", session, nebdev!.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)
dumpLabel.text = String(format: "EEP page [%d] : %02x %02x %02x %02x %02x %02x %02x %02x",
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
}
}
//
// Sensor data
//
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
label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)")
accelGraph.add(double3(Double(x), Double(y), Double(z)))
// 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
label.text = String("Gyro - x:\(xq), y:\(yq), z:\(zq)")
gyroGraph.add(double3(Double(x), Double(y), Double(z)))
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
let x = (Int32(data[4]) & 0xff) | (Int32(data[5]) << 8) | (Int32(data[6]) << 16) | (Int32(data[7]) << 24)
let xf = Float(x) / 100.0;
label.text = String("Humidity : \(xf)")
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 y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
label.text = String("Mag - x:\(x), y:\(y), z:\(z)")
magGraph.add(double3(Double(x), Double(y), Double(z)))
//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:
let x = (Int32(data[4]) & 0xff) | (Int32(data[5]) << 8) | (Int32(data[6]) << 16) | (Int32(data[7]) << 24)
let xf = Float(x) / 100.0;
label.text = String("Temperature : \(xf)")
//print("Temperature \(xf)")
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
label.text = String("IMU - x:\(x), y:\(y), z:\(z)")
accelGraph.add(double3(Double(x), Double(y), Double(z)))
let gx = (Int16(data[10]) & 0xff) | (Int16(data[11]) << 8)
let gy = (Int16(data[12]) & 0xff) | (Int16(data[13]) << 8)
let gz = (Int16(data[14]) & 0xff) | (Int16(data[15]) << 8)
gyroGraph.add(double3(Double(gx), Double(gy), Double(gz)))
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
label.text = String("Accel - x:\(x), y:\(y), z:\(z)")
accelGraph.add(double3(Double(x), Double(y), Double(z)))
let mx = (Int16(data[10]) & 0xff) | (Int16(data[11]) << 8)
let my = (Int16(data[12]) & 0xff) | (Int16(data[13]) << 8)
let mz = (Int16(data[14]) & 0xff) | (Int16(data[15]) << 8)
magGraph.add(double3(Double(mx), Double(my), Double(mz)))
break
default:
break
}
cmdView.setNeedsDisplay()
}
func didReceiveBatteryLevel(sender: Neblina, level: UInt8) {
print("Batt level \(level)")
}
// MARK : UITableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return /*FusionCmdList.count + */NebCmdList.count //+ CtrlName.count
//return 1//detailItem
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cellView = tableView.dequeueReusableCell(withIdentifier: "CellCommand", for: indexPath)
let labelView = cellView.viewWithTag(255) as! UILabel
// let switchCtrl = cellView.viewWithTag(2) as! UIControl//UISegmentedControl
// var buttonCtrl = cellView.viewWithTag(3) as! UIButton
// buttonCtrl.hidden = true
//switchCtrl.addTarget(self, action: "switchAction:", forControlEvents: UIControlEvents.ValueChanged)
/* if (indexPath!.row < FusionCmdList.count) {
labelView.text = FusionCmdList[indexPath!.row].Name //NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String
} else */
if ((indexPath as NSIndexPath).row < /*FusionCmdList.count + */NebCmdList.count) {
labelView.text = NebCmdList[(indexPath as NSIndexPath).row].Name// - FusionCmdList.count].Name
switch (NebCmdList[(indexPath as NSIndexPath).row].Actuator)
{
case ACTUATOR_TYPE_SWITCH:
let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UISegmentedControl
control.isHidden = false
let b = cellView.viewWithTag(2) as! UIButton
b.isHidden = true
let t = cellView.viewWithTag(3) as! UITextField
t.isHidden = true
break
case ACTUATOR_TYPE_BUTTON:
let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UIButton
control.isHidden = false
if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty
{
control.setTitle(NebCmdList[(indexPath as NSIndexPath).row].Text, for: UIControl.State())
}
let s = cellView.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cellView.viewWithTag(3) as! UITextField
t.isHidden = true
break
case ACTUATOR_TYPE_TEXT_FIELD:
let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UITextField
control.isHidden = false
if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty
{
control.text = NebCmdList[(indexPath as NSIndexPath).row].Text
}
let s = cellView.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let b = cellView.viewWithTag(2) as! UIButton
b.isHidden = true
break
case ACTUATOR_TYPE_TEXT_FIELD_BUTTON:
let tfcontrol = cellView.viewWithTag(4) as! UITextField
tfcontrol.isHidden = false
/* if !NebCmdList[(indexPath! as NSIndexPath).row].Text.isEmpty
{
tfcontrol.text = NebCmdList[(indexPath! as NSIndexPath).row].Text
}*/
let bucontrol = cellView.viewWithTag(2) as! UIButton
bucontrol.isHidden = false
if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty
{
bucontrol.setTitle(NebCmdList[(indexPath as NSIndexPath).row].Text, for: UIControl.State())
}
let s = cellView.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cellView.viewWithTag(3) as! UITextField
t.isHidden = true
break
case ACTUATOR_TYPE_TEXT_FIELD_SWITCH:
let tfcontrol = cellView.viewWithTag(4) as! UITextField
tfcontrol.isHidden = false
let bucontrol = cellView.viewWithTag(1) as! UISegmentedControl
bucontrol.isHidden = false
let s = cellView.viewWithTag(2) as! UIButton
s.isHidden = true
let t = cellView.viewWithTag(3) as! UITextField
t.isHidden = true
break
default:
//switchCtrl.enabled = false
// switchCtrl.hidden = true
// buttonCtrl.hidden = true
break
}
}
// else {
// labelView.text = CtrlName[indexPath!.row /*- FusionCmdList.count*/ - NebCmdList.count] //NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String
// }
//cellView.textLabel!.text = NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String
return cellView;
}
func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath?) -> Bool
{
return false
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
if (nebdev == nil) {
return
}
nebdev!.getSystemStatus()
}
}
| 67275fe00f58196a8ad6761e2d2a2654 | 35.748144 | 192 | 0.654256 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.