repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
zjjzmw1/robot | robot/robot/CodeFragment/Category/UITextView+JCTextView.swift | 3 | 1347 | //
// UITextView+JCTextView.swift
// JCSwiftKitDemo
//
// Created by molin.JC on 2017/1/23.
// Copyright © 2017年 molin. All rights reserved.
//
import UIKit
extension UITextView {
/// 选中所有文字
func selectAllText() {
let range = self.textRange(from: self.beginningOfDocument, to: self.endOfDocument);
self.selectedTextRange = range;
}
/// 当前选中的字符串范围
func currentSelectedRange() -> NSRange? {
let beginning = self.beginningOfDocument;
let selectedRange = self.selectedTextRange;
let selectionStart = selectedRange?.start;
let selectionEnd = selectedTextRange?.end;
let location = self.offset(from: beginning, to: selectionStart!);
let length = self.offset(from: selectionStart!, to: selectionEnd!);
return NSRange.init(location: location, length: length);
}
/// 选中指定范围的文字
func setSelectedRange(range: NSRange) {
let beginning = self.beginningOfDocument;
let startPosition = self.position(from: beginning, offset: range.location);
let endPosition = self.position(from: beginning, offset: NSMaxRange(range));
let selectionRange = self.textRange(from: startPosition!, to: endPosition!);
self.selectedTextRange = selectionRange;
}
}
| mit | a8e200bffb306d7c2bd0ecf1dd3818b5 | 33.052632 | 91 | 0.669243 | 4.493056 | false | false | false | false |
candyan/RepairMan | RepairMan/AppDelegate.swift | 1 | 2770 | //
// AppDelegate.swift
// RepairMan
//
// Created by Cherry on 8/16/15.
// Copyright © 2015 ABRS. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
// Applicaton Delegate
extension AppDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.setupApplication()
self.setupLeanCloud()
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.rootViewController = AppManager.sharedManager.rootNavigator
if AVUser.currentUser() == nil {
AppManager.sharedManager.rootNavigator.setViewControllers([LaunchViewController()], animated: false)
AppManager.sharedManager.rootNavigator.navigationBarHidden = true
} else {
AppManager.sharedManager.rootNavigator.setViewControllers([HomeViewController()], animated: false)
}
self.window!.makeKeyAndVisible()
return true
}
}
extension AppDelegate {
func setupApplication() {
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().barTintColor = UIColor(hex: 0x4A90E2)
let titleTextAttributes = [
NSFontAttributeName: UIFont(name: "Helvetica", size: 18)!,
NSForegroundColorAttributeName: UIColor.whiteColor()]
UINavigationBar.appearance().titleTextAttributes = titleTextAttributes
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-1000, -100), forBarMetrics: .Default)
let backButtonImage = UIImage(named: "NaviBack")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 25, 0, 0), resizingMode: .Stretch)
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, forState: .Normal, barMetrics: .Default)
// UIText Setup
UITextField.appearance().tintColor = UIColor(hex: 0x4A90E2)
UITextView.appearance().tintColor = UIColor(hex: 0x4A90E2)
// UILabel Setup
UILabel.appearance().backgroundColor = UIColor.clearColor()
// UITableView Cell Setup
UITableView.appearance().backgroundColor = UIColor.whiteColor()
UITableView.appearance().backgroundView = nil
UITableViewCell.appearance().backgroundColor = UIColor.whiteColor()
}
func setupLeanCloud() {
ABRSRepairOrder.registerSubclass()
AVOSCloud.setApplicationId("XBvsVbmtLdgaWp4BX5lQx1b2",
clientKey: "mS6YsrOQswTDVbSh7r0gvgzI")
}
}
| mit | f0ec184c3990f35d8a2fe6344914852f | 35.434211 | 140 | 0.683279 | 5.214689 | false | false | false | false |
cornerstonecollege/402 | boyoung_chae/GestureRecognizer/CustomViews/ViewController.swift | 1 | 1380 | //
// ViewController.swift
// CustomViews
//
// Created by Boyoung on 2016-10-13.
// Copyright © 2016 Boyoung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let frame = CGRect(x: 0, y: 50, width: 100, height: 100)
let view1 = FirstCustomView(frame: frame)
self.view.addSubview(view1)
let frame2 = CGRect(x: 200, y: 50, width: 100, height: 100)
let view2 = FirstCustomView(frame: frame2)
self.view.addSubview(view2)
let frame3 = CGRect(x: 0, y: 0, width: 200, height: 250)
let view3 = FirstCustomView(frame: frame3)
view3.center = self.view.center
self.view.addSubview(view3)
let circleFrame = CGRect(x: 100, y: 100, width: 100, height: 100)
let circle = CircleView(frame: circleFrame)
//circle.backgroundColor = UIColor.yellow
self.view.addSubview(circle)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didPanGesture(_ pan: UIPanGestureRecognizer) {
pan.view!.center = pan.location(in: self.view)
}
}
| gpl-3.0 | e3359eaf7fa947da5c59e7a921c1e817 | 29.644444 | 80 | 0.626541 | 4.128743 | false | false | false | false |
aipeople/PokeIV | PokeIV/LoadingCell.swift | 1 | 2449 | //
// LoadingCell.swift
// PokeIV
//
// Created by aipeople on 8/15/16.
// Github: https://github.com/aipeople/PokeIV
// Copyright © 2016 su. All rights reserved.
//
import UIKit
import Cartography
import Shimmer
class LoadingCell: UITableViewCell {
// MARK: - Properties
let container = UIView()
let separator = UIView()
let shimmeringView = FBShimmeringView()
// MARK: - Life Cycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Setup constraints
self.contentView.addSubview(self.container)
constrain(self.container) { (view) in
view.center == view.superview!.center
view.width == view.superview!.width - 20
view.height == view.superview!.height - 10
}
self.container.addSubview(self.separator)
constrain(self.separator) { (view) in
view.left == view.superview!.left + 10
view.right == view.superview!.right - 10
view.bottom == view.superview!.bottom - 71
view.height == 1
}
self.container.addSubview(self.shimmeringView)
// Setup views
self.backgroundColor = UIColor.clearColor()
self.selectionStyle = .None
self.container.backgroundColor = App.Color.Background.Level2
self.container.layer.cornerRadius = 2
self.separator.backgroundColor = UIColor(white: 0, alpha: 0.15)
let image = UIImage(named: "image_cell_placeholder")
let placeholderView = UIImageView(image: image)
placeholderView.tintColor = App.Color.Text.Disable
self.shimmeringView.frame = CGRect(
origin: CGPoint(x: 10, y: 10),
size: placeholderView.frame.size
)
self.shimmeringView.contentView = placeholderView;
self.shimmeringView.shimmeringAnimationOpacity = 0.25
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.shimmeringView.shimmering = true;
}
override func removeFromSuperview() {
super.removeFromSuperview()
self.shimmeringView.shimmering = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| gpl-3.0 | fdc12cc2974a0c298047bbef4d84c931 | 28.142857 | 74 | 0.60335 | 4.744186 | false | false | false | false |
SwiftAndroid/swift | test/SILGen/import_as_member.swift | 5 | 1896 | // RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s 2>&1 | FileCheck --check-prefix=SIL %s
// REQUIRES: objc_interop
import ImportAsMember.A
import ImportAsMember.Proto
import ImportAsMember.Class
public func returnGlobalVar() -> Double {
return Struct1.globalVar
}
// SIL-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double {
// SIL: %0 = global_addr @IAMStruct1GlobalVar : $*Double
// SIL: %2 = load %0 : $*Double
// SIL: return %2 : $Double
// SIL-NEXT: }
// SIL-LABEL: sil {{.*}}useProto{{.*}} (@owned IAMProto) -> () {
// TODO: Add in body checks
public func useProto(p: IAMProto) {
p.mutateSomeState()
let v = p.someValue
p.someValue = v+1
}
// SIL-LABEL: sil {{.*}}anchor{{.*}} () -> () {
func anchor() {}
// SIL-LABEL: sil {{.*}}useClass{{.*}}
// SIL: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options):
public func useClass(d: Double, opts: SomeClass.Options) {
// SIL: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass
// SIL: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]])
let o = SomeClass(value: d)
// SIL: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> ()
// SIL: apply [[APPLY_FN]]([[OBJ]], [[OPTS]])
o.applyOptions(opts)
}
extension SomeClass {
// SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_
// SIL: bb0([[DOUBLE:%[0-9]+]] : $Double
// SIL-NOT: value_metatype
// SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// SIL: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
public func useSpecialInit() -> Struct1 {
// FIXME: the below triggers an assert, due to number or params mismatch
// return Struct1(specialLabel:())
}
public func useGlobal() -> Double {
return Struct1.globalVar
}
| apache-2.0 | 219d9980f44df3af0339948e01259943 | 32.263158 | 126 | 0.631329 | 3.257732 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/AddArticlesToReadingListViewController.swift | 1 | 6076 | import UIKit
import CocoaLumberjackSwift
protocol AddArticlesToReadingListDelegate: NSObjectProtocol {
func addArticlesToReadingListWillClose(_ addArticlesToReadingList: AddArticlesToReadingListViewController)
func addArticlesToReadingListDidDisappear(_ addArticlesToReadingList: AddArticlesToReadingListViewController)
func addArticlesToReadingList(_ addArticlesToReadingList: AddArticlesToReadingListViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList)
}
extension AddArticlesToReadingListDelegate where Self: EditableCollection {
func addArticlesToReadingListWillClose(_ addArticlesToReadingList: AddArticlesToReadingListViewController) {
editController.close()
}
func addArticlesToReadingList(_ addArticlesToReadingList: AddArticlesToReadingListViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList) {
editController.close()
}
}
extension AddArticlesToReadingListDelegate {
func addArticlesToReadingListDidDisappear(_ addArticlesToReadingList: AddArticlesToReadingListViewController) {
}
}
@objc(WMFAddArticlesToReadingListViewController)
class AddArticlesToReadingListViewController: ViewController {
private let dataStore: MWKDataStore
private let articles: [WMFArticle]
public let moveFromReadingList: ReadingList?
private let readingListsViewController: ReadingListsViewController
public weak var delegate: AddArticlesToReadingListDelegate?
@objc var eventLogAction: (() -> Void)?
@objc public init(with dataStore: MWKDataStore, articles: [WMFArticle], moveFromReadingList: ReadingList? = nil, theme: Theme) {
self.dataStore = dataStore
self.articles = articles
self.moveFromReadingList = moveFromReadingList
self.readingListsViewController = ReadingListsViewController(with: dataStore, articles: articles)
super.init()
self.theme = theme
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func closeButtonPressed() {
dismiss(animated: true)
delegate?.addArticlesToReadingListWillClose(self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
delegate?.addArticlesToReadingListDidDisappear(self)
}
@objc private func createNewReadingListButtonPressed() {
readingListsViewController.createReadingList(with: articles, moveFromReadingList: moveFromReadingList)
}
override func accessibilityPerformEscape() -> Bool {
closeButtonPressed()
return true
}
private var isCreateNewReadingListButtonViewHidden: Bool = false {
didSet {
if isCreateNewReadingListButtonViewHidden {
navigationBar.removeUnderNavigationBarView()
readingListsViewController.createNewReadingListButtonView.button.removeTarget(self, action: #selector(createNewReadingListButtonPressed), for: .touchUpInside)
} else {
readingListsViewController.createNewReadingListButtonView.button.addTarget(self, action: #selector(createNewReadingListButtonPressed), for: .touchUpInside)
navigationBar.addUnderNavigationBarView(readingListsViewController.createNewReadingListButtonView)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "close"), style: .plain, target: self, action: #selector(closeButtonPressed))
let title = moveFromReadingList != nil ? WMFLocalizedString("move-articles-to-reading-list", value:"Move {{PLURAL:%1$d|%1$d article|%1$d articles}} to reading list", comment:"Title for the view in charge of moving articles to a reading list - %1$@ is replaced with the number of articles to move") : WMFLocalizedString("add-articles-to-reading-list", value:"Add {{PLURAL:%1$d|%1$d article|%1$d articles}} to reading list", comment:"Title for the view in charge of adding articles to a reading list - %1$@ is replaced with the number of articles to add")
navigationItem.title = String.localizedStringWithFormat(title, articles.count)
navigationBar.displayType = .modal
navigationBar.isBarHidingEnabled = false
navigationBar.isUnderBarViewHidingEnabled = true
isCreateNewReadingListButtonViewHidden = readingListsViewController.isEmpty
addChild(readingListsViewController)
view.wmf_addSubviewWithConstraintsToEdges(readingListsViewController.view)
readingListsViewController.didMove(toParent: self)
readingListsViewController.delegate = self
scrollView = readingListsViewController.scrollView
apply(theme: theme)
}
// MARK: Themeable
override func apply(theme: Theme) {
super.apply(theme: theme)
readingListsViewController.apply(theme: theme)
}
}
// MARK: ReadingListsViewControllerDelegate
extension AddArticlesToReadingListViewController: ReadingListsViewControllerDelegate {
func readingListsViewController(_ readingListsViewController: ReadingListsViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList) {
if let moveFromReadingList = moveFromReadingList {
do {
try dataStore.readingListsController.remove(articles: articles, readingList: moveFromReadingList)
} catch let error {
DDLogError("Error removing articles after move: \(error)")
}
}
delegate?.addArticlesToReadingList(self, didAddArticles: articles, to: readingList)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) {
self.dismiss(animated: true)
}
eventLogAction?()
}
func readingListsViewControllerDidChangeEmptyState(_ readingListsViewController: ReadingListsViewController, isEmpty: Bool) {
isCreateNewReadingListButtonViewHidden = isEmpty
}
}
| mit | 960ac90f8c92dcf48a25f010e9b783c3 | 46.46875 | 561 | 0.743088 | 5.836695 | false | false | false | false |
russelhampton05/MenMew | App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/ThemePopupViewController.swift | 1 | 6813 | //
// ThemePopupViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 11/11/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
class ThemePopupViewController: UIViewController {
//IBOutlets
@IBOutlet var themeLabel: UILabel!
@IBOutlet var themeTitle: UILabel!
@IBOutlet var theme1View: UIView!
@IBOutlet var theme2View: UIView!
@IBOutlet var theme3View: UIView!
@IBOutlet var theme4View: UIView!
@IBOutlet var popupView: UIView!
@IBOutlet var confirmButton: UIButton!
@IBOutlet var cancelButton: UIButton!
@IBOutlet var theme1GestureRecognizer: UITapGestureRecognizer!
@IBOutlet var theme2GestureRecognizer: UITapGestureRecognizer!
@IBOutlet var theme3GestureRecognizer: UITapGestureRecognizer!
@IBOutlet var theme4GestureRecognizer: UITapGestureRecognizer!
//Variables
var newTheme: Theme?
var oldTheme: Theme?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
self.showAnimate()
themeTitle.text = currentServer!.theme!
oldTheme = currentTheme
initializeGestureRecognizers()
loadCircles()
loadTheme()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func confirmButtonPressed(_ sender: Any) {
currentServer!.theme = themeTitle.text
ServerManager.setTheme(server: currentServer!, theme: themeTitle.text!)
removeAnimate()
}
@IBAction func cancelButtonPressed(_ sender: Any) {
currentTheme = oldTheme
removeAnimate()
}
//Popup view animation
func showAnimate() {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
UIView.animate(withDuration: 0.5, animations: {
self.view.alpha = 1.0
self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
//Popup remove animation
func removeAnimate() {
UIView.animate(withDuration: 0.5, animations: {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
}, completion:{(finished : Bool) in
if (finished)
{
if let parent = self.parent as? AppSettingsViewController {
parent.themeButton.setTitle(currentServer!.theme, for: .normal)
parent.reloadTheme()
}
self.view.removeFromSuperview()
}
})
}
//Theme press function
func themeTapped(selectedTheme: UITapGestureRecognizer) {
if selectedTheme == theme1GestureRecognizer {
newTheme = Theme.init(type: "Salmon")
themeTitle.text = "Salmon"
}
else if selectedTheme == theme2GestureRecognizer {
newTheme = Theme.init(type: "Light")
themeTitle.text = "Light"
}
else if selectedTheme == theme3GestureRecognizer {
newTheme = Theme.init(type: "Midnight")
themeTitle.text = "Midnight"
}
else if selectedTheme == theme4GestureRecognizer {
newTheme = Theme.init(type: "Slate")
themeTitle.text = "Slate"
}
currentTheme = newTheme
loadTheme()
}
//Initialize tap gestures on theme buttons
func initializeGestureRecognizers() {
theme1GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(themeTapped(selectedTheme:)))
theme2GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(themeTapped(selectedTheme:)))
theme3GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(themeTapped(selectedTheme:)))
theme4GestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(themeTapped(selectedTheme:)))
theme1View.isUserInteractionEnabled = true
theme2View.isUserInteractionEnabled = true
theme3View.isUserInteractionEnabled = true
theme4View.isUserInteractionEnabled = true
theme1View.addGestureRecognizer(theme1GestureRecognizer)
theme2View.addGestureRecognizer(theme2GestureRecognizer)
theme3View.addGestureRecognizer(theme3GestureRecognizer)
theme4View.addGestureRecognizer(theme4GestureRecognizer)
}
//Set theme buttons to be circles
func loadCircles() {
theme1View.layer.cornerRadius = theme1View.frame.size.width/2
theme1View.clipsToBounds = true
theme2View.layer.cornerRadius = theme2View.frame.size.width/2
theme2View.clipsToBounds = true
theme3View.layer.cornerRadius = theme3View.frame.size.width/2
theme3View.clipsToBounds = true
theme4View.layer.cornerRadius = theme4View.frame.size.width/2
theme4View.clipsToBounds = true
}
func loadTheme() {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
//Background and Tint
self.view.tintColor = currentTheme!.invert!
self.popupView.backgroundColor = currentTheme!.secondary!
//Labels
self.themeLabel.textColor = currentTheme!.invert!
self.themeTitle.textColor = currentTheme!.invert!
//Views
self.theme1View.backgroundColor = UIColor(red: 255, green: 106, blue: 92)
self.theme2View.backgroundColor = UIColor(red: 255, green: 141, blue: 43)
self.theme3View.backgroundColor = UIColor(red: 55, green: 30, blue: 96)
self.theme4View.backgroundColor = UIColor(red: 27, green: 27, blue: 27)
//Buttons
if currentTheme!.name! == "Salmon" {
self.confirmButton.backgroundColor = currentTheme!.invert!
self.confirmButton.setTitleColor(currentTheme!.highlight!, for: .normal)
self.cancelButton.backgroundColor = currentTheme!.invert!
self.cancelButton.setTitleColor(currentTheme!.highlight!, for: .normal)
}
else {
self.confirmButton.backgroundColor = currentTheme!.highlight!
self.confirmButton.setTitleColor(currentTheme!.primary!, for: .normal)
self.cancelButton.backgroundColor = currentTheme!.highlight!
self.cancelButton.setTitleColor(currentTheme!.primary!, for: .normal)
}
})
}
}
| mit | c64772d4331f722bf8d292d7102d2335 | 35.234043 | 118 | 0.628743 | 5.042191 | false | false | false | false |
hellogaojun/Swift-coding | swift学习教材案例/Swifter.playground/Pages/tuple.xcplaygroundpage/Contents.swift | 1 | 367 |
import UIKit
func swapMe1<T>(inout a: T, inout b: T) {
let temp = a
a = b
b = temp
}
func swapMe2<T>(inout a: T, inout b: T) {
(a,b) = (b,a)
}
var a = 1
var b = 2
(a, b)
swapMe1(&a, b: &b)
(a, b)
swapMe2(&a, b: &b)
(a, b)
let rect = CGRectMake(0, 0, 100, 100)
let (small, large) = rect.rectsByDividing(20, fromEdge: .MinXEdge)
small
large
| apache-2.0 | c5d7c1999fe9cbff4ad4ebf91d198466 | 10.46875 | 66 | 0.553134 | 2.146199 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGenerator/TulsiProjectInfoExtractor.swift | 1 | 5175 | // Copyright 2016 The Tulsi 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 Foundation
// Provides functionality to generate a TulsiGeneratorConfig from a TulsiProject.
public final class TulsiProjectInfoExtractor {
public enum ExtractorError: Error {
case ruleEntriesFailed(String)
}
private let project: TulsiProject
private let localizedMessageLogger: LocalizedMessageLogger
var workspaceInfoExtractor: BazelWorkspaceInfoExtractorProtocol
public var bazelURL: URL {
get { return workspaceInfoExtractor.bazelURL as URL }
set { workspaceInfoExtractor.bazelURL = newValue }
}
public var bazelExecutionRoot: String {
return workspaceInfoExtractor.bazelExecutionRoot
}
public var bazelOutputBase: String {
return workspaceInfoExtractor.bazelOutputBase
}
public var workspaceRootURL: URL {
return workspaceInfoExtractor.workspaceRootURL
}
public init(bazelURL: URL,
project: TulsiProject) {
self.project = project
let bundle = Bundle(for: type(of: self))
localizedMessageLogger = LocalizedMessageLogger(bundle: bundle)
workspaceInfoExtractor = BazelWorkspaceInfoExtractor(bazelURL: bazelURL,
workspaceRootURL: project.workspaceRootURL,
localizedMessageLogger: localizedMessageLogger)
}
public func extractTargetRules() -> [RuleInfo] {
return workspaceInfoExtractor.extractRuleInfoFromProject(project)
}
public func ruleEntriesForInfos(_ infos: [RuleInfo],
startupOptions: TulsiOption,
extraStartupOptions: TulsiOption,
buildOptions: TulsiOption,
compilationModeOption: TulsiOption,
platformConfigOption: TulsiOption,
prioritizeSwiftOption: TulsiOption,
use64BitWatchSimulatorOption: TulsiOption,
features: Set<BazelSettingFeature>) throws -> RuleEntryMap {
return try ruleEntriesForLabels(infos.map({ $0.label }),
startupOptions: startupOptions,
extraStartupOptions: extraStartupOptions,
buildOptions: buildOptions,
compilationModeOption: compilationModeOption,
platformConfigOption: platformConfigOption,
prioritizeSwiftOption: prioritizeSwiftOption,
use64BitWatchSimulatorOption: use64BitWatchSimulatorOption,
features: features)
}
public func ruleEntriesForLabels(_ labels: [BuildLabel],
startupOptions: TulsiOption,
extraStartupOptions: TulsiOption,
buildOptions: TulsiOption,
compilationModeOption: TulsiOption,
platformConfigOption: TulsiOption,
prioritizeSwiftOption: TulsiOption,
use64BitWatchSimulatorOption: TulsiOption,
features: Set<BazelSettingFeature>) throws -> RuleEntryMap {
do {
return try workspaceInfoExtractor.ruleEntriesForLabels(labels,
startupOptions: startupOptions,
extraStartupOptions: extraStartupOptions,
buildOptions: buildOptions,
compilationModeOption: compilationModeOption,
platformConfigOption: platformConfigOption,
prioritizeSwiftOption: prioritizeSwiftOption,
use64BitWatchSimulatorOption: use64BitWatchSimulatorOption,
features: features)
} catch BazelWorkspaceInfoExtractorError.aspectExtractorFailed(let info) {
throw ExtractorError.ruleEntriesFailed(info)
}
}
public func extractBuildfiles(_ targets: [BuildLabel]) -> Set<BuildLabel> {
return workspaceInfoExtractor.extractBuildfiles(targets)
}
}
| apache-2.0 | eb466a87c4fa0a2a59a7c7d15e9d25a0 | 47.820755 | 120 | 0.579324 | 6.460674 | false | true | false | false |
WaterReporter/WaterReporter-iOS | WaterReporter/WaterReporter/ActivityMapViewController.swift | 1 | 10825 | //
// ActivityMapViewController.swift
// WaterReporter
//
// Created by Viable Industries on 8/1/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Alamofire
import Foundation
import Kingfisher
import Mapbox
import SwiftyJSON
import UIKit
class ActivityMapViewController: UIViewController, MGLMapViewDelegate {
var reports = [AnyObject]() // THIS NEEDS TO BE A SET NOT AN ARRAY
var reportObject: AnyObject!
var reportLongitude:Double!
var reportLatitude:Double!
override func viewDidLoad() {
super.viewDidLoad()
self.setCoordinateDefaults()
//
// Setup map view and add it to the view controller
//
self.setupMap()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupMap() {
let styleURL = NSURL(string: "mapbox://styles/rdawes1/circfufio0013h4nlhibdw240")
let mapView = MGLMapView(frame: view.bounds, styleURL:styleURL)
mapView.delegate = self
mapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: reportLatitude, longitude: reportLongitude), zoomLevel: 15, animated: false)
//
// Add default center pin to the map
//
self.addReportToMap(mapView, report: reportObject, latitude: reportLatitude, longitude: reportLongitude, center:true)
//
// Load additional region based pins
//
self.loadAllReportsInRegion(mapView)
//
// Add map to subview
//
view.addSubview(mapView)
}
func addReportToMap(mapView: AnyObject, report: AnyObject, latitude: Double, longitude: Double, center:Bool) {
let _report = JSON(report)
let thisAnnotation = MGLPointAnnotation()
let _title = _report["properties"]["report_description"].string
var _subtitle: String = "Reported on "
let _date = "\(_report["properties"]["report_date"])"
thisAnnotation.report = report
let dateString = _date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let stringToFormat = dateFormatter.dateFromString(dateString)
dateFormatter.dateFormat = "MMM d, yyyy"
let displayDate = dateFormatter.stringFromDate(stringToFormat!)
if let thisDisplayDate: String? = displayDate {
_subtitle += thisDisplayDate!
}
thisAnnotation.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
thisAnnotation.title = _title
thisAnnotation.subtitle = _subtitle
mapView.addAnnotation(thisAnnotation)
if center {
// Center the map on the annotation.
mapView.setCenterCoordinate(thisAnnotation.coordinate, zoomLevel: 15, animated: false)
// Pop-up the callout view.
mapView.selectAnnotation(thisAnnotation, animated: true)
}
}
func loadAllReportsInRegion(mapView: AnyObject) {
//
// Send a request to the defined endpoint with the given parameters
//
let region = getViewportBoundaryString(mapView.visibleCoordinateBounds)
let polygon = "SRID=4326;POLYGON((" + region + "))"
let parameters = [
"q": "{\"filters\":[{\"name\":\"geometry\",\"op\":\"intersects\",\"val\":\"" + polygon + "\"}],\"order_by\": [{\"field\":\"created\",\"direction\":\"desc\"}]}"
]
print("polygon \(polygon)")
print("parameters \(parameters)")
Alamofire.request(.GET, Endpoints.GET_MANY_REPORTS, parameters: parameters)
.responseJSON { response in
switch response.result {
case .Success(let value):
print("value \(value)")
let returnValue = value["features"] as! [AnyObject]
self.reports = returnValue // WE NEED TO FILTER DOWN SO THERE ARE NO DUPLICATE REPORTS LOADED ONTO THE MAP
self.addReportsToMap(mapView, reports:self.reports)
case .Failure(let error):
print(error)
break
}
}
}
func addReportsToMap(mapView: AnyObject, reports: NSArray) {
let _reportObject = JSON(self.reportObject)
for _report in reports {
let _thisReport = JSON(_report)
if "\(_thisReport["id"])" != "\(_reportObject["id"])" {
let _geometry = _thisReport["geometry"]["geometries"][0]["coordinates"]
reportLongitude = _geometry[0].double
reportLatitude = _geometry[1].double
self.addReportToMap(mapView, report: _report, latitude: reportLatitude, longitude: reportLongitude, center:false)
}
}
}
func getViewportBoundaryString(boundary: MGLCoordinateBounds) -> String {
print("boundary")
print(boundary)
let topLeft: String = String(format:"%f %f", boundary.ne.longitude, boundary.sw.latitude)
let topRight: String = String(format:"%f %f", boundary.ne.longitude, boundary.ne.latitude)
let bottomRight: String = String(format:"%f %f", boundary.sw.longitude, boundary.ne.latitude)
let bottomLeft: String = String(format:"%f %f", boundary.sw.longitude, boundary.sw.latitude)
return [topLeft, topRight, bottomRight, bottomLeft, topLeft].joinWithSeparator(",")
}
func setCoordinateDefaults() {
let _tempReport = JSON(self.reportObject)
let reportCoordinates = _tempReport["geometry"]["geometries"][0]["coordinates"]
reportLongitude = reportCoordinates[0].double
reportLatitude = reportCoordinates[1].double
}
//
// MARK: Mapbox Overrides
//
func mapView(mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
self.loadAllReportsInRegion(mapView)
}
func mapView(mapView: MGLMapView, viewForAnnotation annotation: MGLAnnotation) -> MGLAnnotationView? {
guard annotation is MGLPointAnnotation else {
return nil
}
let report = JSON(annotation.report)
let reuseIdentifier = "report_\(report["id"])"
// For better performance, always try to reuse existing annotations.
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier)
if annotationView == nil {
// Add outline to the Report marker view
//
annotationView = MGLAnnotationView(reuseIdentifier: reuseIdentifier)
annotationView!.frame = CGRectMake(0, 0, 64, 64)
annotationView?.backgroundColor = UIColor.clearColor()
// Add Report > Image to the marker view
//
let reportImageURL: NSURL = NSURL(string: "\(report["properties"]["images"][0]["properties"]["icon"])")!
let reportImageView = UIImageView()
var reportImageUpdate: Image?
reportImageView.frame = CGRect(x: 0, y: 0, width: 64, height: 64)
reportImageView.kf_indicatorType = .Activity
reportImageView.kf_showIndicatorWhenLoading = true
reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: {
(image, error, cacheType, imageUrl) in
reportImageUpdate = Image(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up)
reportImageView.image = reportImageUpdate
reportImageView.layer.cornerRadius = reportImageView.frame.size.width / 2
reportImageView.clipsToBounds = true
reportImageView.layer.cornerRadius = reportImageView.frame.width / 2
reportImageView.layer.borderWidth = 4
reportImageView.layer.borderColor = UIColor.whiteColor().CGColor
})
//
//
annotationView?.addSubview(reportImageView)
annotationView?.bringSubviewToFront(reportImageView)
// If report is closed, at the action marker view
//
if "\(report["properties"]["state"])" == "closed" {
print("show report view closed badge")
let reportBadgeImageView = UIImageView()
let reportBadgeImage = UIImage(named: "icon--Badge")!
reportBadgeImageView.contentMode = .ScaleAspectFill
reportBadgeImageView.image = reportBadgeImage
reportBadgeImageView.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
annotationView?.addSubview(reportBadgeImageView)
annotationView?.bringSubviewToFront(reportBadgeImageView)
}
else {
print("hide report closed badge")
}
}
return annotationView
}
func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
func mapView(mapView: MGLMapView, rightCalloutAccessoryViewForAnnotation annotation: MGLAnnotation) -> UIView? {
let annotationButton: UIButton = UIButton(type: .DetailDisclosure)
return annotationButton
}
func mapView(mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
//
// Hide the pop up
//
mapView.deselectAnnotation(annotation, animated: false)
//
// Load the activity controller from the storyboard
//
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("ActivityTableViewController") as! ActivityTableViewController
nextViewController.singleReport = true
nextViewController.reports = [annotation.report]
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
| agpl-3.0 | 3165e0bdce59d91d87404b45ed3706ee | 35.200669 | 171 | 0.595436 | 5.5 | false | false | false | false |
flutter/flutter | examples/flutter_view/macos/Runner/MainViewController.swift | 3 | 2389 | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Foundation
import AppKit
import FlutterMacOS
/**
The code behind a storyboard view which splits a flutter view and a macOS view.
*/
class MainViewController: NSViewController, NativeViewControllerDelegate {
static let emptyString: String = ""
static let ping: String = "ping"
static let channel: String = "increment"
var nativeViewController: NativeViewController?
var flutterViewController: FlutterViewController?
var messageChannel: FlutterBasicMessageChannel?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.identifier == "NativeViewControllerSegue" {
self.nativeViewController = segue.destinationController as? NativeViewController
// Since`MainViewController` owns the platform channel, but not the
// UI elements that trigger an action, those UI elements need a reference
// to this controller to send messages on the platform channel.
self.nativeViewController?.delegate = self
}
if segue.identifier == "FlutterViewControllerSegue" {
self.flutterViewController = segue.destinationController as? FlutterViewController
RegisterMethodChannel(registry: self.flutterViewController!)
weak var weakSelf = self
messageChannel?.setMessageHandler({ (message, reply) in
// Dispatch an event, incrementing the counter in this case, when *any*
// message is received.
// Depending on the order of initialization, the nativeViewController
// might not be initialized until this point.
weakSelf?.nativeViewController?.didReceiveIncrement()
reply(MainViewController.emptyString)
})
}
}
func RegisterMethodChannel(registry: FlutterPluginRegistry) {
let registrar = registry.registrar(forPlugin: "")
messageChannel = FlutterBasicMessageChannel(
name: MainViewController.channel,
binaryMessenger: registrar.messenger,
codec: FlutterStringCodec.sharedInstance())
}
// Call in any instance where `ping` is to be sent through the `increment`
// channel.
func didTapIncrementButton() {
self.messageChannel?.sendMessage(MainViewController.ping)
}
}
| bsd-3-clause | 3903263ff13b22da60cbaa2708ccc474 | 33.623188 | 88 | 0.738803 | 5.093817 | false | false | false | false |
binarylevel/Tinylog-iOS | Tinylog/Views/Cells/TLITaskTableViewCell.swift | 1 | 10288 | //
// TLITaskTableViewCell.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
import TTTAttributedLabel
import SGBackgroundView
class TLITaskTableViewCell: TLITableViewCell {
let kLabelHorizontalInsets: CGFloat = 60.0
let kLabelVerticalInsets: CGFloat = 10.0
var didSetupConstraints = false
let taskLabel:TTTAttributedLabel = TTTAttributedLabel.newAutoLayoutView()
var bgView:SGBackgroundView?
let checkBoxButton:TLICheckBoxButton = TLICheckBoxButton.newAutoLayoutView()
var checkMarkIcon:UIImageView?
var currentTask:TLITask? {
didSet {
//Fetch all objects from list
let cdc:TLICDController = TLICDController.sharedInstance
let fetchRequestTotal:NSFetchRequest = NSFetchRequest(entityName: "Task")
let positionDescriptor = NSSortDescriptor(key: "position", ascending: false)
fetchRequestTotal.sortDescriptors = [positionDescriptor]
fetchRequestTotal.predicate = NSPredicate(format: "archivedAt = nil AND list = %@", currentTask!.list!)
fetchRequestTotal.fetchBatchSize = 20
do {
let results:NSArray = try cdc.context!.executeFetchRequest(fetchRequestTotal)
let fetchRequestCompleted:NSFetchRequest = NSFetchRequest(entityName: "Task")
fetchRequestCompleted.sortDescriptors = [positionDescriptor]
fetchRequestCompleted.predicate = NSPredicate(format: "archivedAt = nil AND completed = %@ AND list = %@", NSNumber(bool: true), currentTask!.list!)
fetchRequestCompleted.fetchBatchSize = 20
let resultsCompleted:NSArray = try cdc.context!.executeFetchRequest(fetchRequestCompleted)
let total:Int = results.count - resultsCompleted.count
currentTask?.list!.total = total
checkBoxButton.circleView?.layer.borderColor = UIColor(rgba: currentTask!.list!.color!).CGColor
checkBoxButton.checkMarkIcon?.image = checkBoxButton.checkMarkIcon?.image?.imageWithColor(UIColor(rgba: currentTask!.list!.color!))
} catch let error as NSError {
fatalError(error.localizedDescription)
}
updateFonts()
taskLabel.activeLinkAttributes = [kCTForegroundColorAttributeName: UIColor(rgba: currentTask!.list!.color!)]
if let boolValue = currentTask?.completed?.boolValue {
if boolValue {
checkBoxButton.checkMarkIcon!.hidden = false
checkBoxButton.alpha = 0.5
taskLabel.textColor = UIColor.lightGrayColor()
taskLabel.linkAttributes = [kCTForegroundColorAttributeName: UIColor.lightGrayColor()]
} else {
checkBoxButton.checkMarkIcon!.hidden = true
checkBoxButton.alpha = 1.0
taskLabel.textColor = UIColor.tinylogTextColor()
taskLabel.linkAttributes = [kCTForegroundColorAttributeName: UIColor(rgba: currentTask!.list!.color!)]
}
}
updateAttributedText()
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
bgView = SGBackgroundView(frame: CGRectZero)
bgView?.bgColor = UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
bgView?.lineColor = UIColor(red: 224.0 / 255.0, green: 224.0 / 255.0, blue: 224.0 / 255.0, alpha: 1.0)
bgView?.xPosLine = 16.0
self.backgroundView = bgView!
taskLabel.lineBreakMode = .ByTruncatingTail
taskLabel.numberOfLines = 0
taskLabel.textAlignment = .Left
taskLabel.textColor = UIColor.tinylogTextColor()
contentView.addSubview(taskLabel)
checkBoxButton.tableViewCell = self
self.contentView.addSubview(checkBoxButton)
updateFonts()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if !didSetupConstraints {
taskLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: 20.0)
taskLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: 16.0)
taskLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 50.0)
taskLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 20.0)
checkBoxButton.autoSetDimensionsToSize(CGSizeMake(30.0, 30.0))
checkBoxButton.autoAlignAxis(.Horizontal, toSameAxisOfView: self.contentView, withOffset: 0.0)
checkBoxButton.autoPinEdge(.Left, toEdge: .Right, ofView: taskLabel, withOffset: 10.0)
didSetupConstraints = true
}
super.updateConstraints()
}
override func updateFonts() {
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let useSystemFontSize:String = userDefaults.objectForKey("kSystemFontSize") as! String
if useSystemFontSize == "on" {
if TLISettingsFontPickerViewController.selectedKey() == "Avenir" {
taskLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "HelveticaNeue" {
taskLabel.font = UIFont.preferredHelveticaNeueFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "Courier" {
taskLabel.font = UIFont.preferredCourierFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "Georgia" {
taskLabel.font = UIFont.preferredGeorgiaFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "Menlo" {
taskLabel.font = UIFont.preferredMenloFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "TimesNewRoman" {
taskLabel.font = UIFont.preferredTimesNewRomanFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "Palatino" {
taskLabel.font = UIFont.preferredPalatinoFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "Iowan" {
taskLabel.font = UIFont.preferredIowanFontForTextStyle(UIFontTextStyleBody)
} else if TLISettingsFontPickerViewController.selectedKey() == "SanFrancisco" {
taskLabel.font = UIFont.preferredSFFontForTextStyle(UIFontTextStyleBody)
}
} else {
let fontSize:Float = userDefaults.floatForKey("kFontSize")
taskLabel.font = UIFont.tinylogFontOfSize(CGFloat(fontSize))
}
}
override func layoutSubviews() {
super.layoutSubviews()
let size:CGSize = self.contentView.bounds.size
self.contentView.setNeedsLayout()
self.contentView.layoutIfNeeded()
taskLabel.preferredMaxLayoutWidth = CGRectGetWidth(taskLabel.frame)
if self.editing {
bgView?.width = size.width + 78.0
bgView?.height = size.height
} else {
bgView?.width = size.width
bgView?.height = size.height
}
}
func updateAttributedText() {
taskLabel.setText(currentTask?.displayLongText, afterInheritingLabelAttributesAndConfiguringWithBlock: { (mutableAttributedString) -> NSMutableAttributedString! in
return mutableAttributedString;
})
if let text = taskLabel.text {
let total:NSString = text as NSString
let words:NSArray = total.componentsSeparatedByString(" ")
for word in words {
let character = word as! NSString
if character.hasPrefix("#") {
let value:NSString = character.substringWithRange(NSMakeRange(1, character.length - 1))
let range:NSRange = total.rangeOfString(character as String)
let url:NSURL = NSURL(string: NSString(format: "tag://%@", value) as String)!
let tagModel:TLITag = TLITag.existing(value, context: currentTask!.managedObjectContext!)!
let tags:NSMutableSet = currentTask?.valueForKeyPath("tags") as! NSMutableSet
tags.addObject(tagModel)
taskLabel.addLinkToURL(url, withRange: range)
} else if character.hasPrefix("http://") || character.hasPrefix("https://") {
let value:NSString = character.substringWithRange(NSMakeRange(0, character.length))
let range:NSRange = total.rangeOfString(character as String)
let url:NSURL = NSURL(string: NSString(format: "%@", value) as String)!
taskLabel.addLinkToURL(url, withRange: range)
} else if character.hasPrefix("@") {
let value:NSString = character.substringWithRange(NSMakeRange(1, character.length - 1))
let range:NSRange = total.rangeOfString(character as String)
let url:NSURL = NSURL(string: NSString(format: "mention://%@", value) as String)!
let mention:TLIMention = TLIMention.existing(value, context: currentTask!.managedObjectContext!)!
let mentions:NSMutableSet = currentTask?.valueForKeyPath("mentions") as! NSMutableSet
mentions.addObject(mention)
taskLabel.addLinkToURL(url, withRange: range)
}
}
}
}
}
| mit | 60c9cb13271159e4d91f2e5442571bff | 48.695652 | 171 | 0.630699 | 5.518777 | false | false | false | false |
SimonFairbairn/SwiftyMarkdown | Sources/SwiftyMarkdown/PerfomanceLog.swift | 2 | 1251 | //
// PerfomanceLog.swift
// SwiftyMarkdown
//
// Created by Simon Fairbairn on 04/02/2020.
//
import Foundation
import os.log
class PerformanceLog {
var timer : TimeInterval = 0
let enablePerfomanceLog : Bool
let log : OSLog
let identifier : String
init( with environmentVariableName : String, identifier : String, log : OSLog ) {
self.log = log
self.enablePerfomanceLog = (ProcessInfo.processInfo.environment[environmentVariableName] != nil)
self.identifier = identifier
}
func start() {
guard enablePerfomanceLog else { return }
self.timer = Date().timeIntervalSinceReferenceDate
os_log("--- TIMER %{public}@ began", log: self.log, type: .info, self.identifier)
}
func tag( with string : String) {
guard enablePerfomanceLog else { return }
if timer == 0 {
self.start()
}
os_log("TIMER %{public}@: %f %@", log: self.log, type: .info, self.identifier, Date().timeIntervalSinceReferenceDate - self.timer, string)
}
func end() {
guard enablePerfomanceLog else { return }
self.timer = Date().timeIntervalSinceReferenceDate
os_log("--- TIMER %{public}@ finished. Total time: %f", log: self.log, type: .info, self.identifier, Date().timeIntervalSinceReferenceDate - self.timer)
self.timer = 0
}
}
| mit | 4cf7f0418f16cc8351f353cd26aa786b | 27.431818 | 154 | 0.702638 | 3.465374 | false | false | false | false |
jianghongbing/APIReferenceDemo | WebKit/WKNavigationDelegate/WKNavigationDelegate/WebViewController.swift | 1 | 5248 | //
// ViewController.swift
// WKNavigationDelegate
//
// Created by pantosoft on 2018/12/12.
// Copyright © 2018 jianghongbing. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
var loadLocal = false
lazy var webView: WKWebView = {
let webView = WKWebView(frame: self.view.bounds)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
self.view.addSubview(webView)
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(false, animated: true)
if loadLocal {
let path = Bundle.main.path(forResource: "index", ofType: "html")
let fileURL = URL(fileURLWithPath: path!)
webView.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
}else {
let url = URL(string: "https://www.baidu.com")
let request = URLRequest(url: url!)
webView.load(request)
}
}
@IBAction func loadLocalHTML(_ sender: Any) {
}
@IBAction func reload(_ sender: Any) {
webView.reload()
}
@IBAction func goBack(_ sender: Any) {
if webView.canGoBack {
webView.goBack()
}
}
@IBAction func goForward(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
}
//WKNavigationDelegate: 导航代理
extension WebViewController: WKNavigationDelegate {
//当webView开始加载网页内容的时候,会被触发
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print(#function, #line, "navigation:\(navigation!)")
}
//当webView开始接收数据的时候,会被触发
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
print(#function, #line, "navigaiton:\(navigation!)")
}
//当web发生重定向的时候,会被触发
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
print(#function, #line, "navigaiton:\(navigation!)")
}
//当网页需要鉴定的时候,会被触发
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print(#function, #line, "challenge:\(challenge)")
completionHandler(.useCredential, nil)
}
//在刚开始加载web就发送错误时,会被触发
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(#function, #line, "navigaiton:\(navigation!)", "error:\(error)")
}
//在接收数据的时候发生错误,会被触发
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(#function, #line, "navigaiton:\(navigation!)", "error:\(error)")
}
//在指定的navigation完成时,会被触发
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print(#function, #line, "navigaiton:\(navigation!)")
navigationItem.title = webView.title
}
//在webConten处理进程结束的时候,会被触发
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
print(#function, #line)
}
//在webView跳转网页之前,对指定的action是否进行导航
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print(#function, #line, navigationAction)
switch navigationAction.navigationType {
// case linkActivated //带有herf的a标签的类型
//
// case formSubmitted //表单提交
//
// case backForward //通过历史记录后退或者前进
//
// case reload //重新加载
//
// case formResubmitted //重新提交表单
//
// case other //其他
//下面类型允许跳转
case .linkActivated, .formSubmitted, .formResubmitted, .other:
decisionHandler(.allow)
//重新加载,前进或者后退不允许跳转
case .backForward, .reload:
decisionHandler(.cancel)
}
}
//在获取响应后,决定是否跳转
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
print(#function, #line, navigationResponse)
guard navigationResponse.isForMainFrame else {
decisionHandler(.cancel)
return
}
if let urlString = navigationResponse.response.url?.relativeString, urlString.contains("5.html"){
decisionHandler(.cancel)
}else {
decisionHandler(.allow)
}
// navigationResponse.isForMainFrame ? decisionHandler(.allow) : decisionHandler(.cancel)
}
}
| mit | 33472666b1bea9614c75832e73ab8ccf | 33.535714 | 182 | 0.647983 | 4.712476 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/TabBar/TabBar.swift | 1 | 6601 | //
// Wire
// Copyright (C) 2016 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 UIKit
protocol TabBarDelegate: AnyObject {
func tabBar(_ tabBar: TabBar, didSelectItemAt index: Int)
}
final class TabBar: UIView {
fileprivate let stackView = UIStackView()
// MARK: - Properties
weak var delegate: TabBarDelegate?
var animatesTransition = true
fileprivate(set) var items: [UITabBarItem] = []
private let tabInset: CGFloat = 16
private let selectionLineView = UIView()
private(set) var tabs: [Tab] = []
private lazy var lineLeadingConstraint: NSLayoutConstraint = selectionLineView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: tabInset)
private var didUpdateInitialBarPosition = false
fileprivate(set) var selectedIndex: Int {
didSet {
updateButtonSelection()
}
}
fileprivate var selectedTab: Tab {
return self.tabs[selectedIndex]
}
private var titleObservers: [NSKeyValueObservation] = []
deinit {
titleObservers.forEach { $0.invalidate() }
}
// MARK: - Initialization
init(items: [UITabBarItem], selectedIndex: Int = 0) {
precondition(!items.isEmpty, "TabBar must be initialized with at least one item")
self.items = items
self.selectedIndex = selectedIndex
super.init(frame: CGRect.zero)
self.accessibilityTraits = .tabBar
setupViews()
createConstraints()
updateButtonSelection()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
tabs = items.enumerated().map(makeButtonForItem)
tabs.forEach(stackView.addArrangedSubview)
stackView.distribution = .fillEqually
stackView.axis = .horizontal
stackView.alignment = .fill
addSubview(stackView)
addSubview(selectionLineView)
selectionLineView.backgroundColor = SemanticColors.TabBar.backgroundSeperatorSelected
}
override func layoutSubviews() {
super.layoutSubviews()
if !didUpdateInitialBarPosition, bounds != .zero {
didUpdateInitialBarPosition = true
updateLinePosition(animated: false)
}
}
private func updateLinePosition(animated: Bool) {
let offset = CGFloat(selectedIndex) * selectionLineView.bounds.width
guard offset != lineLeadingConstraint.constant else { return }
updateLinePosition(offset: offset, animated: animated)
}
private func updateLinePosition(offset: CGFloat, animated: Bool) {
lineLeadingConstraint.constant = offset + tabInset
if animated {
UIView.animate(
withDuration: 0.35,
delay: 0,
options: [.curveEaseInOut, .beginFromCurrentState],
animations: layoutIfNeeded
)
} else {
layoutIfNeeded()
}
}
func setOffsetPercentage(_ percentage: CGFloat) {
let offset = percentage * (bounds.width - tabInset * 2)
updateLinePosition(offset: offset, animated: false)
}
private func createConstraints() {
let oneOverItemsCount: CGFloat = 1 / CGFloat(items.count)
let widthInset = tabInset * 2 * oneOverItemsCount
[self, selectionLineView, stackView].prepareForLayout()
NSLayoutConstraint.activate([
lineLeadingConstraint,
selectionLineView.heightAnchor.constraint(equalToConstant: 1),
selectionLineView.bottomAnchor.constraint(equalTo: bottomAnchor),
selectionLineView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: oneOverItemsCount, constant: -widthInset),
stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: tabInset),
stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -tabInset),
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.heightAnchor.constraint(equalToConstant: 48),
bottomAnchor.constraint(equalTo: stackView.bottomAnchor)
])
}
fileprivate func makeButtonForItem(_ index: Int, _ item: UITabBarItem) -> Tab {
let tab = Tab()
tab.textTransform = .upper
tab.setTitle(item.title, for: .normal)
if let accessibilityID = item.accessibilityIdentifier {
tab.accessibilityIdentifier = accessibilityID
} else {
tab.accessibilityIdentifier = "Tab\(index)"
}
let changeObserver = item.observe(\.title) { [unowned tab, unowned item] _, _ in
tab.setTitle(item.title, for: .normal)
}
titleObservers.append(changeObserver)
tab.addTarget(self, action: #selector(TabBar.itemSelected(_:)), for: .touchUpInside)
return tab
}
// MARK: - Actions
@objc func itemSelected(_ sender: AnyObject) {
guard
let tab = sender as? Tab,
let selectedIndex = self.tabs.firstIndex(of: tab)
else {
return
}
self.delegate?.tabBar(self, didSelectItemAt: selectedIndex)
setSelectedIndex(selectedIndex, animated: animatesTransition)
}
func setSelectedIndex( _ index: Int, animated: Bool) {
let changes = { [weak self] in
self?.selectedIndex = index
self?.layoutIfNeeded()
}
if animated {
UIView.transition(
with: self,
duration: 0.3,
options: [.transitionCrossDissolve, .allowUserInteraction, .beginFromCurrentState],
animations: changes
)
} else {
changes()
}
updateLinePosition(animated: animated)
}
fileprivate func updateButtonSelection() {
tabs.forEach { $0.isSelected = false }
tabs[selectedIndex].isSelected = true
}
}
| gpl-3.0 | bc125eb77ecec1d85ea932dc0dcbd4c6 | 31.357843 | 151 | 0.647175 | 5.125 | false | false | false | false |
devpunk/cartesian | cartesian/View/DrawProject/Main/VDrawProject.swift | 1 | 5524 | import UIKit
class VDrawProject:VView
{
private weak var controller:CDrawProject!
private(set) weak var viewMenu:VDrawProjectMenu!
private(set) weak var viewScroll:VDrawProjectScroll!
private(set) weak var viewColor:VDrawProjectColor?
private(set) weak var viewSize:VDrawProjectSize?
private(set) weak var viewRotate:VDrawProjectRotate?
private(set) weak var viewFont:VDrawProjectFont?
private(set) weak var viewFontSize:VDrawProjectFontSize?
private(set) weak var viewStore:VDrawProjectStore?
override init(controller:CController)
{
super.init(controller:controller)
self.controller = controller as? CDrawProject
let viewScroll:VDrawProjectScroll = VDrawProjectScroll(
controller:self.controller)
self.viewScroll = viewScroll
let viewMenu:VDrawProjectMenu = VDrawProjectMenu(
controller:self.controller)
self.viewMenu = viewMenu
let viewRules:VDrawProjectRules = VDrawProjectRules(
controller:self.controller)
viewScroll.viewRules = viewRules
addSubview(viewScroll)
addSubview(viewRules)
addSubview(viewMenu)
NSLayoutConstraint.height(
view:viewMenu,
constant:self.controller.modelMenuState.kMenuHeight)
viewMenu.layoutBottom = NSLayoutConstraint.bottomToBottom(
view:viewMenu,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:viewMenu,
toView:self)
NSLayoutConstraint.equals(
view:viewScroll,
toView:self)
NSLayoutConstraint.equals(
view:viewRules,
toView:self)
if let menuBottom:CGFloat = self.controller.modelMenuState.current?.bottom
{
viewMenu.layoutBottom.constant = menuBottom
}
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: public
func viewDidAppeared()
{
viewMenu.viewBar.selectSettings()
viewMenu.viewSettings.viewSize.update()
viewMenu.viewSettings.viewTitle.updateTitle()
viewMenu.viewNodes.refresh()
}
func showColor(title:String, delegate:MDrawProjectColorDelegate)
{
self.viewColor?.removeFromSuperview()
let viewColor:VDrawProjectColor = VDrawProjectColor(
controller:controller,
delegate:delegate)
viewColor.viewBar.labelTitle.text = title
self.viewColor = viewColor
addSubview(viewColor)
NSLayoutConstraint.equals(
view:viewColor,
toView:self)
layoutIfNeeded()
viewColor.animateShow()
}
func showSize(title:String, delegate:MDrawProjectSizeDelegate)
{
self.viewSize?.removeFromSuperview()
let viewSize:VDrawProjectSize = VDrawProjectSize(
controller:controller,
delegate:delegate)
viewSize.viewBar.labelTitle.text = title
self.viewSize = viewSize
addSubview(viewSize)
NSLayoutConstraint.equals(
view:viewSize,
toView:self)
layoutIfNeeded()
viewSize.animateShow()
}
func showRotate(node:DNode)
{
self.viewRotate?.removeFromSuperview()
let viewRotate:VDrawProjectRotate = VDrawProjectRotate(
controller:controller,
node:node)
self.viewRotate = viewRotate
addSubview(viewRotate)
NSLayoutConstraint.equals(
view:viewRotate,
toView:self)
layoutIfNeeded()
viewRotate.animateShow()
}
func showFont(title:String, delegate:MDrawProjectFontDelegate)
{
self.viewFont?.removeFromSuperview()
let viewFont:VDrawProjectFont = VDrawProjectFont(
controller:controller,
delegate:delegate)
viewFont.viewBar.labelTitle.text = title
self.viewFont = viewFont
addSubview(viewFont)
NSLayoutConstraint.equals(
view:viewFont,
toView:self)
layoutIfNeeded()
viewFont.animateShow()
}
func showFontSize(delegate:MDrawProjectFontSizeDelegate)
{
self.viewFontSize?.removeFromSuperview()
let viewFontSize:VDrawProjectFontSize = VDrawProjectFontSize(
controller:controller,
delegate:delegate)
self.viewFontSize = viewFontSize
addSubview(viewFontSize)
NSLayoutConstraint.equals(
view:viewFontSize,
toView:self)
layoutIfNeeded()
viewFontSize.animateShow()
}
func showStore(purchase:MDrawProjectMenuNodesItem)
{
self.viewStore?.removeFromSuperview()
let viewStore:VDrawProjectStore = VDrawProjectStore(
controller:controller,
purchase:purchase)
self.viewStore = viewStore
addSubview(viewStore)
NSLayoutConstraint.equals(
view:viewStore,
toView:self)
layoutIfNeeded()
viewStore.animateShow()
}
//MARK: public
func refresh()
{
viewScroll.refresh()
viewMenu.viewSettings.viewSize.update()
}
}
| mit | 9540af2b860a7b57d3523d2aef37c9b4 | 26.758794 | 82 | 0.605177 | 5.352713 | false | false | false | false |
lappp9/AsyncDisplayKit | examples/LayoutSpecExamples-Swift/Sample/LayoutExampleNode+Layouts.swift | 12 | 3600 | //
// LayoutExampleNode+Layouts.swift
// Sample
//
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// 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
// FACEBOOK 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 AsyncDisplayKit
extension HeaderWithRightAndLeftItems {
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let nameLocationStack = ASStackLayoutSpec.vertical()
nameLocationStack.style.flexShrink = 1.0
nameLocationStack.style.flexGrow = 1.0
if postLocationNode.attributedText != nil {
nameLocationStack.children = [userNameNode, postLocationNode]
} else {
nameLocationStack.children = [userNameNode]
}
let headerStackSpec = ASStackLayoutSpec(direction: .horizontal,
spacing: 40,
justifyContent: .start,
alignItems: .center,
children: [nameLocationStack, postTimeNode])
return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10), child: headerStackSpec)
}
}
extension PhotoWithInsetTextOverlay {
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let photoDimension: CGFloat = constrainedSize.max.width / 4.0
photoNode.style.preferredSize = CGSize(width: photoDimension, height: photoDimension)
// INFINITY is used to make the inset unbounded
let insets = UIEdgeInsets(top: CGFloat.infinity, left: 12, bottom: 12, right: 12)
let textInsetSpec = ASInsetLayoutSpec(insets: insets, child: titleNode)
return ASOverlayLayoutSpec(child: photoNode, overlay: textInsetSpec)
}
}
extension PhotoWithOutsetIconOverlay {
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
iconNode.style.preferredSize = CGSize(width: 40, height: 40);
iconNode.style.layoutPosition = CGPoint(x: 150, y: 0);
photoNode.style.preferredSize = CGSize(width: 150, height: 150);
photoNode.style.layoutPosition = CGPoint(x: 40 / 2.0, y: 40 / 2.0);
let absoluteSpec = ASAbsoluteLayoutSpec(children: [photoNode, iconNode])
// ASAbsoluteLayoutSpec's .sizing property recreates the behavior of ASDK Layout API 1.0's "ASStaticLayoutSpec"
absoluteSpec.sizing = .sizeToFit
return absoluteSpec;
}
}
extension FlexibleSeparatorSurroundingContent {
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
topSeparator.style.flexGrow = 1.0
bottomSeparator.style.flexGrow = 1.0
textNode.style.alignSelf = .center
let verticalStackSpec = ASStackLayoutSpec.vertical()
verticalStackSpec.spacing = 20
verticalStackSpec.justifyContent = .center
verticalStackSpec.children = [topSeparator, textNode, bottomSeparator]
return ASInsetLayoutSpec(insets:UIEdgeInsets(top: 60, left: 0, bottom: 60, right: 0), child: verticalStackSpec)
}
}
| bsd-3-clause | 7388e359e09235eb241e54c6ce5f2d3a | 37.709677 | 115 | 0.713611 | 4.65718 | false | false | false | false |
DianQK/rx-sample-code | TextInput/ViewController.swift | 1 | 2948 | //
// ViewController.swift
// TextInputDemo
//
// Created by DianQK on 18/01/2017.
// Copyright © 2017 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
struct InputModel {
let inputText: Variable<String>
// let isFirstResponder = Variable(false)
}
typealias InputSectionModel = SectionModel<String, InputModel>
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var label: UILabel!
let dataSource = RxCollectionViewSectionedReloadDataSource<InputSectionModel>()
let inputText = Variable("")
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
inputText.asObservable()
.bindTo(label.rx.text)
.disposed(by: disposeBag)
dataSource.configureCell = { dataSource, collectionView, indexPath, element in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InputCollectionViewCell", for: indexPath) as! InputCollectionViewCell
cell.textField.rx.controlEvent(.editingChanged)
.map { cell.textField.text ?? "" }
.filter { !$0.isEmpty }
.subscribe(onNext: { text in
element.inputText.value += text
})
.disposed(by: cell.reuseDisposeBag)
element.inputText.asObservable()
.map({ (text) -> String in
if text.characters.count > indexPath.row {
return String(text.characters.map { $0 }[indexPath.row])
} else {
return ""
}
})
.bindTo(cell.textField.rx.text)
.disposed(by: cell.reuseDisposeBag)
cell.textField.rx.methodInvoked(#selector(UITextField.deleteBackward))
.map { _ in }
.subscribe(onNext: {
guard !element.inputText.value.isEmpty else { return }
let removedIndex = element.inputText.value.index(before: element.inputText.value.endIndex)
element.inputText.value.remove(at: removedIndex)
})
.disposed(by: cell.reuseDisposeBag)
element.inputText.asObservable().map { $0.lengthOfBytes(using: String.Encoding.utf8) }
.map { $0 == indexPath.row }
.distinctUntilChanged()
.bindTo(cell.isInputing)
.disposed(by: cell.reuseDisposeBag)
return cell
}
Observable.just([inputText, inputText, inputText, inputText, inputText, inputText])
.map { $0.map { InputModel(inputText: $0) } }
.map { [InputSectionModel(model: "", items: $0)] }
.bindTo(collectionView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
}
| mit | 17c98713055a139caf768e431e2569e5 | 32.873563 | 149 | 0.587716 | 4.928094 | false | false | false | false |
ramsrib/No-Food-Waste | ios/NoFoodWaster/NoFoodWaster/ConfirmationViewController.swift | 2 | 2390 | //
// ConfirmationViewController.swift
// NoFoodWaste
//
// Created by Ravi Shankar on 29/11/15.
// Copyright © 2015 Ravi Shankar. All rights reserved.
//
import UIKit
class ConfirmationViewController: UIViewController {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var donationDetails: UILabel!
@IBOutlet weak var deliveryDetails: UILabel!
@IBOutlet weak var volunteerDetails: UILabel!
@IBOutlet weak var donationTextView: UITextView!
@IBOutlet weak var deliveryTextView: UITextView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Confirmation"
applyStyle()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.navigationItem.setHidesBackButton(true, animated: false)
navigationItem.title = ""
let barButtonItem = UIBarButtonItem.init(title: "Home", style: .Done, target: self, action: "callHome")
self.navigationItem.leftBarButtonItem = barButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func deliver(sender: AnyObject) {
}
func applyStyle() {
descriptionLabel.backgroundColor = backgroundColor
view.backgroundColor = backgroundColor
donationDetails.backgroundColor = backgroundColor
deliveryDetails.backgroundColor = backgroundColor
volunteerDetails.backgroundColor = backgroundColor
donationTextView.backgroundColor = backgroundColor
deliveryTextView.backgroundColor = backgroundColor
nameLabel.backgroundColor = backgroundColor
phoneLabel.backgroundColor = backgroundColor
containerView.backgroundColor = backgroundColor
}
func callHome() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("MainViewController")
navigationController?.pushViewController(controller, animated: true)
}
}
| apache-2.0 | 890a35060b3044a6e1e40c149128df8b | 29.240506 | 111 | 0.673922 | 5.884236 | false | false | false | false |
ntphan527/MiAR | MiAR/View Controllers/StatusViewController.swift | 2 | 4824 | //
// StatusViewController.swift
// MiAR
//
// Created by Oscar Bonilla on 10/23/17.
// Copyright © 2017 MiAR. All rights reserved.
//
import Foundation
import ARKit
class StatusViewController: UIViewController {
enum MessageType {
case trackingStateEscalation
case planeEstimation
case contentPlacement
case focusSquare
case information
static var all: [MessageType] = [
.trackingStateEscalation,
.planeEstimation,
.contentPlacement,
.focusSquare,
.information
]
}
@IBOutlet weak private var messagePanel: UIVisualEffectView!
@IBOutlet weak private var messageLabel: UILabel!
@IBOutlet weak private var restartExperienceButton: UIButton!
// MARK: - Properties
/// Trigerred when the "Restart Experience" button is tapped.
var restartExperienceHandler: () -> Void = {}
/// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages.
private let displayDuration: TimeInterval = 6
// Timer for hiding messages.
private var messageHideTimer: Timer?
private var timers: [MessageType: Timer] = [:]
// MARK: - Message Handling
func showMessage(_ text: String, autoHide: Bool = true) {
// Cancel any previous hide timer.
messageHideTimer?.invalidate()
messageLabel.text = text
// Make sure status is showing.
setMessageHidden(false, animated: true)
if autoHide {
messageHideTimer = Timer.scheduledTimer(withTimeInterval: displayDuration, repeats: false, block: { [weak self] _ in
self?.setMessageHidden(true, animated: true)
})
}
}
func scheduleMessage(_ text: String, inSeconds seconds: TimeInterval, messageType: MessageType) {
cancelScheduledMessage(for: messageType)
let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [weak self] timer in
self?.showMessage(text)
timer.invalidate()
})
timers[messageType] = timer
}
func cancelScheduledMessage(`for` messageType: MessageType) {
timers[messageType]?.invalidate()
timers[messageType] = nil
}
func cancelAllScheduledMessages() {
for messageType in MessageType.all {
cancelScheduledMessage(for: messageType)
}
}
// MARK: - ARKit
func showTrackingQualityInfo(for trackingState: ARCamera.TrackingState, autoHide: Bool) {
showMessage(trackingState.presentationString, autoHide: autoHide)
}
func escalateFeedback(for trackingState: ARCamera.TrackingState, inSeconds seconds: TimeInterval) {
cancelScheduledMessage(for: .trackingStateEscalation)
let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [unowned self] _ in
self.cancelScheduledMessage(for: .trackingStateEscalation)
var message = trackingState.presentationString
if let recommendation = trackingState.recommendation {
message.append(": \(recommendation)")
}
self.showMessage(message, autoHide: false)
})
timers[.trackingStateEscalation] = timer
}
// MARK: - IBActions
@IBAction private func restartExperience(_ sender: UIButton) {
restartExperienceHandler()
}
// MARK: - Panel Visibility
private func setMessageHidden(_ hide: Bool, animated: Bool) {
// The panel starts out hidden, so show it before animating opacity.
messagePanel.isHidden = false
guard animated else {
messagePanel.alpha = hide ? 0 : 1
return
}
UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: {
self.messagePanel.alpha = hide ? 0 : 1
}, completion: nil)
}
}
extension ARCamera.TrackingState {
var presentationString: String {
switch self {
case .notAvailable:
return "TRACKING UNAVAILABLE"
case .normal:
return "TRACKING NORMAL"
case .limited(.excessiveMotion):
return "TRACKING LIMITED\nExcessive motion"
case .limited(.insufficientFeatures):
return "TRACKING LIMITED\nLow detail"
case .limited(.initializing):
return "Initializing"
}
}
var recommendation: String? {
switch self {
case .limited(.excessiveMotion):
return "Try slowing down your movement, or reset the session."
case .limited(.insufficientFeatures):
return "Try pointing at a flat surface, or reset the session."
default:
return nil
}
}
}
| apache-2.0 | c2b34810569e2f8aa45d2b917ae73545 | 29.14375 | 128 | 0.637363 | 5.282585 | false | false | false | false |
alexktchen/ExchangeRate | Core/Services/UserDefaultDataService.swift | 1 | 3506 | //
// UserDefaultDataService.swift
// ExchangeRate
//
// Created by Alex Chen on 2015/9/30.
// Copyright © 2015 Alex Chen. All rights reserved.
//
import Foundation
public class UserDefaultDataService {
public class var sharedInstance: UserDefaultDataService {
struct Singleton {
static let instance = UserDefaultDataService()
}
return Singleton.instance
}
let aDefaults:NSUserDefaults!
let queryCurrencysData = "queryCurrencysData"
let majorCurrencysData = "majorCurrencysData"
let minorCurrencysData = "minorCurrencysData"
let ExCurrencysData = "ExCurrencysData"
let mainCurrencysData = "mainCurrencysData"
init() {
aDefaults = NSUserDefaults(suiteName: "group.com.AlexChen.extrmeCurrencyShareData")
}
// set today extension of Currencys Data
public func setExCurrencysData(aData: NSData) {
aDefaults.setObject(aData, forKey: ExCurrencysData)
aDefaults.synchronize()
}
// get today extension of Currencys Data
public func getExCurrencysData() -> NSData? {
return aDefaults.objectForKey(ExCurrencysData) as? NSData
}
public func setQueryCurrencysData(aData: NSData) {
aDefaults.setObject(aData, forKey: queryCurrencysData)
aDefaults.synchronize()
}
public func getQueryCurrencysData() -> NSData? {
return aDefaults.objectForKey(queryCurrencysData) as? NSData
}
public func setMajorCurrencysData(aCurrency: Currency) {
let encodedObject = NSKeyedArchiver.archivedDataWithRootObject(aCurrency)
aDefaults.setObject(encodedObject, forKey: majorCurrencysData)
aDefaults.synchronize()
}
public func getMajorCurrencysData() -> Currency? {
aDefaults.synchronize()
if let encodedObject = aDefaults.objectForKey(majorCurrencysData) as? NSData {
let object = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObject)
return object as? Currency
} else {
return nil
}
}
public func setMinorCurrencysData(aCurrency: Currency) {
let encodedObject = NSKeyedArchiver.archivedDataWithRootObject(aCurrency)
aDefaults.setObject(encodedObject, forKey: minorCurrencysData)
aDefaults.synchronize()
}
public func getMinorCurrencysData() -> Currency? {
aDefaults.synchronize()
if let encodedObject = aDefaults.objectForKey(minorCurrencysData) as? NSData {
let object = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObject)
aDefaults.synchronize()
return object as? Currency
} else {
return nil
}
}
func setMainCurrencysData(aCurrencys: [Currency]) {
let encodedObject = NSKeyedArchiver.archivedDataWithRootObject(aCurrencys)
aDefaults.setObject(encodedObject, forKey: mainCurrencysData)
aDefaults.synchronize()
}
func getMainCurrencysData() -> [Currency]? {
aDefaults.synchronize()
if let encodedObject = aDefaults.objectForKey(mainCurrencysData) as? NSData {
let object: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(encodedObject)
aDefaults.synchronize()
return (object as? [Currency])
} else {
return nil
}
}
func removeMainCurrencysData() {
aDefaults.removeObjectForKey(mainCurrencysData)
aDefaults.synchronize()
}
} | mit | 2b7448e2f6734548c953d9ffed7de96c | 30.872727 | 93 | 0.677033 | 4.978693 | false | false | false | false |
36Kr-Mobile/Cupid | CupidDemo/Cupid/Cupid/Cupid.swift | 1 | 3003 | //
// Cupid.swift
// Cupid
//
// Created by Shannon Wu on 15/9/11.
// Copyright © 2015年 36Kr. All rights reserved.
//
import UIKit
/// A central hub for share and OAuth
public struct Cupid {
static var serviceProvider: ShareServiceProvider?
static var intenalNetworkingProvider: CupidNetworkingProvider?
/// Networking provider for request, if you don't specify your own, default will be used.
public static var networkingProvier: CupidNetworkingProvider {
set {
intenalNetworkingProvider = networkingProvier
}
get {
if let networkingProvider = intenalNetworkingProvider {
return networkingProvider
} else {
return SimpleNetworking.sharedInstance
}
}
}
/// Share content to service provider
///
/// - parameter content: the content to share
/// - parameter serviceProvider: the service provider
/// - parameter completionHandler: actions after completion, default to nil
///
/// - throws: errors may occur in share process
public static func shareContent(content: Content, serviceProvider: ShareServiceProvider, completionHandler: ShareCompletionHandler? = nil) throws {
self.serviceProvider = serviceProvider
func completionHandlerCleaner(succeed: Bool) {
completionHandler?(succeed: succeed)
Cupid.serviceProvider = nil
}
do {
try serviceProvider.shareContent(content, completionHandler: completionHandlerCleaner)
}
catch let error {
Cupid.serviceProvider = nil
throw error
}
}
/// OAuth to service provider
///
/// - parameter serviceProvider: the service provider used for OAuth
/// - parameter completionHandler: actions after OAuth completion
///
/// - throws: errors may occur in OAuth process
public static func OAuth(serviceProvider: ShareServiceProvider, completionHandler: NetworkResponseHandler) throws {
self.serviceProvider = serviceProvider
func completionHandlerCleaner(dictionary: NSDictionary?, response: NSURLResponse?, error: NSError?) {
completionHandler(dictionary, response, error)
Cupid.serviceProvider = nil
}
do {
try serviceProvider.OAuth(completionHandler)
}
catch let error {
Cupid.serviceProvider = nil
throw error
}
}
/// Handle URL realted to Cupid, you must call this method to check the callbacks.
///
/// - parameter URL: the URL of the callback
///
/// - returns: nil if the URL is not for Cupid, true for success, false for fail
public static func handleOpenURL(URL: NSURL) -> Bool? {
if let serviceProvider = serviceProvider {
return serviceProvider.handleOpenURL(URL)
}
else {
return false
}
}
}
| mit | 39eab312a2878d66233b3dc2d92507e2 | 31.967033 | 151 | 0.633667 | 5.093379 | false | false | false | false |
tkrajacic/SampleCodeStalker | SampleCodeStalker/Model/CDResourceType.swift | 1 | 1579 | //
// ResourceType.swift
// SampleCodeStalker
//
// Created by Thomas Krajacic on 23.1.2016.
// Copyright © 2016 Thomas Krajacic. All rights reserved.
//
import Foundation
import CoreData
class CDResourceType: ManagedObject {
@NSManaged open fileprivate(set) var id: String
@NSManaged open fileprivate(set) var name: String
@NSManaged open fileprivate(set) var key: Int16
@NSManaged open fileprivate(set) var sortOrder: Int16
// Relationships
@NSManaged open fileprivate(set) var documents: Set<CDDocument>
}
// MARK: - ManagedObjectType
extension CDResourceType: ManagedObjectType {
public static var entityName: String {
return "CDResourceType"
}
public static var defaultSortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(key: "name", ascending: true)]
}
public static var defaultPredicate: NSPredicate {
return NSPredicate(value: true)
}
}
// MARK: - Creation
extension CDResourceType {
@discardableResult public static func updateOrInsertIntoContext(
_ moc: NSManagedObjectContext,
identifier: String,
name: String,
key: Int16,
sortOrder: Int16
) -> CDResourceType {
let resourceType = CDResourceType.findOrCreateInContext(moc, matchingPredicate: NSPredicate(format: "id == '\(identifier)'")) { _ in }
resourceType.id = identifier
resourceType.name = name
resourceType.key = key
resourceType.sortOrder = sortOrder
return resourceType
}
}
| mit | a1f0dcbcdc4f74a9ace75028d84181e3 | 26.684211 | 142 | 0.673638 | 4.781818 | false | false | false | false |
coffee-cup/solis | SunriseSunset/Spring/Misc.swift | 1 | 5946 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public extension String {
func toURL() -> NSURL? {
return NSURL(string: self)
}
}
public func htmlToAttributedString(text: String) -> NSAttributedString! {
let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false)
let htmlString: NSAttributedString?
do {
htmlString = try NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch _ {
htmlString = nil
}
return htmlString
}
public func degreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(CGFloat.pi / 180)
}
public func delay(delay:Double, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
public func imageFromURL(_ Url: String) -> UIImage {
let url = Foundation.URL(string: Url)
let data = try? Data(contentsOf: url!)
return UIImage(data: data!)!
}
public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
public func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
public func stringFromDate(date: NSDate, format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date as Date)
}
public func dateFromString(date: String, format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: date) {
return date
} else {
return Date(timeIntervalSince1970: 0)
}
}
public func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}
return randomString
}
public func timeAgoSinceDate(date: Date, numericDates: Bool) -> String {
let calendar = Calendar.current
let unitFlags = Set<Calendar.Component>(arrayLiteral: Calendar.Component.minute, Calendar.Component.hour, Calendar.Component.day, Calendar.Component.weekOfYear, Calendar.Component.month, Calendar.Component.year, Calendar.Component.second)
let now = Date()
let dateComparison = now.compare(date)
var earliest: Date
var latest: Date
switch dateComparison {
case .orderedAscending:
earliest = now
latest = date
default:
earliest = date
latest = now
}
let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest)
guard
let year = components.year,
let month = components.month,
let weekOfYear = components.weekOfYear,
let day = components.day,
let hour = components.hour,
let minute = components.minute,
let second = components.second
else {
fatalError()
}
if (year >= 2) {
return "\(year)y"
} else if (year >= 1) {
if (numericDates){
return "1y"
} else {
return "1y"
}
} else if (month >= 2) {
return "\(month * 4)w"
} else if (month >= 1) {
if (numericDates){
return "4w"
} else {
return "4w"
}
} else if (weekOfYear >= 2) {
return "\(weekOfYear)w"
} else if (weekOfYear >= 1){
if (numericDates){
return "1w"
} else {
return "1w"
}
} else if (day >= 2) {
return "\(String(describing: components.day))d"
} else if (day >= 1){
if (numericDates){
return "1d"
} else {
return "1d"
}
} else if (hour >= 2) {
return "\(hour)h"
} else if (hour >= 1){
if (numericDates){
return "1h"
} else {
return "1h"
}
} else if (minute >= 2) {
return "\(minute)m"
} else if (minute >= 1){
if (numericDates){
return "1m"
} else {
return "1m"
}
} else if (second >= 3) {
return "\(second)s"
} else {
return "now"
}
}
| mit | 618a1a24e586332f9be802cb92ee7d4a | 30.796791 | 242 | 0.62849 | 4.271552 | false | false | false | false |
ykay/twitter-with-menu | Twitter/TweetDetailsViewController.swift | 1 | 2586 | //
// TweetDetailsViewController.swift
// Twitter
//
// Created by Yuichi Kuroda on 10/4/15.
// Copyright © 2015 Yuichi Kuroda. All rights reserved.
//
import UIKit
class TweetDetailsViewController: UIViewController {
var tweetView: TweetView!
var tweet: Tweet!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "onCancel")
navigationItem.leftBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: Appearance.colorTwitterWhite], forState: UIControlState.Normal)
// So text box doesn't extend beyond navigation bar
self.edgesForExtendedLayout = UIRectEdge.None
tweetView = TweetView()
tweetView.tweet = tweet
tweetView.replyActionHandler = { (tweetId: String, tweetUserScreenname: String) -> Void in
print("Replying to tweet id: \(tweetId)")
print("Replying to screenname: \(tweetUserScreenname)")
let composeViewController = ComposeViewController(inReplyToStatusId: tweetId, inReplyToScreenname: tweetUserScreenname)
self.navigationController?.pushViewController(composeViewController, animated: true)
}
tweetView.userProfileShowHandler = { (user: User) -> Void in
let profileViewController = ProfileViewController(user: user)
self.navigationController?.pushViewController(profileViewController, animated: true)
}
view.addSubview(tweetView)
setupConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// NOTE: The tweet view needs to be a subview of the main view so that it gets constrained within the area under the navigation bar.
// If the tweet view is made into the main view, then it will extend beyond the nav bar and hide behind it.
func setupConstraints() {
tweetView.translatesAutoresizingMaskIntoConstraints = false
let views = [
"tweetView": tweetView,
]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tweetView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[tweetView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
func onCancel() {
navigationController?.popViewControllerAnimated(true)
}
}
| mit | 2164cf230c29eddbe71445179dd7ceaa | 37.014706 | 168 | 0.733462 | 5.048828 | false | false | false | false |
Cin316/X-Schedule | X Schedule/WeekDataViewController.swift | 1 | 7990 | //
// WeekDataViewController.swift
// X Schedule
//
// Created by Nicholas Reichert on 4/4/15.
// Copyright (c) 2015 Nicholas Reichert.
//
import UIKit
import XScheduleKit
class WeekDataViewController: ScheduleViewController {
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var finishedLoadingNum: Int = 0
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var titleLabel1: UILabel!
@IBOutlet weak var emptyLabel1: UILabel!
@IBOutlet weak var titleLabel2: UILabel!
@IBOutlet weak var emptyLabel2: UILabel!
@IBOutlet weak var titleLabel3: UILabel!
@IBOutlet weak var emptyLabel3: UILabel!
@IBOutlet weak var titleLabel4: UILabel!
@IBOutlet weak var emptyLabel4: UILabel!
@IBOutlet weak var titleLabel5: UILabel!
@IBOutlet weak var emptyLabel5: UILabel!
private let daysPerView: Int = 7
override func numberOfDaysPerView() -> Int {
return daysPerView
}
var scheduleMonday: Date {
get {
let calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let weekday: Int = (calendar as NSCalendar).component(.weekday, from: scheduleDate)
let daysPastMonday: Int = weekday-2
let seconds: Double = Double(-24*60*60*daysPastMonday)
return scheduleDate.addingTimeInterval(seconds)
}
}
var tasks: [URLSessionTask] = []
var downloadMethods: [DownloadMethod] = [DownloadMethod](repeating: DownloadMethod.cache, count: 5)
var downloadCount: Int {
get {
var num: Int = 0
for method in downloadMethods {
if (method == DownloadMethod.download) {
num += 1
}
}
return num
}
}
override func viewDidLoad() {
super.viewDidLoad()
refreshSchedule()
}
override func refreshSchedule() {
cancelRequests()
refreshSchedules()
startTaskCounter()
clearWeek()
displayDateLabel()
}
private func clearWeek() {
clearScheduleTables()
}
private func clearScheduleTables() {
//Blank out every schedule.
let blankSchedule: Schedule = Schedule()
for i in 0...4 {
if let tableController = self.children[i] as? ScheduleTableController {
if (downloadMethods[i] == DownloadMethod.download) {
tableController.schedule = blankSchedule
}
}
}
}
private func clearEmptyLabels() {
//Clear all "No classes" labels.
for i in 1...5 {
emptyLabel(i).text = ""
}
}
private func refreshSchedules() {
//Refresh schedule for each day of the week.
for i in 1...5 {
refreshScheduleNum(i)
}
}
private func displayDateLabel() {
dateLabel.text = dateLabelText()
}
private func dateLabelText() -> String {
//Display correctly formatted date label.
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d"
let mondayText: String = dateFormatter.string(from: self.scheduleMonday)
let fridayText: String = dateFormatter.string(from: self.scheduleMonday.addingTimeInterval(60*60*24*4))
let year: Int = (Calendar.current as NSCalendar).component(NSCalendar.Unit.year, from: self.scheduleMonday)
return "\(mondayText) - \(fridayText), \(year)"
}
private func refreshScheduleNum(_ num: Int) {
// Download today's schedule from the St. X website.
let downloadResult = XScheduleManager.getScheduleForDate(downloadDateForNum(num),
completionHandler: { (schedule: Schedule) in
DispatchQueue.main.async {
self.handleCompletionOfDownload(schedule, num: num)
}
},
errorHandler: { (errorText: String) in
DispatchQueue.main.async {
self.handleError(errorText, num: num)
}
}, method: .download
)
let newTask: URLSessionTask? = downloadResult.1
let methodUsed: DownloadMethod = downloadResult.0
downloadMethods[num-1] = methodUsed
if (newTask != nil) {
tasks.append(newTask!)
}
}
private func handleCompletionOfDownload(_ schedule: Schedule, num: Int) {
displayScheduleInTable(schedule, num: num)
displayTitleForSchedule(schedule, titleLabel: titleLabel(num))
displayEmptyLabelForSchedule(schedule, emptyLabel: emptyLabel(num))
markOneTaskAsFinished()
}
private func displayScheduleInTable(_ schedule: Schedule, num: Int) {
if let tableController = children[num-1] as? ScheduleTableController {
tableController.displaySchedule(schedule)
}
}
private func displayTitleForSchedule(_ schedule: Schedule, titleLabel: UILabel) {
//Display normal title.
titleLabel.text = schedule.title
//Add default weekend title if needed.
if (Calendar.current.isDateInWeekend(scheduleMonday)) {
titleLabel.text = "Weekend"
}
}
private func displayEmptyLabelForSchedule(_ schedule: Schedule, emptyLabel: UILabel) {
if (schedule.items.isEmpty) {
emptyLabel.text = "No classes"
} else {
emptyLabel.text = ""
}
}
private func titleLabel(_ num: Int) -> UILabel {
var titleLabel: UILabel!
switch num {
case 1:
titleLabel = self.titleLabel1
case 2:
titleLabel = self.titleLabel2
case 3:
titleLabel = self.titleLabel3
case 4:
titleLabel = self.titleLabel4
case 5:
titleLabel = self.titleLabel5
default:
return UILabel()
}
return titleLabel
}
private func emptyLabel(_ num: Int) -> UILabel {
var emptyLabel: UILabel!
switch num {
case 1:
emptyLabel = self.emptyLabel1
case 2:
emptyLabel = self.emptyLabel2
case 3:
emptyLabel = self.emptyLabel3
case 4:
emptyLabel = self.emptyLabel4
case 5:
emptyLabel = self.emptyLabel5
default:
return UILabel()
}
return emptyLabel
}
private func downloadDateForNum(_ num: Int) -> Date {
let downloadDate: Date = scheduleMonday.addingTimeInterval(Double(24*60*60*(num-1)))
return downloadDate
}
private func startTaskCounter() {
//Start loading indicator before download.
if (!(downloadCount==0)) {
startLoading()
}
finishedLoadingNum = 0
}
private func markOneTaskAsFinished() {
//Stop loading indicator after everything is complete.
finishedLoadingNum += 1
if(finishedLoadingNum>=downloadCount) {
finishedLoadingNum = 0
stopLoading()
clearTasks()
}
}
private func clearTasks() {
//Clear references to tasks from tasks variable.
tasks = []
}
private func cancelRequests() {
for task in tasks {
task.cancel()
}
clearTasks()
}
private func handleError(_ errorText: String, num: Int) {
displayAlertWithText(errorText)
markOneTaskAsFinished()
}
private func startLoading() {
loadingIndicator.startAnimating()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
private func stopLoading() {
loadingIndicator.stopAnimating()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
| mit | f9061be46dea31a46413b6b2458a8143 | 30.210938 | 115 | 0.591239 | 5.079466 | false | false | false | false |
xxxAIRINxxx/ARNZoomImageTransition | ARNZoomImageTransition/ARNZoomImageTransition/Animation/ImageZoomAnimation.swift | 1 | 5963 | //
// ImageZoomAnimation.swift
// ARNZoomImageTransition
//
// Created by xxxAIRINxxx on 2018/05/02.
// Copyright © 2018 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import ARNTransitionAnimator
protocol ImageTransitionZoomable: class {
func createTransitionImageView() -> UIImageView
// Present, Push
func presentationBeforeAction()
func presentationAnimationAction(percentComplete: CGFloat)
func presentationCancelAnimationAction()
func presentationCompletionAction(didComplete: Bool)
// Dismiss, Pop
func dismissalBeforeAction()
func dismissalAnimationAction(percentComplete: CGFloat)
func dismissalCancelAnimationAction()
func dismissalCompletionAction(didComplete: Bool)
}
extension ImageZoomAnimationVC {
@objc func presentationBeforeAction() {}
@objc func presentationAnimationAction(percentComplete: CGFloat) {}
@objc func presentationCancelAnimationAction() {}
@objc func presentationCompletionAction(didComplete: Bool) {}
@objc func dismissalBeforeAction() {}
@objc func dismissalAnimationAction(percentComplete: CGFloat) {}
@objc func dismissalCancelAnimationAction() {}
@objc func dismissalCompletionAction(didComplete: Bool) {}
}
class ImageZoomAnimationVC: UIViewController, ImageTransitionZoomable {
func createTransitionImageView() -> UIImageView { return UIImageView() }
}
final class ImageZoomAnimation<T: UIViewController> : TransitionAnimatable where T : ImageTransitionZoomable {
fileprivate weak var rootVC: T!
fileprivate weak var modalVC: T!
fileprivate weak var rootNavigation: UINavigationController?
var completion: ((Bool) -> Void)?
fileprivate var sourceImageView: UIImageView?
fileprivate var destinationImageView: UIImageView?
fileprivate var sourceFrame: CGRect = CGRect.zero
fileprivate var destFrame: CGRect = CGRect.zero
deinit {
print("deinit ImageZoomAnimation")
}
init(rootVC: T, modalVC: T, rootNavigation: UINavigationController? = nil) {
self.rootVC = rootVC
self.modalVC = modalVC
self.rootNavigation = rootNavigation
}
func prepareContainer(_ transitionType: TransitionType, containerView: UIView, from fromVC: UIViewController, to toVC: UIViewController) {
if transitionType.isPresenting {
containerView.addSubview(toVC.view)
} else {
if let v = self.rootNavigation?.view {
containerView.addSubview(v)
} else {
containerView.addSubview(toVC.view)
}
containerView.addSubview(fromVC.view)
}
fromVC.view.setNeedsLayout()
fromVC.view.layoutIfNeeded()
toVC.view.setNeedsLayout()
toVC.view.layoutIfNeeded()
}
func willAnimation(_ transitionType: TransitionType, containerView: UIView) {
if transitionType.isPresenting {
self.sourceImageView = rootVC.createTransitionImageView()
self.destinationImageView = modalVC.createTransitionImageView()
containerView.addSubview(sourceImageView!)
rootVC.presentationBeforeAction()
modalVC.presentationBeforeAction()
modalVC.view.alpha = 0.0
} else {
self.sourceImageView = modalVC.createTransitionImageView()
self.destinationImageView = rootVC.createTransitionImageView()
self.sourceFrame = self.sourceImageView!.frame
self.destFrame = self.destinationImageView!.frame
containerView.addSubview(sourceImageView!)
rootVC.dismissalBeforeAction()
modalVC.dismissalBeforeAction()
}
}
func updateAnimation(_ transitionType: TransitionType, percentComplete: CGFloat) {
print(percentComplete)
if transitionType.isPresenting {
self.sourceImageView?.frame = self.destinationImageView!.frame
self.modalVC.view.alpha = 1.0 * percentComplete
self.rootVC.presentationAnimationAction(percentComplete: percentComplete)
self.modalVC.presentationAnimationAction(percentComplete: percentComplete)
} else {
let p = 1.0 - (1.0 * percentComplete)
let frame = CGRect(
x: destFrame.origin.x - (destFrame.origin.x - sourceFrame.origin.x) * p,
y: destFrame.origin.y - (destFrame.origin.y - sourceFrame.origin.y) * p,
width: destFrame.size.width + (sourceFrame.size.width - destFrame.size.width) * p,
height: destFrame.size.height + (sourceFrame.size.height - destFrame.size.height) * p
)
self.sourceImageView!.frame = frame
self.modalVC.view.alpha = p
self.rootVC.dismissalAnimationAction(percentComplete: percentComplete)
self.modalVC.dismissalAnimationAction(percentComplete: percentComplete)
}
}
func finishAnimation(_ transitionType: TransitionType, didComplete: Bool) {
self.sourceImageView?.removeFromSuperview()
self.destinationImageView?.removeFromSuperview()
if transitionType.isPresenting {
self.rootVC.presentationCompletionAction(didComplete: didComplete)
self.modalVC.presentationCompletionAction(didComplete: didComplete)
} else {
self.rootVC.dismissalCompletionAction(didComplete: didComplete)
self.modalVC.dismissalCompletionAction(didComplete: didComplete)
}
self.completion?(didComplete)
}
}
extension ImageZoomAnimation {
func sourceVC() -> UIViewController { return self.rootVC }
func destVC() -> UIViewController { return self.modalVC }
}
| mit | c1b1ae6b2b050abc7e83e58b20cdb530 | 33.264368 | 142 | 0.664542 | 5.439781 | false | false | false | false |
James-swift/JMSCycleScrollView | Pods/JMSPageControl/JMSPageControl/Lib/JMSDotView.swift | 1 | 955 | //
// JMSDotView.swift
// JMSPageControl
//
// Created by James.xiao on 2017/7/4.
// Copyright © 2017年 James.xiao. All rights reserved.
//
import UIKit
public class JMSDotView: JMSAbstractDotView {
public override init() {
super.init()
self.setupViews()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setupViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func changeActivityState(active: Bool) {
if active {
self.backgroundColor = .white
}else {
self.backgroundColor = .clear
}
}
// MARK: - UI
private func setupViews() {
self.backgroundColor = .clear
self.layer.cornerRadius = self.frame.width / 2
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2
}
}
| mit | 86e48ae6f6d916a934ccc67d15c8b4ae | 21.139535 | 60 | 0.590336 | 4.231111 | false | false | false | false |
duongsonthong/waveFormLibrary | waveFormLibrary/PlayButtonView.swift | 2 | 2911 | //
// PlayButtonView.swift
// Created by SSd on 11/15/16.
//
import UIKit
class PlayButtonView: UIButton {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
let mFrame : CGRect
let utilFunction = UtilFunction()
var isPlayStatus : Bool = false
var fillColor = UIColor(red: 225/255, green: 216/255, blue: 227/255, alpha: 1.0)
let caShape = CAShapeLayer()
let triangleShape = CAShapeLayer()
override init(frame: CGRect) {
mFrame = frame
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
caShape.frame = CGRect(x: 0, y: 0, width: mFrame.width, height: mFrame.height)
let startAngle = CGFloat(0.0)
let endAngle = CGFloat(2.0 * M_PI)
let clockwise = true
let circlePath = utilFunction.createCirclePath(arcCenter: CGPoint(x: mFrame.size.width/2,y : mFrame.size.height/2), radius: mFrame.size.width/2, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
caShape.fillColor = fillColor.cgColor
caShape.path = circlePath.cgPath
//triangle
let triangleWidth = mFrame.width/2
let xPosition = isPlayStatus ? caShape.frame.width/2-triangleWidth/2 : caShape.frame.width/2-triangleWidth/2+caShape.frame.width/10
triangleShape.frame = CGRect(x: xPosition, y: caShape.frame.width/2-triangleWidth/2, width: triangleWidth, height:triangleWidth)
var path = UIBezierPath()
if isPlayStatus {
//playing
let lineWidth = triangleWidth/3
path.move(to: CGPoint(x: lineWidth/2, y: 0))
path.addLine(to: CGPoint(x: lineWidth/2, y: triangleWidth))
path.close()
path.move(to: CGPoint(x: triangleWidth-lineWidth/2, y: 0))
path.addLine(to: CGPoint(x: triangleWidth-lineWidth/2, y: triangleWidth))
path.close()
triangleShape.lineWidth = lineWidth
}else {
//pause
triangleShape.lineWidth = CGFloat(1)
let x1 = CGPoint(x: 0, y: 0)
let x2 = CGPoint(x: 0, y: triangleWidth)
let x3 = CGPoint(x: triangleWidth, y: triangleWidth/2)
path = utilFunction.createTrianglePath(x1: x1, x2: x2, x3: x3)
}
triangleShape.strokeColor = UIColor.white.cgColor
triangleShape.path = path.cgPath
triangleShape.fillColor = UIColor.white.cgColor
triangleShape.backgroundColor = UIColor.clear.cgColor
caShape.addSublayer(triangleShape)
layer.addSublayer(caShape)
}
public func setPlayStatus(isPlay : Bool){
isPlayStatus = isPlay
self.setNeedsDisplay()
}
}
| mit | b8fbb7f814b0e724f4dc917a998f8ef5 | 36.805195 | 218 | 0.631398 | 3.993141 | false | false | false | false |
gabrielrigon/OnboardingKit | Example/Athlee-Onboarding/Athlee-Onboarding/DeviceTarget.swift | 1 | 789 | //
// DeviceTarget.swift
// Athlee-Onboarding
//
// Created by mac on 07/07/16.
// Copyright © 2016 Athlee. All rights reserved.
//
import UIKit
public struct DeviceTarget {
public static let CURRENT_DEVICE: CGFloat = UIScreen.mainScreen().bounds.height
public static let IPHONE_4: CGFloat = 480
public static let IPHONE_5: CGFloat = 568
public static let IPHONE_6: CGFloat = 667
public static let IPHONE_6_Plus: CGFloat = 736
public static let IS_IPHONE_4 = UIScreen.mainScreen().bounds.height == IPHONE_4
public static let IS_IPHONE_5 = UIScreen.mainScreen().bounds.height == IPHONE_5
public static let IS_IPHONE_6 = UIScreen.mainScreen().bounds.height == IPHONE_6
public static let IS_IPHONE_6_Plus = UIScreen.mainScreen().bounds.height == IPHONE_6_Plus
} | mit | a8e86eb2820c0fbcfc181f8cfcb63273 | 33.304348 | 91 | 0.727157 | 3.631336 | false | false | false | false |
khizkhiz/swift | test/SILGen/scalar_to_tuple_args.swift | 2 | 3356 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func inoutWithDefaults(x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(x: inout Int, y: Int = #line) {}
func scalarWithDefaults(x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(x: Int, y: Int = #line) {}
func tupleWithDefaults(x x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(x: Int...) {}
func variadicSecond(x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @_Tv20scalar_to_tuple_args1xSi : $*Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17inoutWithDefaultsFTRSi1ySi1zSi_T_
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[X_ADDR]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args27inoutWithCallerSideDefaultsFTRSi1ySi_T_
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[X_ADDR]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args18scalarWithDefaultsFTSi1ySi1zSi_T_
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args28scalarWithCallerSideDefaultsFTSi1ySi_T_
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @_TF20scalar_to_tuple_args17tupleWithDefaultsFT1xTSiSi_1ySi1zSi_T_
// CHECK: [[X1:%.*]] = load [[X_ADDR]]
// CHECK: [[X2:%.*]] = load [[X_ADDR]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @_TF20scalar_to_tuple_args13variadicFirstFtGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[MEMORY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 1
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: store [[X]] to [[ADDR]]
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @_TF20scalar_to_tuple_args14variadicSecondFtSiGSaSi__T_
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: [[ARRAY:%.*]] = tuple_extract [[ALLOC_ARRAY]] {{.*}}, 0
// CHECK: [[X:%.*]] = load [[X_ADDR]]
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
| apache-2.0 | a78415c984cfc6bc086df2b1caf6a2b5 | 50.6 | 128 | 0.605546 | 3.128731 | false | false | false | false |
wesj/Project105 | ShareOverlay/ShareViewController.swift | 1 | 8706 | //
// ShareViewController.swift
// ShareOverlay
//
// Created by Wes Johnston on 10/15/14.
// Copyright (c) 2014 Wes Johnston. All rights reserved.
//
import UIKit
import Social
import MobileCoreServices
class ShareViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var items: [String] = ["Send to device", "Bookmark Page", "Add to reading list"]
var images: [String] = ["overlay_send_tab_icon.png", "overlay_bookmark_icon.png", "overlay_readinglist_icon.png"]
@IBOutlet weak var table: UITableView!
@IBOutlet weak var listContainer: UIView!
@IBOutlet weak var background: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleView: UILabel!
@IBOutlet weak var urlView: UILabel!
let ANIM_DURATION = 0.5
override func loadView() {
super.loadView()
listContainer.alpha = 0;
background.alpha = 0;
var myExtensionContext : NSExtensionContext = self.extensionContext!
var inputItems = myExtensionContext.inputItems
for item in inputItems as [NSExtensionItem] {
setTitle(item.attributedContentText?.string as String?)
for attachment in item.attachments as [NSItemProvider] {
attachment.loadItemForTypeIdentifier(kUTTypeURL as NSString, options: nil) {
(decoder: NSSecureCoding!, error: NSError!) -> Void in
// This is semi-async, and if we find the text late, the extension view doesn't update. Need a better solution here
if let url : NSURL = (decoder as? NSURL) {
self.setUrl(url.absoluteString!);
} else {
self.setUrl("");
}
}
let options: [NSObject : AnyObject] = [
NSItemProviderPreferredImageSizeKey: imageView.frame.width
];
attachment.loadPreviewImageWithOptions(options) {
(decoder: NSSecureCoding!, error: NSError!) -> Void in
if let image : UIImage = (decoder as? UIImage) {
self.imageView.image = image;
}
}
/* Doesn't work :(
attachment.loadItemForTypeIdentifier(kUTTypeImage as NSString, options: nil) {
(decoder: NSSecureCoding!, error: NSError!) -> Void in
self.imageView.image = decoder as? UIImage
}
*/
}
}
setupListHeight();
setupContainerHeight();
}
private func setTitle(title: NSString?) {
if (title == nil) {
titleView.text = "";
return;
}
titleView.text = title;
}
private func setUrl(url: NSString) {
urlView!.text = url
}
private func setupContainerHeight() {
let frame = listContainer.frame;
let h : CGFloat = imageView.frame.height; // table.frame.height;// +
listContainer.frame = CGRect(x: frame.origin.x, y: UIScreen.mainScreen().bounds.height - h, width: frame.width, height: h)
}
private func setupListHeight() {
let frame = table.frame;
let c : CGFloat = CGFloat(items.count);
let h : CGFloat = 44 * c
table.frame = CGRect(x: frame.origin.x, y: UIScreen.mainScreen().bounds.height - h, width: frame.width, height: h)
}
override func viewDidLoad() {
super.viewDidLoad()
table.dataSource = self;
table.delegate = self;
}
override func viewDidAppear(animated: Bool) {
let start = self.listContainer.frame;
self.listContainer.frame.origin.y = start.origin.y + 100;
UIView.animateWithDuration(ANIM_DURATION, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
self.background.alpha = 1.0;
self.listContainer.alpha = 1.0;
self.listContainer.frame = start
}, completion: { (ret: Bool) -> Void in
})
}
override func viewDidDisappear(animated: Bool) {
UIView.animateWithDuration(ANIM_DURATION, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
self.background.alpha = 0;
self.listContainer.alpha = 0;
self.listContainer.frame.origin.y = self.listContainer.frame.origin.y + 100;
}, completion: { (ret: Bool) -> Void in
})
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// View recycling doesn't seem to work in Extensions. At least not with a View from the storyboard.
// Thankfully, this list is really short.
var cell:ShareListCellTableViewCell = ShareListCellTableViewCell();
cell.textLabel?.text = self.items[indexPath.row]
cell.shareImageView?.image = UIImage(named: self.images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0) {
self.getUrl() {
(var url : NSURL?) -> Void in
if (url != nil) {
Bookmarks.add(url!);
Bookmarks.printList();
/* We could post some JSON to the server
var url : NSURL = NSURL(string: "http://www.google.com")!
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
println("Got \(error): \(response)");
});
task.resume()
*/
self.viewDidDisappear(true);
}
}
} else {
self.rowClicked()
}
}
/* Left over from using the built in share UI
func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
func didSelectPost() {
ReadingList.printToConsole()
getUrl() {
(var url : NSURL?) -> Void in
if (url != nil) {
ReadingList.add(url!)
}
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}
}
func configurationItems() -> [AnyObject]! {
var items : [SLComposeSheetConfigurationItem] = [];
var item : SLComposeSheetConfigurationItem = SLComposeSheetConfigurationItem()
item.title = "Add bookmark";
item.value = "My value";
item.tapHandler = rowClicked
items.append(item)
var item2 : SLComposeSheetConfigurationItem = SLComposeSheetConfigurationItem()
item2.title = "Add to reading list";
item2.tapHandler = openApp
items.append(item2)
return items;
}
private func openApp() {
}
*/
// A simple function to be called whenever you click on one of the "configuration" rows.
// Adds the current url to the ReadingList, and closes the dialog
private func rowClicked() -> Void {
self.getUrl() {
(var url : NSURL?) -> Void in
if (url != nil) {
ReadingList.add(url!);
ReadingList.printToConsole()
self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
}
}
}
// Get the url passed to us from the sharing app
// Takes a callback function
private func getUrl(callback: (NSURL?) -> Void) {
var myExtensionContext : NSExtensionContext = self.extensionContext!
var inputItems = myExtensionContext.inputItems
for item in inputItems as [NSExtensionItem] {
for attachment in item.attachments as [NSItemProvider] {
attachment.loadItemForTypeIdentifier(kUTTypeURL as NSString, options: nil) {
(decoder: NSSecureCoding!, error: NSError!) -> Void in
callback(decoder as? NSURL);
}
}
}
}
}
| mpl-2.0 | b5de37f1d8cefe9a813f965caeccf42d | 37.017467 | 137 | 0.58408 | 5.03237 | false | true | false | false |
Ahyufei/DouYuTV | DYTV/DYTV/Classes/Main/View/CollectionBaseCell.swift | 1 | 1216 | //
// CollectionBaseCell.swift
// DYTV
//
// Created by Yufei on 2017/1/15.
// Copyright © 2017年 张玉飞. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
// MARK:- 控件属性
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
// MARK:- 定义模型
var anchor : AnchorModel? {
didSet {
// 0.校验模型是否有值
guard let anchor = anchor else { return }
// 1.取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: UIControlState())
// 2.昵称的显示
nickNameLabel.text = anchor.nickname
// 3.设置封面图片
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL)
}
}
}
| mit | a0023c018dafec73551167cf3998bdf6 | 26.341463 | 80 | 0.539697 | 4.556911 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | Pods/RxTest/Platform/DataStructures/PriorityQueue.swift | 13 | 3323 | //
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
private let _hasHigherPriority: (Element, Element) -> Bool
private let _isEqual: (Element, Element) -> Bool
private var _elements = [Element]()
init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _elements.count == 0
}
mutating func dequeue() -> Element? {
guard let front = peek() else {
return nil
}
removeAt(0)
return front
}
mutating func remove(_ element: Element) {
for i in 0 ..< _elements.count {
if _isEqual(_elements[i], element) {
removeAt(i)
return
}
}
}
private mutating func removeAt(_ index: Int) {
let removingLast = index == _elements.count - 1
if !removingLast {
_elements.swapAt(index, _elements.count - 1)
}
_ = _elements.popLast()
if !removingLast {
bubbleToHigherPriority(index)
bubbleToLowerPriority(index)
}
}
private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while unbalancedIndex > 0 {
let parentIndex = (unbalancedIndex - 1) / 2
guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break }
_elements.swapAt(unbalancedIndex, parentIndex)
unbalancedIndex = parentIndex
}
}
private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while true {
let leftChildIndex = unbalancedIndex * 2 + 1
let rightChildIndex = unbalancedIndex * 2 + 2
var highestPriorityIndex = unbalancedIndex
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
_elements.swapAt(highestPriorityIndex, unbalancedIndex)
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue : CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
| gpl-3.0 | 8fb495978c71d94a4fcc6e687c0c826d | 28.927928 | 133 | 0.622216 | 4.82148 | false | false | false | false |
OneBestWay/EasyCode | SwiftExtensions/SwiftExtensions/DateExtensions.swift | 1 | 2632 | //
// DateExtensions.swift
// SwiftExtensions
//
// Created by GK on 2016/12/2.
// Copyright © 2016年 GK. All rights reserved.
//
import Foundation
extension Calendar {
//计算任意一天的开始,可以间接计算任意一天的结束
func startOfDay(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = false) -> Date? {
guard let newDate = self.date(byAdding: component, value: value, to: date, wrappingComponents: wrappingComponents) else {
return nil
}
return self.startOfDay(for: newDate)
}
}
extension Date {
// 返回据当前日期的时间间隔,例如一小时以前,两分钟以前
func timeAgoString() -> String? {
let components = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: self, to: Date())
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
if components.year != nil , components.year != 0 {
formatter.allowedUnits = .year
}else if components.month != nil ,components.month != 0 {
formatter.allowedUnits = .month
}else if components.day != nil ,components.day != 0 {
formatter.allowedUnits = .day
}else if components.hour != nil ,components.hour != 0 {
formatter.allowedUnits = .hour
}else if components.minute != nil ,components.minute != 0 {
formatter.allowedUnits = .minute
}else {
formatter.allowedUnits = .second
}
guard let timeString = formatter.string(from: components) else {
return nil
}
return String(format: NSLocalizedString("%@ ago", comment: "Format string for relative time ago"), timeString)
}
//得到当前日期之前的日期,例如1小时以前的日期,一个月以前的日期
func getDate(daysAgo days: Double = 0, hoursAgo hours: Double = 0, minutesAgo minutes: Double = 0, secondsAgo seconds: Double = 0) -> Date {
let hoursPerDay: Double = 24
let hoursMeasurement = Measurement(value: (days * hoursPerDay) + hours, unit: UnitDuration.hours)
let minutesMeasurement = Measurement(value: minutes, unit: UnitDuration.minutes)
let secondsMeasurement = Measurement(value: seconds, unit: UnitDuration.seconds)
let totalMeasurement = hoursMeasurement + minutesMeasurement + secondsMeasurement
let totalTimeInterval = totalMeasurement.converted(to: UnitDuration.seconds).value
return self - totalTimeInterval
}
}
| mit | 3f11a37385b8d61bc0a65f28961c4315 | 38.854839 | 144 | 0.647511 | 4.388988 | false | false | false | false |
MozzazIncorporation/cordova-plugin-iosrtc | src/PluginMediaStreamRenderer.swift | 1 | 7352 | import Foundation
import AVFoundation
class PluginMediaStreamRenderer : NSObject, RTCEAGLVideoViewDelegate {
@objc var webView: UIView
@objc var eventListener: (_ data: NSDictionary) -> Void
@objc var elementView: UIView
@objc var videoView: RTCEAGLVideoView
@objc var pluginMediaStream: PluginMediaStream?
@objc var rtcAudioTrack: RTCAudioTrack?
@objc var rtcVideoTrack: RTCVideoTrack?
@objc init(
webView: UIView,
eventListener: @escaping (_ data: NSDictionary) -> Void
) {
NSLog("PluginMediaStreamRenderer#init()")
// The browser HTML view.
self.webView = webView
self.eventListener = eventListener
// The video element view.
self.elementView = UIView()
// The effective video view in which the the video stream is shown.
// It's placed over the elementView.
self.videoView = RTCEAGLVideoView()
self.elementView.isUserInteractionEnabled = false
self.elementView.isHidden = true
self.elementView.backgroundColor = UIColor.black
self.elementView.addSubview(self.videoView)
self.elementView.layer.masksToBounds = true
self.videoView.isUserInteractionEnabled = false
// Place the video element view inside the WebView's superview
self.webView.superview?.addSubview(self.elementView)
}
deinit {
NSLog("PluginMediaStreamRenderer#deinit()")
}
@objc func run() {
NSLog("PluginMediaStreamRenderer#run()")
self.videoView.delegate = self
}
@objc func render(_ pluginMediaStream: PluginMediaStream) {
NSLog("PluginMediaStreamRenderer#render()")
if self.pluginMediaStream != nil {
self.reset()
}
self.pluginMediaStream = pluginMediaStream
// Take the first audio track.
for (_, track) in pluginMediaStream.audioTracks {
self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack
break
}
// Take the first video track.
for (_, track) in pluginMediaStream.videoTracks {
self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack
break
}
if self.rtcVideoTrack != nil {
self.rtcVideoTrack!.add(self.videoView)
}
}
@objc func mediaStreamChanged() {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged()")
if self.pluginMediaStream == nil {
return
}
let oldRtcVideoTrack: RTCVideoTrack? = self.rtcVideoTrack
self.rtcAudioTrack = nil
self.rtcVideoTrack = nil
// Take the first audio track.
for (_, track) in self.pluginMediaStream!.audioTracks {
self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack
break
}
// Take the first video track.
for (_, track) in pluginMediaStream!.videoTracks {
self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack
break
}
// If same video track as before do nothing.
if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil &&
oldRtcVideoTrack!.label == self.rtcVideoTrack!.label {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | same video track as before")
}
// Different video track.
else if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil &&
oldRtcVideoTrack!.label != self.rtcVideoTrack!.label {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | has a new video track")
oldRtcVideoTrack!.remove(self.videoView)
self.rtcVideoTrack!.add(self.videoView)
}
// Did not have video but now it has.
else if oldRtcVideoTrack == nil && self.rtcVideoTrack != nil {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track added")
self.rtcVideoTrack!.add(self.videoView)
}
// Had video but now it has not.
else if oldRtcVideoTrack != nil && self.rtcVideoTrack == nil {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track removed")
oldRtcVideoTrack!.remove(self.videoView)
}
}
@objc func refresh(_ data: NSDictionary) {
let elementLeft = data.object(forKey: "elementLeft") as? Float ?? 0
let elementTop = data.object(forKey: "elementTop") as? Float ?? 0
let elementWidth = data.object(forKey: "elementWidth") as? Float ?? 0
let elementHeight = data.object(forKey: "elementHeight") as? Float ?? 0
var videoViewWidth = data.object(forKey: "videoViewWidth") as? Float ?? 0
var videoViewHeight = data.object(forKey: "videoViewHeight") as? Float ?? 0
let visible = data.object(forKey: "visible") as? Bool ?? true
let opacity = data.object(forKey: "opacity") as? Float ?? 1
let zIndex = data.object(forKey: "zIndex") as? Float ?? 0
let mirrored = data.object(forKey: "mirrored") as? Bool ?? false
let clip = data.object(forKey: "clip") as? Bool ?? true
let borderRadius = data.object(forKey: "borderRadius") as? Float ?? 0
NSLog("PluginMediaStreamRenderer#refresh() [elementLeft:%@, elementTop:%@, elementWidth:%@, elementHeight:%@, videoViewWidth:%@, videoViewHeight:%@, visible:%@, opacity:%@, zIndex:%@, mirrored:%@, clip:%@, borderRadius:%@]",
String(elementLeft), String(elementTop), String(elementWidth), String(elementHeight),
String(videoViewWidth), String(videoViewHeight), String(visible), String(opacity), String(zIndex),
String(mirrored), String(clip), String(borderRadius))
let videoViewLeft: Float = (elementWidth - videoViewWidth) / 2
let videoViewTop: Float = (elementHeight - videoViewHeight) / 2
self.elementView.frame = CGRect(
x: CGFloat(elementLeft),
y: CGFloat(elementTop),
width: CGFloat(elementWidth),
height: CGFloat(elementHeight)
)
// NOTE: Avoid a zero-size UIView for the video (the library complains).
if videoViewWidth == 0 || videoViewHeight == 0 {
videoViewWidth = 1
videoViewHeight = 1
self.videoView.isHidden = true
} else {
self.videoView.isHidden = false
}
self.videoView.frame = CGRect(
x: CGFloat(videoViewLeft),
y: CGFloat(videoViewTop),
width: CGFloat(videoViewWidth),
height: CGFloat(videoViewHeight)
)
if visible {
self.elementView.isHidden = false
} else {
self.elementView.isHidden = true
}
self.elementView.alpha = CGFloat(opacity)
self.elementView.layer.zPosition = CGFloat(zIndex)
// if the zIndex is 0 (the default) bring the view to the top, last one wins
if zIndex == 0 {
self.webView.superview?.bringSubview(toFront: self.elementView)
}
if !mirrored {
self.elementView.transform = CGAffineTransform.identity
} else {
self.elementView.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
if clip {
self.elementView.clipsToBounds = true
} else {
self.elementView.clipsToBounds = false
}
self.elementView.layer.cornerRadius = CGFloat(borderRadius)
}
@objc func close() {
NSLog("PluginMediaStreamRenderer#close()")
self.reset()
self.elementView.removeFromSuperview()
}
/**
* Private API.
*/
fileprivate func reset() {
NSLog("PluginMediaStreamRenderer#reset()")
if self.rtcVideoTrack != nil {
self.rtcVideoTrack!.remove(self.videoView)
}
self.pluginMediaStream = nil
self.rtcAudioTrack = nil
self.rtcVideoTrack = nil
}
/**
* Methods inherited from RTCEAGLVideoViewDelegate.
*/
func videoView(_ videoView: RTCEAGLVideoView!, didChangeVideoSize size: CGSize) {
NSLog("PluginMediaStreamRenderer | video size changed [width:%@, height:%@]",
String(describing: size.width), String(describing: size.height))
self.eventListener([
"type": "videoresize",
"size": [
"width": Int(size.width),
"height": Int(size.height)
]
])
}
}
| mit | d6c1e455ecf5f601471de6710666ae99 | 27.71875 | 226 | 0.712867 | 3.752935 | false | false | false | false |
tristanchu/FlavorFinder | FlavorFinder/FlavorFinder/Voting.swift | 1 | 784 | //
// Voting.swift
// FlavorFinder
//
// Created by Jon on 10/27/15.
// Copyright © 2015 TeamFive. All rights reserved.
//
// see https://medium.com/hacking-and-gonzo/how-reddit-ranking-algorithms-work-ef111e33d0d9#.gct33voi1
import Foundation
func _confidence(ups: Int, downs: Int) -> Double {
let n = Double(ups) + Double(downs)
if (n == 0) {
return 0
}
let z = 1.0 // statistical confidence level: 1.0 = 85%, 1.6 = 95%
let phat = Double(ups) / n;
let comp1 = phat*(1-phat)
let comp2 = ((comp1+z*z/(4*n))/n)
return sqrt(phat+z*z/(2*n)-z*comp2)/(1+z*z/n)
}
func confidence(ups: Int, downs: Int) -> Double {
if (ups + downs == 0) {
return 0
} else {
return _confidence(ups, downs: downs)
}
}
| mit | b6ffd6af6ddb2342388b8c5cd65a8e64 | 22.029412 | 102 | 0.579821 | 2.7 | false | false | false | false |
smdls/C0 | C0/Document.swift | 1 | 19410 | /*
Copyright 2017 S
This file is part of C0.
C0 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.
C0 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 C0. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
protocol SceneEntityDelegate: class {
func changedUpdateWithPreference(_ sceneEntity: SceneEntity)
}
final class SceneEntity {
let preferenceKey = "preference", cutsKey = "cuts", materialsKey = "materials"
weak var delegate: SceneEntityDelegate?
var preference = Preference(), cutEntities = [CutEntity]()
init() {
let cutEntity = CutEntity()
cutEntity.sceneEntity = self
cutEntities = [cutEntity]
cutsFileWrapper = FileWrapper(directoryWithFileWrappers: [String(0): cutEntity.fileWrapper])
materialsFileWrapper = FileWrapper(directoryWithFileWrappers: [String(0): cutEntity.materialWrapper])
rootFileWrapper = FileWrapper(directoryWithFileWrappers: [
preferenceKey : preferenceFileWrapper,
cutsKey: cutsFileWrapper,
materialsKey: materialsFileWrapper
])
}
var rootFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = rootFileWrapper.fileWrappers {
if let fileWrapper = fileWrappers[preferenceKey] {
preferenceFileWrapper = fileWrapper
}
if let fileWrapper = fileWrappers[cutsKey] {
cutsFileWrapper = fileWrapper
}
if let fileWrapper = fileWrappers[materialsKey] {
materialsFileWrapper = fileWrapper
}
}
}
}
var preferenceFileWrapper = FileWrapper()
var cutsFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = cutsFileWrapper.fileWrappers {
let sortedFileWrappers = fileWrappers.sorted {
$0.key.localizedStandardCompare($1.key) == .orderedAscending
}
cutEntities = sortedFileWrappers.map {
return CutEntity(fileWrapper: $0.value, index: Int($0.key) ?? 0, sceneEntity: self)
}
}
}
}
var materialsFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = materialsFileWrapper.fileWrappers {
let sortedFileWrappers = fileWrappers.sorted {
$0.key.localizedStandardCompare($1.key) == .orderedAscending
}
for (i, cutEntity) in cutEntities.enumerated() {
if i < sortedFileWrappers.count {
cutEntity.materialWrapper = sortedFileWrappers[i].value
}
}
}
}
}
func read() {
readPreference()
for cutEntity in cutEntities {
cutEntity.read()
}
}
func write() {
writePreference()
for cutEntity in cutEntities {
cutEntity.write()
}
}
func allWrite() {
isUpdatePreference = true
writePreference()
for cutEntity in cutEntities {
cutEntity.isUpdate = true
cutEntity.isUpdateMaterial = true
cutEntity.write()
}
}
var isUpdatePreference = false {
didSet {
if isUpdatePreference != oldValue {
delegate?.changedUpdateWithPreference(self)
}
}
}
func readPreference() {
if let data = preferenceFileWrapper.regularFileContents, let preference = Preference.with(data) {
self.preference = preference
}
}
func writePreference() {
if isUpdatePreference {
writePreference(with: preference.data)
isUpdatePreference = false
}
}
func writePreference(with data: Data) {
rootFileWrapper.removeFileWrapper(preferenceFileWrapper)
preferenceFileWrapper = FileWrapper(regularFileWithContents: data)
preferenceFileWrapper.preferredFilename = preferenceKey
rootFileWrapper.addFileWrapper(preferenceFileWrapper)
}
func insert(_ cutEntity: CutEntity, at index: Int) {
if index < cutEntities.count {
for i in (index ..< cutEntities.count).reversed() {
let cutEntity = cutEntities[i]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
cutEntity.fileWrapper.preferredFilename = String(i + 1)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.materialWrapper.preferredFilename = String(i + 1)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntity.index = i + 1
}
}
cutEntity.fileWrapper.preferredFilename = String(index)
cutEntity.index = index
cutEntity.materialWrapper.preferredFilename = String(index)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntities.insert(cutEntity, at: index)
cutEntity.sceneEntity = self
}
func removeCutEntity(at index: Int) {
let cutEntity = cutEntities[index]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.sceneEntity = nil
cutEntities.remove(at: index)
for i in index ..< cutEntities.count {
let cutEntity = cutEntities[i]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
cutEntity.fileWrapper.preferredFilename = String(i)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.materialWrapper.preferredFilename = String(i)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntity.index = i
}
}
var cuts: [Cut] {
return cutEntities.map { $0.cut }
}
}
final class CutEntity: Equatable {
weak var sceneEntity: SceneEntity!
var cut: Cut, index: Int
var fileWrapper = FileWrapper(), materialWrapper = FileWrapper()
var isUpdate = false, isUpdateMaterial = false, useWriteMaterial = false, isReadContent = true
init(fileWrapper: FileWrapper, index: Int, sceneEntity: SceneEntity? = nil) {
cut = Cut()
self.fileWrapper = fileWrapper
self.index = index
self.sceneEntity = sceneEntity
}
init(cut: Cut = Cut(), index: Int = 0) {
self.cut = cut
self.index = index
}
func read() {
if let s = fileWrapper.preferredFilename {
index = Int(s) ?? 0
} else {
index = 0
}
isReadContent = false
readContent()
}
func readContent() {
if !isReadContent {
if let data = fileWrapper.regularFileContents, let cut = Cut.with(data) {
self.cut = cut
}
if let materialsData = materialWrapper.regularFileContents, !materialsData.isEmpty {
if let materialCellIDs = NSKeyedUnarchiver.unarchiveObject(with: materialsData) as? [MaterialCellID] {
cut.materialCellIDs = materialCellIDs
useWriteMaterial = true
}
}
isReadContent = true
}
}
func write() {
if isUpdate {
writeCut(with: cut.data)
isUpdate = false
isUpdateMaterial = false
if useWriteMaterial {
writeMaterials(with: Data())
useWriteMaterial = false
}
}
if isUpdateMaterial {
writeMaterials(with: NSKeyedArchiver.archivedData(withRootObject: cut.materialCellIDs))
isUpdateMaterial = false
useWriteMaterial = true
}
}
func writeCut(with data: Data) {
sceneEntity.cutsFileWrapper.removeFileWrapper(fileWrapper)
fileWrapper = FileWrapper(regularFileWithContents: data)
fileWrapper.preferredFilename = String(index)
sceneEntity.cutsFileWrapper.addFileWrapper(fileWrapper)
}
func writeMaterials(with data: Data) {
sceneEntity.materialsFileWrapper.removeFileWrapper(materialWrapper)
materialWrapper = FileWrapper(regularFileWithContents: data)
materialWrapper.preferredFilename = String(index)
sceneEntity.materialsFileWrapper.addFileWrapper(materialWrapper)
isUpdateMaterial = false
}
static func == (lhs: CutEntity, rhs: CutEntity) -> Bool {
return lhs === rhs
}
}
final class Preference: NSObject, NSCoding {
var version = Bundle.main.version
var isFullScreen = false, windowFrame = NSRect()
var scene = Scene()
init(version: Int = Bundle.main.version, isFullScreen: Bool = false, windowFrame: NSRect = NSRect(), scene: Scene = Scene()) {
self.version = version
self.isFullScreen = isFullScreen
self.windowFrame = windowFrame
self.scene = scene
super.init()
}
static let dataType = "C0.Preference.1", versionKey = "0", isFullScreenKey = "1", windowFrameKey = "2", sceneKey = "3"
init?(coder: NSCoder) {
version = coder.decodeInteger(forKey: Preference.versionKey)
isFullScreen = coder.decodeBool(forKey: Preference.isFullScreenKey)
windowFrame = coder.decodeRect(forKey: Preference.windowFrameKey)
scene = coder.decodeObject(forKey: Preference.sceneKey) as? Scene ?? Scene()
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(version, forKey: Preference.versionKey)
coder.encode(isFullScreen, forKey: Preference.isFullScreenKey)
coder.encode(windowFrame, forKey: Preference.windowFrameKey)
coder.encode(scene, forKey: Preference.sceneKey)
}
}
final class MaterialCellID: NSObject, NSCoding {
var material: Material, cellIDs: [UUID]
init(material: Material, cellIDs: [UUID]) {
self.material = material
self.cellIDs = cellIDs
super.init()
}
static let dataType = "C0.MaterialCellID.1", materialKey = "0", cellIDsKey = "1"
init?(coder: NSCoder) {
material = coder.decodeObject(forKey: MaterialCellID.materialKey) as? Material ?? Material()
cellIDs = coder.decodeObject(forKey: MaterialCellID.cellIDsKey) as? [UUID] ?? []
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(material, forKey: MaterialCellID.materialKey)
coder.encode(cellIDs, forKey: MaterialCellID.cellIDsKey)
}
}
@NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate {}
final class Document: NSDocument, NSWindowDelegate, SceneEntityDelegate {
let sceneEntity = SceneEntity()
var window: NSWindow {
return windowControllers.first!.window!
}
weak var screen: Screen!, sceneView: SceneView!
override init() {
super.init()
}
convenience init(type typeName: String) throws {
self.init()
fileType = typeName
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
addWindowController(windowController)
screen = windowController.contentViewController!.view as! Screen
let sceneView = SceneView()
sceneView.displayActionNode = screen.actionNode
sceneView.sceneEntity = sceneEntity
self.sceneView = sceneView
screen.contentView = sceneView
setupWindow(with: sceneEntity.preference)
sceneEntity.delegate = self
}
private func setupWindow(with preference: Preference) {
if preference.windowFrame.isEmpty, let frame = NSScreen.main()?.frame {
let fitSizeWithHiddenCommand = NSSize(width: 860, height: 740), fitSizeWithShownCommand = NSSize(width: 1050, height: 740)
let size = sceneView.isHiddenCommand ? fitSizeWithHiddenCommand : fitSizeWithShownCommand
let origin = NSPoint(x: round((frame.width - size.width)/2), y: round((frame.height - size.height)/2))
preference.windowFrame = NSRect(origin: origin, size: size)
}
window.setFrame(preference.windowFrame, display: false)
if preference.isFullScreen {
window.toggleFullScreen(nil)
}
window.delegate = self
}
override func fileWrapper(ofType typeName: String) throws -> FileWrapper {
sceneEntity.write()
return sceneEntity.rootFileWrapper
}
override func read(from fileWrapper: FileWrapper, ofType typeName: String) throws {
sceneEntity.rootFileWrapper = fileWrapper
sceneEntity.read()
}
func changedUpdateWithPreference(_ sceneEntity: SceneEntity) {
if sceneEntity.isUpdatePreference {
updateChangeCount(.changeDone)
}
}
func windowDidResize(_ notification: Notification) {
sceneEntity.preference.windowFrame = window.frame
sceneEntity.isUpdatePreference = true
}
func windowDidEnterFullScreen(_ notification: Notification) {
sceneEntity.preference.isFullScreen = true
sceneEntity.isUpdatePreference = true
}
func windowDidExitFullScreen(_ notification: Notification) {
sceneEntity.preference.isFullScreen = false
sceneEntity.isUpdatePreference = true
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let action = menuItem.action else {
return true
}
switch action {
case #selector(shownCommand(_:)):
menuItem.state = !sceneView.isHiddenCommand ? NSOnState : NSOffState
case #selector(hiddenCommand(_:)):
menuItem.state = sceneView.isHiddenCommand ? NSOnState : NSOffState
case #selector(exportMovie720pFromSelectionCut(_:)):
menuItem.title = String(format: "Export 720p Movie with %@...".localized, "C\(sceneView.timeline.selectionCutEntity.index + 1)")
case #selector(exportMovie1080pFromSelectionCut(_:)):
menuItem.title = String(format: "Export 1080p Movie with %@...".localized, "C\(sceneView.timeline.selectionCutEntity.index + 1)")
default:
break
}
return true
}
@IBAction func shownCommand(_ sender: Any?) {
for document in NSDocumentController.shared().documents {
(document as? Document)?.sceneView.isHiddenCommand = false
}
}
@IBAction func hiddenCommand(_ sender: Any?) {
for document in NSDocumentController.shared().documents {
(document as? Document)?.sceneView.isHiddenCommand = true
}
}
@IBAction func exportMovie720p(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1280, height: 720), fps: 24, isSelectionCutOnly: false)
}
@IBAction func exportMovie1080p(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1920, height: 1080), fps: 24, isSelectionCutOnly: false)
}
@IBAction func exportMovie720pFromSelectionCut(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", name: "C\(sceneView.timeline.selectionCutEntity.index + 1)", size: CGSize(width: 1280, height: 720), fps: 24, isSelectionCutOnly: true)
}
@IBAction func exportMovie1080pFromSelectionCut(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", name: "C\(sceneView.timeline.selectionCutEntity.index + 1)", size: CGSize(width: 1920, height: 1080), fps: 24, isSelectionCutOnly: true)
}
@IBAction func exportImage720p(_ sender: Any?) {
sceneView.renderView.exportImage(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1280, height: 720))
}
@IBAction func exportImage1080p(_ sender: Any?) {
sceneView.renderView.exportImage(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1920, height: 1080))
}
@IBAction func screenshot(_ sender: Any?) {
let savePanel = NSSavePanel()
savePanel.nameFieldStringValue = "screenshot"
savePanel.allowedFileTypes = [String(kUTTypePNG)]
savePanel.beginSheetModal(for: window) { [unowned savePanel] result in
if result == NSFileHandlingPanelOKButton, let url = savePanel.url {
do {
try self.screenshotImage?.PNGRepresentation?.write(to: url)
try FileManager.default.setAttributes([FileAttributeKey.extensionHidden: savePanel.isExtensionHidden], ofItemAtPath: url.path)
}
catch {
self.screen.errorNotification(NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError))
}
}
}
}
var screenshotImage: NSImage? {
let padding = 5.0.cf*sceneView.layer.contentsScale
let bounds = sceneView.clipView.layer.bounds.inset(by: -padding)
if let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let ctx = CGContext(data: nil, width: Int(bounds.width*sceneView.layer.contentsScale), height: Int(bounds.height*sceneView.layer.contentsScale), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue), let color = screen.rootView.layer.backgroundColor {
ctx.setFillColor(color)
ctx.fill(CGRect(x: 0, y: 0, width: bounds.width*sceneView.layer.contentsScale, height: bounds.height*sceneView.layer.contentsScale))
ctx.translateBy(x: padding*sceneView.layer.contentsScale, y: padding*sceneView.layer.contentsScale)
ctx.scaleBy(x: sceneView.layer.contentsScale, y: sceneView.layer.contentsScale)
CATransaction.disableAnimation {
sceneView.clipView.layer.render(in: ctx)
}
if let cgImage = ctx.makeImage() {
return NSImage(cgImage: cgImage, size: NSSize())
}
}
return nil
}
@IBAction func openHelp(_ sender: Any?) {
if let url = URL(string: "https://github.com/smdls/C0") {
NSWorkspace.shared().open(url)
}
}
}
| gpl-3.0 | 208614c91bf6edfc71dfc2a11510cbeb | 39.4375 | 378 | 0.63694 | 4.857357 | false | false | false | false |
dwalks12/DWSegmentControl | Example/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift | 1 | 4684 | //
// Completable+AndThen.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/2/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Single<E>) -> Single<E> {
let completable = self.primitiveSequence.asObservable()
return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> {
let completable = self.primitiveSequence.asObservable()
return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen(_ second: Completable) -> Completable {
let completable = self.primitiveSequence.asObservable()
return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Observable<E>) -> Observable<E> {
let completable = self.primitiveSequence.asObservable()
return ConcatCompletable(completable: completable, second: second.asObservable())
}
}
final fileprivate class ConcatCompletable<Element> : Producer<Element> {
fileprivate let _completable: Observable<Never>
fileprivate let _second: Observable<Element>
init(completable: Observable<Never>, second: Observable<Element>) {
self._completable = completable
self._second = second
}
override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O : ObserverType, O.E == Element {
let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final fileprivate class ConcatCompletableSink<O: ObserverType>
: Sink<O>
, ObserverType {
typealias E = Never
typealias Parent = ConcatCompletable<O.E>
private let _parent: Parent
private let _subscription = SerialDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .error(let error):
self.forwardOn(.error(error))
case .next:
break
case .completed:
let otherSink = ConcatCompletableSinkOther(parent: self)
_subscription.disposable = _parent._second.subscribe(otherSink)
}
}
func run() -> Disposable {
_subscription.disposable = _parent._completable.subscribe(self)
return _subscription
}
}
final fileprivate class ConcatCompletableSinkOther<O: ObserverType>
: ObserverType {
typealias E = O.E
typealias Parent = ConcatCompletableSink<O>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<O.E>) {
_parent.forwardOn(event)
}
}
| mit | 58fef1fdf90f78e08cc33211f164c4e1 | 36.166667 | 148 | 0.686312 | 4.744681 | false | false | false | false |
acazares/Multi-Life-Cellular-Survival | Multi-Life: Cellular Survival/Multi-Life: Cellular Survival/Population.swift | 1 | 7154 | //
// Population.swift
// Multi-Life: Cellular Survival
//
// Created by Alexander Cazares on 4/7/15.
// Copyright (c) 2015 Alexander Cazares. All rights reserved.
//
import Foundation
class Population
{
var grid:[[Cell]]; // Grid of Cell's as a 2D Array
let gridRows:Int = 22; // "Height"
let gridColumns:Int = 32; // "Width"
// Constructor
init()
{
self.grid = [[Cell]](count: self.gridColumns, repeatedValue: [Cell]()); // Initialize the columns with empty arrays of cells
for (var c = 0; c < self.gridColumns; c++) // Traverse each column
{
self.grid[c] = [Cell](count: self.gridRows, repeatedValue: DeadCell()); // Initialize each column with dead cells
}
}
/*
updadePopulation() -> void
This method will update the population (grid) based on Conway's rules in order to determine
what cells will be alive in the next generation.
*/
func updatePopulation() -> Void
{
/*
Lines (38-42) do the same initialization that is done in the constructor. newPopulation will be
the grid that will contain all the cells in the next generation.
*/
var newPopulation = [[Cell]](count: self.gridColumns, repeatedValue: [Cell]());
for (var c = 0; c < self.gridColumns; c++)
{
newPopulation[c] = [Cell](count: self.gridRows, repeatedValue: DeadCell());
}
for (var c = 0; c < self.gridColumns; c++) { // Traverse the columns
for (var r = 0; r < self.gridRows; r++) { // Traverse the rows
var neighborsAlive:Int = 0; // Number of AliveCell's that are neighbors of the (c,r) Cell
var left:Int = max(0, c-1); // Left column
var right:Int = min(c+1, self.gridColumns-1); // Right column
var up:Int = max(0, r-1); // Top row
var down:Int = min(r+1, gridRows-1); // Bottom row
var neighbors = [Point](); // Array that will hold the locations of the neighbors of the (c,r) Cell
var topLeftN:Point = Point(x: left, y: up); // Top left neighbor
var leftN:Point = Point(x: left, y: r); // Left neighbor
var bottomLeftN:Point = Point(x: left, y: down); // Bottom left neighbor
var upN:Point = Point(x: c, y: up); // Top neighbor
var downN:Point = Point(x: c, y: down); // Bottom neighbor
var topRightN:Point = Point(x: right, y: up); // Top right neighbor
var rightN:Point = Point(x: right, y: r); // Right neighbor
var bottomRightN:Point = Point(x: right, y: down); // Bottom right neighbor
var currentCell:Point = Point(x: c, y: r); // Location of current (c,r)
/*
The next 8 "if" statements will make sure all actual neighbors are added to the
array of neighbors. When a cell is on some edge of the grid, it will not have all
8 neighbors. When computing neighbors above, if a neighbor does not exist the math
will make the non-existent neighbor the current (c,r) cell. These Points should
not be added to the array.
*/
if (topLeftN != currentCell)
{
neighbors.append(topLeftN);
}
if (leftN != currentCell)
{
neighbors.append(leftN);
}
if (bottomLeftN != currentCell)
{
neighbors.append(bottomLeftN);
}
if (upN != currentCell)
{
neighbors.append(upN);
}
if (downN != currentCell)
{
neighbors.append(downN);
}
if (topRightN != currentCell)
{
neighbors.append(topRightN);
}
if (rightN != currentCell)
{
neighbors.append(rightN);
}
if (bottomRightN != currentCell)
{
neighbors.append(bottomRightN);
}
for neighbor in neighbors
{
if (self.isCellAlive(neighbor.x, gridRow: neighbor.y)) // Checks to see if a neighbor is alive
{
neighborsAlive++; // Count the number of AliveCells
}
}
/*
This "if" statement will determine whether the current (c,r) cell will
live on to the next generation
*/
if (self.isCellAlive(c, gridRow: r)) { // Cell is alive
if (neighborsAlive < 2 || neighborsAlive > 3) { // Has less than 2 or greater than 3 neighbors
newPopulation[c][r] = DeadCell(); // Dies
}
else {
newPopulation[c][r] = AliveCell(); // Lives
}
}
else { // Cell is Dead
if (neighborsAlive == 3) { // Has exactly three alive neighbors
newPopulation[c][r] = AliveCell(); // Comes back to life
}
else {
newPopulation[c][r] = DeadCell(); // Stays dead
}
}
}
}
self.grid = newPopulation; // Update the grid
}
/*
isCellAlive(int,int) -> bool
Returns whether the cell at the location specified in the
grid is alive. The first int specifying which column and the
second which row.
*/
func isCellAlive(gridColumn:Int, gridRow:Int) -> Bool
{
return self.grid[gridColumn][gridRow].isAlive();
}
/*
currentAliveCells() -> Array<Point>
Returns the locations of all the AliveCell's in the grid
as an Array of Points.
*/
func currentAliveCells() -> [Point]
{
var aliveCells = [Point](); // Initialize the Array that will hold the AliveCell's
for (var c = 0; c < self.gridColumns; c++) { // Traverse the columns
for (var r = 0; r < self.gridRows; r++) { // Traverse the rows
if (self.grid[c][r].isAlive()) { // Cell at specified location is alive
aliveCells.append(Point(x: c, y: r)); // Add it to the array
}
}
}
return aliveCells; // Return the array containing the Point's of AliveCells
}
/*
resurrect(int,int) -> void
This method will set an AliveCell at the specified location. The
first int specifying which column and the second which row.
*/
func resurrect(gridColumn:Int, gridRow:Int)
{
self.grid[gridColumn][gridRow] = AliveCell();
}
}
| mit | 115ac9f486066840d8ebe3246808be33 | 37.462366 | 132 | 0.501677 | 4.615484 | false | false | false | false |
aleksandrshoshiashvili/AwesomeSpotlightView | AwesomeSpotlightView/Classes/AwesomeSpotlightView.swift | 1 | 16547 | //
// AwesomeSpotlightView.swift
// AwesomeSpotlightView
//
// Created by Alex Shoshiashvili on 24.02.17.
// Copyright © 2017 Alex Shoshiashvili. All rights reserved.
//
import UIKit
// MARK: - AwesomeSpotlightViewDelegate
@objc public protocol AwesomeSpotlightViewDelegate: AnyObject {
@objc optional func spotlightView(_ spotlightView: AwesomeSpotlightView, willNavigateToIndex index: Int)
@objc optional func spotlightView(_ spotlightView: AwesomeSpotlightView, didNavigateToIndex index: Int)
@objc optional func spotlightViewWillCleanup(_ spotlightView: AwesomeSpotlightView, atIndex index: Int)
@objc optional func spotlightViewDidCleanup(_ spotlightView: AwesomeSpotlightView)
}
@objcMembers
public class AwesomeSpotlightView: UIView {
public weak var delegate: AwesomeSpotlightViewDelegate?
// MARK: - private variables
private static let kAnimationDuration = 0.3
private static let kCutoutRadius: CGFloat = 4.0
private static let kMaxLabelWidth = 280.0
private static let kMaxLabelSpacing: CGFloat = 35.0
private static let kEnableContinueLabel = false
private static let kEnableSkipButton = false
private static let kEnableArrowDown = false
private static let kShowAllSpotlightsAtOnce = false
private static let kTextLabelFont = UIFont.systemFont(ofSize: 20.0)
private static let kContinueLabelFont = UIFont.systemFont(ofSize: 13.0)
private static let kSkipButtonFont = UIFont.boldSystemFont(ofSize: 13.0)
private static let kSkipButtonLastStepTitle = "Done".localized
private var spotlightMask = CAShapeLayer()
private var arrowDownImageView = UIImageView()
private var arrowDownSize = CGSize(width: 12, height: 18)
private var delayTime: TimeInterval = 0.35
private var hitTestPoints: [CGPoint] = []
// MARK: - public variables
public var spotlightsArray: [AwesomeSpotlight] = []
public var textLabel = UILabel()
public var continueLabel = UILabel()
public var skipSpotlightButton = UIButton()
public var animationDuration = kAnimationDuration
public var cutoutRadius: CGFloat = kCutoutRadius
public var maxLabelWidth = kMaxLabelWidth
public var labelSpacing: CGFloat = kMaxLabelSpacing
public var enableArrowDown = kEnableArrowDown
public var showAllSpotlightsAtOnce = kShowAllSpotlightsAtOnce
public var continueButtonModel = AwesomeTabButton(
title: "Continue".localized,
font: kContinueLabelFont,
isEnable: kEnableContinueLabel
)
public var skipButtonModel = AwesomeTabButton(
title: "Skip".localized,
font: kSkipButtonFont,
isEnable: kEnableSkipButton
)
public var skipButtonLastStepTitle = kSkipButtonLastStepTitle
public var spotlightMaskColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.6) {
didSet {
spotlightMask.fillColor = spotlightMaskColor.cgColor
}
}
public var textLabelFont = kTextLabelFont {
didSet {
textLabel.font = textLabelFont
}
}
public var isShowed: Bool {
return currentIndex != 0
}
public var currentIndex = 0
// MARK: - Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
}
convenience public init(frame: CGRect, spotlight: [AwesomeSpotlight]) {
self.init(frame: frame)
self.spotlightsArray = spotlight
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup
private func setup() {
setupMask()
setupTouches()
setupTextLabel()
setupArrowDown()
isHidden = true
}
private func setupMask() {
spotlightMask.fillRule = .evenOdd
spotlightMask.fillColor = spotlightMaskColor.cgColor
layer.addSublayer(spotlightMask)
}
private func setupTouches() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(userDidTap))
addGestureRecognizer(tapGestureRecognizer)
}
private func setupTextLabel() {
let textLabelRect = CGRect(x: 0, y: 0, width: maxLabelWidth, height: 0)
textLabel = UILabel(frame: textLabelRect)
textLabel.backgroundColor = .clear
textLabel.textColor = .white
textLabel.font = textLabelFont
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
textLabel.textAlignment = .center
textLabel.alpha = 0
addSubview(textLabel)
}
private func setupArrowDown() {
let arrowDownIconName = "arrowDownIcon"
if let bundlePath = Bundle.main.path(forResource: "AwesomeSpotlightViewBundle", ofType: "bundle") {
if let _ = Bundle(path: bundlePath)?.path(forResource: arrowDownIconName, ofType: "png") {
let arrowDownImage = UIImage(named: arrowDownIconName, in: Bundle(path: bundlePath), compatibleWith: nil)
arrowDownImageView = UIImageView(image: arrowDownImage)
arrowDownImageView.alpha = 0
addSubview(arrowDownImageView)
}
}
}
private func setupContinueLabel() {
let continueLabelWidth = skipButtonModel.isEnable ? 0.7 * bounds.size.width : bounds.size.width
let continueLabelHeight: CGFloat = 30.0
if #available(iOS 11.0, *) {
continueLabel = UILabel(
frame: CGRect(
x: 0,
y: bounds.size.height - continueLabelHeight - safeAreaInsets.bottom,
width: continueLabelWidth,
height: continueLabelHeight
)
)
} else {
continueLabel = UILabel(
frame: CGRect(
x: 0,
y: bounds.size.height - continueLabelHeight,
width: continueLabelWidth,
height: continueLabelHeight
)
)
}
continueLabel.font = continueButtonModel.font
continueLabel.textAlignment = .center
continueLabel.text = continueButtonModel.title
continueLabel.alpha = 0
continueLabel.backgroundColor = continueButtonModel.backgroundColor ?? .white
addSubview(continueLabel)
}
private func setupSkipSpotlightButton() {
let continueLabelWidth = 0.7 * bounds.size.width
let skipSpotlightButtonWidth = bounds.size.width - continueLabelWidth
let skipSpotlightButtonHeight: CGFloat = 30.0
if #available(iOS 11.0, *) {
skipSpotlightButton = UIButton(
frame: CGRect(
x: continueLabelWidth,
y: bounds.size.height - skipSpotlightButtonHeight - safeAreaInsets.bottom,
width: skipSpotlightButtonWidth,
height: skipSpotlightButtonHeight
)
)
} else {
skipSpotlightButton = UIButton(
frame: CGRect(
x: continueLabelWidth,
y: bounds.size.height - skipSpotlightButtonHeight,
width: skipSpotlightButtonWidth,
height: skipSpotlightButtonHeight
)
)
}
skipSpotlightButton.addTarget(self, action: #selector(skipSpotlight), for: .touchUpInside)
skipSpotlightButton.setTitle(skipButtonModel.title, for: [])
skipSpotlightButton.titleLabel?.font = skipButtonModel.font
skipSpotlightButton.alpha = 0
skipSpotlightButton.tintColor = .white
skipSpotlightButton.backgroundColor = skipButtonModel.backgroundColor ?? .clear
addSubview(skipSpotlightButton)
}
// MARK: - Touches
@objc func userDidTap(_ recognizer: UITapGestureRecognizer) {
goToSpotlightAtIndex(index: currentIndex + 1)
}
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
let localPoint = convert(point, from: self)
hitTestPoints.append(localPoint)
guard currentIndex < spotlightsArray.count else {
return view
}
let currentSpotlight = spotlightsArray[currentIndex]
if currentSpotlight.rect.contains(localPoint), currentSpotlight.isAllowPassTouchesThroughSpotlight {
if hitTestPoints.filter({ $0 == localPoint }).count == 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: {
self.cleanup()
})
}
return nil
}
return view
}
// MARK: - Presenter
public func start() {
start(fromIndex: 0)
}
public func start(fromIndex index: Int) {
alpha = 0
isHidden = false
textLabel.font = textLabelFont
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 1
}) { (finished) in
self.goToSpotlightAtIndex(index: index)
}
}
// MARK: - Private
private func goToSpotlightAtIndex(index: Int) {
if index >= spotlightsArray.count {
cleanup()
} else if showAllSpotlightsAtOnce {
showSpotlightsAllAtOnce()
} else {
showSpotlightAtIndex(index: index)
}
}
private func showSpotlightsAllAtOnce() {
if let firstSpotlight = spotlightsArray.first {
continueButtonModel.isEnable = false
skipButtonModel.isEnable = false
setCutoutToSpotlight(spotlight: firstSpotlight)
animateCutoutToSpotlights(spotlights: spotlightsArray)
currentIndex = spotlightsArray.count
}
}
private func showSpotlightAtIndex(index: Int) {
currentIndex = index
let currentSpotlight = spotlightsArray[index]
delegate?.spotlightView?(self, willNavigateToIndex: index)
showTextLabel(spotlight: currentSpotlight)
showArrowIfNeeded(spotlight: currentSpotlight)
if currentIndex == 0 {
setCutoutToSpotlight(spotlight: currentSpotlight)
}
animateCutoutToSpotlight(spotlight: currentSpotlight)
showContinueLabelIfNeeded(index: index)
showSkipButtonIfNeeded(index: index)
}
private func showArrowIfNeeded(spotlight: AwesomeSpotlight) {
if enableArrowDown {
let arrowImageOrigin = CGPoint(
x: spotlight.rect.origin.x + spotlight.rect.width / 2.0 - arrowDownSize.width / 2.0,
y: spotlight.rect.origin.y - arrowDownSize.height * 2
)
arrowDownImageView.frame = .init(
origin: arrowImageOrigin,
size: arrowDownSize
)
UIView.animate(withDuration: animationDuration, animations: {
self.arrowDownImageView.alpha = 1
})
}
}
private func showTextLabel(spotlight: AwesomeSpotlight) {
textLabel.alpha = 0
calculateTextPositionAndSizeWithSpotlight(spotlight: spotlight)
UIView.animate(withDuration: animationDuration) {
self.textLabel.alpha = 1
}
}
private func showContinueLabelIfNeeded(index: Int) {
if continueButtonModel.isEnable {
if index == 0 {
setupContinueLabel()
UIView.animate(withDuration: animationDuration, delay: delayTime, options: .curveLinear, animations: {
self.continueLabel.alpha = 1
})
} else if index >= spotlightsArray.count - 1 && continueLabel.alpha != 0 {
continueLabel.alpha = 0
continueLabel.removeFromSuperview()
}
}
}
private func showSkipButtonIfNeeded(index: Int) {
if skipButtonModel.isEnable && index == 0 {
setupSkipSpotlightButton()
UIView.animate(withDuration: animationDuration, delay: delayTime, options: .curveLinear, animations: {
self.skipSpotlightButton.alpha = 1
})
} else if skipSpotlightButton.isEnabled && index == spotlightsArray.count - 1 {
skipSpotlightButton.setTitle(skipButtonLastStepTitle, for: .normal)
}
}
@objc func skipSpotlight() {
goToSpotlightAtIndex(index: spotlightsArray.count)
}
private func skipAllSpotlights() {
goToSpotlightAtIndex(index: spotlightsArray.count)
}
// MARK: Helper
private func calculateRectWithMarginForSpotlight(_ spotlight: AwesomeSpotlight) -> CGRect {
var rect = spotlight.rect
rect.size.width += spotlight.margin.left + spotlight.margin.right
rect.size.height += spotlight.margin.bottom + spotlight.margin.top
rect.origin.x = rect.origin.x - (spotlight.margin.left + spotlight.margin.right) / 2.0
rect.origin.y = rect.origin.y - (spotlight.margin.top + spotlight.margin.bottom) / 2.0
return rect
}
private func calculateTextPositionAndSizeWithSpotlight(spotlight: AwesomeSpotlight) {
textLabel.frame = CGRect(x: 0, y: 0, width: maxLabelWidth, height: 0)
textLabel.attributedText = spotlight.showedText
if enableArrowDown && currentIndex == 0 {
labelSpacing += 18
}
textLabel.sizeToFit()
let rect = calculateRectWithMarginForSpotlight(spotlight)
var y = rect.origin.y + rect.size.height + labelSpacing
let bottomY = y + textLabel.frame.size.height + labelSpacing
if bottomY > bounds.size.height {
y = rect.origin.y - labelSpacing - textLabel.frame.size.height
}
let x : CGFloat = CGFloat(floor(bounds.size.width - textLabel.frame.size.width) / 2.0)
textLabel.frame = CGRect(origin: CGPoint(x: x, y: y), size: textLabel.frame.size)
}
// MARK: - Cutout and Animate
private func cutoutToSpotlight(spotlight: AwesomeSpotlight, isFirst : Bool = false) -> UIBezierPath {
var rect = calculateRectWithMarginForSpotlight(spotlight)
if isFirst {
let x = floor(spotlight.rect.origin.x + (spotlight.rect.size.width / 2.0))
let y = floor(spotlight.rect.origin.y + (spotlight.rect.size.height / 2.0))
let center = CGPoint(x: x, y: y)
rect = CGRect(origin: center, size: .zero)
}
let spotlightPath = UIBezierPath(rect: bounds)
var cutoutPath = UIBezierPath()
switch spotlight.shape {
case .rectangle:
cutoutPath = UIBezierPath(rect: rect)
case .roundRectangle:
cutoutPath = UIBezierPath(roundedRect: rect, cornerRadius: cutoutRadius)
case .circle:
cutoutPath = UIBezierPath(ovalIn: rect)
}
spotlightPath.append(cutoutPath)
return spotlightPath
}
private func cutoutToSpotlightCGPath(spotlight: AwesomeSpotlight, isFirst : Bool = false) -> CGPath {
return cutoutToSpotlight(spotlight: spotlight, isFirst: isFirst).cgPath
}
private func setCutoutToSpotlight(spotlight: AwesomeSpotlight) {
spotlightMask.path = cutoutToSpotlightCGPath(spotlight: spotlight, isFirst: true)
}
private func animateCutoutToSpotlight(spotlight: AwesomeSpotlight) {
let path = cutoutToSpotlightCGPath(spotlight: spotlight)
animateCutoutWithPath(path: path)
}
private func animateCutoutToSpotlights(spotlights: [AwesomeSpotlight]) {
let spotlightPath = UIBezierPath(rect: bounds)
for spotlight in spotlights {
var cutoutPath = UIBezierPath()
switch spotlight.shape {
case .rectangle:
cutoutPath = UIBezierPath(rect: spotlight.rect)
case .roundRectangle:
cutoutPath = UIBezierPath(roundedRect: spotlight.rect, cornerRadius: cutoutRadius)
case .circle:
cutoutPath = UIBezierPath(ovalIn: spotlight.rect)
}
spotlightPath.append(cutoutPath)
}
animateCutoutWithPath(path: spotlightPath.cgPath)
}
private func animateCutoutWithPath(path: CGPath) {
let animationKeyPath = "path"
let animation = CABasicAnimation(keyPath: animationKeyPath)
animation.delegate = self
animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
animation.duration = animationDuration
animation.isRemovedOnCompletion = false
animation.fillMode = .forwards
animation.fromValue = spotlightMask.path
animation.toValue = path
spotlightMask.add(animation, forKey: animationKeyPath)
spotlightMask.path = path
}
// MARK: - Cleanup
private func cleanup() {
delegate?.spotlightViewWillCleanup?(self, atIndex: currentIndex)
UIView.animate(withDuration: animationDuration, animations: {
self.alpha = 0
}) { (finished) in
if finished {
self.removeFromSuperview()
self.currentIndex = 0
self.textLabel.alpha = 0
self.continueLabel.alpha = 0
self.skipSpotlightButton.alpha = 0
self.hitTestPoints = []
self.delegate?.spotlightViewDidCleanup?(self)
}
}
}
// MARK: - Objective-C Support Function
// Objective-C provides support function because it does not correspond to struct
public func setContinueButtonEnable(_ isEnable:Bool) {
self.continueButtonModel.isEnable = isEnable
}
public func setSkipButtonEnable(_ isEnable:Bool) {
self.skipButtonModel.isEnable = isEnable
}
}
extension AwesomeSpotlightView: CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
delegate?.spotlightView?(self, didNavigateToIndex: currentIndex)
}
}
| mit | 6cdbfafbd923d11cb30db9c3834b1cf7 | 31.635108 | 113 | 0.698417 | 4.520765 | false | false | false | false |
MobileOrg/mobileorg | Classes/Sync/Dropbox/DropboxTransferManager.swift | 1 | 8880 | //
// DropboxTransferManager.swift
// MobileOrg
//
// Created by Mario Martelli on 16.12.16.
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
import Foundation
import SwiftyDropbox
@objcMembers final class DropboxTransferManager: NSObject {
var activeTransfer:TransferContext? = nil
var transfers:[TransferContext] = []
var _active = false
var paused = false
var active:Bool{
get { return _active }
set {_active = newValue }
}
func queueSize() -> Int {
return transfers.count
}
func busy() -> Bool {
return (transfers.count > 0 || active)
}
func abort() {
transfers.removeAll()
}
// Workaround to suffice to TransferManager protocol
static let instance = DropboxTransferManager()
override init() {
let filePath = Bundle.main.path(forResource: "AppKey", ofType: "plist")
let plist = NSDictionary(contentsOfFile:filePath!)
let dkist = plist?["Dropbox API Key"] as? NSDictionary
let appKey = dkist?.object(forKey: "AppKey") as! String
DropboxClientsManager.setupWithAppKey(appKey)
}
/// Login to Dropbox
/// Login takes place over Dropbox App if installed
/// otherwise over WebView. Authflow is handled afterwards asynchronely
/// Further infos: http://dropbox.github.io/SwiftyDropbox/api-docs/latest/
///
/// - Parameter rootController: viewController from where the call was made
func login(_ rootController: UIViewController) {
DropboxClientsManager.authorizeFromController(UIApplication.shared,
controller: rootController,
openURL: { (url: URL) -> Void in
UIApplication.shared.open(url, options: [:], completionHandler: nil)})
}
/// Handle Dropbox Authorisation FLow
/// Triggered by AppDelegate
///
/// - Parameter url: URL used for Authorisation
/// - Returns: always true 🙄
func handleAuthFlow(url: URL) -> Bool {
DropboxClientsManager.handleRedirectURL(url, completion: { authResult in
switch authResult {
case .success:
NotificationCenter.default.post(name: Notification.Name(rawValue: "dropboxloginsuccess"), object: nil)
print("Success! User is logged into Dropbox.")
case .cancel:
print("Authorization flow was manually cancelled by user!")
case .error(_, let description):
print("Error: \(description ?? "Unknown")")
case .none:
print("Unknown result.")
}
})
return true
}
/// Indicates whether a Dropbox link is established or not
///
/// - Returns: State of Dropbox link
func isLinked() -> Bool {
return DropboxClientsManager.authorizedClient != nil
}
/// Unlinks the user from Dropbox
func unlink() {
DropboxClientsManager.unlinkClients()
}
func enqueueTransfer(_ context: TransferContext){
transfers.append(context)
ShowStatusView()
dispatchNextTransfer()
}
func dispatchNextTransfer() {
if paused { return }
if let syncManager = SyncManager.instance(),
transfers.count > 0,
transfers.first?.remoteUrl != nil,
!active {
activeTransfer = transfers.first
activeTransfer?.success = true
transfers.remove(at: 0)
let filename = activeTransfer?.remoteUrl.lastPathComponent
// Update status view text
syncManager.transferFilename = filename
syncManager.progressTotal = 0
syncManager.updateStatus()
active = true
UIApplication.shared.isNetworkActivityIndicatorVisible = true
processRequest( activeTransfer!)
}
// processRequest
}
func processRequest(_ context: TransferContext) {
if !isLinked() {
activeTransfer?.errorText = "Not logged in, please login from the Settings page.";
activeTransfer?.success = false;
requestFinished(activeTransfer!)
return;
}
if context.dummy {
activeTransfer?.success = true
requestFinished(activeTransfer!)
return
}
let remoteUrl = context.remoteUrl.absoluteString
let path = remoteUrl.replacingOccurrences(of: "dropbox:///", with: "/")
if context.transferType == TransferTypeDownload {
downloadFile(from: path, to: context.localFile)
} else {
uploadFile(to: path, from: context.localFile)
}
}
func requestFinished(_ context: TransferContext) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if !context.success && context.abortOnFailure {
transfers.removeAll()
}
if context.success {
context.delegate.transferComplete!(context)
} else {
context.delegate.transferFailed!(context)
}
active = false
self.activeTransfer = nil
dispatchNextTransfer()
}
func pause() {
paused = true
}
func resume() {
paused = false
dispatchNextTransfer()
}
func downloadFile(from: String, to: String) {
if let client = DropboxClientsManager.authorizedClient {
let destURL = URL(string: "file://\((activeTransfer?.localFile)!)")
let destination: (URL, HTTPURLResponse) -> URL = { temporaryURL, response in
return destURL!
}
// Unescape URL
if let unescapedFrom = from.removingPercentEncoding {
// Download file from dropbox
// files reside in app's root folder
UIApplication.shared.isNetworkActivityIndicatorVisible = true
client.files.download(path: unescapedFrom, overwrite: true, destination: destination)
.response { response, error in
if response != nil {
self.activeTransfer?.success = true
self.requestFinished(self.activeTransfer!)
}
if let error = error {
switch error as CallError {
case .routeError(let boxed, _, _, _):
switch boxed.unboxed as Files.DownloadError {
case .path(let lookupError):
switch lookupError {
case .notFound:
self.activeTransfer?.statusCode = 404
self.activeTransfer?.errorText = "The file \(String(describing: self.activeTransfer?.remoteUrl.lastPathComponent)) could not be found"
default:
self.activeTransfer?.errorText = error.description
}
default:
self.activeTransfer?.errorText = error.description
}
default:
self.activeTransfer?.errorText = error.description
}
self.activeTransfer?.success = false
self.requestFinished(self.activeTransfer!)
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
.progress { progressData in
let mgr = SyncManager.instance()
mgr?.progressTotal = 100
mgr?.progressCurrent = Int32(progressData.fractionCompleted * 100.0)
mgr?.updateStatus()
}
}
}
}
func uploadFile(to: String, from: String) {
if let client = DropboxClientsManager.authorizedClient,
let data = NSData(contentsOfFile: from) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// TODO: mute should be set by the user
client.files.upload(path: to, mode: .overwrite, autorename: false, clientModified: nil, mute: false, input: Data(referencing: data))
.response { response, error in
if response != nil {
self.activeTransfer?.success = true
self.requestFinished(self.activeTransfer!)
}
if let error = error {
self.activeTransfer?.errorText = error.description
self.activeTransfer?.success = false
self.requestFinished(self.activeTransfer!)
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
.progress { progressData in
let mgr = SyncManager.instance()
mgr?.progressTotal = 100
mgr?.progressCurrent = Int32(progressData.fractionCompleted * 100.0)
mgr?.updateStatus()
}
}
}
}
| gpl-2.0 | a499989c4b4d0c93137d3beb35cbe3a4 | 30.590747 | 154 | 0.639631 | 4.96199 | false | false | false | false |
jmgc/swift | stdlib/public/Darwin/CoreFoundation/CoreFoundation.swift | 1 | 885 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreFoundation
public protocol _CFObject: AnyObject, Hashable {}
extension _CFObject {
public var hashValue: Int {
return Int(bitPattern: CFHash(self))
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.hashValue)
}
public static func ==(left: Self, right: Self) -> Bool {
return CFEqual(left, right)
}
}
| apache-2.0 | e1e390c03bae560f709f09ea3a819738 | 33.038462 | 80 | 0.587571 | 4.758065 | false | false | false | false |
jkolb/Asheron | Sources/Asheron/Identifier.swift | 1 | 5011 | /*
The MIT License (MIT)
Copyright (c) 2020 Justin Kolb
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.
*/
public struct DBType {
public enum Source {
case unknown
case server
case portal // & highres
case cell
case local
}
public static let landBlock = DBType(source: .cell, name: "LandBlock", enumCode: 1, idRange: nil, fileExtension: [])
public static let lbi = DBType(source: .cell, name: "LandBlockInfo", enumCode: 2, idRange: nil, fileExtension: ["lbi"])
public static let envCell = DBType(source: .cell, name: "EnvCell", enumCode: 3, idRange: UInt32(0x01010000)...UInt32(0x013EFFFF), fileExtension: [])
public static let lbo = DBType(source: .unknown, name: "LandBlockObjects", enumCode: 4, idRange: nil, fileExtension: ["lbo"])
public static let instantiation = DBType(source: .unknown, name: "Instantiation", enumCode: 5, idRange: nil, fileExtension: ["ins"])
public static let gfxObj = DBType(source: .portal, name: "GraphicsObject", enumCode: 6, idRange: UInt32(0x01000000)...UInt32(0x0100FFFF), fileExtension: ["obj"])
public static let setup = DBType(source: .portal, name: "Setup", enumCode: 7, idRange: UInt32(0x02000000)...UInt32(0x0200FFFF), fileExtension: ["set"])
public static let anim = DBType(source: .portal, name: "Animation", enumCode: 8, idRange: UInt32(0x03000000)...UInt32(0x0300FFFF), fileExtension: ["anm"])
public static let animationHook = DBType(source: .unknown, name: "AnimationHook", enumCode: 9, idRange: nil, fileExtension: ["hk"])
public static let palette = DBType(source: .portal, name: "Palette", enumCode: 10, idRange: UInt32(0x04000000)...UInt32(0x0400FFFF), fileExtension: ["pal"])
public static let surfaceTexture = DBType(source: .portal, name: "SurfaceTexture", enumCode: 11, idRange: UInt32(0x05000000)...UInt32(0x05FFFFFF), fileExtension: ["texture"])
public static let renderSurface = DBType(source: .portal, name: "Texture", enumCode: 12, idRange: UInt32(0x06000000)...UInt32(0x07FFFFFF), fileExtension: ["bmp", "jpg", "dds", "tga", "iff", "256", "csi", "alp"])
public static let surface = DBType(source: .portal, name: "Surface", enumCode: 13, idRange: UInt32(0x08000000)...UInt32(0x0800FFFF), fileExtension: ["surface"])
public static let mtable = DBType(source: .portal, name: "MotionTable", enumCode: 14, idRange: UInt32(0x09000000)...UInt32(0x0900FFFF), fileExtension: ["dsc"])
public static let wave = DBType(source: .portal, name: "Wave", enumCode: 15, idRange: UInt32(0x0A000000)...UInt32(0x0A00FFFF), fileExtension: ["wav", "mp3"])
public static let environment = DBType(source: .portal, name: "Environment", enumCode: 16, idRange: UInt32(0x0A000000)...UInt32(0x0A00FFFF), fileExtension: ["env"])
public var source: Source
public var name: String
public var enumCode: UInt32
public var idRange: ClosedRange<UInt32>?
public var fileExtension: [String]
public init(source: Source, name: String, enumCode: UInt32, idRange: ClosedRange<UInt32>?, fileExtension: [String]) {
self.source = source
self.name = name
self.enumCode = enumCode
self.idRange = idRange
self.fileExtension = fileExtension
}
public func matches(id: Identifier) -> Bool {
guard let idRange = idRange else {
return false
}
return idRange.contains(id.bits)
}
}
public struct Identifier : Comparable, Hashable, CustomStringConvertible, Packable {
public let bits: UInt32
public init(_ bits: UInt32) {
self.bits = bits
}
public static func <(a: Identifier, b: Identifier) -> Bool {
return a.bits < b.bits
}
public var description: String {
return String(format: "%08X", bits)
}
public init(from dataStream: DataStream) {
self.bits = UInt32(from: dataStream)
}
@inlinable public func encode(to dataStream: DataStream) {
bits.encode(to: dataStream)
}
}
| mit | 72ec6ef6f0c9ff8601d1d523b105740d | 51.197917 | 215 | 0.70006 | 3.851653 | false | false | false | false |
tad-iizuka/swift-sdk | Source/AlchemyLanguageV1/Models/Entities.swift | 3 | 1867 | /**
* Copyright IBM Corporation 2015
*
* 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 RestKit
/**
**Entities**
Reponse object for **Entity** related calls
*/
public struct Entities: JSONDecodable {
/** extracted language */
public let language: String?
/** the URL information was requested for */
public let url: String?
/** the number of transactions made by the call */
public let totalTransactions: Int?
/** the detected entity text */
public let text: String?
/** see **Entity** */
public let entitites: [Entity]?
/// Used internally to initialize an Entities object
public init(json: JSON) throws {
let status = try json.getString(at: "status")
guard status == "OK" else {
throw JSON.Error.valueNotConvertible(value: json, to: Entities.self)
}
language = try? json.getString(at: "language")
url = try? json.getString(at: "url")
if let totalTransactionsString = try? json.getString(at: "totalTransactions") {
totalTransactions = Int(totalTransactionsString)
} else {
totalTransactions = nil
}
text = try? json.getString(at: "text")
entitites = try? json.decodedArray(at: "entities", type: Entity.self)
}
}
| apache-2.0 | ba98f7e4cd95ac67fcdc578de70b662a | 28.634921 | 87 | 0.649705 | 4.382629 | false | false | false | false |
Touchwonders/Transition | Examples/NavigationTransitionsExample/Transition/Transition/InteractiveZoomTransition.swift | 1 | 8759 | //
// MIT License
//
// Copyright (c) 2017 Touchwonders B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Transition
class InteractiveZoomTransition : SharedElementTransition {
private struct State {
let sharedElementFrame: CGRect
let toViewTransform: CGAffineTransform
let fromViewTransform: CGAffineTransform
}
private weak var interactionController: TransitionInteractionController?
private var operationContext: TransitionOperationContext!
private var context: UIViewControllerContextTransitioning!
init(interactionController: TransitionInteractionController) {
self.interactionController = interactionController
}
var timingParameters: AnimationTimingParameters {
return AnimationTimingParameters(mass: 0.1, stiffness: 15, damping: 2.0, initialVelocity: CGVector(dx: 0, dy: 0))
}
var selectedImage: UIImageView?
private var initialState: State!
private var targetState: State!
private var sharedElementTransitioningView: UIView? {
return (sharedElement as? ZoomTransitionItem)?.transitioningView
}
func setup(in operationContext: TransitionOperationContext) {
self.operationContext = operationContext
self.context = operationContext.context
guard let item = sharedElement as? ZoomTransitionItem else { return }
guard let itemImageView = item.imageView else { return }
/// The selectedImage is
if isPresenting, let fromViewController = context.fromViewController as? CollectionViewController, let selectedImage = fromViewController.selectedImage {
self.selectedImage = selectedImage
} else if !isPresenting, let toViewController = context.toViewController as? CollectionViewController, let selectedImage = toViewController.selectedImage {
self.selectedImage = selectedImage
}
self.selectedImage?.isHidden = true
/// The transitioningView is a snapshot of the imageView that can be moved safely inside the transitionContext, keeping the original imageView in its view hierarchy:
let transitioningView = item.transitioningView
transitioningView.frame = item.initialFrame
context.containerView.addSubview(transitioningView)
itemImageView.isHidden = true
let scale = item.targetFrame.width / item.initialFrame.width
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
let origin = CGVector(dx: item.initialFrame.origin.x - context.fromView.bounds.midX, dy: item.initialFrame.origin.y - context.fromView.bounds.midY)
let scaled = CGVector(dx: origin.dx * scale, dy: origin.dy * scale)
let delta = CGVector(dx: origin.dx - scaled.dx, dy: origin.dy - scaled.dy)
let translation = CGPoint(x: item.targetFrame.origin.x - item.initialFrame.origin.x, y: item.targetFrame.origin.y - item.initialFrame.origin.y)
let translationTransform = CGAffineTransform(translationX: translation.x + delta.dx, y: translation.y + delta.dy)
let fromViewTransform = scaleTransform.concatenating(translationTransform)
let toViewTransform = fromViewTransform.inverted()
initialState = State(sharedElementFrame: item.initialFrame, toViewTransform: toViewTransform, fromViewTransform: .identity)
targetState = State(sharedElementFrame: item.targetFrame, toViewTransform: .identity, fromViewTransform: fromViewTransform)
}
private func applyState(_ state: State) {
sharedElementTransitioningView?.frame = state.sharedElementFrame
context.toView.transform = state.toViewTransform
context.fromView.transform = state.fromViewTransform
}
var isPresenting: Bool {
return operationContext.operation.isPresenting
}
func animation() {
if animatingPosition == .end {
applyState(targetState)
} else {
applyState(initialState)
}
}
func completion(position: UIViewAnimatingPosition) {
guard let item = sharedElement as? ZoomTransitionItem else { return }
context.fromView.transform = .identity
context.toView.transform = .identity
sharedElementTransitioningView?.removeFromSuperview()
item.imageView?.isHidden = false
selectedImage?.isHidden = false
}
var animatingPosition: UIViewAnimatingPosition = .end
var sharedElement: SharedElement? = nil
func startInteraction(in context: UIViewControllerContextTransitioning, gestureRecognizer: UIGestureRecognizer) {
let locationInContainer = gestureRecognizer.location(in: context.containerView)
if let view = context.containerView.hitTest(locationInContainer, with: nil), view == sharedElement?.transitioningView {
guard let item = sharedElement as? ZoomTransitionItem else { return }
guard let transitioningView = sharedElementTransitioningView else { return }
item.touchOffset = CGVector(dx: locationInContainer.x - transitioningView.center.x, dy: locationInContainer.y - transitioningView.center.y)
}
}
public func updateInteraction(in context: UIViewControllerContextTransitioning, interactionController: TransitionInteractionController, progress: TransitionProgress) {
guard let gesture = interactionController.gestureRecognizer as? UIPanGestureRecognizer else { return }
guard let item = sharedElement as? ZoomTransitionItem else { return }
let transitioningView = item.transitioningView
let translationInView = gesture.translation(in: gesture.view)
context.fromView.transform = CGAffineTransform(translationX: 0.0, y: max(0.0, translationInView.y))
switch progress {
case .fractionComplete(let fraction):
let scale = item.initialFrame.width / item.targetFrame.width
let origin = CGVector(dx: item.targetFrame.origin.x - context.toView.bounds.midX, dy: item.targetFrame.origin.y - context.toView.bounds.midY)
let scaled = CGVector(dx: origin.dx * scale, dy: origin.dy * scale)
let delta = CGVector(dx: origin.dx - scaled.dx, dy: origin.dy - scaled.dy)
let translation = CGPoint(x: item.initialFrame.origin.x - item.targetFrame.origin.x, y: item.initialFrame.origin.y - item.targetFrame.origin.y)
let translationTransform = CGAffineTransform(translationX: translation.x + delta.dx, y: translation.y + delta.dy)
var transform = context.toView.transform
transform.a = scale - (CGFloat(fraction) * (scale - 1.0))
transform.d = scale - (CGFloat(fraction) * (scale - 1.0))
transform.tx = translationTransform.tx - (CGFloat(fraction) * translationTransform.tx)
transform.ty = translationTransform.ty - (CGFloat(fraction) * translationTransform.ty)
context.toView.transform = transform
var sharedElementFrame = transitioningView.frame
sharedElementFrame.size.width = item.initialFrame.width - (CGFloat(fraction) * (item.initialFrame.width - item.targetFrame.width))
sharedElementFrame.size.height = item.initialFrame.height - (CGFloat(fraction) * (item.initialFrame.height - item.targetFrame.height))
transitioningView.frame = sharedElementFrame
transitioningView.center = CGPoint(x: (item.initialFrame.midX + 10.0) + translationInView.x, y: (item.initialFrame.midY + 10.0) + translationInView.y)
default: return
}
}
}
| mit | 291172ae6ceb09c243fd1abf46cc1914 | 50.828402 | 173 | 0.708186 | 5.039701 | false | false | false | false |
dgollub/pokealmanac | PokeAlmanac/MapViewController.swift | 1 | 19023 | //
// MapViewController.swift
// PokeAlmanac
//
// Created by 倉重ゴルプ ダニエル on 2016/04/19.
// Copyright © 2016年 Daniel Kurashige-Gollub. All rights reserved.
//
import Foundation
import UIKit
import MapKit
import CoreLocation
private let ANNOTATION_POKEMON_RESUSE_IDENTIFIER = "pokemonAnnotationViewReuseIdentifier"
private let ANNOTATION_DEFAULT_RESUSE_IDENTIFIER = "defaultAnnotationViewReuseIdentifier"
private let BUTTON_TAG_ATTACK = 1
private let BUTTON_TAG_CATCH = 2
public class PokemonAnnotation : NSObject, MKAnnotation {
public let pokemon: Pokemon
public var coordinate: CLLocationCoordinate2D
public let title: String?
public let subtitle: String?
public let image: UIImage?
public var found: NSDate?
public init(coordinate: CLLocationCoordinate2D, pokemon: Pokemon, image: UIImage? = nil, found: NSDate? = nil) {
self.pokemon = pokemon
self.coordinate = coordinate
self.title = pokemon.name.capitalizedString
self.subtitle = "Weight: \(pokemon.weight), Height: \(pokemon.height)"
if let image = image {
self.image = image
} else {
self.image = UIImage(named: "IconUnknownPokemon")
}
self.found = found
}
}
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var buttonScanMap: UIBarButtonItem?
@IBOutlet weak var buttonActionSheet: UIBarButtonItem?
@IBOutlet weak var mapView: MKMapView?
var locationManager: CLLocationManager?
var initialLocation: CLLocation?
var pokemonAnnotations: [PokemonAnnotation] = []
let busyIndicator = BusyOverlay()
var centerMapFirstTime: dispatch_once_t = 0
override func viewDidLoad() {
super.viewDidLoad()
log("MapViewController")
busyIndicator.showOverlay()
locationManager = CLLocationManager()
locationManager?.delegate = self
// set center to Akihabara
initialLocation = CLLocation(latitude: 35.7021, longitude: 139.7753) // CLLocationDegrees
mapView?.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
log("viewWillAppear")
locationManager?.requestWhenInUseAuthorization()
mapView?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
logWarn("didReceiveMemoryWarning")
}
@IBAction func showActionSheet(sender: AnyObject) {
log("showActionSheet")
let actionSheet = UIAlertController(title: "Choose", message: "What do you want to do?", preferredStyle: .ActionSheet)
let resetLocationAction = UIAlertAction(title: "Zoom To Start Location", style: .Default) { (action) in
self.zoomInToLocation(self.initialLocation)
}
actionSheet.addAction(resetLocationAction)
let authStatus = CLLocationManager.authorizationStatus()
if authStatus != CLAuthorizationStatus.AuthorizedAlways &&
authStatus != CLAuthorizationStatus.AuthorizedWhenInUse {
let askForLocationAction = UIAlertAction(title: "Allow your location", style: .Default) { (action) in
self.locationManager?.requestWhenInUseAuthorization()
}
actionSheet.addAction(askForLocationAction)
}
let scanAction = UIAlertAction(title: "Scan For Pokemons", style: .Default) { (action) in
self.scanMap(action)
}
actionSheet.addAction(scanAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
actionSheet.addAction(cancelAction)
self.presentViewController(actionSheet, animated: true, completion: nil)
}
@IBAction func scanMap(sender: AnyObject) {
log("scanMap")
self.setupPokemonsOnMap(self.initialLocation)
}
func zoomInToLocation(selectedLocation: CLLocation?) {
if let location = selectedLocation {
let coords = location.coordinate
let mapRegion = MKCoordinateRegionMakeWithDistance(coords, 100, 100)
self.mapView?.setCenterCoordinate(coords, animated: true)
self.mapView?.setRegion(mapRegion, animated: true)
}
}
func setupPokemonsOnMap(aLocation: CLLocation? = nil) {
log("setupPokemonsOnMap")
// if we have already set up pokemons for this map, don't set up more
// there should be a radius of 100m (or 500m or whatever) in which we allow
// pokemons to show up, but that's it - if the user zooms out too much we
// do not add more pokemons - this scanner is not that strong
var pokemonsToAdd: Int = randomInt(3...6)
if pokemonAnnotations.count == 0 || pokemonAnnotations.count < 4 {
// have at least 3 pokemon on the map at any time
pokemonsToAdd = 4 - pokemonAnnotations.count
} else if pokemonAnnotations.count > 10 {
pokemonsToAdd = 0
}
var location: CLLocation? = aLocation
if let _ = location {} else {
location = self.initialLocation
}
if pokemonsToAdd > 0 {
if let location = location {
var left = 0
self.busyIndicator.showOverlay()
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
let dl = Downloader()
let pokemonsJsons = DB().loadPokemons()
let transformer = Transformer()
for _ in 1...pokemonsToAdd {
let index = randomInt(0...pokemonsJsons.count - 1)
let pokemon = transformer.jsonToPokemonModel(pokemonsJsons[index])!
let pokemonCoords = self.getRandomCoordinates(location.coordinate)
if let image = dl.getPokemonSpriteFromCache(pokemon) {
let annotation = PokemonAnnotation(coordinate: pokemonCoords, pokemon: pokemon, image: image)
self.pokemonAnnotations.append(annotation)
// put the annotation on the map
self.mapView?.addAnnotation(annotation)
} else {
left += 1
dl.downloadPokemonSprite(pokemon, completed: { (error) in
// ignore
})
}
}
if left > 0 {
self.setupPokemonsOnMap(location)
}
self.busyIndicator.hideOverlayView()
})
}
}
}
func getRandomCoordinates(fromCoords: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let randomMeters = randomInt(5...120)
let randomBearing = randomInt(0...359)
let coords = self.locationWithBearing(Double(randomBearing), distanceMeters: Double(randomMeters), origin: fromCoords)
return coords
}
// from http://stackoverflow.com/a/31127466/193165
func locationWithBearing(bearing: Double, distanceMeters: Double, origin: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
let distRadians = distanceMeters / (6372797.6)
let rbearing = bearing * M_PI / 180.0
let lat1 = origin.latitude * M_PI / 180
let lon1 = origin.longitude * M_PI / 180
let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(rbearing))
let lon2 = lon1 + atan2(sin(rbearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))
return CLLocationCoordinate2D(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI)
}
// CLLocationManagerDelegate callbacks
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
logWarn("CLLocationManager failed: \(error)")
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
log("didChangeAuthorizationStatus: \(status.rawValue) \(status)")
switch (status) {
case .Denied:
fallthrough
case .Restricted:
showErrorAlert(self, message: "Please enable location services in the Settings app.", title: "Location Disabled")
return
case .NotDetermined:
break
case .AuthorizedAlways:
fallthrough
case .AuthorizedWhenInUse:
self.mapView?.showsUserLocation = true
break
}
}
// MKMapViewDelegate callbacks
func mapViewDidFinishLoadingMap(mapView: MKMapView) {
log("mapViewDidFinishLoadingMap")
busyIndicator.hideOverlayView()
}
func mapView(mapView: MKMapView, didFailToLocateUserWithError error: NSError) {
logWarn("didFailToLocateUserWithError \(error)")
if let _ = self.presentedViewController {
//
} else {
var msg = "Unknown error"
if let err = CLError(rawValue: error.code) {
msg = err == CLError.LocationUnknown ? "Sorry, could not find your location." : "Error while finding your location."
}
showErrorAlert(self, message: msg, title: "Error")
}
}
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
log("didUpdateUserLocation: \(userLocation)")
dispatch_once(¢erMapFirstTime) {
if let location = userLocation.location {
self.initialLocation = location
}
self.zoomInToLocation(userLocation.location)
}
}
func mapViewDidFinishRenderingMap(mapView: MKMapView, fullyRendered: Bool) {
log("mapViewDidFinishRenderingMap \(fullyRendered)")
if fullyRendered {
self.setupPokemonsOnMap(self.initialLocation)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
var view: MKAnnotationView? = nil
if let pokemonAnnotation: PokemonAnnotation = annotation as? PokemonAnnotation {
view = mapView.dequeueReusableAnnotationViewWithIdentifier(ANNOTATION_POKEMON_RESUSE_IDENTIFIER)
if let view = view {
view.annotation = annotation
} else {
view = MKAnnotationView(annotation: annotation, reuseIdentifier: ANNOTATION_POKEMON_RESUSE_IDENTIFIER)
}
view?.image = pokemonAnnotation.image
view?.canShowCallout = true
let buttonCatch = UIButton(type: .DetailDisclosure) // .Custom does not show!
buttonCatch.setImage(UIImage(named: "IconFrisbee"), forState: .Normal)
buttonCatch.setImage(UIImage(named: "IconFrisbeeFilled"), forState: .Selected)
buttonCatch.userInteractionEnabled = true
buttonCatch.tag = BUTTON_TAG_CATCH
view?.rightCalloutAccessoryView = buttonCatch
let buttonAttack = UIButton(type: .DetailDisclosure) // .Custom does not show!
buttonAttack.setImage(UIImage(named: "IconBaseball"), forState: .Normal)
buttonAttack.setImage(UIImage(named: "IconBaseballFilled"), forState: .Selected)
buttonAttack.userInteractionEnabled = true
buttonAttack.tag = BUTTON_TAG_ATTACK
view?.leftCalloutAccessoryView = buttonAttack
} else {
view = mapView.dequeueReusableAnnotationViewWithIdentifier(ANNOTATION_DEFAULT_RESUSE_IDENTIFIER)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: ANNOTATION_DEFAULT_RESUSE_IDENTIFIER)
}
view?.canShowCallout = true
}
return view
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let pokemonAnnotation: PokemonAnnotation = view.annotation as? PokemonAnnotation {
log("\(pokemonAnnotation.pokemon.name)")
if control.tag == BUTTON_TAG_ATTACK {
attackPokemon(pokemonAnnotation)
} else if control.tag == BUTTON_TAG_CATCH {
catchPokemon(pokemonAnnotation)
}
}
}
func attackPokemon(annotation: PokemonAnnotation) {
// check if we have any pokemons in our backpack first.
let backpack = DB().loadPokemonsFromBackpackAsPokemonAnnotations()
let count = backpack.count
if count > 0 {
let actionSheet = UIAlertController(title: "Choose", message: "Which Pokemon do you want to use in the battle against \(annotation.pokemon.name.capitalizedString)?", preferredStyle: .ActionSheet)
// TODO(dkg): Implement real battle system here. Obviously. :-)
var alreadySelected: [Int] = []
let numberOfPokemonsToChooseFrom = count > 3 ? 3 : count
for _ in 1...numberOfPokemonsToChooseFrom {
var rndIndex = randomInt(0...count - 1)
// make sure we only include a given pokemon once in the selection "screen"
while let _ = alreadySelected.indexOf(rndIndex) {
rndIndex = randomInt(0...count - 1)
}
alreadySelected.append(rndIndex)
let pokemon = backpack[rndIndex].pokemon
let pokemonToAttachWithAction = UIAlertAction(title: "Choose \(pokemon.name.capitalizedString)", style: .Default) { (action) in
let winChance = randomInt(0...50) // TODO(dkg): use actual PokemonSpecies.capture_rate for this!
let playerChance = randomInt(0...100)
if playerChance <= winChance {
self.putCaughtPokemonInBackpack(annotation,
message: "You chose wisely and caught \(annotation.pokemon.name.capitalizedString).\nCongratulations!\nYou put it in your backpack.",
title: "You Won!")
} else {
showErrorAlert(self, message: "You chose ... poorly.\n", title: "You Lost!", completion: {
self.runAwayPokemon(annotation, message: "The \(annotation.pokemon.name.capitalizedString) ran away.", title: "Oh dear!")
})
}
}
actionSheet.addAction(pokemonToAttachWithAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
actionSheet.addAction(cancelAction)
self.presentViewController(actionSheet, animated: true, completion: nil)
} else {
showErrorAlert(self, message: "You will need to catch at least one Pokemon first before you can battle others!", title: "No Pokemon!")
}
}
func catchPokemon(annotation: PokemonAnnotation) {
let chance = randomInt(0...100)
let pokemon = annotation.pokemon
let actionSheet = UIAlertController(title: "Catch \(pokemon.name.capitalizedString)?", message: "You have a \(chance)% chance to succeed.", preferredStyle: .ActionSheet)
let tryCatchAction = UIAlertAction(title: "Try!", style: .Default) { (action) in
let catchChance = randomInt(0...100)
if catchChance <= chance && chance > 0 {
self.putCaughtPokemonInBackpack(annotation,
message: "You successfully caught \(pokemon.name.capitalizedString).\nCongratulations!\nYou put it in your backpack.",
title: "You got it!")
} else {
showErrorAlert(self, message: "You failed.", title: ":-(", completion: {
self.runAwayPokemon(annotation, message: "The \(pokemon.name.capitalizedString) ran away.", title: "Oh dear!")
})
}
}
actionSheet.addAction(tryCatchAction)
let leaveAction = UIAlertAction(title: "Leave?", style: .Cancel) { (action) in
self.runAwayPokemon(annotation, message: "The Pokemon was startled by your noise when you left.", title: "Oh no!")
}
actionSheet.addAction(leaveAction)
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func putCaughtPokemonInBackpack(annotation: PokemonAnnotation, message: String, title: String) {
self.mapView?.removeAnnotation(annotation)
let index = self.pokemonAnnotations.indexOf(annotation)
self.pokemonAnnotations.removeAtIndex(index!)
let pokemon = annotation.pokemon
let coords = annotation.coordinate
DB().savePokemonInBackpack(pokemon, latitude: coords.latitude, longitude: coords.longitude)
// TODO(dkg): put pokemon in backpack!
showErrorAlert(self, message: message, title: title, completion: {
if self.pokemonAnnotations.count == 0 {
self.scanMap(annotation)
}
})
}
func runAwayPokemon(annotation: PokemonAnnotation, message: String, title: String) {
// there is a chance that the pokemon will run away anyway
let runAwayChance = randomInt(0...100)
if runAwayChance > 65 {
showErrorAlert(self, message: message, title: title, completion: {
let coords = annotation.coordinate
let newCoords = self.getRandomCoordinates(coords)
self.mapView?.removeAnnotation(annotation)
annotation.coordinate = newCoords
self.mapView?.addAnnotation(annotation)
})
} else {
self.mapView?.deselectAnnotation(annotation, animated: true)
}
}
}
| mit | c8547fc8046dfe21629a8646c145e7c5 | 40.484716 | 207 | 0.593316 | 5.367232 | false | false | false | false |
Jgzhu/DouYUZhiBo-Swift | DouYUZhiBo-Swift/DouYUZhiBo-Swift/Classes/Home/Model/RecommendGroupModel.swift | 1 | 943 | //
// RecommendGroupModel.swift
// DouYUZhiBo-Swift
//
// Created by 江贵铸 on 2016/11/24.
// Copyright © 2016年 江贵铸. All rights reserved.
//
import UIKit
class RecommendGroupModel: NSObject {
var room_list:[[String:Any]]? {
didSet{
guard let room_list = room_list else {
return
}
for dict in room_list {
RecomModel.append(RecommendModel(dict: dict))
}
}
}
//每一组显示的图标
var name_icon:String = "home_header_normal"
var tag_name : String = ""
var icon_url : String = ""
//每一组里面对应的模型数组
lazy var RecomModel:[RecommendModel] = [RecommendModel]()
override init() {
super.init()
}
init(dict:[String:Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | 6ccb4f47e3dd10f60b10d7dec2f8a328 | 22.368421 | 72 | 0.565315 | 3.7 | false | false | false | false |
Lweek/Formulary | Formulary/UIKit Extensions/KeyboardNotification.swift | 2 | 2912 | // Thanks to Kristopher Johnson
// https://gist.github.com/kristopherjohnson/13d5f18b0d56b0ea9242
import UIKit
/// Wrapper for the NSNotification userInfo values associated with a keyboard notification.
///
/// It provides properties retrieve userInfo dictionary values with these keys:
///
/// - UIKeyboardFrameBeginUserInfoKey
/// - UIKeyboardFrameEndUserInfoKey
/// - UIKeyboardAnimationDurationUserInfoKey
/// - UIKeyboardAnimationCurveUserInfoKey
struct KeyboardNotification {
let notification: NSNotification
let userInfo: NSDictionary
/// Initializer
///
/// :param: notification Keyboard-related notification
init(_ notification: NSNotification) {
self.notification = notification
if let userInfo = notification.userInfo {
self.userInfo = userInfo
}
else {
self.userInfo = NSDictionary()
}
}
/// Start frame of the keyboard in screen coordinates
var screenFrameBegin: CGRect {
if let value = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue {
return value.CGRectValue()
}
else {
return CGRectZero
}
}
/// End frame of the keyboard in screen coordinates
var screenFrameEnd: CGRect {
if let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
return value.CGRectValue()
}
else {
return CGRectZero
}
}
/// Keyboard animation duration
var animationDuration: Double {
if let number = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber {
return number.doubleValue
}
else {
return 0.25
}
}
/// Keyboard animation curve
///
/// Note that the value returned by this method may not correspond to a
/// UIViewAnimationCurve enum value. For example, in iOS 7 and iOS 8,
/// this returns the value 7.
var animationCurve: Int {
if let number = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
return number.integerValue
}
return UIViewAnimationCurve.EaseInOut.rawValue
}
/// Start frame of the keyboard in coordinates of specified view
///
/// :param: view UIView to whose coordinate system the frame will be converted
/// :returns: frame rectangle in view's coordinate system
func frameBeginForView(view: UIView) -> CGRect {
return view.convertRect(screenFrameBegin, fromView: view.window)
}
/// Start frame of the keyboard in coordinates of specified view
///
/// :param: view UIView to whose coordinate system the frame will be converted
/// :returns: frame rectangle in view's coordinate system
func frameEndForView(view: UIView) -> CGRect {
return view.convertRect(screenFrameEnd, fromView: view.window)
}
} | mit | 59dea50420a57a02441ea7db2fdfc281 | 31.366667 | 91 | 0.65625 | 5.483992 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/SlidingModal/SlidingModalPresentationAnimator.swift | 1 | 5538 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
/// `SlidingModalPresentationAnimator` handles the animations for a custom sliding view controller transition.
final class SlidingModalPresentationAnimator: NSObject {
// MARK: - Constants
private enum AnimationDuration {
static let presentation: TimeInterval = 0.2
static let dismissal: TimeInterval = 0.3
}
// MARK: - Properties
private let isPresenting: Bool
// MARK: - Setup
/// Instantiate a SlidingModalPresentationAnimator object.
///
/// - Parameter isPresenting: true to animate presentation or false to animate dismissal
required public init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
// MARK: - Private
// Animate presented view controller presentation
private func animatePresentation(using transitionContext: UIViewControllerContextTransitioning) {
guard let presentedViewController = transitionContext.viewController(forKey: .to),
let sourceViewController = transitionContext.viewController(forKey: .from) else {
return
}
guard let presentedViewControllerView = presentedViewController.view else {
return
}
let containerView = transitionContext.containerView
let slidingModalContainerView = SlidingModalContainerView.instantiate()
slidingModalContainerView.alpha = 0
slidingModalContainerView.updateDimmingViewAlpha(0.0)
// Add presented view controller view to slidingModalContainerView content view
slidingModalContainerView.setContentView(presentedViewControllerView)
// Add slidingModalContainerView to container view
containerView.vc_addSubViewMatchingParent(slidingModalContainerView)
containerView.layoutIfNeeded()
// Adapt slidingModalContainerView content view height from presentedViewControllerView height
if let slidingModalPresentable = presentedViewController as? SlidingModalPresentable {
let slidingModalContainerViewContentViewWidth = slidingModalContainerView.contentViewFrame.width
let presentableHeight = slidingModalPresentable.layoutHeightFittingWidth(slidingModalContainerViewContentViewWidth)
slidingModalContainerView.updateContentViewMaxHeight(presentableHeight)
slidingModalContainerView.updateContentViewLayout()
}
// Hide slidingModalContainerView content view
slidingModalContainerView.prepareDismissAnimation()
containerView.layoutIfNeeded()
let animationDuration = self.transitionDuration(using: transitionContext)
slidingModalContainerView.preparePresentAnimation()
slidingModalContainerView.alpha = 1
UIView.animate(withDuration: animationDuration, animations: {
containerView.layoutIfNeeded()
slidingModalContainerView.updateDimmingViewAlpha(1.0)
}, completion: { completed in
transitionContext.completeTransition(completed)
})
}
// Animate presented view controller dismissal
private func animateDismissal(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let slidingModalContainerView = self.slidingModalContainerView(from: transitionContext)
let animationDuration = self.transitionDuration(using: transitionContext)
slidingModalContainerView?.prepareDismissAnimation()
UIView.animate(withDuration: animationDuration, animations: {
containerView.layoutIfNeeded()
slidingModalContainerView?.updateDimmingViewAlpha(0.0)
}, completion: { completed in
transitionContext.completeTransition(completed)
})
}
private func slidingModalContainerView(from transitionContext: UIViewControllerContextTransitioning) -> SlidingModalContainerView? {
let modalContentView = transitionContext.containerView.subviews.first(where: { view -> Bool in
view is SlidingModalContainerView
}) as? SlidingModalContainerView
return modalContentView
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension SlidingModalPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.isPresenting ? AnimationDuration.presentation : AnimationDuration.dismissal
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if self.isPresenting {
self.animatePresentation(using: transitionContext)
} else {
self.animateDismissal(using: transitionContext)
}
}
}
| apache-2.0 | 3f8b93fe5d99c0d24867d7d61a663595 | 40.022222 | 136 | 0.720116 | 6.394919 | false | false | false | false |
ytfhqqu/iCC98 | iCC98/iCC98/TopicTableViewController.swift | 1 | 10234 | //
// TopicTableViewController.swift
// iCC98
//
// Created by Duo Xu on 5/5/17.
// Copyright © 2017 Duo Xu.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import SVProgressHUD
import CC98Kit
class TopicTableViewController: BaseTableViewController {
@IBOutlet weak var firstPageButton: UIBarButtonItem!
@IBOutlet weak var lastPageButton: UIBarButtonItem!
@IBOutlet weak var previousPageButton: UIBarButtonItem!
@IBOutlet weak var nextPageButton: UIBarButtonItem!
@IBOutlet weak var pageIndicatorButton: UIBarButtonItem!
// MARK: - Data
/**
设置数据。
- parameter boardId: 要获取主题的版面的编号。
*/
func setData(boardId: Int) {
self.boardId = boardId
fetchData(boardId: boardId, pagination: (from: 0, size: 20))
}
/// 要获取主题的版面的编号。
private var boardId: Int?
/// 版面的总页数(每页 20 条)。
private var totalPages: Int = 0 {
didSet {
updatePageToolbar()
}
}
/// 当前所在页面,从 0 开始计数。
private var currentPage = 0 {
didSet {
updatePageToolbar()
// 获取数据
if boardId != nil {
fetchData(boardId: boardId!, pagination: (from: currentPage * 20, size: 20))
}
}
}
/// 主题的信息。
private var topics = [TopicInfo]() {
didSet {
lastUpdated = Date()
tableView.reloadData()
if hasData {
// 滚动到顶端
tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
}
}
}
/// 表示是否有数据。
override var hasData: Bool {
return !topics.isEmpty
}
/// 最后更新的时间。
private var lastUpdated: Date?
/// 获取数据。
private func fetchData(boardId: Int, pagination: (from: Int, size: Int)) {
isLoading = true
// 获取总页数
_ = CC98API.getBoard(id: boardId, accessToken: OAuthUtility.accessToken) { [weak self] result in
switch result {
case .success(_, let data):
if let boardInfo = data, let totalTopicCount = boardInfo.topicCount {
self?.totalPages = totalTopicCount / 20 + ((totalTopicCount % 20 > 0) ? 1 : 0)
}
default:
break
}
}
// 获取主题
_ = CC98API.getTopics(onBoard: boardId, pagination: pagination, accessToken: OAuthUtility.accessToken) { [weak self] result in
switch result {
case .success(_, let data):
if let topicInfoArray = data {
self?.topics = topicInfoArray
}
case .failure(let status, let message):
switch status {
case 401,
// 有些版面只是没有登录,但也会返回 403
403 where !OAuthUtility.accessTokenIsValid:
if let vc = UIApplication.shared.keyWindow?.rootViewController {
SVProgressHUD.showRequiresAuthorization()
OAuthUtility.authorize(displaySafariOn: vc) { result in
switch result {
case .success(token: _):
self?.fetchData(boardId: self?.boardId ?? 0, pagination: (from: 0, size: 20))
default:
break
}
}
}
case 403:
SVProgressHUD.showAccessDeniedError()
self?.navigationController?.popViewController(animated: true)
self?.dismiss(animated: true, completion: nil)
default:
SVProgressHUD.showError(statusCode: status, message: message)
}
case .noResponse:
SVProgressHUD.showNoResponseError()
}
self?.isLoading = false
}
}
// MARK: - UI
/// 更新页面工具栏的状态。
private func updatePageToolbar() {
// “首页”按钮
firstPageButton.isEnabled = currentPage > 0
// “末页”按钮
lastPageButton.isEnabled = currentPage < totalPages - 1
// “上页”按钮
previousPageButton.isEnabled = currentPage > 0
// “下页”按钮
nextPageButton.isEnabled = currentPage < totalPages - 1
// 页面指示器
pageIndicatorButton.title = "\(currentPage + 1) / \(totalPages)"
}
// MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
updatePageToolbar()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isToolbarHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isToolbarHidden = true
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return topics.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let lastUpdated = lastUpdated {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/M/d H:mm"
formatter.timeZone = TimeZone(secondsFromGMT: 8 * 60 * 60)
return "最后更新:" + formatter.string(from: lastUpdated)
} else {
return nil
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Topic Cell", for: indexPath)
// Configure the cell...
if let topicCell = cell as? TopicTableViewCell {
topicCell.setData(topicInfo: topics[indexPath.row])
}
return cell
}
// 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.
if segue.identifier == "New Post" {
// 新建主题
if let newPostTVC = segue.destination as? NewPostTableViewController, let boardId = boardId {
newPostTVC.setData(newPostType: .newTopic(boardId: boardId))
}
} else if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) {
let topicInfo = topics[indexPath.row]
if segue.identifier == "Topic-Posts", let postTVC = segue.destination as? PostTableViewController {
// 查看发言列表
postTVC.setData(topicId: topicInfo.id ?? 0)
postTVC.navigationItem.title = topicInfo.title
}
}
}
// MARK: - Action
/// 刷新操作。
@IBAction func refresh(_ sender: UIRefreshControl) {
refreshUpdateUI()
if !isLoading {
// 获取数据
if boardId != nil {
fetchData(boardId: boardId!, pagination: (from: currentPage * 20, size: 20))
}
}
}
@IBAction func tapFirstPage(_ sender: UIBarButtonItem) {
currentPage = 0
}
@IBAction func tapLastPage(_ sender: UIBarButtonItem) {
currentPage = totalPages - 1
}
@IBAction func tapPreviousPage(_ sender: UIBarButtonItem) {
currentPage -= 1
}
@IBAction func tapNextPage(_ sender: UIBarButtonItem) {
currentPage += 1
}
@IBAction func tapPageIndicator(_ sender: UIBarButtonItem) {
// 创建并展示一个输入页码的对话框
let alertController = UIAlertController(title: "跳转到页码", message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel)
let okAction = UIAlertAction(title: "确定", style: .default) { [weak self] action in
if let inputText = (alertController.textFields?.first)?.text,
let number = Int(inputText),
let totalPages = self?.totalPages,
number >= 1 && number <= totalPages {
self?.currentPage = number - 1
} else {
SVProgressHUD.showInvalidPageNumberError()
}
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
alertController.addTextField { textField in
textField.placeholder = "页码"
textField.keyboardType = .numberPad
}
self.present(alertController, animated: true)
}
}
| mit | 7c954e6a861c3b5d88f9a578d0873068 | 35.652985 | 134 | 0.58587 | 4.89681 | false | false | false | false |
spacedrabbit/CatAerisWeatherDemo | CatAerisWeatherDemo/View Controllers/WeatherDisplayViewController.swift | 1 | 5735 | //
// WeatherDisplayViewController.swift
// CatAerisWeatherDemo
//
// Created by Louis Tur on 8/31/16.
// Copyright © 2016 catthoughts. All rights reserved.
//
import UIKit
import SnapKit
import Aeris
class WeatherDisplayViewController: UIViewController, LocationHelperDelegate, AerisRequestManagerDelegate {
internal var currentPlace: AWFPlace = AWFPlace()
internal var locationHelper: LocationHelper = LocationHelper.manager
internal var aerisManager: AerisRequestManager = AerisRequestManager.shared
internal var tenDayManager: TenDayViewManager = TenDayViewManager.shared
internal let tenDayForecastView: TenDayCollectionView = TenDayViewManager.shared.collectionView
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupViewHierarchy()
self.configureConstraints()
self.locationHelper.delegate = self
self.aerisManager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tenDayForecastView.snp.makeConstraints { (make) in
make.height.equalTo(200).priority(991.0)
make.bottom.equalTo(self.containerView).inset(AppLayout.StandardMargin).priority(990.0)
make.left.equalTo(self.containerView).offset(AppLayout.StandardMargin)
make.right.equalTo(self.containerView).inset(AppLayout.StandardMargin)
make.top.equalTo(self.currentWeatherCard.snp.bottom)
}
}
// ---------------------------------------------------------------- //
// MARK: - Setup
fileprivate func configureConstraints() {
self.loadingView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
self.containerView.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(AppLayout.StandardMargin + AppLayout.StatusBar)
make.left.equalTo(self.view).offset(AppLayout.StandardMargin)
make.bottom.right.equalTo(self.view).inset(AppLayout.StandardMargin)
}
self.currentWeatherCard.snp.makeConstraints { (make) in
make.top.equalTo(self.containerView).offset(AppLayout.StandardMargin)
make.centerX.equalTo(self.containerView)
make.width.equalTo(self.containerView).inset(AppLayout.StandardMargin)
}
}
fileprivate func setupViewHierarchy() {
self.view.addSubview(containerView)
self.containerView.addSubview(currentWeatherCard)
self.containerView.addSubview(tenDayForecastView)
self.view.addSubview(loadingView)
self.view.backgroundColor = AppColors.DarkBackground
self.containerView.layer.cornerRadius = AppLayout.StandardMargin
}
// ---------------------------------------------------------------- //
// MARK: - UI Updates
internal func updateUIElements(_ place: AWFPlace, forecast: AWFForecast, completion: (()->Void)?) {
self.currentWeatherCard.updateUI(withPlace: place)
var weeklyForecastPeriods: [AWFForecastPeriod] = []
for period in forecast.periods as! [AWFForecastPeriod] {
let dateHelper = DateConversionHelper(withDate: period.timestamp)
if dateHelper.isTodaysDate() {
self.currentWeatherCard.updateUI(withForecastPeriod: period)
continue
}
weeklyForecastPeriods.append(period)
}
if weeklyForecastPeriods.count > 0 {
self.tenDayManager.updateForecasts(weeklyForecastPeriods)
}
if completion != nil {
completion!()
}
}
// ---------------------------------------------------------------- //
// MARK: - LocationHelperDelegate
func authorizationStatusDidChange(_ status: LocationHelperStatus) {
// not entirely sure how I'm going to use this yet, but likely will be needed for something
switch status {
case .ready:
print("Location Status is Ready")
case .notReady:
print("Location Status is Not Ready")
case .denied:
print("Location Status is Denied")
}
}
func alertRequiresDisplay(_ alert: UIAlertController) {
self.show(alert, sender: self)
}
func trackedLocationDidChange(_ location: CLLocation) {
self.aerisManager.beginPlaceRequestForCoordinates(location.coordinate)
}
// ---------------------------------------------------------------- //
// MARK: - AerisRequestManagerDelegate
func placesRequestDidFinish(_ place: AWFPlace) {
self.currentPlace = place
self.aerisManager.beginForecastRequestForPlace(self.currentPlace)
}
func placesRequestDidFailWithError(_ error: NSError) {
print("Places request failed: \(error)")
}
func forecastRequestDidFinish(_ forecast: AWFForecast, forPlace place: AWFPlace) {
self.updateUIElements(place, forecast: forecast) {
// TODO: make sure interactively is fine, and that the view is actually removed
self.loadingView.animateOut()
}
}
func forecastRequestDidFailWithError(_ error: NSError) {
print("Forecast request failed: \(error)")
}
// ---------------------------------------------------------------- //
// MARK: - Lazy Init
internal lazy var containerView: UIView = {
let view: UIView = UIView()
view.backgroundColor = AppColors.StandardBackground
return view
}()
internal lazy var currentWeatherCard: CurrentWeatherCardView = CurrentWeatherCardView(frame: CGRect.zero)
internal lazy var locationLabel: UILabel = {
let label: UILabel = UILabel()
label.font = AppFont.StandardFont
label.textColor = AppColors.StandardTextColor
return label
}()
internal lazy var loadingView: LoadingView = {
let loadingView: LoadingView = LoadingView()
return loadingView
}()
}
| mit | 9100fe36bd10a030fc3572e77126ddfc | 30.679558 | 107 | 0.676317 | 4.696151 | false | false | false | false |
osorioabel/checklist-app | checklist-app/checklist-app/Controllers/ListDetailViewController.swift | 1 | 3426 | //
// ListDetailViewController.swift
// checklist-app
//
// Created by Abel Osorio on 2/16/16.
// Copyright © 2016 Abel Osorio. All rights reserved.
//
import UIKit
protocol ListDetailViewControllerDelegate : class {
func listDetailViewControllerDidCancel(controller :ListDetailViewController)
func listDetailViewController(controller: ListDetailViewController,didFinishAddingChecklist checklist: Checklist)
func listDetailViewController(controller: ListDetailViewController,didFinishEditingChecklist checklist: Checklist)
}
class ListDetailViewController : UITableViewController, UITextFieldDelegate, IconPickerViewControllerDelegate{
@IBOutlet weak var textField : UITextField!
@IBOutlet weak var doneBarButton : UIBarItem!
@IBOutlet weak var iconImageView : UIImageView!
var iconName = "Folder"
weak var delegate:ListDetailViewControllerDelegate?
var checklistToEdit : Checklist?
override func viewDidLoad() {
super.viewDidLoad()
if let checklist = checklistToEdit{
title = "Edit Checklist"
textField.text = checklist.name
doneBarButton.enabled = true
iconName = checklist.iconName
}
iconImageView.image = UIImage(named: iconName)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textField.becomeFirstResponder()
}
// MARK: - TextField delegate
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == 1 {
return indexPath
}else{
return nil
}
}
// MARK: - Actions
@IBAction func cancel(){
delegate?.listDetailViewControllerDidCancel(self)
}
@IBAction func done() {
if let checklist = checklistToEdit {
checklist.name = textField.text!
checklist.iconName = iconName
delegate?.listDetailViewController(self,didFinishEditingChecklist: checklist)
} else {
let checklist = Checklist(name: textField.text!,iconName:iconName)
delegate?.listDetailViewController(self,didFinishAddingChecklist: checklist)
}
}
// MARK: - TextField delegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool {
let oldText: NSString = textField.text!
let newText: NSString = oldText.stringByReplacingCharactersInRange( range, withString: string)
doneBarButton.enabled = (newText.length > 0)
return true
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PickIcon"{
let controller = segue.destinationViewController as! IconPickerViewController
controller.delegate = self
}
}
// MARK: - IconPickerViewControllerDelegate
func iconPicker(picker: IconPickerViewController, didPickIcon iconName: String) {
self.iconName = iconName
iconImageView.image = UIImage(named: iconName)
navigationController?.popViewControllerAnimated(true)
}
} | mit | d9097832ddb65fa76a55abac55f1ab94 | 29.589286 | 131 | 0.659562 | 5.966899 | false | false | false | false |
itsthejb/ocmock | Examples/SwiftExamples/SwiftExamples/MasterViewController.swift | 9 | 2998 | //
// MasterViewController.swift
// SwiftExamples
//
// Created by Erik Doernenburg on 11/06/2014.
// Copyright (c) 2014 Mulle Kybernetik. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var objects = NSMutableArray()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insertObject(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as NSDate
(segue.destinationViewController as DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = objects[indexPath.row] as NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| apache-2.0 | 67d074355cfd7f6fc7123c2e2f9af276 | 33.45977 | 157 | 0.667445 | 5.624765 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/Alamofire/Tests/ManagerTests.swift | 37 | 10795 | // ManagerTests.swift
//
// Copyright (c) 2014–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.
@testable import Alamofire
import Foundation
import XCTest
class ManagerTestCase: BaseTestCase {
// MARK: Initialization Tests
func testInitializerWithDefaultArguments() {
// Given, When
let manager = Manager()
// Then
XCTAssertNotNil(manager.session.delegate, "session delegate should not be nil")
XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate")
XCTAssertNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should be nil")
}
func testInitializerWithSpecifiedArguments() {
// Given
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let delegate = Manager.SessionDelegate()
let serverTrustPolicyManager = ServerTrustPolicyManager(policies: [:])
// When
let manager = Manager(
configuration: configuration,
delegate: delegate,
serverTrustPolicyManager: serverTrustPolicyManager
)
// Then
XCTAssertNotNil(manager.session.delegate, "session delegate should not be nil")
XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate")
XCTAssertNotNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should not be nil")
}
func testThatFailableInitializerSucceedsWithDefaultArguments() {
// Given
let delegate = Manager.SessionDelegate()
let session: NSURLSession = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}()
// When
let manager = Manager(session: session, delegate: delegate)
// Then
if let manager = manager {
XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate")
XCTAssertNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should be nil")
} else {
XCTFail("manager should not be nil")
}
}
func testThatFailableInitializerSucceedsWithSpecifiedArguments() {
// Given
let delegate = Manager.SessionDelegate()
let session: NSURLSession = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}()
let serverTrustPolicyManager = ServerTrustPolicyManager(policies: [:])
// When
let manager = Manager(session: session, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager)
// Then
if let manager = manager {
XCTAssertTrue(manager.delegate === manager.session.delegate, "manager delegate should equal session delegate")
XCTAssertNotNil(manager.session.serverTrustPolicyManager, "session server trust policy manager should not be nil")
} else {
XCTFail("manager should not be nil")
}
}
func testThatFailableInitializerFailsWithWhenDelegateDoesNotEqualSessionDelegate() {
// Given
let delegate = Manager.SessionDelegate()
let session: NSURLSession = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: configuration, delegate: Manager.SessionDelegate(), delegateQueue: nil)
}()
// When
let manager = Manager(session: session, delegate: delegate)
// Then
XCTAssertNil(manager, "manager should be nil")
}
func testThatFailableInitializerFailsWhenSessionDelegateIsNil() {
// Given
let delegate = Manager.SessionDelegate()
let session: NSURLSession = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}()
// When
let manager = Manager(session: session, delegate: delegate)
// Then
XCTAssertNil(manager, "manager should be nil")
}
// MARK: Start Requests Immediately Tests
func testSetStartRequestsImmediatelyToFalseAndResumeRequest() {
// Given
let manager = Alamofire.Manager()
manager.startRequestsImmediately = false
let URL = NSURL(string: "https://httpbin.org/get")!
let URLRequest = NSURLRequest(URL: URL)
let expectation = expectationWithDescription("\(URL)")
var response: NSHTTPURLResponse?
// When
manager.request(URLRequest)
.response { _, responseResponse, _, _ in
response = responseResponse
expectation.fulfill()
}
.resume()
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(response, "response should not be nil")
XCTAssertTrue(response?.statusCode == 200, "response status code should be 200")
}
// MARK: Deinitialization Tests
func testReleasingManagerWithPendingRequestDeinitializesSuccessfully() {
// Given
var manager: Manager? = Alamofire.Manager()
manager?.startRequestsImmediately = false
let URL = NSURL(string: "https://httpbin.org/get")!
let URLRequest = NSURLRequest(URL: URL)
// When
let request = manager?.request(URLRequest)
manager = nil
// Then
XCTAssertTrue(request?.task.state == .Suspended, "request task state should be '.Suspended'")
XCTAssertNil(manager, "manager should be nil")
}
func testReleasingManagerWithPendingCanceledRequestDeinitializesSuccessfully() {
// Given
var manager: Manager? = Alamofire.Manager()
manager!.startRequestsImmediately = false
let URL = NSURL(string: "https://httpbin.org/get")!
let URLRequest = NSURLRequest(URL: URL)
// When
let request = manager!.request(URLRequest)
request.cancel()
manager = nil
// Then
let state = request.task.state
XCTAssertTrue(state == .Canceling || state == .Completed, "state should be .Canceling or .Completed")
XCTAssertNil(manager, "manager should be nil")
}
}
// MARK: -
class ManagerConfigurationHeadersTestCase: BaseTestCase {
enum ConfigurationType {
case Default, Ephemeral, Background
}
func testThatDefaultConfigurationHeadersAreSentWithRequest() {
// Given, When, Then
executeAuthorizationHeaderTestForConfigurationType(.Default)
}
func testThatEphemeralConfigurationHeadersAreSentWithRequest() {
// Given, When, Then
executeAuthorizationHeaderTestForConfigurationType(.Ephemeral)
}
func testThatBackgroundConfigurationHeadersAreSentWithRequest() {
// Given, When, Then
executeAuthorizationHeaderTestForConfigurationType(.Background)
}
private func executeAuthorizationHeaderTestForConfigurationType(type: ConfigurationType) {
// Given
let manager: Manager = {
let configuration: NSURLSessionConfiguration = {
let configuration: NSURLSessionConfiguration
switch type {
case .Default:
configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
case .Ephemeral:
configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
case .Background:
let identifier = "com.alamofire.test.manager-configuration-tests"
configuration = NSURLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier)
}
var headers = Alamofire.Manager.defaultHTTPHeaders
headers["Authorization"] = "Bearer 123456"
configuration.HTTPAdditionalHeaders = headers
return configuration
}()
return Manager(configuration: configuration)
}()
let expectation = expectationWithDescription("request should complete successfully")
var response: Response<AnyObject, NSError>?
// When
manager.request(.GET, "https://httpbin.org/headers")
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be a success")
if let
headers = response.result.value?["headers" as NSString] as? [String: String],
authorization = headers["Authorization"]
{
XCTAssertEqual(authorization, "Bearer 123456", "authorization header value does not match")
} else {
XCTFail("failed to extract authorization header value")
}
} else {
XCTFail("response should not be nil")
}
}
}
| mit | 17c19b98e67f9936ff2a3610629356ec | 37.546429 | 133 | 0.66645 | 5.872144 | false | true | false | false |
Raizlabs/RZTransitions | RZTransitions-Demo/RZTransitions-Demo/ViewControllers/RZSimpleViewController.swift | 1 | 6263 | //
// RZSimpleViewController.swift
// RZTransitions-Demo
//
// Created by Eric Slosser on 11/13/15.
// Copyright 2015 Raizlabs and other contributors
// http://raizlabs.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
@objc(RZSimpleViewController)
final class RZSimpleViewController: UIViewController
{
@IBOutlet weak var popButton: UIButton?
@IBOutlet weak var pushButton: UIButton?
@IBOutlet weak var modalButton: UIButton?
@IBOutlet weak var collectionViewButton: UIButton?
var pushPopInteractionController: RZTransitionInteractionController?
var presentInteractionController: RZTransitionInteractionController?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Create the push and pop interaction controller that allows a custom gesture
// to control pushing and popping from the navigation controller
pushPopInteractionController = RZHorizontalInteractionController()
if let vc = pushPopInteractionController as? RZHorizontalInteractionController {
vc.nextViewControllerDelegate = self
vc.attachViewController(self, withAction: .PushPop)
RZTransitionsManager.shared().setInteractionController( vc, fromViewController:self.dynamicType, toViewController:nil, forAction: .PushPop);
}
// Create the presentation interaction controller that allows a custom gesture
// to control presenting a new VC via a presentViewController
presentInteractionController = RZVerticalSwipeInteractionController()
if let vc = presentInteractionController as? RZVerticalSwipeInteractionController {
vc.nextViewControllerDelegate = self;
vc.attachViewController(self, withAction:.Present);
}
// Setup the push & pop animations as well as a special animation for pushing a
// RZSimpleCollectionViewController
RZTransitionsManager.shared().setAnimationController( RZCardSlideAnimationController(),
fromViewController:self.dynamicType,
forAction:.PushPop);
RZTransitionsManager.shared().setAnimationController( RZZoomPushAnimationController(),
fromViewController:self.dynamicType,
toViewController:RZSimpleCollectionViewController.self,
forAction:.PushPop);
// Setup the animations for presenting and dismissing a new VC
RZTransitionsManager.shared().setAnimationController( RZCirclePushAnimationController(),
fromViewController:self.dynamicType,
forAction:.PresentDismiss);
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
RZTransitionsManager.shared().setInteractionController( presentInteractionController,
fromViewController:self.dynamicType,
toViewController:nil,
forAction:.Present);
}
}
// MARK: - Actions
extension RZSimpleViewController {
@IBAction func pushNewViewController(_: AnyObject) {
navigationController?.pushViewController(nextSimpleViewController(), animated:true);
}
@IBAction func popViewController(_: AnyObject) {
navigationController?.popViewControllerAnimated(true);
}
@IBAction func showModal(_: AnyObject) {
presentViewController(nextSimpleColorViewController(), animated:true, completion:({}));
}
@IBAction func showCollectionView(_: AnyObject) {
navigationController?.pushViewController(RZSimpleCollectionViewController(), animated:true);
}
}
// MARK: - RZTransitionInteractionControllerDelegate
extension RZSimpleViewController: RZTransitionInteractionControllerDelegate {
func nextSimpleViewController() -> UIViewController {
let newVC = RZSimpleViewController()
newVC.transitioningDelegate = RZTransitionsManager.shared()
return newVC;
}
func nextSimpleColorViewController() -> UIViewController {
let newColorVC = RZSimpleColorViewController()
newColorVC.transitioningDelegate = RZTransitionsManager.shared()
// Create a dismiss interaction controller that will be attached to the presented
// view controller to allow for a custom dismissal
let dismissInteractionController = RZVerticalSwipeInteractionController()
dismissInteractionController.attachViewController(newColorVC, withAction:.Dismiss)
RZTransitionsManager.shared().setInteractionController(dismissInteractionController,
fromViewController:self.dynamicType,
toViewController:nil,
forAction:.Dismiss)
return newColorVC
}
func nextViewControllerForInteractor(interactor: RZTransitionInteractionController) -> UIViewController {
if (interactor is RZVerticalSwipeInteractionController) {
return nextSimpleColorViewController();
}
else {
return nextSimpleViewController();
}
}
}
| mit | 9989ab453e8ce65485211134df4493fd | 40.476821 | 152 | 0.730002 | 5.577026 | false | false | false | false |
lelandjansen/fatigue | ios/fatigue/ImageCreditsView.swift | 1 | 1837 | import UIKit
class ImageCreditsView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
weak var delegate: ImageCreditsDelegate?
let creditsLabel: UILabel = {
let label = UILabel()
label.text = "Aircraft, clouds, and mountain images designed by Freepik. Air traffic control tower image designed by Graphiqastock/Freepik. Images modified with permission."
label.numberOfLines = 0
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.textColor = .dark
return label
}()
let websiteButton: UIButton = {
let button = UIButton()
button.setTitle("http://www.freepik.com", for: .normal)
button.setTitleColor(.violet, for: .normal)
button.addTarget(self, action: #selector(handleWebsiteButton), for: .touchUpInside)
return button
}()
func handleWebsiteButton() {
delegate?.openUrl(URL(string: websiteButton.title(for: .normal)!)!)
}
func setupViews() {
addSubview(creditsLabel)
addSubview(websiteButton)
let padding: CGFloat = 16
creditsLabel.anchorWithConstantsToTop(
nil,
left: leftAnchor,
bottom: centerYAnchor,
right: rightAnchor,
leftConstant: padding,
bottomConstant: padding / 2,
rightConstant: padding
)
websiteButton.anchorWithConstantsToTop(
centerYAnchor,
left: leftAnchor,
right: rightAnchor,
topConstant: padding / 2,
leftConstant: padding,
rightConstant: padding
)
}
}
| apache-2.0 | c904625a9b6d0c70ff0590249bb052c7 | 29.114754 | 181 | 0.596625 | 5.060606 | false | false | false | false |
tardieu/swift | test/IRGen/generic_metatypes.swift | 3 | 16959 | // RUN: %swift -Xllvm -new-mangling-for-tests -target x86_64-apple-macosx10.9 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target i386-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target x86_64-apple-ios7.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target i386-apple-tvos9.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target x86_64-apple-tvos9.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target i386-apple-watchos2.0 -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-32 %s
// RUN: %swift -Xllvm -new-mangling-for-tests -target x86_64-unknown-linux-gnu -disable-objc-interop -emit-ir -parse-stdlib -primary-file %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-64 %s
// REQUIRES: CODEGENERATOR=X86
// CHECK: define hidden %swift.type* [[GENERIC_TYPEOF:@_T017generic_metatypes0A6TypeofxmxlF]](%swift.opaque* noalias nocapture, %swift.type* [[TYPE:%.*]])
func genericTypeof<T>(_ x: T) -> T.Type {
// CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* {{.*}}, %swift.type* [[TYPE]], i1 false)
// CHECK: ret %swift.type* [[METATYPE]]
return type(of: x)
}
struct Foo {}
class Bar {}
// CHECK: define hidden %swift.type* @_T017generic_metatypes27remapToSubstitutedMetatypes{{.*}}(%C17generic_metatypes3Bar*) {{.*}} {
func remapToSubstitutedMetatypes(_ x: Foo, y: Bar)
-> (Foo.Type, Bar.Type)
{
// CHECK: call %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture undef, %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}})
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: [[BAR_META:%.*]] = call %swift.type* [[GENERIC_TYPEOF]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[T0]])
// CHECK: ret %swift.type* [[BAR_META]]
return (genericTypeof(x), genericTypeof(y))
}
// CHECK: define hidden void @_T017generic_metatypes23remapToGenericMetatypesyyF()
func remapToGenericMetatypes() {
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: call void @_T017generic_metatypes0A9Metatypes{{.*}}(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}} %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}} %swift.type* [[T0]])
genericMetatypes(Foo.self, Bar.self)
}
func genericMetatypes<T, U>(_ t: T.Type, _ u: U.Type) {}
protocol Bas {}
// CHECK: define hidden { %swift.type*, i8** } @_T017generic_metatypes14protocolTypeof{{.*}}(%P17generic_metatypes3Bas_* noalias nocapture dereferenceable({{.*}}))
func protocolTypeof(_ x: Bas) -> Bas.Type {
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X:%.*]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]]
// CHECK: [[BUFFER:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X]], i32 0, i32 0
// CHECK: [[METADATA_I8:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-32: [[VW_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_I8]], i32 -1
// CHECK-64: [[VW_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_I8]], i64 -1
// CHECK: [[VW:%.*]] = load i8**, i8*** [[VW_ADDR]]
// CHECK: [[PROJECT_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VW]], i32 2
// CHECK-32: [[PROJECT_PTR:%.*]] = load i8*, i8** [[PROJECT_ADDR]], align 4
// CHECK-64: [[PROJECT_PTR:%.*]] = load i8*, i8** [[PROJECT_ADDR]], align 8
// CHECK-32: [[PROJECT:%.*]] = bitcast i8* [[PROJECT_PTR]] to %swift.opaque* ([12 x i8]*, %swift.type*)*
// CHECK-64: [[PROJECT:%.*]] = bitcast i8* [[PROJECT_PTR]] to %swift.opaque* ([24 x i8]*, %swift.type*)*
// CHECK-32: [[PROJECTION:%.*]] = call %swift.opaque* [[PROJECT]]([12 x i8]* [[BUFFER]], %swift.type* [[METADATA]])
// CHECK-64: [[PROJECTION:%.*]] = call %swift.opaque* [[PROJECT]]([24 x i8]* [[BUFFER]], %swift.type* [[METADATA]])
// CHECK: [[METATYPE:%.*]] = call %swift.type* @swift_getDynamicType(%swift.opaque* [[PROJECTION]], %swift.type* [[METADATA]], i1 true)
// CHECK: [[T0:%.*]] = getelementptr inbounds %P17generic_metatypes3Bas_, %P17generic_metatypes3Bas_* [[X]], i32 0, i32 2
// CHECK-32: [[WTABLE:%.*]] = load i8**, i8*** [[T0]], align 4
// CHECK-64: [[WTABLE:%.*]] = load i8**, i8*** [[T0]], align 8
// CHECK: [[T0:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* [[METATYPE]], 0
// CHECK: [[T1:%.*]] = insertvalue { %swift.type*, i8** } [[T0]], i8** [[WTABLE]], 1
// CHECK: ret { %swift.type*, i8** } [[T1]]
return type(of: x)
}
struct Zim : Bas {}
class Zang : Bas {}
// CHECK-LABEL: define hidden { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA3ZimVmF() #0
func metatypeErasure(_ z: Zim.Type) -> Bas.Type {
// CHECK: ret { %swift.type*, i8** } {{.*}} @_T017generic_metatypes3ZimVMf, {{.*}} @_T017generic_metatypes3ZimVAA3BasAAWP
return z
}
// CHECK-LABEL: define hidden { %swift.type*, i8** } @_T017generic_metatypes15metatypeErasureAA3Bas_pXpAA4ZangCmF(%swift.type*) #0
func metatypeErasure(_ z: Zang.Type) -> Bas.Type {
// CHECK: [[RET:%.*]] = insertvalue { %swift.type*, i8** } undef, %swift.type* %0, 0
// CHECK: [[RET2:%.*]] = insertvalue { %swift.type*, i8** } [[RET]], i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T017generic_metatypes4ZangCAA3BasAAWP, i32 0, i32 0), 1
// CHECK: ret { %swift.type*, i8** } [[RET2]]
return z
}
struct OneArg<T> {}
struct TwoArgs<T, U> {}
struct ThreeArgs<T, U, V> {}
struct FourArgs<T, U, V, W> {}
struct FiveArgs<T, U, V, W, X> {}
func genericMetatype<A>(_ x: A.Type) {}
// CHECK-LABEL: define hidden void @_T017generic_metatypes20makeGenericMetatypesyyF() {{.*}} {
func makeGenericMetatypes() {
// CHECK: call %swift.type* @_T017generic_metatypes6OneArgVyAA3FooVGMa() [[NOUNWIND_READNONE:#[0-9]+]]
genericMetatype(OneArg<Foo>.self)
// CHECK: call %swift.type* @_T017generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa() [[NOUNWIND_READNONE]]
genericMetatype(TwoArgs<Foo, Bar>.self)
// CHECK: call %swift.type* @_T017generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa() [[NOUNWIND_READNONE]]
genericMetatype(ThreeArgs<Foo, Bar, Foo>.self)
// CHECK: call %swift.type* @_T017generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa() [[NOUNWIND_READNONE]]
genericMetatype(FourArgs<Foo, Bar, Foo, Bar>.self)
// CHECK: call %swift.type* @_T017generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa() [[NOUNWIND_READNONE]]
genericMetatype(FiveArgs<Foo, Bar, Foo, Bar, Foo>.self)
}
// CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes6OneArgVyAA3FooVGMa() [[NOUNWIND_READNONE_OPT:#[0-9]+]]
// CHECK: call %swift.type* @_T017generic_metatypes6OneArgVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]]
// CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes6OneArgVMa(%swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type* }, { %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes6OneArgVMP {{.*}}, i8* [[BUFFER_PTR]])
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.end
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMa() [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: call %swift.type* @_T017generic_metatypes7TwoArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]])
// CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes7TwoArgsVMa(%swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type* }, { %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes7TwoArgsVMP {{.*}}, i8* [[BUFFER_PTR]])
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.end
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMa() [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: call %swift.type* @_T017generic_metatypes9ThreeArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE]]
// CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes9ThreeArgsVMa(%swift.type*, %swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2
// CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes9ThreeArgsVMP {{.*}}, i8* [[BUFFER_PTR]])
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.end
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMa() [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: call %swift.type* @_T017generic_metatypes8FourArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]]) [[NOUNWIND_READNONE]]
// CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes8FourArgsVMa(%swift.type*, %swift.type*, %swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2
// CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 3
// CHECK: store %swift.type* %3, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes8FourArgsVMP {{.*}}, i8* [[BUFFER_PTR]])
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.end
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: define linkonce_odr hidden %swift.type* @_T017generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMa() [[NOUNWIND_READNONE_OPT]]
// CHECK: [[T0:%.*]] = call %swift.type* @_T017generic_metatypes3BarCMa()
// CHECK: call %swift.type* @_T017generic_metatypes8FiveArgsVMa(%swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}, %swift.type* [[T0]], %swift.type* {{.*}} @_T017generic_metatypes3FooVMf, {{.*}}) [[NOUNWIND_READNONE]]
// CHECK-LABEL: define hidden %swift.type* @_T017generic_metatypes8FiveArgsVMa(%swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type*)
// CHECK: [[BUFFER:%.*]] = alloca { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.start
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 0
// CHECK: store %swift.type* %0, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 1
// CHECK: store %swift.type* %1, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 2
// CHECK: store %swift.type* %2, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_ELT:%.*]] = getelementptr inbounds { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }, { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]], i32 0, i32 3
// CHECK: store %swift.type* %3, %swift.type** [[BUFFER_ELT]]
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_rt_swift_getGenericMetadata(%swift.type_pattern* {{.*}} @_T017generic_metatypes8FiveArgsVMP {{.*}}, i8* [[BUFFER_PTR]])
// CHECK: [[BUFFER_PTR:%.*]] = bitcast { %swift.type*, %swift.type*, %swift.type*, %swift.type*, %swift.type* }* [[BUFFER]] to i8*
// CHECK: call void @llvm.lifetime.end
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: attributes [[NOUNWIND_READNONE_OPT]] = { nounwind readnone "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu"
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
| apache-2.0 | 1f32714a3693325c323cc2f1558b085b | 79.374408 | 309 | 0.638953 | 3.047439 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsType.swift | 1 | 1548 | //
// ProfileSettingsType.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileSettings {
class func payloadType(forPayloadSettings payloadSettings: [String: Any]) -> PayloadType {
guard var domain = payloadSettings[PayloadKey.payloadType] as? String else {
Log.shared.error(message: "Payload with content: \(payloadSettings) is missing required key: \"PayloadType\".", category: String(describing: self))
return .custom
}
if domain == kManifestDomainConfiguration {
domain = kManifestDomainConfiguration
}
return self.payloadType(forDomain: domain)
}
class func payloadType(forDomain domain: String) -> PayloadType {
guard let types = ProfilePayloads.shared.payloadTypes(forDomain: domain) else {
Log.shared.error(message: "Unknown PayloadType: \(domain), this content will be ignored.", category: String(describing: self))
return .custom
}
if types.count == 1, let type = types.first {
return type
} else {
// FIXME: Need to compare the actual keys to see which one it most likely is...
//let domainKeys = Set(payloadSettings.keys)
//let keys = Array(domainKeys.subtracting(kPayloadSubkeys))
// FIXME: Just return manifestApple until this is implemented.
return .manifestsApple
}
}
}
| mit | e112abe2d83eab499c05d45038598946 | 33.377778 | 159 | 0.65223 | 4.604167 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Main Window Profile List/MainWindowTableView.swift | 1 | 30670 | //
// MainWindowTableView.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
// MARK: -
// MARK: Protocols
// MAKR: -
protocol MainWindowTableViewDelegate: class {
func shouldRemoveItems(atIndexes: IndexSet)
func profileIdentifier(atRow: Int) -> UUID?
}
// MARK: -
// MARK: Classes
// MAKR: -
class MainWindowTableViewController: NSObject, MainWindowOutlineViewSelectionDelegate, MainWindowTableViewDelegate {
// MARK: -
// MARK: Variables
let tableView = MainWindowTableView()
let cellView = MainWindowTableViewCellView()
let scrollView = OverlayScrollView(frame: NSRect.zero)
var alert: Alert?
var updateSelectedProfileIdentifiers = true
var selectedProfileGroup: OutlineViewChildItem?
var selectedProfileIdentitifers: [UUID]?
// MARK: -
// MARK: Initialization
override init() {
super.init()
// ---------------------------------------------------------------------
// Setup Table Column
// ---------------------------------------------------------------------
let tableColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "MainWindowTableViewTableColumn"))
tableColumn.isEditable = false
// ---------------------------------------------------------------------
// Setup TableView
// ---------------------------------------------------------------------
self.tableView.addTableColumn(tableColumn)
self.tableView.translatesAutoresizingMaskIntoConstraints = true
self.tableView.floatsGroupRows = false
self.tableView.rowSizeStyle = .default
self.tableView.headerView = nil
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.target = self
self.tableView.doubleAction = #selector(self.editProfile(tableView:))
self.tableView.allowsMultipleSelection = true
self.tableView.registerForDraggedTypes(kMainWindowDragDropUTIs)
// Things I've tried to remove the separator between the views in the outline view
/*
self.tableView.gridColor = .clear
self.tableView.gridStyleMask = NSTableViewGridLineStyle(rawValue: 0)
self.tableView.intercellSpacing = NSZeroSize
*/
// ---------------------------------------------------------------------
// Setup ScrollView
// ---------------------------------------------------------------------
self.scrollView.documentView = self.tableView
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.autoresizesSubviews = true
// ---------------------------------------------------------------------
// Setup Notification Observers
// ---------------------------------------------------------------------
NotificationCenter.default.addObserver(self, selector: #selector(didRemoveProfilesFromGroup(_:)), name: .didRemoveProfilesFromGroup, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didSaveProfile(_:)), name: .didSaveProfile, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: .didRemoveProfilesFromGroup, object: nil)
NotificationCenter.default.removeObserver(self, name: .didSaveProfile, object: nil)
}
// MARK: -
// MARK: MainWindowOutlineViewDelegate Functions
func selected(item: OutlineViewChildItem, sender: Any?) {
self.selectedProfileGroup = item
self.reloadTableView(updateSelection: (self.selectedProfileIdentitifers != nil) ? true : false)
}
func updated(item: OutlineViewChildItem, sender: Any?) {
// TODO: Another weak check using the identifier because it isn't equatable
if let selectedProfileGroup = self.selectedProfileGroup, selectedProfileGroup.identifier == item.identifier {
reloadTableView()
}
}
// MARK: -
// MARK: TableView Actions
@objc func editProfile(tableView: NSTableView) {
if
0 <= self.tableView.clickedRow,
let identifier = self.profileIdentifier(atRow: self.tableView.clickedRow) {
ProfileController.sharedInstance.editProfile(withIdentifier: identifier)
} else {
Log.shared.error(message: "Failed to get identifier for selected profile.", category: String(describing: self))
}
}
// MARK: -
// MARK: Notification Functions
@objc func didRemoveProfilesFromGroup(_ notification: NSNotification?) {
guard let group = notification?.object as? OutlineViewChildItem, group.identifier == self.selectedProfileGroup?.identifier else {
return
}
if
let userInfo = notification?.userInfo,
let indexSet = userInfo[NotificationKey.indexSet] as? IndexSet,
let indexLast = indexSet.last,
let profileIdentifiers = self.selectedProfileGroup?.profileIdentifiers,
!profileIdentifiers.isEmpty {
var newIndex = (indexLast - indexSet.count)
if newIndex < 0 { newIndex = 0 }
self.tableView.reloadData()
self.tableView.selectRowIndexes(IndexSet(integer: newIndex), byExtendingSelection: false)
}
self.tableViewSelectionDidChange(Notification(name: .emptyNotification))
}
@objc func didSaveProfile(_ notification: NSNotification?) {
if
let userInfo = notification?.userInfo,
let profileIdentifier = userInfo[NotificationKey.identifier] as? UUID,
let groupProfileIdentifiers = self.selectedProfileGroup?.profileIdentifiers,
groupProfileIdentifiers.contains(profileIdentifier) {
self.reloadTableView()
}
}
// -------------------------------------------------------------------------
// Convenience method to reaload data in table view and keep current selection
// -------------------------------------------------------------------------
private func reloadTableView(updateSelection: Bool = true) {
var rowIndexesToSelect: IndexSet?
// ---------------------------------------------------------------------
// Verify that the group has atleast one identifier, else just reload and don't select anything
// ---------------------------------------------------------------------
guard let groupProfileIdentifiers = self.selectedProfileGroup?.profileIdentifiers, !groupProfileIdentifiers.isEmpty else {
self.tableView.reloadData()
return
}
// ---------------------------------------------------------------------
// Get the indexes of the currently selected profile(s)
// ---------------------------------------------------------------------
if let selectedIdentifiers = self.selectedProfileIdentitifers {
rowIndexesToSelect = groupProfileIdentifiers.indexes(ofItems: selectedIdentifiers)
}
self.tableView.reloadData()
// ---------------------------------------------------------------------
// Select all currently selected profiles that exist in the group
// ---------------------------------------------------------------------
if let indexes = rowIndexesToSelect {
self.updateSelectedProfileIdentifiers = updateSelection
self.tableView.selectRowIndexes(indexes, byExtendingSelection: false)
}
}
func removeItems(atIndexes: IndexSet, withIdentifiers: [UUID]) {
if let selectedProfileGroup = self.selectedProfileGroup {
selectedProfileGroup.removeProfiles(atIndexes: atIndexes, withIdentifiers: withIdentifiers)
}
}
func shouldRemoveItems(atIndexes: IndexSet) {
// ---------------------------------------------------------------------
// Verify there is a mainWindow present
// ---------------------------------------------------------------------
guard 0 < atIndexes.count,
let mainWindow = NSApplication.shared.mainWindow,
let selectedProfileGroup = self.selectedProfileGroup else {
return
}
// ---------------------------------------------------------------------
// Create the alert message depending on how may groups were selected
// Currently only one is allowed to be selected, that might change in a future release.
// ---------------------------------------------------------------------
var identifiers = [UUID]()
var alertMessage = ""
var alertInformativeText = ""
if selectedProfileGroup is MainWindowAllProfilesGroup {
if atIndexes.count == 1 {
let identifier = selectedProfileGroup.profileIdentifiers[atIndexes.first!]
identifiers.append(identifier)
let title = ProfileController.sharedInstance.titleOfProfile(withIdentifier: identifier)
alertMessage = NSLocalizedString("Are you sure you want to delete the profile \"\(title ?? identifier.uuidString)\"?", comment: "")
alertInformativeText = NSLocalizedString("This cannot be undone", comment: "")
} else {
alertMessage = NSLocalizedString("Are you sure you want to delete the following profiles?", comment: "")
for index in atIndexes {
let identifier = selectedProfileGroup.profileIdentifiers[index]
identifiers.append(identifier)
let title = ProfileController.sharedInstance.titleOfProfile(withIdentifier: identifier)
alertInformativeText += "\t\(title ?? identifier.uuidString)\n"
}
alertInformativeText += NSLocalizedString("\nThis cannot be undone", comment: "")
}
} else {
if atIndexes.count == 1 {
let identifier = selectedProfileGroup.profileIdentifiers[atIndexes.first!]
identifiers.append(identifier)
let title = ProfileController.sharedInstance.titleOfProfile(withIdentifier: identifier)
alertMessage = NSLocalizedString("Are you sure you want to remove the profile \"\(title ?? identifier.uuidString)\" from group \"\(selectedProfileGroup.title)\"?", comment: "")
alertInformativeText = NSLocalizedString("The profile will still be available under \"All Profiles\"", comment: "")
} else {
alertMessage = NSLocalizedString("Are you sure you want to remove the following profiles from group \"\(selectedProfileGroup.title)\"?", comment: "")
for index in atIndexes {
let identifier = selectedProfileGroup.profileIdentifiers[index]
identifiers.append(identifier)
let title = ProfileController.sharedInstance.titleOfProfile(withIdentifier: identifier)
alertInformativeText += "\t\(title ?? identifier.uuidString)\n"
}
alertInformativeText += NSLocalizedString("\nAll profiles will still be available under \"All Profiles\"", comment: "")
}
}
// ---------------------------------------------------------------------
// Show remove profile alert to user
// ---------------------------------------------------------------------
self.alert = Alert()
self.alert?.showAlertDelete(message: alertMessage, informativeText: alertInformativeText, window: mainWindow) { delete in
if delete {
self.removeItems(atIndexes: atIndexes, withIdentifiers: identifiers)
}
}
}
func profileIdentifier(atRow: Int) -> UUID? {
if let selectedProfileGroup = self.selectedProfileGroup, atRow < selectedProfileGroup.profileIdentifiers.count {
return selectedProfileGroup.profileIdentifiers[atRow]
}
return nil
}
func profileIdentifiers(atIndexes indexes: IndexSet) -> [UUID]? {
if let selectedProfileGroup = self.selectedProfileGroup {
return selectedProfileGroup.profileIdentifiers.objectsAtIndexes(indexes: indexes)
}
return nil
}
}
extension MainWindowTableViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
if let selectedProfileGroup = self.selectedProfileGroup {
return selectedProfileGroup.profileIdentifiers.count
}
return 0
}
// -------------------------------------------------------------------------
// Drag/Drop Support
// -------------------------------------------------------------------------
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
let pasteboard = info.draggingPasteboard
guard let availableType = pasteboard.availableType(from: kMainWindowDragDropUTIs) else { return NSDragOperation() }
if availableType == .backwardsCompatibleFileURL, pasteboard.canReadObject(forClasses: [NSURL.self], options: kMainWindowDragDropFilteringOptions) {
tableView.setDropRow(-1, dropOperation: .on)
return .copy
}
return NSDragOperation()
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
if let selectedGroup = self.selectedProfileGroup {
return selectedGroup.outlineViewController.outlineView(selectedGroup.outlineViewController.outlineView, acceptDrop: info, item: selectedGroup, childIndex: 0)
}
return false
}
func tableView(_ tableView: NSTableView, updateDraggingItemsForDrag draggingInfo: NSDraggingInfo) {
if let draggingData = draggingInfo.draggingPasteboard.data(forType: .profile) {
do {
let profileIdentifiers = try JSONDecoder().decode([UUID].self, from: draggingData)
draggingInfo.numberOfValidItemsForDrop = profileIdentifiers.count
} catch {
Log.shared.error(message: "Failed to decode dragged item: \(draggingInfo)", category: String(describing: self))
}
}
}
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
guard let allProfileIdentifiers = self.selectedProfileGroup?.profileIdentifiers else { return false }
do {
let encodedData = try JSONEncoder().encode(allProfileIdentifiers.objectsAtIndexes(indexes: rowIndexes))
pboard.clearContents()
pboard.declareTypes([.profile], owner: nil)
pboard.setData(encodedData, forType: .profile)
} catch {
Log.shared.error(message: "Failed to encode payloads with error: \(error)", category: String(describing: self))
}
return true
}
func tableView(_ tableView: NSTableView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
if operation == .move {
// -----------------------------------------------------------------
// Verify a group is selected and editable (as we are to remove items from this group)
// -----------------------------------------------------------------
guard let selectedProfileGroup = self.selectedProfileGroup, selectedProfileGroup.isEditable else {
return
}
// -----------------------------------------------------------------
// Verify a valid profile identifier array is passed
// -----------------------------------------------------------------
guard let draggingData = session.draggingPasteboard.data(forType: .profile) else {
return
}
do {
let profileIdentifiers = try JSONDecoder().decode([UUID].self, from: draggingData)
// -----------------------------------------------------------------
// Remove the passed profile identifiers from the current group
// -----------------------------------------------------------------
selectedProfileGroup.removeProfiles(withIdentifiers: profileIdentifiers)
reloadTableView()
} catch {
Log.shared.error(message: "Failed to decode dragged items", category: String(describing: self))
}
}
}
}
// FIXME: A "bug" where if you select 4 profiles in one group, then select another group where only 1 profile of the four is present,
// then if you click that profile when it's selected the selection doesnt change, as it is the only selection, even if the internal selection state is 4 and won't change.
// You need to click another profile or outside to get the selection to update. This should be fixed
extension MainWindowTableViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
36
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let selectedProfileGroup = self.selectedProfileGroup, row < selectedProfileGroup.profileIdentifiers.count else {
return nil
}
let identifier = selectedProfileGroup.profileIdentifiers[row]
guard let profile = ProfileController.sharedInstance.profile(withIdentifier: identifier) else { return nil }
return self.cellView.cellView(title: profile.settings.title, identifier: identifier, payloadCount: profile.enabledPayloadsCount, errorCount: 0, versionFormatSupported: profile.versionFormatSupported)
}
func tableViewSelectionDidChange(_ notification: Notification) {
if self.updateSelectedProfileIdentifiers {
guard let profileIdentifiers = self.selectedProfileGroup?.profileIdentifiers as NSArray?,
let selectedProfileIdentifiers = profileIdentifiers.objects(at: self.tableView.selectedRowIndexes) as? [UUID] else {
return
}
self.selectedProfileIdentitifers = selectedProfileIdentifiers
// FIXME: Replace this with a delegate call maybe? If it's only there to update selection of the preview
NotificationCenter.default.post(name: .didChangeProfileSelection, object: self, userInfo: [NotificationKey.identifiers: selectedProfileIdentifiers,
NotificationKey.indexSet: self.tableView.selectedRowIndexes])
} else {
self.updateSelectedProfileIdentifiers = true
}
}
}
class MainWindowTableView: NSTableView {
// MARK: -
// MARK: Variables
var clickedProfile: UUID?
var clickedProfileRow: Int = -1
var clickedProfileInSelection: Bool = false
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(frame: NSRect.zero)
}
// -------------------------------------------------------------------------
// Override menu(for event:) to show a contextual menu
// -------------------------------------------------------------------------
override func menu(for event: NSEvent) -> NSMenu? {
// ---------------------------------------------------------------------
// Get row that was clicked
// ---------------------------------------------------------------------
let point = self.convert(event.locationInWindow, from: nil)
self.clickedProfileRow = self.row(at: point)
if self.clickedProfileRow == -1 {
return nil
}
// ---------------------------------------------------------------------
// Verify a MainWindowLibraryGroup was clicked, else don't return a menu
// ---------------------------------------------------------------------
guard
let delegate = self.delegate as? MainWindowTableViewDelegate,
let clickedProfileIdentifier = delegate.profileIdentifier(atRow: self.clickedProfileRow) else {
return nil
}
self.clickedProfile = clickedProfileIdentifier
let selectedRowIndexes = self.selectedRowIndexes
/*
TODO: Here I wanted to draw the blue focus ring around the views affected by the right click action.
It should do that by defaut (?) but doesn't. I haven't found a good way to force that either.
if let clickedView = self.rowView(atRow: self.clickedProfileRow, makeIfNecessary: false) {
clickedView.focusRingType = .exterior
}
*/
// ---------------------------------------------------------------------
// Create menu
// ---------------------------------------------------------------------
let menu = NSMenu()
// ---------------------------------------------------------------------
// Get the clicked profile's title
// ---------------------------------------------------------------------
let profileTitle = ProfileController.sharedInstance.titleOfProfile(withIdentifier: clickedProfileIdentifier) ?? clickedProfileIdentifier.uuidString
// ---------------------------------------------------------------------
// Add item: "Edit <Profile>"
// ---------------------------------------------------------------------
let menuItemEdit = NSMenuItem()
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
menuItemEdit.title = NSLocalizedString("Edit \(selectedRowIndexes.count) Profiles", comment: "")
} else {
menuItemEdit.title = NSLocalizedString("Edit \"\(profileTitle)\"", comment: "")
}
menuItemEdit.identifier = NSUserInterfaceItemIdentifier("edit")
menuItemEdit.target = self
menuItemEdit.action = #selector(self.editProfile(_:))
menu.addItem(menuItemEdit)
// ---------------------------------------------------------------------
// Add item: "Duplicate <Profile>"
// ---------------------------------------------------------------------
let menuItemDuplicate = NSMenuItem()
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
menuItemDuplicate.title = NSLocalizedString("Duplicate", comment: "")
} else {
menuItemDuplicate.title = NSLocalizedString("Duplicate \"\(profileTitle)\"", comment: "")
}
menuItemDuplicate.identifier = .menuItemDuplicate
menuItemDuplicate.target = self
menuItemDuplicate.action = #selector(self.duplicateProfile(_:))
menu.addItem(menuItemDuplicate)
// ---------------------------------------------------------------------
// Add item: "Export <Profile>"
// ---------------------------------------------------------------------
let menuItemExport = NSMenuItem()
// FIXME: Does not currently support exporting multiple profiles.
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
menuItemExport.title = NSLocalizedString("Export", comment: "")
} else {
menuItemExport.title = NSLocalizedString("Export \"\(profileTitle)\"", comment: "")
}
menuItemExport.identifier = .menuItemExport // NSUserInterfaceItemIdentifier("export")
menuItemExport.target = self
menuItemExport.action = #selector(self.exportProfile(_:))
menu.addItem(menuItemExport)
// ---------------------------------------------------------------------
// Add item: "Show In Finder"
// ---------------------------------------------------------------------
let menuItemShowInFinder = NSMenuItem()
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
menuItemShowInFinder.title = NSLocalizedString("Show \(selectedRowIndexes.count) Profiles In Finder", comment: "")
} else {
menuItemShowInFinder.title = NSLocalizedString("Show \"\(profileTitle)\" In Finder", comment: "")
}
menuItemShowInFinder.identifier = NSUserInterfaceItemIdentifier("showInFinder")
menuItemShowInFinder.target = self
menuItemShowInFinder.action = #selector(self.showInFinder(_:))
menu.addItem(menuItemShowInFinder)
// ---------------------------------------------------------------------
// Add item: "Delete"
// ---------------------------------------------------------------------
var deleteString: String
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
deleteString = NSLocalizedString("Delete \(selectedRowIndexes.count) Profiles", comment: "")
} else {
deleteString = NSLocalizedString("Delete", comment: "")
}
let menuItemDelete = NSMenuItem()
menuItemDelete.title = deleteString
menuItemDelete.identifier = NSUserInterfaceItemIdentifier("delete")
menuItemDelete.target = self
menuItemDelete.action = #selector(self.removeSelectedProfiles(_:))
menu.addItem(menuItemDelete)
// ---------------------------------------------------------------------
// Return menu
// ---------------------------------------------------------------------
return menu
}
// -------------------------------------------------------------------------
// Override keyDown to catch backspace to delete item in table view
// -------------------------------------------------------------------------
override func keyDown(with event: NSEvent) {
if event.charactersIgnoringModifiers == String(Character(UnicodeScalar(NSEvent.SpecialKey.delete.rawValue)!)) {
if let delegate = self.delegate as? MainWindowTableViewDelegate, 0 < self.selectedRowIndexes.count {
delegate.shouldRemoveItems(atIndexes: self.selectedRowIndexes)
}
}
super.keyDown(with: event)
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.identifier {
case .menuItemDuplicate?,
.menuItemExport?: // "export":
return (self.selectedRowIndexes.contains(self.clickedProfileRow) && 1 < self.selectedRowIndexes.count) ? false : true
default:
return true
}
}
@objc func editProfile(_ sender: NSTableView?) {
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
guard let delegate = self.delegate as? MainWindowTableViewDelegate else { return }
for row in self.selectedRowIndexes {
if let profileIdentifier = delegate.profileIdentifier(atRow: row) {
ProfileController.sharedInstance.editProfile(withIdentifier: profileIdentifier)
}
}
} else if let clickedIdentifier = self.clickedProfile {
ProfileController.sharedInstance.editProfile(withIdentifier: clickedIdentifier)
}
}
@objc func duplicateProfile(_ sender: NSTableView?) {
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
guard let delegate = self.delegate as? MainWindowTableViewDelegate else { return }
for row in self.selectedRowIndexes {
if let profileIdentifier = delegate.profileIdentifier(atRow: row) {
ProfileController.sharedInstance.duplicateProfile(withIdentifier: profileIdentifier, promptWindow: nil)
}
}
} else if let clickedIdentifier = self.clickedProfile {
ProfileController.sharedInstance.duplicateProfile(withIdentifier: clickedIdentifier, promptWindow: nil)
}
}
@objc func exportProfile(_ sender: NSTableView?) {
if let clickedIdentifier = self.clickedProfile {
ProfileController.sharedInstance.exportProfile(withIdentifier: clickedIdentifier, promptWindow: nil)
}
}
@objc func showInFinder(_ sender: NSTableView?) {
var profileURLs = [URL]()
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
guard let delegate = self.delegate as? MainWindowTableViewDelegate else { return }
for row in self.selectedRowIndexes {
if
let profileIdentifier = delegate.profileIdentifier(atRow: row),
let profile = ProfileController.sharedInstance.profile(withIdentifier: profileIdentifier),
let profileURL = profile.fileURL {
profileURLs.append(profileURL)
}
}
} else if
let clickedIdentifier = self.clickedProfile,
let profile = ProfileController.sharedInstance.profile(withIdentifier: clickedIdentifier),
let profileURL = profile.fileURL {
profileURLs.append(profileURL)
}
if !profileURLs.isEmpty {
NSWorkspace.shared.activateFileViewerSelecting(profileURLs)
}
}
@objc func removeSelectedProfiles(_ sender: Any?) {
guard let delegate = self.delegate as? MainWindowTableViewDelegate else { return }
if 1 < selectedRowIndexes.count, selectedRowIndexes.contains(self.clickedProfileRow) {
delegate.shouldRemoveItems(atIndexes: self.selectedRowIndexes)
} else {
if self.clickedProfile != nil, self.clickedProfileRow != -1 {
delegate.shouldRemoveItems(atIndexes: IndexSet(integer: self.clickedProfileRow))
}
}
}
}
extension MainWindowTableView: NSMenuDelegate {
func menuDidClose(_ menu: NSMenu) {
// ---------------------------------------------------------------------
// Reset variables set when menu was created
// ---------------------------------------------------------------------
self.clickedProfile = nil
self.clickedProfileRow = -1
}
}
| mit | 79ce557996f5e2a5a85ddd0c9f56ac58 | 46.255778 | 207 | 0.566761 | 6.027712 | false | false | false | false |
zisko/swift | test/IRGen/enum_resilience.swift | 1 | 13050 | // 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-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_enum
import resilient_struct
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }>
// CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }>
// Public fixed layout struct contains a public resilient struct,
// cannot use spare bits
// CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }>
// Public resilient struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }>
// Internal fixed layout struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }>
// Public fixed layout struct contains a fixed layout struct,
// can use spare bits
// CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }>
public class Class {}
public struct Reference {
public var n: Class
}
@_fixed_layout public enum Either {
case Left(Reference)
case Right(Reference)
}
public enum ResilientEither {
case Left(Reference)
case Right(Reference)
}
enum InternalEither {
case Left(Reference)
case Right(Reference)
}
@_fixed_layout public struct ReferenceFast {
public var n: Class
}
@_fixed_layout public enum EitherFast {
case Left(ReferenceFast)
case Right(ReferenceFast)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S15enum_resilience25functionWithResilientEnumy010resilient_A06MediumOAEF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithResilientEnum(_ m: Medium) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S14resilient_enum6MediumOMa"()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return m
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S15enum_resilience33functionWithIndirectResilientEnumy010resilient_A00E8ApproachOAEF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach {
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S14resilient_enum16IndirectApproachOMa"()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return ia
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S15enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF"
public func constructResilientEnumNoPayload() -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S14resilient_enum6MediumOMa"()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 17
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 0, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Paper
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S15enum_resilience29constructResilientEnumPayloady010resilient_A06MediumO0G7_struct4SizeVF"
public func constructResilientEnumPayload(_ s: Size) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S16resilient_struct4SizeVMa"()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @"$S14resilient_enum6MediumOMa"()
// CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8***
// CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 17
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 -2, %swift.type* [[METADATA2]])
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Postcard(s)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @"$S15enum_resilience19resilientSwitchTestySi0c1_A06MediumOF"(%swift.opaque* noalias nocapture)
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S14resilient_enum6MediumOMa"()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.opaque* noalias %0, %swift.type* [[METADATA]])
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 15
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* noalias [[ENUM_STORAGE]], %swift.type* [[METADATA]])
// CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [
// CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]]
// CHECK: i32 0, label %[[PAPER_CASE:.*]]
// CHECK: i32 1, label %[[CANVAS_CASE:.*]]
// CHECK: ]
// CHECK: ; <label>:[[PAPER_CASE]]
// CHECK: br label %[[END:.*]]
// CHECK: ; <label>:[[CANVAS_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[PAMPHLET_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[DEFAULT_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[END]]
// CHECK: ret
public func resilientSwitchTest(_ m: Medium) -> Int {
switch m {
case .Paper:
return 1
case .Canvas:
return 2
case .Pamphlet(let m):
return resilientSwitchTest(m)
default:
return 3
}
}
public func reabstraction<T>(_ f: (Medium) -> T) {}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S15enum_resilience25resilientEnumPartialApplyyySi0c1_A06MediumOXEF"(i8*, %swift.opaque*)
public func resilientEnumPartialApply(_ f: (Medium) -> Int) {
// CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_allocObject
// CHECK: call swiftcc void @"$S15enum_resilience13reabstractionyyx010resilient_A06MediumOXElF"(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @"$S14resilient_enum6MediumOSiIgid_ACSiIegir_TRTA" to i8*), %swift.opaque* [[CONTEXT:%.*]], %swift.type* @"$SSiN")
reabstraction(f)
// CHECK: ret void
}
// CHECK-LABEL: define internal swiftcc void @"$S14resilient_enum6MediumOSiIgid_ACSiIegir_TRTA"(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself)
// Enums with resilient payloads from a different resilience domain
// require runtime metadata instantiation, just like generics.
public enum EnumWithResilientPayload {
case OneSize(Size)
case TwoSizes(Size, Size)
}
// Make sure we call a function to access metadata of enums with
// resilient layout.
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @"$S15enum_resilience20getResilientEnumTypeypXpyF"()
// CHECK: [[METADATA:%.*]] = call %swift.type* @"$S15enum_resilience24EnumWithResilientPayloadOMa"()
// CHECK-NEXT: ret %swift.type* [[METADATA]]
public func getResilientEnumType() -> Any.Type {
return EnumWithResilientPayload.self
}
// Public metadata accessor for our resilient enum
// CHECK-LABEL: define{{( protected)?}} %swift.type* @"$S15enum_resilience24EnumWithResilientPayloadOMa"()
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @"$S15enum_resilience24EnumWithResilientPayloadOML"
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @"$S15enum_resilience24EnumWithResilientPayloadOMa.once_token", i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*), i8* undef)
// CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @"$S15enum_resilience24EnumWithResilientPayloadOML"
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// Methods inside extensions of resilient enums fish out type parameters
// from metadata -- make sure we can do that
extension ResilientMultiPayloadGenericEnum {
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @"$S14resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF"(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself)
// CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 2
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
public func getTypeParameter() -> T.Type {
return T.self
}
}
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
// CHECK: call void @swift_initEnumMetadataMultiPayload(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 2, i8*** {{.*}})
public protocol Prot {
}
private enum ProtGenEnumWithSize<T: Prot> {
case c1(s1: Size)
case c2(s2: Size)
}
// CHECK-LABEL: define{{( protected)?}} internal %T15enum_resilience19ProtGenEnumWithSize33_59077B69D65A4A3BEE0C93708067D5F0LLO* @"$S15enum_resilienceytWh2_"(%T15enum_resilience19ProtGenEnumWithSize
// CHECK: ret %T15enum_resilience19ProtGenEnumWithSize33_59077B69D65A4A3BEE0C93708067D5F0LLO* %0
| apache-2.0 | 37bbeeaaf6c5f07122b75c5edbf58277 | 45.942446 | 277 | 0.666054 | 3.412657 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/FeedBack/Controller/FeedBackViewController.swift | 1 | 13086 | //
// FeedBackViewController.swift
// OMS-WH
//
// Created by ___Gwy on 2017/8/21.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class FeedBackViewController: UIViewController {
var sectionIndex :IndexPath?
var orderModel:OrderListModel?
fileprivate var dataSource : DealOrderInfoModel?{
didSet{
setUp()
}
}
///附件信息
fileprivate var attachmentDataSource :Array<AttachmentModel> = [AttachmentModel]()
fileprivate let viewModel = DealOrderVM()
fileprivate let vm = OperInfoViewModel()
//出库单内数据
fileprivate var modifiedinsideModel = [FeedBackMedModel]()
//出库单外数据
fileprivate var modifiedoutsideModel = [FeedBackMedModel]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "报台"
view.addSubview(table)
view.addSubview(confirmBtn)
table.tableHeaderView = headerView
if let soNo = orderModel?.sONo {
viewModel.requestOrderData(soNo: soNo, { (dataSource, error) in
if let dataSource = dataSource {
self.dataSource = dataSource
self.table.reloadData()
}
})
}
NotificationCenter.default.addObserver(self, selector: #selector(attachmentDidFinished), name: NSNotification.Name.AttachmentDidFinished, object: nil)
}
fileprivate func setUp(){
headerView.orderDetailInfo = dataSource
headerView.parentVC = self
getfbOperInfoPreDictory()
}
///列表
fileprivate lazy var table:UITableView = {
let table = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 50), style: .grouped)
table.separatorStyle = .none
table.dataSource = self
table.delegate = self
table.register(DealOrderTableViewCell.self)
return table
}()
///表头信息
fileprivate lazy var headerView:DealOrderHeaderView = {
let headerView = DealOrderHeaderView()
headerView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 85)
headerView.backgroundColor = UIColor.white
return headerView
}()
///确认按钮
fileprivate lazy var confirmBtn:UIButton = {
let btn = UIButton(imageName: "", fontSize: 16, color: UIColor.white, title: "提交", bgColor: kAppearanceColor)
btn.frame = CGRect(x: 0, y: kScreenHeight - 50 - 64, width: kScreenWidth, height: 50)
btn.backgroundColor = kAppearanceColor
btn.addTarget(self, action: #selector(FeedBackViewController.submitToNetWork), for: .touchUpInside)
return btn
}()
@objc private func submitToNetWork(){
if let operSOIAOrgCode = fbOperInfoPreDictory["operSOIAOrgCode"] {
vm.iaOrgCertCheck(operSOIAOrgCode: operSOIAOrgCode) { (iares) in
self.vm.vmOrgCertCheck(dataSource: self.dataSource) { (res1,res2) in
self.vm.ptOrgCertCheckt(dataSource: self.dataSource, finished: { (ptres) in
if ptres && res1 && res2 && iares{
self.dealData()
}
})
}
}
}else{
SVProgressHUD.showError("请先选择配送商")
}
}
fileprivate func dealData(){
MedLog(message: fbOperInfoPreDictory)
var params : [String:Any] = [:]
fbOperInfoPreDictory.forEach({ (arg) in
let (key, value) = arg
params[key] = value
})
if attachmentDataSource.count > 0 {
params["attachmentList"] = attachmentLists()
}
if modifiedoutsideModel.count <= 0 && modifiedinsideModel.count <= 0 {
//没有物料
let reason = ReasonForMetailEmptyViewController()
reason.callBackSelectedReason = { reason,reasonMark in
params["opFdMedMaterialEmptyReason"] = reason
params["opFdMedMaterialEmptyReasonRemark"] = reasonMark
self.emptyMedMaterialSubmit(params: params)
}
self.navigationController?.pushViewController(reason, animated: false)
}else{
let notInSODetailList = modifiedoutsideModel.filter({$0.useQty > 0}).map({$0.toJSON()})
let inSODetailList = modifiedinsideModel.filter({$0.useQty > 0}).map({$0.toJSON()})
params["notInSODetailList"] = notInSODetailList
params["inSODetailList"] = inSODetailList
MedLog(message: params)
let online = "oms-api-v3/order/operation/feedBackOrderSubmit"
viewModel.submitToNetwork(url:online,paramters: params) { (finish, _) in
if finish {
SVProgressHUD.showSuccess("订单\(self.dataSource?.sONo ?? "")报台成功!")
NotificationCenter.default.post(name: NSNotification.Name.OrderSubmitFinished, object: nil, userInfo: ["OrderSubmitFinished":self.sectionIndex ?? ""])
self.navigationController?.popViewController(animated: true)
}else{
SVProgressHUD.showError("请求出错了")
}
}
}
}
fileprivate func emptyMedMaterialSubmit(params : [String:Any]){
viewModel.medMetailEmptySubmit(paramters: params) { (result, error) in
if result {
SVProgressHUD.showSuccess("订单\(self.dataSource?.sONo ?? "")报台成功!")
NotificationCenter.default.post(name: NSNotification.Name.OrderSubmitFinished, object: nil, userInfo: ["OrderSubmitFinished":self.sectionIndex ?? ""])
self.navigationController?.popViewController(animated: false)
}else{
SVProgressHUD.showError("请求出错了")
}
}
}
//手术信息 相关
fileprivate let feedBacImageArr = [#imageLiteral(resourceName: "to_operationInfo"),#imageLiteral(resourceName: "od_feedback"),#imageLiteral(resourceName: "to_instrumentConsumeInfo"),#imageLiteral(resourceName: "to_instrumentConsumeInfo"),#imageLiteral(resourceName: "to_attachment")]
fileprivate let feedBackNameArr = ["手术信息","患者信息","器械消耗信息(出库单内)","器械消耗信息(出库单外)","附件信息"]
var fbOperInfoPreDictory : [String:String] = ["patientIDType":"IDDXCGRID","retrieveIsNeeded":"N"]
fileprivate func getfbOperInfoPreDictory() {
fbOperInfoPreDictory["sONo"] = dataSource?.sONo
fbOperInfoPreDictory["dTName"] = dataSource?.initDTCodeName
fbOperInfoPreDictory["dTCode"] = dataSource?.initDTCode
fbOperInfoPreDictory["hPName"] = dataSource?.initHPCodeName
fbOperInfoPreDictory["hPCode"] = dataSource?.initHPCode
fbOperInfoPreDictory["wardDeptCode"] = dataSource?.initWardDeptCode
fbOperInfoPreDictory["wardDeptCodeName"] = dataSource?.initWardDeptCodeName
fbOperInfoPreDictory["operSOIAOrgCode"] = dataSource?.operSOIAOrgCode
fbOperInfoPreDictory["operSOIAOrgCodeName"] = dataSource?.operSOIAOrgCodeName
fbOperInfoPreDictory["operationDate"] = dataSource?.operationDate
fbOperInfoPreDictory["patientDiseaseInfo"] = dataSource?.patientDiseaseInfo
fbOperInfoPreDictory["operationFeedbackRemark"] = dataSource?.operationFeedbackRemark
fbOperInfoPreDictory["patientName"] = dataSource?.patientName
fbOperInfoPreDictory["patientAge"] = "\(dataSource?.patientAge ?? 0)"
fbOperInfoPreDictory["patientSex"] = dataSource?.patientSex
fbOperInfoPreDictory["patientSocialInsuranceTypeName"] = dataSource?.patientSocialInsuranceTypeName
fbOperInfoPreDictory["patientIDTypeName"] = dataSource?.patientIDTypeName
fbOperInfoPreDictory["patientIDNo"] = dataSource?.patientIDNo
fbOperInfoPreDictory["patientEntryDate"] = dataSource?.patientEntryDate
fbOperInfoPreDictory["patientHPNo"] = dataSource?.patientHPNo
fbOperInfoPreDictory["patientWard"] = dataSource?.patientWard
fbOperInfoPreDictory["patientRoom"] = dataSource?.patientRoom
fbOperInfoPreDictory["patientBedNo"] = dataSource?.patientBedNo
fbOperInfoPreDictory["retrieveIsNeeded"] = dataSource?.retrieveIsNeeded
fbOperInfoPreDictory["retrieveEstDate"] = dataSource?.retrieveEstDate
fbOperInfoPreDictory["retrieveDesc"] = dataSource?.retrieveDesc
fbOperInfoPreDictory["patientInfectionInfo"] = dataSource?.patientInfectionInfo
fbOperInfoPreDictory["patientTel"] = dataSource?.patientTel
fbOperInfoPreDictory["patientAddress"] = dataSource?.patientAddress
fbOperInfoPreDictory["patientIsInfection"] = dataSource?.patientIsInfection
}
}
extension FeedBackViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DealOrderTableViewCell") as! DealOrderTableViewCell
cell.nameLB.text = feedBackNameArr[indexPath.row]
cell.imageName.image = feedBacImageArr[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
switch indexPath.row {
case 0:
operationInfoEvent()
case 1:
patientInfo()
case 2:
istrumentInfoInside()
case 3:
istrumentInfoOutside()
default:
attachmentEvent()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 5
}
//附件
fileprivate func attachmentLists() ->[[String:Any]] {
var attachmentList : [[String:Any]] = [[String:Any]]()
for item in self.attachmentDataSource {
attachmentList.append(item.toDict())
}
return attachmentList
}
fileprivate func operationInfoEvent(){
let operInfo = FeedBackOperInfoViewController()
operInfo.dealOrderModel = dataSource
operInfo.feedBackOperInfoDictory = fbOperInfoPreDictory
operInfo.modifiedDictory = { (modifiedDic:[String:String]) in
self.fbOperInfoPreDictory = modifiedDic
}
self.navigationController?.pushViewController(operInfo, animated: true)
}
fileprivate func patientInfo(){
let pateintVC = FeedBackPateintViewController()
pateintVC.dealOrderModel = dataSource
pateintVC.modifiedDictory = { (modifiedDic:[String:String]) in
for (k, v) in modifiedDic {
self.fbOperInfoPreDictory.updateValue(v, forKey: k)
}
}
pateintVC.feedBackPatientInfoDictory = fbOperInfoPreDictory
self.navigationController?.pushViewController(pateintVC, animated: true)
}
fileprivate func istrumentInfoInside(){
let instrumentConsumption = InstrumentConsumptionInfoViewController()
instrumentConsumption.vcType = .insideOutBound
instrumentConsumption.orderModel = orderModel
instrumentConsumption.modifiedModel = { (modifiedModel:[FeedBackMedModel]) in
self.modifiedinsideModel = modifiedModel
}
instrumentConsumption.dataSource = modifiedinsideModel
self.navigationController?.pushViewController(instrumentConsumption, animated: true)
}
fileprivate func istrumentInfoOutside(){
let instrumentConsumption = InstrumentConsumptionInfoViewController()
instrumentConsumption.vcType = .outSideOutBound
instrumentConsumption.orderModel = orderModel
instrumentConsumption.modifiedModel = { (modifiedModel:[FeedBackMedModel]) in
self.modifiedoutsideModel = modifiedModel
}
instrumentConsumption.notInSODetailList = modifiedoutsideModel
self.navigationController?.pushViewController(instrumentConsumption, animated: true)
}
fileprivate func attachmentEvent(){
let attachment = storyboard(storyboardName: "Attachment", viewControllerName: "AttachmentViewController") as! AttachmentViewController
attachment.attachmentDataSource = attachmentDataSource
self.navigationController?.pushViewController(attachment, animated: true)
}
@objc func attachmentDidFinished(notification:Notification) {
let dic = notification.userInfo as? [String:AnyObject]
if let dic = dic {
let model = dic["AttachmentDidFinished"] as? [AttachmentModel]
if let attachment = model {
attachmentDataSource = attachment
}
}
}
}
| mit | 47959b7f213953bd907811dff1a55254 | 43.362069 | 287 | 0.661174 | 4.70212 | false | false | false | false |
scottrhoyt/Noonian | Sources/NoonianKit/Utilities/Tasks/CommandTask.swift | 1 | 1281 | //
// BeforeBuildTask.swift
// Noonian
//
// Created by Scott Hoyt on 11/2/16.
// Copyright © 2016 Scott Hoyt. All rights reserved.
//
import Foundation
public struct CommandTask: ConfigurableItem, Equatable {
let name: String
let commands: [String]
public init(name: String, commands: [String]) {
self.name = name
self.commands = commands
}
public init(name: String, commands: [ShellCommand]) {
self.init(name: name, commands: commands.map { $0.join() })
}
init(name: String, configuration: Any) throws {
// Configuration could be either a string or an array of strings.
// If it is neither, then we have to throw an error.
var commands = [String]()
if let stringCommand = configuration as? String {
commands.append(stringCommand)
} else if let arrayCommands = configuration as? [String] {
commands += arrayCommands
} else {
throw UtilityError.cannotConfigure(item: name, with: configuration)
}
self.init(name: name, commands: commands)
}
}
// MARK: - CommandTask: Equatable
public func == (lhs: CommandTask, rhs: CommandTask) -> Bool {
return lhs.name == rhs.name &&
lhs.commands == rhs.commands
}
| mit | e23e7ff6ca40080578b616028b650700 | 27.444444 | 79 | 0.627344 | 4.050633 | false | true | false | false |
Nyx0uf/MPDRemote | src/iOS/views/AlbumHeaderView.swift | 1 | 4913 | // AlbumHeaderView.swift
// Copyright (c) 2017 Nyx0uf
//
// 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
final class AlbumHeaderView : UIView
{
// MARK: - Public properties
// Album cover
private(set) var image: UIImage!
// Album title
@IBOutlet private(set) var lblTitle: TopAlignedLabel!
// Album artist
@IBOutlet private(set) var lblArtist: UILabel!
// Album genre
@IBOutlet private(set) var lblGenre: UILabel!
// Album year
@IBOutlet private(set) var lblYear: UILabel!
// Size of the cover
var coverSize: CGSize!
// MARK: - Initializers
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
// MARK: - Drawing
override func draw(_ dirtyRect: CGRect)
{
guard let _ = image else {return}
let imageRect = CGRect(.zero, coverSize)
image.draw(in: imageRect, blendMode: .sourceAtop, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.saveGState()
context?.clip(to: imageRect)
let startPoint = CGPoint(imageRect.minX, imageRect.midY)
let endPoint = CGPoint(imageRect.maxX, imageRect.midY)
let color = backgroundColor!
let gradientColors: [CGColor] = [color.withAlphaComponent(0.05).cgColor, color.withAlphaComponent(0.75).cgColor, color.withAlphaComponent(0.9).cgColor]
let locations: [CGFloat] = [0.0, 0.9, 1.0]
let gradient = CGGradient(colorsSpace: CGColorSpace.NYXAppropriateColorSpace(), colors: gradientColors as CFArray, locations: locations)
context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
context?.restoreGState()
}
// MARK: - Public
func updateHeaderWithAlbum(_ album: Album)
{
// Set cover
var image: UIImage? = nil
if let coverURL = album.localCoverURL
{
if let cover = UIImage.loadFromFileURL(coverURL)
{
image = cover
}
else
{
let coverSize = NSKeyedUnarchiver.unarchiveObject(with: Settings.shared.data(forKey: kNYXPrefCoversSize)!) as! NSValue
image = generateCoverForAlbum(album, size: coverSize.cgSizeValue)
}
}
else
{
let coverSize = NSKeyedUnarchiver.unarchiveObject(with: Settings.shared.data(forKey: kNYXPrefCoversSize)!) as! NSValue
image = generateCoverForAlbum(album, size: coverSize.cgSizeValue)
}
self.image = image
// Analyze colors
let x = KawaiiColors(image: image!, precision: 8, samplingEdge: .right)
x.analyze()
backgroundColor = x.edgeColor
lblTitle.textColor = x.primaryColor
lblTitle.backgroundColor = backgroundColor
lblArtist.textColor = x.secondaryColor
lblArtist.backgroundColor = backgroundColor
lblGenre.textColor = x.thirdColor
lblGenre.backgroundColor = backgroundColor
lblYear.textColor = x.thirdColor
lblYear.backgroundColor = backgroundColor
setNeedsDisplay()
// Update frame for title / artist
let s = album.name as NSString
let width = frame.width - (coverSize.width + 8.0)
let r = s.boundingRect(with: CGSize(width, 40.0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : lblTitle.font], context: nil)
lblTitle.frame = CGRect(coverSize.width + 4.0, 4.0, ceil(r.width), ceil(r.height))
lblArtist.frame = CGRect(coverSize.width + 4.0, lblTitle.bottom + 4.0, width - (coverSize.width + 8.0), 18.0)
lblTitle.text = album.name
lblArtist.text = album.artist
lblGenre.text = album.genre
lblYear.text = album.year
// Accessibility
var stra = "\(album.name) \(NYXLocalizedString("lbl_by")) \(album.artist)\n"
if let tracks = album.tracks
{
stra += "\(tracks.count) \(tracks.count == 1 ? NYXLocalizedString("lbl_track") : NYXLocalizedString("lbl_tracks"))\n"
let total = tracks.reduce(Duration(seconds: 0)){$0 + $1.duration}
let minutes = total.seconds / 60
stra += "\(minutes) \(minutes == 1 ? NYXLocalizedString("lbl_minute") : NYXLocalizedString("lbl_minutes"))\n"
}
accessibilityLabel = stra
}
}
| mit | 449b991b925870bd1694e3d190e1d615 | 36.503817 | 157 | 0.733768 | 3.710725 | false | false | false | false |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/EVENotifications.swift | 1 | 1620 | //
// EVENotifications.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVENotificationsItem: EVEObject {
public var notificationID: Int64 = 0
public var typeID: Int = 0
public var senderID: Int64 = 0
public var senderName: String = ""
public var sentDate: Date = Date.distantPast
public var read: Bool = false
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"notificationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"senderID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"senderName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"sentDate":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"read":EVESchemeElementType.Bool(elementName:nil, transformer:nil),
]
}
}
public class EVENotifications: EVEResult {
public var notifications: [EVENotificationsItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"notifications":EVESchemeElementType.Rowset(elementName: nil, type: EVENotificationsItem.self, transformer: nil),
]
}
}
| mit | e95b4dd2302664b1d7c631dd62781a3d | 27.910714 | 116 | 0.746757 | 3.800469 | false | false | false | false |
mozilla-mobile/firefox-ios | Push/PushCrypto.swift | 2 | 14362 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
/// Class to wrap ecec which does the encryption, decryption and key generation with OpenSSL.
/// This supports aesgcm and the newer aes128gcm.
/// For each standard of decryption, two methods are supplied: one with Data parameters and return value,
/// and one with a String based one.
class PushCrypto {
// Stateless, we provide a singleton for convenience.
public static var sharedInstance = PushCrypto()
}
// AES128GCM
extension PushCrypto {
func aes128gcm(payload data: String, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let payload = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aes128gcm(payload: payload,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aes128gcm(payload: Data, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
var plaintextLen = ece_aes128gcm_plaintext_max_length(payload.getBytes(), payload.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let err = ece_webpush_aes128gcm_decrypt(
rawRecvPrivKey.getBytes(),
rawRecvPrivKey.count,
authSecret.getBytes(),
authSecret.count,
payload.getBytes(),
payload.count,
&plaintext,
&plaintextLen)
if err != ECE_OK {
throw PushCryptoError.decryptionError(errCode: err)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aes128gcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int = 4096, padLen: Int = 0) throws -> String {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let payloadData = try aes128gcm(plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs,
padLen: padLen)
guard let payload = payloadData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return payload
}
func aes128gcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int = 4096, padLen: Int = 0) throws -> Data {
let rs = UInt32(rsInt)
// rs needs to be >= 18.
assert(rsInt >= Int(ECE_AES128GCM_MIN_RS))
var payloadLen = ece_aes128gcm_payload_max_length(rs, padLen, plaintext.count) + 1
var payload = [UInt8](repeating: 0, count: payloadLen)
let err = ece_webpush_aes128gcm_encrypt(
rawRecvPubKey.getBytes(),
rawRecvPubKey.count,
authSecret.getBytes(),
authSecret.count,
rs,
padLen,
plaintext.getBytes(),
plaintext.count,
&payload,
&payloadLen)
if err != ECE_OK {
throw PushCryptoError.encryptionError(errCode: err)
}
return Data(bytes: payload, count: payloadLen)
}
}
// AESGCM
extension PushCrypto {
func aesgcm(ciphertext data: String, withHeaders headers: PushCryptoHeaders, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let ciphertext = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aesgcm(ciphertext: ciphertext,
withHeaders: headers,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aesgcm(ciphertext: Data, withHeaders headers: PushCryptoHeaders, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
var rs = UInt32(0)
let paramsErr = ece_webpush_aesgcm_headers_extract_params(
headers.cryptoKey,
headers.encryption,
&salt,
saltLength,
&rawSenderPubKey,
rawSenderPubKeyLength,
&rs)
if paramsErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: paramsErr)
}
var plaintextLen = ece_aesgcm_plaintext_max_length(rs, ciphertext.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let decryptErr = ece_webpush_aesgcm_decrypt(
rawRecvPrivKey.getBytes(),
rawRecvPrivKey.count,
authSecret.getBytes(),
authSecret.count,
&salt,
salt.count,
&rawSenderPubKey,
rawSenderPubKey.count,
rs,
ciphertext.getBytes(),
ciphertext.count,
&plaintext,
&plaintextLen)
if decryptErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: decryptErr)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aesgcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, ciphertext: String) {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let (headers, messageData) = try aesgcm(
plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs,
padLen: padLen)
guard let message = messageData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return (headers, message)
}
func aesgcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, data: Data) {
let rs = UInt32(rsInt)
// rs needs to be >= 3.
assert(rsInt >= Int(ECE_AESGCM_MIN_RS))
var ciphertextLength = ece_aesgcm_ciphertext_max_length(rs, padLen, plaintext.count) + 1
var ciphertext = [UInt8](repeating: 0, count: ciphertextLength)
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
let encryptErr = ece_webpush_aesgcm_encrypt(
rawRecvPubKey.getBytes(),
rawRecvPubKey.count,
authSecret.getBytes(),
authSecret.count,
rs,
padLen,
plaintext.getBytes(),
plaintext.count,
&salt,
saltLength,
&rawSenderPubKey,
rawSenderPubKeyLength,
&ciphertext,
&ciphertextLength)
if encryptErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: encryptErr)
}
var cryptoKeyHeaderLength = 0
var encryptionHeaderLength = 0
let paramsSizeErr = ece_webpush_aesgcm_headers_from_params(
salt,
saltLength,
rawSenderPubKey,
rawSenderPubKeyLength,
rs,
nil,
&cryptoKeyHeaderLength,
nil,
&encryptionHeaderLength)
if paramsSizeErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsSizeErr)
}
var cryptoKeyHeaderBytes = [CChar](repeating: 0, count: cryptoKeyHeaderLength)
var encryptionHeaderBytes = [CChar](repeating: 0, count: encryptionHeaderLength)
let paramsErr = ece_webpush_aesgcm_headers_from_params(
salt,
saltLength,
rawSenderPubKey,
rawSenderPubKeyLength,
rs,
&cryptoKeyHeaderBytes,
&cryptoKeyHeaderLength,
&encryptionHeaderBytes,
&encryptionHeaderLength)
if paramsErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsErr)
}
guard let cryptoKeyHeader = String(data: Data(
bytes: cryptoKeyHeaderBytes,
count: cryptoKeyHeaderLength),
encoding: .ascii),
let encryptionHeader = String(data: Data(
bytes: encryptionHeaderBytes,
count: encryptionHeaderLength),
encoding: .ascii)
else { throw PushCryptoError.base64EncodeError }
let headers = PushCryptoHeaders(encryption: encryptionHeader, cryptoKey: cryptoKeyHeader)
return (headers, Data(bytes: ciphertext, count: ciphertextLength))
}
}
extension PushCrypto {
func generateKeys() throws -> PushKeys {
// The subscription private key. This key should never be sent to the app
// server. It should be persisted with the endpoint and auth secret, and used
// to decrypt all messages sent to the subscription.
let privateKeyLength = Int(ECE_WEBPUSH_PRIVATE_KEY_LENGTH)
var rawRecvPrivKey = [UInt8](repeating: 0, count: privateKeyLength)
// The subscription public key. This key should be sent to the app server,
// and used to encrypt messages. The Push DOM API exposes the public key via
// `pushSubscription.getKey("p256dh")`.
let publicKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawRecvPubKey = [UInt8](repeating: 0, count: publicKeyLength)
// The shared auth secret. This secret should be persisted with the
// subscription information, and sent to the app server. The DOM API exposes
// the auth secret via `pushSubscription.getKey("auth")`.
let authSecretLength = Int(ECE_WEBPUSH_AUTH_SECRET_LENGTH)
var authSecret = [UInt8](repeating: 0, count: authSecretLength)
let err = ece_webpush_generate_keys(
&rawRecvPrivKey,
privateKeyLength,
&rawRecvPubKey,
publicKeyLength,
&authSecret,
authSecretLength)
if err != ECE_OK {
throw PushCryptoError.keyGenerationError(errCode: err)
}
guard let privKey = Data(bytes: rawRecvPrivKey, count: privateKeyLength).base64urlSafeEncodedString,
let pubKey = Data(bytes: rawRecvPubKey, count: publicKeyLength).base64urlSafeEncodedString,
let authKey = Data(bytes: authSecret, count: authSecretLength).base64urlSafeEncodedString
else { throw PushCryptoError.base64EncodeError }
return PushKeys(p256dhPrivateKey: privKey, p256dhPublicKey: pubKey, auth: authKey)
}
}
struct PushKeys {
let p256dhPrivateKey: String
let p256dhPublicKey: String
let auth: String
}
enum PushCryptoError: Error {
case base64DecodeError
case base64EncodeError
case decryptionError(errCode: Int32)
case encryptionError(errCode: Int32)
case keyGenerationError(errCode: Int32)
case utf8EncodingError
}
struct PushCryptoHeaders {
let encryption: String
let cryptoKey: String
}
extension String {
/// Returns a base64 url safe decoding of the given string.
/// The string is allowed to be padded
/// What is padding?: http://stackoverflow.com/a/26632221
var base64urlSafeDecodedData: Data? {
// We call this method twice: once with the last two args as nil, 0 – this gets us the length
// of the decoded string.
let length = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, nil, 0)
guard length > 0 else { return nil }
// The second time, we actually decode, and copy it into a made to measure byte array.
var bytes = [UInt8](repeating: 0, count: length)
let checkLength = ece_base64url_decode(self, self.count, ECE_BASE64URL_REJECT_PADDING, &bytes, length)
guard checkLength == length else { return nil }
return Data(bytes: bytes, count: length)
}
}
extension Data {
/// Returns a base64 url safe encoding of the given data.
var base64urlSafeEncodedString: String? {
let length = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, nil, 0)
guard length > 0 else { return nil }
var bytes = [CChar](repeating: 0, count: length)
let checkLength = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, &bytes, length)
guard checkLength == length else { return nil }
return String(data: Data(bytes: bytes, count: length), encoding: .ascii)
}
}
| mpl-2.0 | 6c8b6a3c51da73ce14c1402efd05c2b8 | 38.021739 | 189 | 0.625487 | 4.507219 | false | false | false | false |
OpenCraft/LocalNotificationManager | LocalNotificationManager/Classes/LocalNotificationRegister.swift | 1 | 3321 | //
// LocalNotificationRegister.swift
// Registration
//
// Created by Cristian Madrid on 2/23/17.
// Copyright © 2017 Unicred Brasil. All rights reserved.
//
import UserNotifications
import UIKit
public protocol LocalNotificationRegister {
init(application: UIApplication)
func register() -> LocalNotificationRegisterFetch
func application(didRegister notificationSettings: UIUserNotificationSettings)
}
class LocalNotificationRegisterFactory {
static func instantiate(application: UIApplication) -> LocalNotificationRegister {
if #available(iOS 10, *) {
return LocalNotificationRegisterNewestiOS(application: application)
}
if #available(iOS 9, *) {
return LocalNotificationRegisterLegacyiOS(application: application)
} else {
return LocalNotificationRegisterLegacyiOS(application: application)
}
}
}
public class LocalNotificationRegisterBase: LocalNotificationRegister {
@discardableResult public func register() -> LocalNotificationRegisterFetch {
fatalError("You must implement this function")
}
fileprivate var application: UIApplication?
fileprivate let fetcher = LocalNotificationRegisterFetch()
required public init(application: UIApplication) {
self.application = application
}
public func application(didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types.contains(.alert) {
self.fetcher.doSuccess()
} else {
self.fetcher.doFailure()
}
}
}
@available(iOS 9, *)
@available(iOS 8, *)
public class LocalNotificationRegisterLegacyiOS: LocalNotificationRegisterBase {
override public func register() -> LocalNotificationRegisterFetch {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
return fetcher
}
}
@available(iOS 10, *)
public class LocalNotificationRegisterNewestiOS: LocalNotificationRegisterBase {
override public func register() -> LocalNotificationRegisterFetch {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.badge, .alert, .sound]) { granted, _ in
if granted {
self.fetcher.doSuccess()
} else {
self.fetcher.doFailure()
}
}
application?.registerForRemoteNotifications()
return fetcher
}
}
public class LocalNotificationRegisterFetch {
private var onSuccessClosure: ((Void) -> Void)? = nil
private var onFailureClosure: ((Void) -> Void)? = nil
@discardableResult func onSuccess(success: @escaping (Void) -> Void) -> Self {
onSuccessClosure = success
return self
}
@discardableResult func onFailure(error: @escaping (Void) -> Void) -> Self {
onFailureClosure = error
return self
}
final fileprivate func doSuccess() {
if let success = onSuccessClosure {
success()
}
}
final fileprivate func doFailure() {
if let failure = onFailureClosure {
failure()
}
}
}
| mit | 2539693e9d3c4d7021bfd89d5399b6da | 30.619048 | 139 | 0.674699 | 5.286624 | false | false | false | false |
Breinify/brein-api-library-ios | BreinifyApi/engine/BreinEngine.swift | 1 | 8700 | //
// Created by Marco Recchioni
// Copyright (c) 2020 Breinify. All rights reserved.
//
import Foundation
/**
Creates the Rest Engine and provides the methods to
invoke activity and lookup calls
*/
public class BreinEngine {
public typealias apiSuccess = (_ result: BreinResult) -> Void
public typealias apiFailure = (_ error: NSDictionary) -> Void
/**
creation of rest engine - currently it is only Alamofire
*/
var restEngine: IRestEngine!
/**
Contains the instance of the locationManager -> this enables the API to
detect the location information if the info.plist of the app has the
permissions.
*/
var locationManager = BreinLocationManager(ignoreLocationRequest: false)
/**
Creates the BreinEngine instance with a given breinEngineType
*/
public init(engineType: BreinEngineType) {
restEngine = URLSessionEngine()
}
/**
Sends an activity to the Breinify server
- Parameter activity: data to be send
- Parameter successBlock : A callback function that is invoked in case of success.
- Parameter failureBlock : A callback function that is invoked in case of an error.
Important:
* due to the fact that the locationManager will invoke CLLocationManager it must run on the
main thread
*/
public func sendActivity(_ activity: BreinActivity!,
success successBlock: @escaping BreinEngine.apiSuccess,
failure failureBlock: @escaping BreinEngine.apiFailure) throws {
if activity != nil {
if activity.getConfig().getWithLocationManagerUsage() == true {
// necessary to invoke CLLocationManager
// need to come back to main thread
DispatchQueue.main.async {
self.locationManager.fetchWithCompletion {
location, error in
// save the retrieved location data
activity.getUser()?.setLocationData(location)
// print("latitude is: \(location?.coordinate.latitude)")
// print("longitude is: \(location?.coordinate.longitude)")
do {
try self.restEngine.doRequest(activity,
success: successBlock,
failure: failureBlock)
} catch {
BreinLogger.shared.log("Breinify activity with locationmanger usage error is: \(error)")
}
}
}
} else {
do {
try restEngine.doRequest(activity,
success: successBlock,
failure: failureBlock)
} catch {
BreinLogger.shared.log("Breinify doRequest error is: \(error)")
}
}
}
}
/**
Performs a temporalData request
- Parameter breinTemporalData: contains the appropriate data in order to perform the request
- Parameter successBlock : A callback function that is invoked in case of success.
- Parameter failureBlock : A callback function that is invoked in case of an error.
- returns: result from Breinify engine
*/
public func performTemporalDataRequest(_ breinTemporalData: BreinTemporalData!,
success successBlock: @escaping apiSuccess,
failure failureBlock: @escaping apiFailure) throws {
if breinTemporalData != nil {
// necessary to invoke CLLocationManager
// need to come back to main thread
DispatchQueue.main.async {
self.locationManager.fetchWithCompletion {
location, error in
// save the retrieved location data
breinTemporalData.getUser()?.setLocationData(location)
BreinLogger.shared.log("Breinify latitude is: \(location?.coordinate.latitude ?? -1)")
BreinLogger.shared.log("Breinify longitude is: \(location?.coordinate.longitude ?? -1)")
do {
return try self.restEngine.doTemporalDataRequest(breinTemporalData,
success: successBlock,
failure: failureBlock)
} catch {
BreinLogger.shared.log("Breinify performTemporalDataRequest error is: \(error)")
}
}
}
}
}
/**
Performs a lookup. This will be delegated to the configured restEngine.
- Parameter breinLookup: contains the appropriate data for the lookup request
- Parameter successBlock : A callback function that is invoked in case of success.
- Parameter failureBlock : A callback function that is invoked in case of an error.
- returns: if succeeded a BreinResponse object or null
*/
public func performLookUp(_ breinLookup: BreinLookup!,
success successBlock: @escaping apiSuccess,
failure failureBlock: @escaping apiFailure) throws {
if breinLookup != nil {
// necessary to invoke CLLocationManager
// need to come back to main thread
DispatchQueue.main.async {
self.locationManager.fetchWithCompletion {
location, error in
// save the retrieved location data
breinLookup.getUser()?.setLocationData(location)
BreinLogger.shared.log("Breinify latitude is: \(String(describing: location?.coordinate.latitude))")
BreinLogger.shared.log("Breinify longitude is: \(String(describing: location?.coordinate.longitude))")
do {
if breinLookup != nil {
return try self.restEngine.doLookup(breinLookup,
success: successBlock,
failure: failureBlock)
}
} catch {
BreinLogger.shared.log("Breinify performLookUp error is: \(error)")
}
}
}
}
}
/**
Invokes the recommendation request
- Parameter breinRecommendation: contains the breinRecommendation object
- Parameter successBlock : A callback function that is invoked in case of success.
- Parameter failureBlock : A callback function that is invoked in case of an error.
- return result of request or null
*/
public func invokeRecommendation(_ breinRecommendation: BreinRecommendation!,
success successBlock: @escaping BreinEngine.apiSuccess,
failure failureBlock: @escaping BreinEngine.apiFailure) throws {
if breinRecommendation != nil {
// necessary to invoke CLLocationManager
// need to come back to main thread
DispatchQueue.main.async {
self.locationManager.fetchWithCompletion { location, error in
// save the retrieved location data
breinRecommendation.getUser()?.setLocationData(location)
if let loc = location {
BreinLogger.shared.log("Breinify latitude is: \(loc.coordinate.latitude)")
BreinLogger.shared.log("Breinify longitude is: \(loc.coordinate.longitude)")
}
do {
if breinRecommendation != nil {
return try self.restEngine.doRecommendation(breinRecommendation,
success: successBlock,
failure: failureBlock)
}
} catch {
BreinLogger.shared.log("Breinify invokeRecommendation error is: \(error)")
}
}
}
}
}
/**
Returns the rest engine
- returns: engine itself
*/
public func getRestEngine() -> IRestEngine! {
restEngine
}
/**
Configuration of engine
- parameter breinConfig: configuration object
*/
public func configure(_ breinConfig: BreinConfig!) {
restEngine.configure(breinConfig)
}
}
| mit | 36a69edccd383fbfce80bd7d84cb372b | 35.864407 | 122 | 0.553103 | 5.697446 | false | false | false | false |
CoderPug/cocoalima.com | Sources/App/Model/podcastEpisode.swift | 1 | 4049 | //
// podcastEpisode.swift
// cocoalima
//
// Created by Jose Torres on 15/1/17.
//
//
import Vapor
import Fluent
final class Episode: Model {
var id: Node?
/// Date format : YYYYMMdd
var date: String
/// Date format : MMM d, yyyy
var formattedDate: String
var title: String
var imageURL: String
var audioURL: String
var duration: Int
/// Duration format: hh:mm:ss
var formattedDuration: String
var shortDescription: String
var fullDescription: String
var exists: Bool = false
init(title: String, shortDescription: String, fullDescription: String, imageURL: String, audioURL: String, date: String, duration: Int) {
self.title = title
self.shortDescription = shortDescription
self.fullDescription = fullDescription
self.imageURL = imageURL
self.audioURL = audioURL
self.date = date
self.duration = duration
self.formattedDate = self.date.formattedDateB()
self.formattedDuration = self.duration.toDurationString()
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
title = try node.extract("title")
shortDescription = try node.extract("shortdescription")
fullDescription = try node.extract("fulldescription")
imageURL = try node.extract("imageurl")
audioURL = try node.extract("audiourl")
date = try node.extract("date")
duration = try node.extract("duration")
formattedDate = date.formattedDateB()
formattedDuration = duration.toDurationString()
}
convenience init(node: Node) throws {
self.init()
id = try node.extract("id")
title = try node.extract("title")
shortDescription = try node.extract("shortdescription")
fullDescription = try node.extract("fulldescription")
imageURL = try node.extract("imageurl")
audioURL = try node.extract("audiourl")
date = try node.extract("date")
duration = try node.extract("duration")
formattedDate = date.formattedDateB()
formattedDuration = duration.toDurationString()
}
convenience init() {
self.init(title: "", shortDescription: "", fullDescription: "", imageURL: "", audioURL: "", date: "", duration: 0)
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"title": title,
"imageurl": imageURL,
"audiourl": audioURL,
"date": date,
"shortdescription": shortDescription,
"fulldescription": fullDescription,
"formattedDate": date.formattedDateB(),
"duration": duration,
"formattedDuration": duration.toDurationString()
])
}
static func prepare(_ database: Database) throws {
try database.create("episodes") { episodes in
episodes.id()
episodes.string("title")
episodes.string("imageurl")
episodes.string("audiourl")
episodes.string("date")
episodes.string("formattedDate")
episodes.string("shortdescription")
episodes.int("duration")
episodes.string("formattedDuration")
episodes.string("fulldescription", length: 3000)
}
}
static func revert(_ database: Database) throws {
try database.delete("episodes")
}
// MARK:
func update(title: String, shortDescription: String, fullDescription: String, imageURL: String, audioURL: String, date: String, duration: Int) {
self.title = title
self.shortDescription = shortDescription
self.fullDescription = fullDescription
self.imageURL = imageURL
self.audioURL = audioURL
self.date = date
self.duration = duration
self.formattedDuration = self.duration.toDurationString()
self.formattedDate = self.date.formattedDateB()
}
}
| mit | aa8cd0868fe444d05ad57afc267c1462 | 32.46281 | 148 | 0.614473 | 4.664747 | false | false | false | false |
klesh/cnodejs-swift | CNode/Options/MessagesCell.swift | 1 | 2298 | //
// MessagesCell.swift
// CNode
//
// Created by Klesh Wong on 1/11/16.
// Copyright © 2016 Klesh Wong. All rights reserved.
//
import UIKit
import SwiftyJSON
protocol MessagesCellDelegate : class {
func avatarTapped(author: String, cell: MessagesCell)
}
class MessagesCell : UITableViewCell {
@IBOutlet weak var theAvatar: UIButton!
@IBOutlet weak var theAuthor: UILabel!
@IBOutlet weak var theType: UILabel!
@IBOutlet weak var theElapse: UILabel!
@IBOutlet weak var theReply: UIWebView!
@IBOutlet weak var theContent: CNWebView!
@IBOutlet weak var theTopic: UILabel!
weak var delegate: MessagesCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
Utils.circleUp(theAvatar)
}
func bind(message: JSON) {
theAvatar.kf_setImageWithURL(Utils.toURL(message["author"]["avatar_url"].string), forState: .Normal)
theAuthor.text = message["author"]["loginname"].string
theTopic.text = message["topic"]["title"].string
let hasReply = nil != message["reply"]["id"].string
if message["type"].stringValue == "at" {
if hasReply {
theType.text = "在回复中@了你"
} else {
theType.text = "在主题中@了你"
}
} else {
theType.text = "回复了您的话题"
}
if hasReply {
theElapse.text = Utils.relativeTillNow(message["reply"]["create_at"].stringValue.toDateFromISO8601())
theContent.loadHTMLAsPageOnce(message["reply"]["content"].stringValue, baseURL: ApiClient.BASE_URL)
} else {
theElapse.text = Utils.relativeTillNow(message["topic"]["last_reply_at"].stringValue.toDateFromISO8601())
theContent.hidden = true
}
let textColor = message["has_read"].boolValue ? UIColor.darkGrayColor() : UIColor.darkTextColor()
theAuthor.textColor = textColor
theType.textColor = textColor
theElapse.textColor = textColor
theTopic.textColor = textColor
}
@IBAction func avatarDidTapped(sender: AnyObject) {
if let d = delegate {
d.avatarTapped(theAuthor.text!, cell: self)
}
}
}
| apache-2.0 | 29ba5134e4e5468df047685de14df765 | 31.271429 | 117 | 0.616202 | 4.270321 | false | false | false | false |
alphatroya/KeyboardManager | Tests/KeyboardManagerTests/Helpers.swift | 1 | 2719 | //
// MIT License
//
// Copyright (c) 2021
//
// 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 KeyboardManager
import UIKit
extension KeyboardManagerTests {
func postTestNotification(name: Notification.Name) {
notificationCenter.post(name: name, object: nil, userInfo: [
UIResponder.keyboardFrameEndUserInfoKey: NSValue(cgRect: endFrame),
UIResponder.keyboardFrameBeginUserInfoKey: NSValue(cgRect: beginFrame),
UIResponder.keyboardAnimationDurationUserInfoKey: animationDuration,
UIResponder.keyboardIsLocalUserInfoKey: isLocal,
UIResponder.keyboardAnimationCurveUserInfoKey: curve,
])
}
func postWrongTestNotification() {
notificationCenter.post(name: UIResponder.keyboardDidShowNotification, object: nil, userInfo: [
UIResponder.keyboardFrameEndUserInfoKey: NSValue(cgRect: endFrame),
UIResponder.keyboardAnimationCurveUserInfoKey: 10,
])
}
func compareWithTestData(another data: KeyboardManagerEvent.Data) -> Bool {
let isFrameEqual = data.frame.begin == beginFrame &&
data.frame.end == endFrame
return isFrameEqual &&
data.animationDuration == animationDuration &&
data.animationCurve == curve &&
data.isLocal == isLocal
}
func compare(lhs: KeyboardManagerEvent.Data, rhs: KeyboardManagerEvent.Data) -> Bool {
return lhs.animationCurve == rhs.animationCurve &&
lhs.animationDuration == rhs.animationDuration &&
lhs.isLocal == rhs.isLocal &&
lhs.frame.begin == rhs.frame.begin &&
lhs.frame.end == rhs.frame.end
}
}
| mit | 13e8807d1b4775d51aa23e5b72881c00 | 43.57377 | 103 | 0.710188 | 5.169202 | false | true | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/AccountService+MergeDuplicates.swift | 1 | 1628 | import Foundation
extension AccountService {
func mergeDuplicatesIfNecessary() {
guard let count = try? WPAccount.lookupNumberOfAccounts(in: managedObjectContext), count > 1 else {
return
}
let accounts = allAccounts()
let accountGroups = Dictionary(grouping: accounts) { $0.userID }
for group in accountGroups.values where group.count > 1 {
mergeDuplicateAccounts(accounts: group)
}
if managedObjectContext.hasChanges {
ContextManager.sharedInstance().save(managedObjectContext)
}
}
private func mergeDuplicateAccounts(accounts: [WPAccount]) {
// For paranoia
guard accounts.count > 1 else {
return
}
// If one of the accounts is the default account, merge the rest into it.
// Otherwise just use the first account.
var destination = accounts.first!
if let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext), accounts.contains(defaultAccount) {
destination = defaultAccount
}
for account in accounts where account != destination {
mergeAccount(account: account, into: destination)
}
let service = BlogService(managedObjectContext: managedObjectContext)
service.deduplicateBlogs(for: destination)
}
private func mergeAccount(account: WPAccount, into destination: WPAccount) {
// Move all blogs to the destination account
destination.addBlogs(account.blogs)
managedObjectContext.delete(account)
}
}
| gpl-2.0 | 8dfa22b7aad6126e1a3547805ebce70b | 32.916667 | 142 | 0.660934 | 5.320261 | false | false | false | false |
ahayman/RxStream | RxStreamTests/ThrottleTests.swift | 1 | 8969 | //
// ThrottleTests.swift
// RxStream
//
// Created by Aaron Hayman on 3/27/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import XCTest
@testable import Rx
class ThrottleTests: XCTestCase {
func testTimedThrottleLastWork() {
var completions = [String:() -> Void]()
var keys = [String]()
var drops = [String]()
let throttle = TimedThrottle(interval: 0.1, delayFirst: true)
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[0])
return
}
completions[keys[0]] = completion
}
XCTAssertEqual(completions.count, 0, "Work should be delayed")
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[1])
return
}
completions[keys[1]] = completion
}
XCTAssertEqual(completions.count, 0, "Work should be delayed")
XCTAssertEqual(drops, [keys[0]], "First work should be dropped")
wait(for: 0.1)
XCTAssertEqual(completions.count, 1, "Only 1 work should pass through the throttle.")
XCTAssertNotNil(completions[keys[1]], "The last work should execute. The prior work should have been discarded.")
completions[keys[1]]?()
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[2])
return
}
completions[keys[2]] = completion
}
XCTAssertEqual(completions.count, 1, "Next work should buffer.")
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[3])
return
}
completions[keys[3]] = completion
}
XCTAssertEqual(completions.count, 1, "Next work should buffer.")
XCTAssertEqual(drops, [keys[0], keys[2]], "Pending work should drop.")
wait(for: 0.1)
XCTAssertEqual(completions.count, 2, "Next work should pass through the throttle.")
XCTAssertNotNil(completions[keys[3]], "The last work should execute.")
}
func testTimeThrottleFirstFire() {
var completions = [String:() -> Void]()
var keys = [String]()
let throttle = TimedThrottle(interval: 0.1, delayFirst: false)
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else { return }
completions[keys[0]] = completion
}
XCTAssertEqual(completions.count, 1, "First Work should not be delayed")
completions[keys[0]]?()
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else { return }
completions[keys[1]] = completion
}
XCTAssertEqual(completions.count, 1, "Next Work should be delayed.")
wait(for: 0.1)
XCTAssertEqual(completions.count, 2, "Second work should pass through the throttle.")
XCTAssertNotNil(completions[keys[1]], "The next work should execute.")
}
func testPressureThrottleLimit() {
var completions = [String:() -> Void]()
var keys = [String]()
var drops = [String]()
let throttle = PressureThrottle(buffer: 0, limit: 2)
// Pressure: 1
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[0])
return
}
completions[keys[0]] = completion
}
XCTAssertEqual(completions.count, 1, "First Work within limit should execute.")
XCTAssertNotNil(completions[keys[0]], "Verify correct work executed.")
XCTAssertEqual(drops, [])
// Pressure: 2
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[1])
return
}
completions[keys[1]] = completion
}
XCTAssertEqual(completions.count, 2, "Second Work within limit should execute.")
XCTAssertNotNil(completions[keys[1]], "Verify correct work executed.")
XCTAssertEqual(drops, [])
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[2])
return
}
completions[keys[2]] = completion
}
XCTAssertEqual(completions.count, 2, "Third Work within exceeds limit shouldn't execute.")
XCTAssertNil(completions[keys[2]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[2]])
// Pressure: 1
completions[keys[0]]?()
XCTAssertEqual(completions.count, 2, "Third Work shouldn't be buffered. Shouldn't execute.")
XCTAssertNil(completions[keys[2]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[2]])
// Pressure: 2
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[3])
return
}
completions[keys[3]] = completion
}
XCTAssertEqual(completions.count, 3, "Fourth Work within limit, should execute.")
XCTAssertNotNil(completions[keys[3]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[2]])
// Pressure: 1
completions[keys[1]]?()
// Pressure: 0
completions[keys[3]]?()
// Pressure: 1
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[4])
return
}
completions[keys[4]] = completion
}
XCTAssertEqual(completions.count, 4, "Fourth Work within limit, should execute.")
XCTAssertNotNil(completions[keys[4]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[2]])
// Pressure: 2
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[5])
return
}
completions[keys[5]] = completion
}
XCTAssertEqual(completions.count, 5, "Fourth Work within limit, should execute.")
XCTAssertNotNil(completions[keys[5]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[2]])
}
func testPressureThrottleBuffer() {
var completions = [String:() -> Void]()
var drops = [String]()
var keys = [String]()
let throttle = PressureThrottle(buffer: 2, limit: 1)
// Pressure: 1, Buffer: 0
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[0])
return
}
completions[keys[0]] = completion
}
XCTAssertEqual(completions.count, 1, "First Work within limit should execute.")
XCTAssertNotNil(completions[keys[0]], "Verify correct work executed.")
XCTAssertEqual(drops, [])
// Pressure: 1, Buffer: 1
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[1])
return
}
completions[keys[1]] = completion
}
XCTAssertEqual(completions.count, 1, "Second Work should be buffered.")
XCTAssertEqual(drops, [])
// Pressure: 1, Buffer: 2
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[2])
return
}
completions[keys[2]] = completion
}
XCTAssertEqual(completions.count, 1, "Third Work should be buffered.")
XCTAssertEqual(drops, [])
// Pressure: 1, Buffer: 2
keys.append(String.newUUID())
throttle.process { signal in
guard case .perform(let completion) = signal else {
drops.append(keys[3])
return
}
completions[keys[3]] = completion
}
XCTAssertEqual(completions.count, 1, "Fourth work should be dropped, exceeds buffer.")
XCTAssertEqual(drops, [keys[3]])
// Pressure: 1, Buffer: 1
completions[keys[0]]?()
XCTAssertEqual(completions.count, 2, "Second work should be pulled from buffer and executed.")
XCTAssertNotNil(completions[keys[1]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[3]])
// Pressure: 1, Buffer: 0
completions[keys[1]]?()
XCTAssertEqual(completions.count, 3, "Third work should be pulled from buffer and executed.")
XCTAssertNotNil(completions[keys[2]], "Verify correct work executed.")
XCTAssertEqual(drops, [keys[3]])
// Pressure: 0, Buffer: 0
completions[keys[2]]?()
XCTAssertEqual(completions.count, 3, "Buffer empty, nothing else should execute. Fourth work should have been dropped.")
XCTAssertEqual(drops, [keys[3]])
}
}
| mit | 7915a874f3bfddfdc4aa04efbfef41ed | 30.247387 | 124 | 0.637154 | 4.332367 | false | false | false | false |
CeranPaul/SketchCurves | SketchGen/Easel2D.swift | 1 | 6968 | //
// Easel2D.swift
// SketchCurves
//
import UIKit
/// A utility canvas for showing objects in two dimensions
/// - Attention: This class name needs to linked in the storyboard's Identity Inspector in an app to be seen
/// - Requires: A global parameter named modelGeo that contains curves to be drawn
class Easel2D: UIView {
// Declare pen properties
var black: CGColor
var blue: CGColor
var green: CGColor
var grey: CGColor
var orange: CGColor
var brown: CGColor
// Prepare pen widths
let thick = CGFloat(4.0)
let standard = CGFloat(3.0)
let thin = CGFloat(1.5)
/// Transforms between model and screen space
var modelToDisplay, displayToModel: CGAffineTransform?
/// Do some of the setup only one time
required init(coder aDecoder: NSCoder) {
// Prepare colors
let colorSpace = CGColorSpaceCreateDeviceRGB()
let blackComponents: [CGFloat] = [0.0, 0.0, 0.0, 1.0]
black = CGColor(colorSpace: colorSpace, components: blackComponents)!
let blueComponents: [CGFloat] = [0.0, 0.0, 1.0, 1.0]
blue = CGColor(colorSpace: colorSpace, components: blueComponents)!
let greenComponents: [CGFloat] = [0.0, 1.0, 0.0, 1.0]
green = CGColor(colorSpace: colorSpace, components: greenComponents)!
let greyComponents: [CGFloat] = [0.7, 0.7, 0.7, 1.0]
grey = CGColor(colorSpace: colorSpace, components: greyComponents)!
let orangeComponents: [CGFloat] = [1.0, 0.65, 0.0, 1.0]
orange = CGColor(colorSpace: colorSpace, components: orangeComponents)!
let brownComponents: [CGFloat] = [0.63, 0.33, 0.18, 1.0]
brown = CGColor(colorSpace: colorSpace, components: brownComponents)!
super.init(coder: aDecoder)! // Done here to be able to use "self.bounds" for scaling below
guard !modelGeo.displayCurves.isEmpty else { // Bail if there isn't anything to plot
print("Nothing to scale!")
return
}
var brick = modelGeo.displayCurves.first!.getExtent()
for (xedni, wire) in modelGeo.displayCurves.enumerated() {
if xedni > 0 {
brick = brick + wire.getExtent()
}
}
/// Bounding area for play
let arena = CGRect(x: brick.getOrigin().x, y: brick.getOrigin().y, width: brick.getWidth(), height: brick.getHeight())
/// Transforms to and from model coordinates
let tforms = findScaleAndCenter(displayRect: self.bounds, subjectRect: arena)
modelToDisplay = tforms.toDisplay
displayToModel = tforms.toModel
}
/// Perform the plotting
override func draw(_ rect: CGRect) {
guard !modelGeo.displayCurves.isEmpty else { // Bail if there isn't anything to plot
return
}
// Preserve settings that were used before
let context = UIGraphicsGetCurrentContext()!
context.saveGState(); // Preserve settings that were used before
for wire in modelGeo.displayCurves { // Traverse through the entire collection
// Choose the appropriate pen
switch wire.usage {
case .arc:
context.setStrokeColor(blue)
context.setLineWidth(thick)
context.setLineDash(phase: 0, lengths: []); // To clear any previous dash pattern
case .sweep:
context.setStrokeColor(grey)
context.setLineWidth(thin)
context.setLineDash(phase: 0, lengths: [CGFloat(10), CGFloat(8)]);
case .extent:
context.setStrokeColor(brown)
context.setLineWidth(thin)
context.setLineDash(phase: 5, lengths: [CGFloat(10), CGFloat(8)]) // To clear any previous dash pattern
case .ideal:
context.setStrokeColor(black)
context.setLineWidth(thin)
context.setLineDash(phase: 0, lengths: [CGFloat(3), CGFloat(3)]) // To clear any previous dash pattern
case .approx:
context.setStrokeColor(green)
context.setLineWidth(standard)
context.setLineDash(phase: 0, lengths: []); // To clear any previous dash pattern
default:
context.setStrokeColor(black)
context.setLineWidth(thin)
context.setLineDash(phase: 0, lengths: []); // To clear any previous dash pattern
}
wire.draw(context: context, tform: modelToDisplay!)
} // End of loop through the display list
context.restoreGState(); // Restore prior settings
} // End of drawRect
/// Determines parameters to center the model on the screen.
/// - Parameter: displayRect: Bounds of the plotting area
/// - Parameter: subjectRect: A CGRect that bounds the model space used
/// - Returns: A tuple containing transforms between model and display space
/// - Makes no checks to see that the CGRects are non-zero
func findScaleAndCenter(displayRect: CGRect, subjectRect: CGRect) -> (toDisplay: CGAffineTransform, toModel: CGAffineTransform) {
let rangeX = subjectRect.width
let rangeY = subjectRect.height
/// For an individual edge
let margin = CGFloat(20.0) // Measured in "points", not pixels, or model units
let twoMargins = CGFloat(2.0) * margin
let scaleX = (displayRect.width - twoMargins) / rangeX
let scaleY = (displayRect.height - twoMargins) / rangeY
let scale = min(scaleX, scaleY)
// Find the middle of the model area for translation
let giro = subjectRect.origin
let middleX = giro.x + 0.5 * rangeX
let middleY = giro.y + 0.5 * rangeY
let transX = (displayRect.width - twoMargins) / 2 - middleX * scale + margin
let transY = (displayRect.height - twoMargins) / 2 + middleY * scale + margin
let modelScale = CGAffineTransform(scaleX: scale, y: -scale) // To make Y positive upwards
let modelTranslate = CGAffineTransform(translationX: transX, y: transY)
/// The combined matrix based on the plot parameters
let modelToDisplay = modelScale.concatenating(modelTranslate)
/// Useful for interpreting screen picks
let displayToModel = modelToDisplay.inverted()
return (modelToDisplay, displayToModel)
}
}
| apache-2.0 | f09a78985092acd030de9b3c380b6b9f | 37.927374 | 136 | 0.581372 | 4.838889 | false | false | false | false |
lzpfmh/actor-platform | actor-apps/app-ios/ActorApp/View/Cells/HeaderCell.swift | 1 | 1558 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class HeaderCell: UATableViewCell {
var titleView = UILabel()
var iconView = UIImageView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = MainAppTheme.list.backyardColor
selectionStyle = UITableViewCellSelectionStyle.None
titleView.textColor = MainAppTheme.list.sectionColor
titleView.font = UIFont.systemFontOfSize(14)
contentView.addSubview(titleView)
iconView.contentMode = UIViewContentMode.ScaleAspectFill
let tapRecognizer = UITapGestureRecognizer(target: self, action: "iconDidTap")
iconView.addGestureRecognizer(tapRecognizer)
iconView.userInteractionEnabled = true
contentView.addSubview(iconView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let height = self.contentView.bounds.height
let width = self.contentView.bounds.width
titleView.frame = CGRectMake(15, height - 28, width - 48, 24)
iconView.frame = CGRectMake(width - 18 - 15, height - 18 - 4, 18, 18)
}
func iconDidTap() {
UIAlertView(title: nil, message: "Tap", delegate: nil, cancelButtonTitle: nil).show()
}
} | mit | 268d2cb5ea298562c00bafe09bc599ed | 31.479167 | 93 | 0.654044 | 5.210702 | false | false | false | false |
bolshedvorsky/swift-corelibs-foundation | Foundation/NSIndexSet.swift | 2 | 32089 | // 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import Dispatch
/* Class for managing set of indexes. The set of valid indexes are 0 .. NSNotFound - 1; trying to use indexes outside this range is an error. NSIndexSet uses NSNotFound as a return value in cases where the queried index doesn't exist in the set; for instance, when you ask firstIndex and there are no indexes; or when you ask for indexGreaterThanIndex: on the last index, and so on.
The following code snippets can be used to enumerate over the indexes in an NSIndexSet:
// Forward
var currentIndex = set.firstIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexGreaterThanIndex(currentIndex)
}
// Backward
var currentIndex = set.lastIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexLessThanIndex(currentIndex)
}
To enumerate without doing a call per index, you can use the method getIndexes:maxCount:inIndexRange:.
*/
internal func __NSIndexSetRangeCount(_ indexSet: NSIndexSet) -> Int {
return indexSet._ranges.count
}
internal func __NSIndexSetRangeAtIndex(_ indexSet: NSIndexSet, _ index: Int, _ location : UnsafeMutablePointer<Int>, _ length : UnsafeMutablePointer<Int>) {
// if Int(index) >= indexSet._ranges.count {
// location.pointee = UInt(bitPattern: NSNotFound)
// length.pointee = UInt(0)
// return
// }
let range = indexSet._ranges[Int(index)]
location.pointee = range.location
length.pointee = range.length
}
internal func __NSIndexSetIndexOfRangeContainingIndex(_ indexSet: NSIndexSet, _ index: Int) -> Int {
var idx = 0
while idx < indexSet._ranges.count {
let range = indexSet._ranges[idx]
if range.location <= index && index <= range.location + range.length {
return idx
}
idx += 1
}
return NSNotFound
}
open class NSIndexSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
// all instance variables are private
internal var _ranges = [NSRange]()
internal var _count = 0
override public init() {
_count = 0
_ranges = []
}
public init(indexesIn range: NSRange) {
_count = range.length
_ranges = _count == 0 ? [] : [range]
}
public init(indexSet: IndexSet) {
_ranges = indexSet.rangeView.map { NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound) }
_count = indexSet.count
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSIndexSet.self {
// return self for immutable type
return self
}
return NSIndexSet(indexSet: self._bridgeToSwift())
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
let set = NSMutableIndexSet()
enumerateRanges(options: []) { (range, _) in
set.add(in: range)
}
return set
}
public static var supportsSecureCoding: Bool { return true }
public required init?(coder aDecoder: NSCoder) { NSUnimplemented() }
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public convenience init(index value: Int) {
self.init(indexesIn: NSRange(location: value, length: 1))
}
open func isEqual(to indexSet: IndexSet) -> Bool {
let otherRanges = indexSet.rangeView.map { NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound) }
if _ranges.count != otherRanges.count {
return false
}
for (r1, r2) in zip(_ranges, otherRanges) {
if r1.length != r2.length || r1.location != r2.location {
return false
}
}
return true
}
open var count: Int {
return _count
}
/* The following six methods will return NSNotFound if there is no index in the set satisfying the query.
*/
open var firstIndex: Int {
return _ranges.first?.location ?? NSNotFound
}
open var lastIndex: Int {
guard !_ranges.isEmpty else {
return NSNotFound
}
return NSMaxRange(_ranges.last!) - 1
}
internal func _indexAndRangeAdjacentToOrContainingIndex(_ idx : Int) -> (Int, NSRange)? {
let count = _ranges.count
guard count > 0 else {
return nil
}
var min = 0
var max = count - 1
while min < max {
let rIdx = (min + max) / 2
let range = _ranges[rIdx]
if range.location > idx {
max = rIdx
} else if NSMaxRange(range) - 1 < idx {
min = rIdx + 1
} else {
return (rIdx, range)
}
}
return (min, _ranges[min])
}
internal func _indexOfRangeContainingIndex(_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
return NSLocationInRange(idx, range) ? rIdx : nil
} else {
return nil
}
}
internal func _indexOfRangeBeforeOrContainingIndex(_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if range.location <= idx {
return rIdx
} else if rIdx > 0 {
return rIdx - 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexOfRangeAfterOrContainingIndex(_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if NSMaxRange(range) - 1 >= idx {
return rIdx
} else if rIdx + 1 < _ranges.count {
return rIdx + 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexClosestToIndex(_ idx: Int, equalAllowed : Bool, following: Bool) -> Int? {
guard _count > 0 else {
return nil
}
if following {
var result = idx
if !equalAllowed {
guard idx < NSNotFound else {
return nil
}
result += 1
}
if let rangeIndex = _indexOfRangeAfterOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : range.location
}
} else {
var result = idx
if !equalAllowed {
guard idx > 0 else {
return nil
}
result -= 1
}
if let rangeIndex = _indexOfRangeBeforeOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : (NSMaxRange(range) - 1)
}
}
return nil
}
open func indexGreaterThanIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: true) ?? NSNotFound
}
open func indexLessThanIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: false) ?? NSNotFound
}
open func indexGreaterThanOrEqual(to value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: true) ?? NSNotFound
}
open func indexLessThanOrEqual(to value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: false) ?? NSNotFound
}
/* Fills up to bufferSize indexes in the specified range into the buffer and returns the number of indexes actually placed in the buffer; also modifies the optional range passed in by pointer to be "positioned" after the last index filled into the buffer.Example: if the index set contains the indexes 0, 2, 4, ..., 98, 100, for a buffer of size 10 and the range (20, 80) the buffer would contain 20, 22, ..., 38 and the range would be modified to (40, 60).
*/
open func getIndexes(_ indexBuffer: UnsafeMutablePointer<Int>, maxCount bufferSize: Int, inIndexRange range: NSRangePointer?) -> Int {
let minIndex : Int
let maxIndex : Int
if let initialRange = range {
minIndex = initialRange.pointee.location
maxIndex = NSMaxRange(initialRange.pointee) - 1
} else {
minIndex = firstIndex
maxIndex = lastIndex
}
guard minIndex <= maxIndex else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(minIndex) {
var rangeIndex = initialRangeIndex
let rangeCount = _ranges.count
var counter = 0
var idx = minIndex
var offset = 0
while rangeIndex < rangeCount && idx <= maxIndex && counter < bufferSize {
let currentRange = _ranges[rangeIndex]
if currentRange.location <= minIndex {
idx = minIndex
offset = minIndex - currentRange.location
} else {
idx = currentRange.location
}
while idx <= maxIndex && counter < bufferSize && offset < currentRange.length {
indexBuffer.advanced(by: counter).pointee = idx
counter += 1
idx += 1
offset += 1
}
if offset >= currentRange.length {
rangeIndex += 1
offset = 0
}
}
if counter > 0, let resultRange = range {
let delta = indexBuffer.advanced(by: counter - 1).pointee - minIndex + 1
resultRange.pointee.location += delta
resultRange.pointee.length -= delta
}
return counter
} else {
return 0
}
}
open func countOfIndexes(in range: NSRange) -> Int {
guard _count > 0 && range.length > 0 else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location) {
var rangeIndex = initialRangeIndex
let maxRangeIndex = NSMaxRange(range) - 1
var result = 0
let firstRange = _ranges[rangeIndex]
if firstRange.location < range.location {
if NSMaxRange(firstRange) - 1 >= maxRangeIndex {
return range.length
}
result = NSMaxRange(firstRange) - range.location
rangeIndex += 1
}
for curRange in _ranges.suffix(from: rangeIndex) {
if NSMaxRange(curRange) - 1 > maxRangeIndex {
if curRange.location <= maxRangeIndex {
result += maxRangeIndex + 1 - curRange.location
}
break
}
result += curRange.length
}
return result
} else {
return 0
}
}
open func contains(_ value: Int) -> Bool {
return _indexOfRangeContainingIndex(value) != nil
}
open func contains(in range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = self._indexOfRangeContainingIndex(range.location) {
return NSMaxRange(_ranges[rIdx]) >= NSMaxRange(range)
} else {
return false
}
}
open func contains(_ indexSet: IndexSet) -> Bool {
var result = true
enumerateRanges(options: []) { range, stop in
if !self.contains(in: range) {
result = false
stop.pointee = true
}
}
return result
}
open func intersects(in range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = _indexOfRangeBeforeOrContainingIndex(range.location) {
if NSMaxRange(_ranges[rIdx]) - 1 >= range.location {
return true
}
}
if let rIdx = _indexOfRangeAfterOrContainingIndex(range.location) {
if NSMaxRange(range) - 1 >= _ranges[rIdx].location {
return true
}
}
return false
}
internal func _enumerateWithOptions<P, R>(_ opts : NSEnumerationOptions, range: NSRange, paramType: P.Type, returnType: R.Type, block: (P, UnsafeMutablePointer<ObjCBool>) -> R) -> Int? {
guard let startRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location), let endRangeIndex = _indexOfRangeBeforeOrContainingIndex(NSMaxRange(range) - 1) else {
return nil
}
var result : Int? = nil
let reverse = opts.contains(.reverse)
let passRanges = paramType == NSRange.self
let findIndex = returnType == Bool.self
var sharedStop = false
let lock = NSLock()
let ranges = _ranges[startRangeIndex...endRangeIndex]
let rangeSequence = (reverse ? AnyCollection(ranges.reversed()) : AnyCollection(ranges))
let iteration = withoutActuallyEscaping(block) { (closure: @escaping (P, UnsafeMutablePointer<ObjCBool>) -> R) -> (Int) -> Void in
return { (rangeIdx) in
lock.lock()
var stop = ObjCBool(sharedStop)
lock.unlock()
if stop.boolValue { return }
let idx = rangeSequence.index(rangeSequence.startIndex, offsetBy: rangeIdx)
let curRange = rangeSequence[idx]
let intersection = NSIntersectionRange(curRange, range)
if passRanges {
if intersection.length > 0 {
let _ = closure(intersection as! P, &stop)
}
if stop.boolValue {
lock.lock()
sharedStop = stop.boolValue
lock.unlock()
return
}
} else if intersection.length > 0 {
let maxIndex = NSMaxRange(intersection) - 1
let indexes = reverse ? stride(from: maxIndex, through: intersection.location, by: -1) : stride(from: intersection.location, through: maxIndex, by: 1)
for idx in indexes {
if findIndex {
let found : Bool = closure(idx as! P, &stop) as! Bool
if found {
result = idx
stop = true
}
} else {
let _ = closure(idx as! P, &stop)
}
if stop.boolValue {
lock.lock()
sharedStop = stop.boolValue
lock.unlock()
return
}
}
}
}
}
if opts.contains(.concurrent) {
DispatchQueue.concurrentPerform(iterations: Int(rangeSequence.count), execute: iteration)
} else {
for idx in 0..<Int(rangeSequence.count) {
iteration(idx)
}
}
return result
}
open func enumerate(_ block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerate(options: [], using: block)
}
open func enumerate(options opts: NSEnumerationOptions = [], using block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: NSRange(location: 0, length: Int.max), paramType: Int.self, returnType: Void.self, block: block)
}
open func enumerate(in range: NSRange, options opts: NSEnumerationOptions = [], using block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self, block: block)
}
open func index(passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return index(options: [], passingTest: predicate)
}
open func index(options opts: NSEnumerationOptions = [], passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: NSRange(location: 0, length: Int.max), paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
open func index(in range: NSRange, options opts: NSEnumerationOptions = [], passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
open func indexes(passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
return indexes(in: NSRange(location: 0, length: Int.max), options: [], passingTest: predicate)
}
open func indexes(options opts: NSEnumerationOptions = [], passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
return indexes(in: NSRange(location: 0, length: Int.max), options: opts, passingTest: predicate)
}
open func indexes(in range: NSRange, options opts: NSEnumerationOptions = [], passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet {
var result = IndexSet()
let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self) { idx, stop in
if predicate(idx, stop) {
result.insert(idx)
}
}
return result
}
/*
The following three convenience methods allow you to enumerate the indexes in the receiver by ranges of contiguous indexes. The performance of these methods is not guaranteed to be any better than if they were implemented with enumerateIndexesInRange:options:usingBlock:. However, depending on the receiver's implementation, they may perform better than that.
If the specified range for enumeration intersects a range of contiguous indexes in the receiver, then the block will be invoked with the intersection of those two ranges.
*/
open func enumerateRanges(_ block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateRanges(options: [], using: block)
}
open func enumerateRanges(options opts: NSEnumerationOptions = [], using block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: NSRange(location: 0, length: Int.max), paramType: NSRange.self, returnType: Void.self, block: block)
}
open func enumerateRanges(in range: NSRange, options opts: NSEnumerationOptions = [], using block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: range, paramType: NSRange.self, returnType: Void.self, block: block)
}
}
public struct NSIndexSetIterator : IteratorProtocol {
public typealias Element = Int
internal let _set: NSIndexSet
internal var _first: Bool = true
internal var _current: Element?
internal init(_ set: NSIndexSet) {
self._set = set
self._current = nil
}
public mutating func next() -> Element? {
if _first {
_current = _set.firstIndex
_first = false
} else if let c = _current {
_current = _set.indexGreaterThanIndex(c)
}
if _current == NSNotFound {
_current = nil
}
return _current
}
}
extension NSIndexSet : Sequence {
public func makeIterator() -> NSIndexSetIterator {
return NSIndexSetIterator(self)
}
}
open class NSMutableIndexSet : NSIndexSet {
open func add(_ indexSet: IndexSet) {
indexSet.rangeView.forEach { add(in: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)) }
}
open override func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSMutableIndexSet.self {
let indexSet = NSMutableIndexSet()
indexSet._ranges = self._ranges
indexSet._count = self._count
return indexSet
}
return NSMutableIndexSet(indexSet: self._bridgeToSwift())
}
open func remove(_ indexSet: IndexSet) {
indexSet.rangeView.forEach { remove(in: NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)) }
}
open func removeAllIndexes() {
_ranges = []
_count = 0
}
open func add(_ value: Int) {
add(in: NSRange(location: value, length: 1))
}
open func remove(_ value: Int) {
remove(in: NSRange(location: value, length: 1))
}
internal func _insertRange(_ range: NSRange, atIndex index: Int) {
_ranges.insert(range, at: index)
_count += range.length
}
internal func _replaceRangeAtIndex(_ index: Int, withRange range: NSRange?) {
let oldRange = _ranges[index]
if let range = range {
_ranges[index] = range
_count += range.length - oldRange.length
} else {
_ranges.remove(at: index)
_count -= oldRange.length
}
}
internal func _removeRangeAtIndex(_ index: Int) {
let range = _ranges.remove(at: index)
_count -= range.length
}
internal func _mergeOverlappingRangesStartingAtIndex(_ index: Int) {
var rangeIndex = index
while _ranges.count > 0 && rangeIndex < _ranges.count - 1 {
var currentRange = _ranges[rangeIndex]
let nextRange = _ranges[rangeIndex + 1]
let currentEnd = currentRange.location + currentRange.length
let nextEnd = nextRange.location + nextRange.length
if nextEnd >= nextRange.location {
// overlaps
if currentEnd < nextEnd {
// next range extends beyond current range
currentRange.length = nextEnd - currentRange.location
_replaceRangeAtIndex(rangeIndex, withRange: currentRange)
_removeRangeAtIndex(rangeIndex + 1)
} else {
_replaceRangeAtIndex(rangeIndex + 1, withRange: nil)
continue
}
} else {
break
}
rangeIndex += 1
}
}
open func add(in r: NSRange) {
var range = r
guard range.length > 0 else {
return
}
let addEnd = range.location + range.length
let startRangeIndex = _indexOfRangeBeforeOrContainingIndex(range.location) ?? 0
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
var currentRange = _ranges[rangeIndex]
let currentEnd = currentRange.location + currentRange.length
if addEnd < currentRange.location {
// new separate range
_insertRange(range, atIndex: rangeIndex)
return
} else if (range.location < currentRange.location) && (addEnd >= currentRange.location) {
if addEnd > currentEnd {
// add range contains range in array
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else {
// overlaps at start, add range ends within range in array
range.length = currentEnd - range.location
_replaceRangeAtIndex(rangeIndex, withRange: range)
}
break
} else if (range.location >= currentRange.location) && (addEnd <= currentEnd) {
// Nothing to add
return
} else if (range.location >= currentRange.location) && (range.location <= currentEnd) && (addEnd > currentEnd) {
// overlaps at end (extends)
currentRange.length = addEnd - currentRange.location
_replaceRangeAtIndex(rangeIndex, withRange: currentRange)
break
}
rangeIndex += 1
}
if rangeIndex == _ranges.count {
_insertRange(range, atIndex: _ranges.count)
}
_mergeOverlappingRangesStartingAtIndex(rangeIndex)
}
open func remove(in range: NSRange) {
guard range.length > 0 else {
return
}
guard let startRangeIndex = (range.location > 0) ? _indexOfRangeAfterOrContainingIndex(range.location) : 0 else {
return
}
let removeEnd = NSMaxRange(range)
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
let curRange = _ranges[rangeIndex]
let curEnd = NSMaxRange(curRange)
if removeEnd < curRange.location {
// Nothing to remove
return
} else if range.location <= curRange.location && removeEnd >= curRange.location {
if removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: nil)
// Don't increment rangeIndex
continue
} else {
self._replaceRangeAtIndex(rangeIndex, withRange: NSRange(location: removeEnd, length: curEnd - removeEnd))
return
}
} else if range.location > curRange.location && removeEnd < curEnd {
let firstPiece = NSRange(location: curRange.location, length: range.location - curRange.location)
let secondPiece = NSRange(location: removeEnd, length: curEnd - removeEnd)
_replaceRangeAtIndex(rangeIndex, withRange: secondPiece)
_insertRange(firstPiece, atIndex: rangeIndex)
} else if range.location > curRange.location && range.location < curEnd && removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: NSRange(location: curRange.location, length: range.location - curRange.location))
}
rangeIndex += 1
}
}
internal func _increment(by amount: Int, startingAt value: Int) {
var range: NSRange
var newRange: NSRange?
if amount > 0 {
if let rIdx = _indexOfRangeAfterOrContainingIndex(value) {
var rangeIndex = rIdx
range = _ranges[rangeIndex]
if value > range.location {
let newLength = range.location + range.length - value
let newLocation = value + amount
newRange = NSRange(location: newLocation, length: newLength) // new second piece
range.length = value - range.location
_replaceRangeAtIndex(rangeIndex, withRange: range) // new first piece
rangeIndex += 1
}
while rangeIndex < _ranges.count {
range = _ranges[rangeIndex]
range.location += amount
_replaceRangeAtIndex(rangeIndex, withRange: range)
rangeIndex += 1
}
// add newly created range (second piece) if necessary
if let range = newRange {
add(in: range)
}
}
}
}
internal func _removeAndDecrement(by amount: Int, startingAt value: Int) {
if amount > 0 {
if let rIdx = _indexOfRangeAfterOrContainingIndex(value) {
var rangeIndex = rIdx
let firstRangeToMerge = rangeIndex > 0 ? rangeIndex - 1 : rangeIndex
let removeEnd = value + amount - 1
while rangeIndex < _ranges.count {
var range = _ranges[rangeIndex]
let rangeEnd = range.location + range.length - 1
if removeEnd < range.location {
// removal occurs before range -> reduce location of range
range.location -= amount
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else if (range.location >= value) && (rangeEnd <= removeEnd) {
// removal encompasses entire range -> remove range
_removeRangeAtIndex(rangeIndex)
continue // do not increase rangeIndex
} else if (value >= range.location) && (removeEnd <= rangeEnd) {
// removal occurs completely within range -> reduce length of range
range.length -= amount
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else if (removeEnd >= range.location) && (removeEnd <= rangeEnd) {
// removal occurs within part of range, beginning of range removed -> reduce location and length
let reduction = removeEnd - range.location + 1
range.length -= reduction
if range.length > 0 {
range.location -= amount - reduction
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else {
_removeRangeAtIndex(rangeIndex)
continue // do not increase rangeIndex
}
} else if (value >= range.location) && (value <= rangeEnd) {
// removal occurs within part of range, end of range removed -> reduce length
let reduction = rangeEnd - value + 1
if reduction > 0 {
range.length -= reduction
_replaceRangeAtIndex(rangeIndex, withRange: range)
}
}
rangeIndex += 1
}
_mergeOverlappingRangesStartingAtIndex(firstRangeToMerge)
}
}
}
/* For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta].
*/
open func shiftIndexesStarting(at index: Int, by delta: Int) {
if delta > 0 {
_increment(by: delta, startingAt: index)
} else {
let positiveDelta = -delta
let idx = positiveDelta > index ? positiveDelta : index
_removeAndDecrement(by: positiveDelta, startingAt: idx - positiveDelta)
}
}
}
extension NSIndexSet : _StructTypeBridgeable {
public typealias _StructType = IndexSet
public func _bridgeToSwift() -> IndexSet {
return IndexSet._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 4d138b73cacf3ce2ab650d8415766a88 | 39.516414 | 461 | 0.556421 | 5.296963 | false | false | false | false |
jkopelioff/SwiftValidator | Validator/MinLengthRule.swift | 6 | 742 | //
// LengthRule.swift
// Validator
//
// Created by Jeff Potter on 3/6/15.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
public class MinLengthRule: Rule {
private var DEFAULT_LENGTH: Int = 3
private var message : String = "Must be at least 3 characters long"
public init(){}
public init(length: Int, message : String = "Must be at least %ld characters long"){
self.DEFAULT_LENGTH = length
self.message = NSString(format: message, self.DEFAULT_LENGTH) as String
}
public func validate(value: String) -> Bool {
return value.characters.count >= DEFAULT_LENGTH
}
public func errorMessage() -> String {
return message
}
}
| mit | 335a69cc2708c45141c7b1afc8bffe62 | 23.733333 | 88 | 0.638814 | 4.099448 | false | false | false | false |
muneebm/AsterockX | AsterockX/ApproachesViewController.swift | 1 | 5782 | //
// ApproachesViewController.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/8/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
import CoreData
class ApproachesViewController: BaseTableViewController {
struct Constants {
static let CloseApproachCell = "CloseApproachCell"
}
var selectedAsteroid: Asteroid!
var closeApproachType: CloseApproachType = .Recent {
didSet {
if allCloseApproaches.count > 0 {
changeArrayForCloseApproachType()
}
}
}
private var selectedCloseApproaches = [CloseApproachData]()
private var allCloseApproaches = [CloseApproachData]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: Constants.CloseApproachCell, bundle: nil), forCellReuseIdentifier: Constants.CloseApproachCell)
if self.selectedAsteroid.closeApproachDetails.count < 2 {
startActitvityIndicator()
Utility.nearEarthObjectWS.neoForReferenceId(selectedAsteroid.neoReferenceId!) {
(result, error) -> Void in
if let error = error {
Utility.displayAlert(self, message: error.localizedDescription)
}
else if let neo = result {
if let approaches = neo.closeApproachDetails {
dispatch_async(dispatch_get_main_queue()) {
() -> Void in
self.selectedAsteroid.addCloseApproachData(approaches, intoManagedObjectContext: self.sharedContext)
self.allCloseApproaches = self.selectedAsteroid.closeApproachDetails
self.changeArrayForCloseApproachType()
}
}
}
self.stopActivityIndicator()
}
}
else {
self.allCloseApproaches = self.selectedAsteroid.closeApproachDetails
self.changeArrayForCloseApproachType()
}
}
func changeArrayForCloseApproachType() {
let today = NSDate()
if self.closeApproachType == .Recent {
self.selectedCloseApproaches = allCloseApproaches.filter({ (closeApproachDetail) -> Bool in
let compResult = today.compare(closeApproachDetail.date!)
return compResult == .OrderedDescending || compResult == .OrderedSame
})
self.selectedCloseApproaches = self.selectedCloseApproaches.sort(){ $0.date!.compare($1.date!) == NSComparisonResult.OrderedDescending }
}
if self.closeApproachType == .Upcoming {
self.selectedCloseApproaches = allCloseApproaches.filter() { today.compare($0.date!) == .OrderedAscending }
self.selectedCloseApproaches = self.selectedCloseApproaches.sort(){ $0.date!.compare($1.date!) == NSComparisonResult.OrderedAscending }
}
tableView.reloadData()
Utility.scrollToTop(tableView)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = selectedCloseApproaches.count
tableView.separatorStyle = count == 0 ? .None : .SingleLine
return count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.CloseApproachCell, forIndexPath: indexPath) as! CloseApproachCell
let closeApproach = selectedCloseApproaches[indexPath.row]
cell.dateLabel.text = Utility.getFormattedStringFromDate(closeApproach.date!, format: Utility.Constants.SectionHeaderDateFormat)
cell.epochDateLabel.text = closeApproach.epochDate != nil ? "\(closeApproach.epochDate!.integerValue)" : nil
var relativeVelocity: String!
let velocityUnit = Settings.velocityUnit()
switch velocityUnit {
case Settings.Constants.KilometersPerSecond:
relativeVelocity = closeApproach.relativeVelocity?.kilometersPerSecond
case Settings.Constants.KilometersPerHours:
relativeVelocity = closeApproach.relativeVelocity?.kilometersPerHour
case Settings.Constants.MilesPerHour:
relativeVelocity = closeApproach.relativeVelocity?.milesPerHour
default:
break
}
if let relVel = Double(relativeVelocity) {
cell.relativeVelocityLabel.text = "\(relVel.roundToDecimals()) " + velocityUnit
}
var missDistance: String!
let distanceUnit = Settings.distanceUnit()
switch distanceUnit {
case Settings.Constants.Astronomical:
missDistance = closeApproach.missDistance?.astronomical
case Settings.Constants.Lunar:
missDistance = closeApproach.missDistance?.lunar
case Settings.Constants.Kilometers:
missDistance = closeApproach.missDistance?.kilometers
case Settings.Constants.Miles:
missDistance = closeApproach.missDistance?.miles
default:
break
}
if let missDist = Double(missDistance) {
cell.missDistanceLabel.text = "\(missDist.roundToDecimals()) " + distanceUnit
}
cell.orbitingBodyLabel.text = closeApproach.orbitingBody
return cell
}
}
| mit | 464b329e32492c9c9e516cd0a74a780e | 37.54 | 149 | 0.612178 | 5.397759 | false | false | false | false |
tingkerians/master | doharmony/AudioEffectsController.swift | 1 | 3262 | //
// AudioEffectsController.swift
// doharmony
//
// Created by Daryl Super Duper Handsum on 15/03/2016.
// Copyright © 2016 Eleazer Toluan. All rights reserved.
//
import UIKit
import AVFoundation
class AudioEffectsController: UIViewController {
@IBOutlet weak var filename: UILabel!
let filemgr = NSFileManager.defaultManager()
var player:AVAudioPlayer!
var audioFile:AVAudioFile!
@IBOutlet weak var playBtn: UIButton!
@IBOutlet weak var stopBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let tag = Layout.currentFrame
let filter = NSPredicate(format: "tag == %ld", NSInteger(tag))
let fetch = RecordingData().fetch("Recordings", predicate: filter)
let file = fetch[0].valueForKey("record")!
let audioFileName = file.stringByDeletingPathExtension + ".m4a"
let recordFilePath = env.documentFolder.stringByAppendingPathComponent("/\(env.recordingFolder)/\(file)")
let recordFileURL = NSURL(fileURLWithPath: recordFilePath)
let audioOutputPath = env.documentFolder.stringByAppendingPathComponent("/\(env.recordingFolder)/Audio/\(audioFileName)")
let audioOutputURL = NSURL.fileURLWithPath(audioOutputPath)
if filemgr.fileExistsAtPath(audioOutputPath) {
do{
try filemgr.removeItemAtPath(audioOutputPath)
}catch let er as NSError{
print(er)
}
}
//export
let exporter = AVAssetExportSession(asset: AVAsset(URL: recordFileURL), presetName: AVAssetExportPresetAppleM4A)!
exporter.outputFileType = AVFileTypeAppleM4A
exporter.outputURL = audioOutputURL
exporter.exportAsynchronouslyWithCompletionHandler({
switch exporter.status{
case .Failed:
print("audio export failed:",exporter.error!)
break
case .Cancelled:
NSLog("audio export cancelled")
break
default:
print("audio export Success")
dispatch_async(dispatch_get_main_queue()) {
self.filename.text = audioFileName
self.playBtn.userInteractionEnabled = true
self.stopBtn.userInteractionEnabled = true
self.playBtn.alpha = 1
self.stopBtn.alpha = 1
}
do{
self.audioFile = try AVAudioFile(forReading: audioOutputURL)
self.player = try AVAudioPlayer(contentsOfURL: audioOutputURL)
}catch let er as NSError{
print("set audio file err:",er)
}
break
}
})
}
@IBAction func closeWindow(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func play(sender: AnyObject) {
player.play()
}
@IBAction func stop(sender: AnyObject) {
player.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| unlicense | 884b3f5c659135fe363eca2b34b017b3 | 34.064516 | 129 | 0.601043 | 5.35468 | false | false | false | false |
paul8263/ImageBoardBrowser | ImageBoardBrowser/ImageInfoTableViewController.swift | 1 | 2664 | //
// ImageInfoTableViewController.swift
// ImageBoardBrowser
//
// Created by Paul Zhang on 10/12/2016.
// Copyright © 2016 Paul Zhang. All rights reserved.
//
import UIKit
import Foundation
import SDWebImage
class ImageInfoTableViewController: UITableViewController {
@IBOutlet weak var previewImageView: UIImageView!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var createDateLabel: UILabel!
var imageInfo: ImageInfo!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
displayData()
tableView.tableFooterView = UIView()
}
private func displayData() {
previewImageView.sd_setImage(with: imageInfo.getPreviewURL())
authorLabel.text = imageInfo.author
scoreLabel.text = "\(imageInfo.score)"
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .short
let formatterDateString = dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(imageInfo.createdAt)))
createDateLabel.text = formatterDateString
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 && indexPath.section == 1 {
let tagArray = imageInfo.tags.components(separatedBy: " ")
performSegue(withIdentifier: "showImageTags", sender: tagArray)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showImageTags" {
let imageTagsTableViewController = segue.destination as! ImageTagsTableViewController
imageTagsTableViewController.imageTagArray = sender as! [String]
}
}
}
| mit | 89fbc75e50ff30ad8425a1c02033eab8 | 33.584416 | 124 | 0.683815 | 5.434694 | false | false | false | false |
mikezucc/dojo-app | dojo/SocketIOClientSwift/SocketEventHandler.swift | 1 | 1890 | //
// EventHandler.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private func emitAckCallback(socket:SocketIOClient, num:Int)
// Curried
(items:AnyObject...) -> Void {
socket.emitAck(num, withData: items)
}
final class SocketEventHandler {
let event:String!
let callback:NormalCallback?
init(event:String, callback:NormalCallback) {
self.event = event
self.callback = callback
}
func executeCallback(_ items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
dispatch_async(dispatch_get_main_queue()) {
self.callback!(items, ack != nil ? emitAckCallback(socket!, ack!) : nil)
}
}
} | gpl-2.0 | 280576395818d7eb5cfc4fd75f038c09 | 38.395833 | 101 | 0.703175 | 4.209354 | false | false | false | false |
benlangmuir/swift | test/SILGen/witness-init-requirement-with-base-class-init.swift | 22 | 1948 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// RUN: %target-swift-emit-sil -verify %s
protocol BestFriend: class {
init()
static func create() -> Self
}
class Animal {
required init(species: String) {}
static func create() -> Self { return self.init() }
required convenience init() { self.init(species: "\(type(of: self))") }
}
class Dog: Animal, BestFriend {}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s4main3DogCAA10BestFriendA2aDPxycfCTW
// CHECK: [[SELF:%.*]] = apply
// CHECK: unchecked_ref_cast [[SELF]] : $Animal to $Dog
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s4main3DogCAA10BestFriendA2aDP6createxyFZTW
// CHECK: [[SELF:%.*]] = apply
// CHECK: unchecked_ref_cast [[SELF]] : $Animal to $Dog
class Base {
init() {}
convenience init(x: Int) {
self.init()
}
}
protocol Initable {
init(x: Int)
}
final class Derived : Base, Initable {}
// CHECK-LABEL: sil hidden [ossa] @$s4main4BaseC1xACSi_tcfC : $@convention(method) (Int, @thick Base.Type) -> @owned Base
// CHECK: [[METHOD:%.*]] = class_method [[SELF_META:%.*]] : $@thick Base.Type, #Base.init!allocator
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[SELF_META]])
// CHECK-NEXT: assign [[RESULT]] to [[BOX:%.*]] :
// CHECK-NEXT: [[FINAL:%.*]] = load [copy] [[BOX]]
// CHECK: return [[FINAL]]
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s4main7DerivedCAA8InitableA2aDP1xxSi_tcfCTW :
// CHECK: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type
// CHECK: [[METHOD:%.*]] = function_ref @$s4main4BaseC1xACSi_tcfC
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]](%1, [[SELF]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = unchecked_ref_cast [[RESULT]] : $Base to $Derived
// CHECK-NEXT: store [[NEW_SELF]] to [init] %0 : $*Derived
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ()
// CHECK-NEXT: return [[TUPLE]]
| apache-2.0 | 178de9e2b1e83e2f293818487e9f79aa | 36.461538 | 121 | 0.606263 | 3.230514 | false | false | false | false |
thiagolioy/SpaceCatSwift- | SpaceCatSwift/SpaceCatSwift/SpaceCatNode.swift | 1 | 521 | //
// SpaceCatNode.swift
// SpaceCatSwift
//
// Created by Thiago Lioy on 7/29/14.
// Copyright (c) 2014 Thiago Lioy. All rights reserved.
//
import SpriteKit
class SpaceCatNode: SKSpriteNode {
class func spaceCat(position:CGPoint!)-> SpaceCatNode {
let spaceCat = SpaceCatNode(imageNamed: "spacecat_1")
spaceCat.position = position;
spaceCat.anchorPoint = CGPointMake(0.5, 0);
spaceCat.name = "SpaceCat";
spaceCat.zPosition = 9;
return spaceCat
}
} | mit | 3c8af75128b826d96e38f2d5cdf42c73 | 22.727273 | 61 | 0.644914 | 3.695035 | false | false | false | false |
ZeeQL/ZeeQL3 | Tests/ZeeQLTests/FormatterTests.swift | 1 | 1370 | //
// FormatterTests.swift
// ZeeQL
//
// Created by Helge Hess on 24/02/17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import XCTest
@testable import ZeeQL
class FormatterTests: XCTestCase {
let person = [ "firstname": "Donald", "lastname": "Duck" ]
func testKeyValueStringFormatter1() {
let s = KeyValueStringFormatter.format("%(firstname)s %(lastname)s",
object: person)
XCTAssertEqual(s, "Donald Duck")
}
func testKeyValueStringFormatterPosArg() {
let s = KeyValueStringFormatter.format("%s %i", "Hello", 42)
XCTAssertEqual(s, "Hello 42")
}
func testKeyValueStringFormatterInvalidPercent() {
let s = KeyValueStringFormatter.format("%(murkel %i", "Hello", 42)
XCTAssertEqual(s, "%(murkel %i")
}
func testKeyValueStringFormatterEndInPercent() {
let s = KeyValueStringFormatter.format("%(firstname)s %", object: person)
XCTAssertEqual(s, "Donald %")
}
static var allTests = [
( "testKeyValueStringFormatter1", testKeyValueStringFormatter1 ),
( "testKeyValueStringFormatterPosArg", testKeyValueStringFormatterPosArg ),
( "testKeyValueStringFormatterInvalidPercent",
testKeyValueStringFormatterInvalidPercent ),
( "testKeyValueStringFormatterEndInPercent",
testKeyValueStringFormatterEndInPercent ),
]
}
| apache-2.0 | 4a1d0cacd41100c260370f8cb3c21ced | 29.422222 | 79 | 0.687363 | 4.359873 | false | true | false | false |
jakecraige/SwiftLint | Source/SwiftLintFramework/Rules/TypeBodyLengthRule.swift | 1 | 3178 | //
// TypeBodyLengthRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct TypeBodyLengthRule: ASTRule, ParameterizedRule {
public init() {}
public let identifier = "type_body_length"
public let parameters = [
RuleParameter(severity: .VeryLow, value: 200),
RuleParameter(severity: .Low, value: 250),
RuleParameter(severity: .Medium, value: 300),
RuleParameter(severity: .High, value: 350),
RuleParameter(severity: .VeryHigh, value: 400)
]
public func validateFile(file: File) -> [StyleViolation] {
return validateFile(file, dictionary: file.structure.dictionary)
}
public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] {
let substructure = dictionary["key.substructure"] as? XPCArray ?? []
return substructure.flatMap { subItem -> [StyleViolation] in
var violations = [StyleViolation]()
if let subDict = subItem as? XPCDictionary,
let kindString = subDict["key.kind"] as? String,
let kind = SwiftDeclarationKind(rawValue: kindString) {
violations.appendContentsOf(
self.validateFile(file, dictionary: subDict) +
self.validateFile(file, kind: kind, dictionary: subDict)
)
}
return violations
}
}
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
let typeKinds: [SwiftDeclarationKind] = [
.Class,
.Struct,
.Enum
]
if !typeKinds.contains(kind) {
return []
}
if let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }),
let bodyOffset = (dictionary["key.bodyoffset"] as? Int64).flatMap({ Int($0) }),
let bodyLength = (dictionary["key.bodylength"] as? Int64).flatMap({ Int($0) }) {
let location = Location(file: file, offset: offset)
let startLine = file.contents.lineAndCharacterForByteOffset(bodyOffset)
let endLine = file.contents.lineAndCharacterForByteOffset(bodyOffset + bodyLength)
for parameter in parameters.reverse() {
if let startLine = startLine?.line, let endLine = endLine?.line
where endLine - startLine > parameter.value {
return [StyleViolation(type: .Length,
location: location,
severity: parameter.severity,
reason: "Type body should be span 200 lines or less: currently spans " +
"\(endLine - startLine) lines")]
}
}
}
return []
}
public let example = RuleExample(
ruleName: "Type body Length Rule",
ruleDescription: "Type body should span 200 lines or less.",
nonTriggeringExamples: [],
triggeringExamples: [],
showExamples: false
)
}
| mit | 894d4b1d50a52c2452909f42ec58f865 | 37.289157 | 96 | 0.58905 | 4.919505 | false | false | false | false |
Aneapiy/Swift-HAR | Swift-HAR/NeuralNet.swift | 1 | 19541 | //
// NeuralNet.swift
// Swift-AI
//
// Created by Collin Hundley on 4/3/17.
//
//
import Foundation
import Accelerate
/// A 3-layer, feed-forward artificial neural network.
public final class NeuralNet {
// MARK: Errors
/// Possible errors that may be thrown by `NeuralNet`.
public enum Error: Swift.Error {
case initialization(String)
case weights(String)
case inference(String)
case train(String)
}
// MARK: Public properties
/// The basic structure of the neural network (read-only).
/// This includes the number of input, hidden and output nodes.
public let structure: Structure
/// The activation function to apply to hidden nodes during inference.
public var hiddenActivation: ActivationFunction
/// The activation function to apply to the output layer during inference.
public var outputActivation: ActivationFunction
/// The cost function to apply during backpropagation.
public var costFunction: CostFunction
/// The 'learning rate' parameter to apply during backpropagation.
/// This property may be safely mutated at any time.
public var learningRate: Float {
// Must update mfLR whenever this property is changed
didSet(newRate) {
cache.mfLR = (1 - momentumFactor) * newRate
}
}
/// The 'momentum factor' to apply during backpropagation.
/// This property may be safely mutated at any time.
public var momentumFactor: Float {
// Must update mfLR whenever this property is changed
didSet(newMomentum) {
cache.mfLR = (1 - newMomentum) * learningRate
}
}
// MARK: Private properties and caches
/// A set of pre-computed values and caches used internally for performance optimization.
fileprivate var cache: Cache
// MARK: Initialization
public init(structure: Structure, config: Configuration, weights: [Float]? = nil) throws {
// Initialize basic properties
self.structure = structure
self.hiddenActivation = config.hiddenActivation
self.outputActivation = config.outputActivation
self.costFunction = config.cost
self.learningRate = config.learningRate
self.momentumFactor = config.momentumFactor
// Initialize computed properties and caches
self.cache = Cache(structure: structure, config: config)
// Set initial weights, or randomize if none are provided
if let weights = weights {
try self.setWeights(weights)
} else {
randomizeWeights()
}
}
}
// MARK: Weights
public extension NeuralNet {
/// Resets the network with the given weights (i.e. from a pre-trained network).
/// This change may safely be performed at any time.
///
/// - Parameter weights: A serialized array of `Float`, to be used as hidden *and* output weights for the network.
/// - IMPORTANT: The number of weights must equal `hidden * (inputs + 1) + outputs * (hidden + 1)`, or the weights will be rejected.
public func setWeights(_ weights: [Float]) throws {
// Ensure valid number of weights
guard weights.count == structure.numHiddenWeights + structure.numOutputWeights else {
throw Error.weights("Invalid number of weights provided: \(weights.count). Expected: \(structure.numHiddenWeights + structure.numOutputWeights).")
}
// Reset all weights in the network
cache.hiddenWeights = Array(weights[0..<structure.numHiddenWeights])
cache.outputWeights = Array(weights[structure.numHiddenWeights..<weights.count])
}
/// Returns a serialized array of the network's current weights.
public func allWeights() -> [Float] {
return cache.hiddenWeights + cache.outputWeights
}
/// Randomizes all of the network's weights.
fileprivate func randomizeWeights() {
// Randomize hidden weights.
for i in 0..<structure.numHiddenWeights {
cache.hiddenWeights[i] = randomHiddenWeight()
}
for i in 0..<structure.numOutputWeights {
cache.outputWeights[i] = randomOutputWeight()
}
}
// TODO: Generate random weights along a normal distribution, rather than a uniform distribution.
// Also, these weights are optimized for sigmoid activation.
// Alternatives should be considered for other activation functions.
/// Generates a random weight for a hidden node, based on the parameters set for the network.
fileprivate func randomHiddenWeight() -> Float {
// Note: Hidden weight distribution depends on number of *input* nodes
return randomWeight(layerInputs: structure.numInputNodes)
}
/// Generates a random weight for an output node, based on the parameters set for the network.
fileprivate func randomOutputWeight() -> Float {
// Note: Output weight distribution depends on number of *hidden* nodes
return randomWeight(layerInputs: structure.numHiddenNodes)
}
/// Generates a single random weight.
///
/// - Parameter layerInputs: The number of inputs to the layer in which this weight will be used.
/// E.g., if this weight will be placed in the hidden layer, `layerInputs` should be the number of input nodes (including bias node).
/// - Returns: A randomly-generated weight optimized for this layer.
private func randomWeight(layerInputs: Int) -> Float {
let range = 1 / sqrt(Float(layerInputs))
let rangeInt = UInt32(2_000_000 * range)
let randomFloat = Float(arc4random_uniform(rangeInt)) - Float(rangeInt / 2)
return randomFloat / 1_000_000
}
}
// MARK: Inference
public extension NeuralNet {
// Note: The inference method is somewhat complex, but testing has shown that
// keeping the code in-line allows the Swift compiler to make better optimizations.
// Thus, we achieve improved performance at the cost of slightly less readable code.
/// Inference: propagates the given inputs through the neural network, returning the network's output.
/// This is the typical method for 'using' a trained neural network.
/// This is also used during the training process.
///
/// - Parameter inputs: An array of `Float`, each element corresponding to one input node.
/// - Returns: The network's output after applying the given inputs.
/// - Throws: An error if an incorrect number of inputs is provided.
/// - IMPORTANT: The number of inputs provided must exactly match the network's number of inputs (defined in its `Structure`).
@discardableResult
public func infer(_ inputs: [Float]) throws -> [Float] {
// Ensure that the correct number of inputs is given
guard inputs.count == structure.inputs else {
throw Error.inference("Invalid number of inputs provided: \(inputs.count). Expected: \(structure.inputs).")
}
// Cache the inputs
// Note: A bias node is inserted at index 0, followed by all of the given inputs
cache.inputCache[0] = 1
// Note: This loop appears to be the fastest way to make this happen
for i in 1..<structure.numInputNodes {
cache.inputCache[i] = inputs[i - 1]
}
// Calculate the weighted sums for the hidden layer inputs
vDSP_mmul(cache.hiddenWeights, 1,
cache.inputCache, 1,
&cache.hiddenOutputCache, 1,
vDSP_Length(structure.hidden), 1,
vDSP_Length(structure.numInputNodes))
// Apply the activation function to the hidden layer nodes
for i in (1...structure.hidden).reversed() {
// Note: Array elements are shifted one index to the right, in order to efficiently insert the bias node at index 0
cache.hiddenOutputCache[i] = hiddenActivation.activation(cache.hiddenOutputCache[i - 1])
}
cache.hiddenOutputCache[0] = 1
// Calculate the weighted sum for the output layer
vDSP_mmul(cache.outputWeights, 1,
cache.hiddenOutputCache, 1,
&cache.outputCache, 1,
vDSP_Length(structure.outputs), 1,
vDSP_Length(structure.numHiddenNodes))
// Apply the activation function to the output layer nodes
for i in 0..<structure.outputs {
cache.outputCache[i] = outputActivation.activation(cache.outputCache[i])
}
// Return the final outputs
return cache.outputCache
}
}
// MARK: Training
public extension NeuralNet {
// Note: The backpropagation method is somewhat complex, but testing has shown that
// keeping the code in-line allows the Swift compiler to make better optimizations.
// Thus, we achieve improved performance at the cost of slightly less readable code.
// Note: Refer to Chapter 3 in the following paper to view the equations applied
// for this backpropagation algorithm (with modifications to allow for customizable activation/cost functions):
// https://www.cheshireeng.com/Neuralyst/doc/NUG14x.pdf
/// Applies modifications to the neural network by comparing its most recent output to the given `labels`, adjusting the network's weights as needed.
/// This method should be used for training a neural network manually.
///
/// - Parameter labels: The 'target' desired output for the most recent inference cycle, as an array `[Float]`.
/// - Throws: An error if an incorrect number of outputs is provided.
/// - IMPORTANT: The number of labels provided must exactly match the network's number of outputs (defined in its `Structure`).
public func backpropagate(_ labels: [Float]) throws {
// Ensure that the correct number of outputs was given
guard labels.count == structure.outputs else {
throw Error.train("Invalid number of labels provided: \(labels.count). Expected: \(structure.outputs).")
}
// -----------------------------------------------------
//
// NOTE:
//
// In the following equations, it is assumed that the network has 3 layers.
// The subscripts [i], [j], [k] will be used to refer to input, hidden and output layers respectively.
// In networks with multiple hidden layers, [i] can be assumed to represent whichever layer preceeds the current layer (j),
// and [k] can be assumed to represent the succeeding layer.
//
// -----------------------------------------------------
// MARK: Output error gradients --------------------------------------
// Note: Rather than calculating the cost gradient with respect to each output weight,
// we calculate the gradient with respect to each output node's INPUT, cache the result,
// and then calculate the gradient for each weight while simultaneously updating the weight.
// This results in lower memory consumption and fewer calculations.
// Calculate the error gradient with respect to each output node's INPUT.
// e[k] = outputActivationDerivative(output) * costDerivative(output)
for (index, output) in cache.outputCache.enumerated() {
cache.outputErrorGradientsCache[index] = outputActivation.derivative(output) *
costFunction.derivative(real: output, target: labels[index])
}
// MARK: Hidden error gradients --------------------------------------
// Important: The cost function does not apply to hidden nodes.
// Instead, the cost derivative component is replaced with the sum of the nodes' error gradients in the succeeding layer
// (with respect to their inputs, as calculated above) multipled by the weight connecting this node to the following layer.
// Below, w' represents the previous (and still current) weight connecting this node to the following layer.
// e[j] = hiddenActivationDerivative(hiddenOutput) * Σ(e[k] * w'[j][k])
// Calculate the sums of the output error gradients multiplied by the output weights
vDSP_mmul(cache.outputErrorGradientsCache, 1,
cache.outputWeights, 1,
&cache.outputErrorGradientSumsCache, 1,
1, vDSP_Length(structure.numHiddenNodes),
vDSP_Length(structure.outputs))
// Calculate the error gradient for each hidden node, with respect to the node's INPUT
for (index ,error) in cache.outputErrorGradientSumsCache.enumerated() {
cache.hiddenErrorGradientsCache[index] = hiddenActivation.derivative(cache.hiddenOutputCache[index]) * error
}
// MARK: Output weights ----------------------------------------------
// Update output weights
// Note: In this equation, w' represents the current (old) weight and w'' represents the PREVIOUS weight.
// In addition, M represents the momentum factor and LR represents the learning rate.
// X[j] represents the jth input to the node (or, the activated output from the jth hidden node)
//
// w[j][k] = w′[j][k] + (1 − M) ∗ LR ∗ e[k] ∗ X[j] + M ∗ (w′[j][k] − w′′[j][k])
for index in 0..<structure.numOutputWeights {
// Pre-computed indices: translates the current weight index into the corresponding output error/hidden output indices
let outputErrorIndex = cache.outputErrorIndices[index]
let hiddenOutputIndex = cache.hiddenOutputIndices[index]
// Note: mFLR is a pre-computed constant which equals (1 - M) * LR
cache.newOutputWeights[index] = cache.outputWeights[index] -
cache.mfLR * cache.outputErrorGradientsCache[outputErrorIndex] * cache.hiddenOutputCache[hiddenOutputIndex] +
momentumFactor * (cache.outputWeights[index] - cache.previousOutputWeights[index])
}
// Efficiently copy output weights from current to 'previous' array
vDSP_mmov(cache.outputWeights,
&cache.previousOutputWeights, 1,
vDSP_Length(structure.numOutputWeights),
1, 1)
// Copy output weights from 'new' to current array
vDSP_mmov(cache.newOutputWeights,
&cache.outputWeights, 1,
vDSP_Length(structure.numOutputWeights),
1, 1)
// MARK: Hidden weights ----------------------------------------------
// Note: This process is almost identical to the process for updating the output weights,
// since the error gradients have already been calculated independently for each layer.
// Update hidden weights
// w[i][j] = w′[i][j] + (1 − M) ∗ LR ∗ e[j] ∗ X[i] + M ∗ (w′[i][j] − w′′[i][j])
for index in 0..<structure.numHiddenWeights {
// Pre-computed indices: translates the current weight index into the corresponding hidden error/input indices
let hiddenErrorIndex = cache.hiddenErrorIndices[index]
let inputIndex = cache.inputIndices[index]
// Note: mfLR is a pre-computed constant which equals (1 - M) * LR
cache.newHiddenWeights[index] = cache.hiddenWeights[index] -
// Note: +1 on hiddenErrorIndex to offset for bias 'error', which is ignored
cache.mfLR * cache.hiddenErrorGradientsCache[hiddenErrorIndex + 1] * cache.inputCache[inputIndex] +
momentumFactor * (cache.hiddenWeights[index] - cache.previousHiddenWeights[index])
}
// Copy hidden weights from current to 'previous' array
vDSP_mmov(cache.hiddenWeights,
&cache.previousHiddenWeights, 1,
vDSP_Length(structure.numHiddenWeights),
1, 1)
// Copy hidden weights from 'new' to current array
vDSP_mmov(cache.newHiddenWeights,
&cache.hiddenWeights, 1,
vDSP_Length(structure.numHiddenWeights),
1, 1)
}
/// Attempts to train the neural network using the given dataset.
///
/// - Parameters:
/// - data: A `Dataset` containing training and validation data, used to train the network.
/// - errorThreshold: The minimum acceptable error, as calculated by the network's cost function.
/// This error will be averaged across the validation set at the end of each training epoch.
/// Once the error has dropped below `errorThreshold`, training will cease and return.
/// This value must be determined by the user, as it varies based on the type of data and desired accuracy.
/// - Returns: A serialized array containing the network's final weights, as calculated during the training process.
/// - Throws: An error if invalid data is provided. Checks are performed in advance to avoid problems during the training cycle.
/// - WARNING: `errorThreshold` should be considered carefully. A value too high will produce a poorly-performing network, while a value too low (i.e. too accurate) may be unachievable, resulting in an infinite training process.
@discardableResult
public func train(_ data: Dataset, errorThreshold: Float, maxEpochs: Int) throws -> [Float] {
// Ensure valid error threshold
guard errorThreshold > 0 else {
throw Error.train("Training error threshold must be greater than zero.")
}
// -----------------------------
// TODO: Allow the trainer to exit early or regenerate new weights if it gets stuck in local minima
// -----------------------------
// Train forever until the desired error threshold is met
var epochCounter = 0
while true {
// Complete one full training epoch
for (index, input) in data.trainInputs.enumerated() {
// Note: We don't care about outputs or error on the training set
try infer(input)
try backpropagate(data.trainLabels[index])
}
// Calculate the total error of the validation set after each training epoch
var error: Float = 0
for (index, inputs) in data.validationInputs.enumerated() {
let outputs = try infer(inputs)
error += costFunction.cost(real: outputs, target: data.validationLabels[index])
}
// Divide error by number of sets to find average error across full validation set
error /= Float(data.validationInputs.count)
print(error)
// Escape training loop if the network has met the error threshold
if error < errorThreshold {
break
}
if epochCounter >= maxEpochs {
break
} else {
epochCounter += 1
}
}
// Return the weights of the newly-trained neural network
return allWeights()
}
}
| apache-2.0 | 0cfb301c5d8af4029a914bceaf33998d | 45.31829 | 232 | 0.626923 | 4.864056 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/ClosingBraceRule.swift | 4 | 2392 | //
// ClosingBraceRule.swift
// SwiftLint
//
// Created by Yasuhiro Inami on 12/19/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
private let whitespaceAndNewlineCharacterSet = CharacterSet.whitespacesAndNewlines
extension File {
fileprivate func violatingClosingBraceRanges() -> [NSRange] {
return match(pattern: "(\\}[ \\t]+\\))", excludingSyntaxKinds: SyntaxKind.commentAndStringKinds())
}
}
public struct ClosingBraceRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "closing_brace",
name: "Closing Brace Spacing",
description: "Closing brace with closing parenthesis " +
"should not have any whitespaces in the middle.",
nonTriggeringExamples: [
"[].map({ })",
"[].map(\n { }\n)"
],
triggeringExamples: [
"[].map({ ↓} )",
"[].map({ ↓}\t)"
],
corrections: [
"[].map({ ↓} )\n": "[].map({ })\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return file.violatingClosingBraceRanges().map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingClosingBraceRanges(), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "})")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
| mit | c8e604df3a4abc5599e2429d22c31d4a | 32.591549 | 110 | 0.612579 | 4.837728 | false | true | false | false |
fs/ios-base-swift | Swift-Base/Tools/Views/TextField.swift | 1 | 1470 | //
// TextField.swift
// Tools
//
// Created by Almaz Ibragimov on 06.01.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import UIKit
@IBDesignable public class TextField: UITextField {
// MARK: - Instance Properties
@IBInspectable public var leftInset: CGFloat = 8.0 {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable public var rightInset: CGFloat = 0.0 {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable public var topInset: CGFloat = 2.0 {
didSet {
self.setNeedsLayout()
}
}
@IBInspectable public var bottomInset: CGFloat = 0.0 {
didSet {
self.setNeedsLayout()
}
}
// MARK: -
public var isTextEmpty: Bool {
return self.text?.isEmpty ?? true
}
// MARK: - Instance Methods
public override func textRect(forBounds bounds: CGRect) -> CGRect {
let leftInset = (self.leftView?.frame.width ?? 0.0) + self.leftInset
let rightInset = (self.rightView?.frame.width ?? 0.0) + self.rightInset
return CGRect(x: leftInset,
y: self.topInset,
width: bounds.width - leftInset - rightInset,
height: bounds.height - self.topInset - self.bottomInset)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
| mit | 63c9acaba1859dd9589d30aca421bbd1 | 23.483333 | 79 | 0.582029 | 4.506135 | false | false | false | false |
nalexn/ViewInspector | Sources/ViewInspector/SwiftUI/NavigationView.swift | 1 | 1856 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct NavigationView: KnownViewType {
public static var typePrefix: String = "NavigationView"
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.NavigationView: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
let path: String
if #available(iOS 13.1, *) {
path = "content"
} else {
path = "_tree|content"
}
let view = try Inspector.attribute(path: path, value: content.view)
return try Inspector.viewsInContainer(view: view, medium: content.medium)
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: SingleViewContent {
func navigationView() throws -> InspectableView<ViewType.NavigationView> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: MultipleViewContent {
func navigationView(_ index: Int) throws -> InspectableView<ViewType.NavigationView> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Global View Modifiers
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func navigationViewStyle() throws -> Any {
let modifier = try self.modifier({ modifier -> Bool in
return modifier.modifierType.hasPrefix("NavigationViewStyleModifier")
}, call: "navigationViewStyle")
return try Inspector.attribute(path: "modifier|style", value: modifier)
}
}
| mit | b56a405545f8e47199766c6fe6fe782f | 30.457627 | 90 | 0.671875 | 4.208617 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Models/ViewModels/DayViewModel.swift | 2 | 1442 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
final class DayViewModel {
let day: Int
let today: Bool
let selected: Bool
let appointments: Int
init(day: Int, today: Bool, selected: Bool, appointments: Int) {
self.day = day
self.today = today
self.selected = selected
self.appointments = appointments
}
}
extension DayViewModel: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return day as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? DayViewModel else { return false }
return today == object.today && selected == object.selected && appointments == object.appointments
}
}
| apache-2.0 | 0027db516ac91f21b37b6b057f1e3f38 | 30.347826 | 106 | 0.711512 | 4.743421 | false | false | false | false |
sparklit/adbutler-ios-sdk | AdButler/AdButler/Placement+ImageView.swift | 1 | 1463 | //
// Placement+ImageView.swift
// AdButler
//
// Created by Ryuichi Saito on 12/3/16.
// Copyright © 2016 AdButler. All rights reserved.
//
import Foundation
public extension Placement {
/**
Asynchronously downloads the image for this `Placement`, and generates the corresponding image view with default gestures associated to it.
- Parameter completionHandler: a success callback block. The block will be given a `UIImageView`.
*/
@objc(getImageView:)
func getImageView(completionHandler complete: @escaping (UIImageView) -> Void) {
guard let imageUrl = imageUrl, let url = URL(string: imageUrl) else {
return
}
let session = URLSession(configuration: .ephemeral)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error requeseting an image with url \(url.absoluteString)")
}
guard let httpResponse = response as? HTTPURLResponse, let data = data, httpResponse.statusCode == 200 else {
return
}
DispatchQueue.main.async {
let image = UIImage(data: data)
let imageView = ABImageView(image: image)
imageView.placement = self
complete(imageView)
imageView.setupGestures()
}
}
task.resume()
}
}
| apache-2.0 | 774fc9a31d0438a2dda9297cad4ed8c1 | 33 | 144 | 0.588919 | 5.058824 | false | false | false | false |
paulofaria/SwiftHTTPServer | Mustache/Rendering/MustacheBox.swift | 3 | 9093 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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.
/**
Mustache templates don't eat raw values: they eat values boxed in `MustacheBox`.
To box something in a `MustacheBox`, you use one variant of the `Box()`
function. It comes in several variants so that nearly anything can be boxed and
feed templates:
- Basic Swift values:
template.render(Box("foo"))
- Dictionaries & collections:
template.render(Box(["numbers": [1,2,3]]))
- Custom types via the `MustacheBoxable` protocol:
extension User: MustacheBoxable { ... }
template.render(Box(user))
- Functions such as `FilterFunction`, `RenderFunction`, `WillRenderFunction` and
`DidRenderFunction`:
let square = Filter { (x: Int?) in Box(x! * x!) }
template.registerInBaseContext("square", Box(square))
**Warning**: the fact that `MustacheBox` is a subclass of NSObject is an
implementation detail that is enforced by the Swift 2 language itself. This may
change in the future: do not rely on it.
*/
public class MustacheBox {
// IMPLEMENTATION NOTE
//
// Why is MustacheBox a subclass of NSObject, and not, say, a Swift struct?
//
// Swift does not allow a class extension to override a method that is
// inherited from an extension to its superclass and incompatible with
// Objective-C.
//
// If MustacheBox were a pure Swift type, this Swift limit would prevent
// NSObject subclasses such as NSNull, NSNumber, etc. to override
// MustacheBoxable.mustacheBox, and provide custom rendering behavior.
//
// For an example of this limitation, see example below:
//
// import Foundation
//
// // A type that is not compatible with Objective-C
// struct MustacheBox { }
//
// // So far so good
// extension NSObject {
// var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// // Error: declarations in extensions cannot override yet
// extension NSNull {
// override var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// This problem does not apply to Objc-C compatible protocols:
//
// import Foundation
//
// // So far so good
// extension NSObject {
// var prop: String { return "NSObject" }
// }
//
// // No error
// extension NSNull {
// override var prop: String { return "NSNull" }
// }
//
// NSObject().prop // "NSObject"
// NSNull().prop // "NSNull"
//
// In order to let the user easily override NSObject.mustacheBox, we had to
// keep its return type compatible with Objective-C, that is to say make
// MustacheBox a subclass of NSObject.
// -------------------------------------------------------------------------
// MARK: - The boxed value
/// The boxed value.
public let value: Any?
/// The only empty box is `Box()`.
public let isEmpty: Bool
/**
The boolean value of the box.
It tells whether the Box should trigger or prevent the rendering of regular
`{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}`.
*/
public let boolValue: Bool
/**
If the boxed value can be iterated (Swift collection, NSArray, NSSet, etc.),
returns an array of `MustacheBox`.
*/
public var arrayValue: [MustacheBox]? {
return converter?.arrayValue()
}
/**
If the boxed value is a dictionary (Swift dictionary, NSDictionary, etc.),
returns a dictionary `[String: MustacheBox]`.
*/
public var dictionaryValue: [String: MustacheBox]? {
return converter?.dictionaryValue()
}
/**
Extracts a key out of a box.
let box = Box(["firstName": "Arthur"])
box["firstName"].value // "Arthur"
- parameter key: A key.
- returns: The MustacheBox for *key*.
*/
public subscript (key: String) -> MustacheBox {
return keyedSubscript?(key: key) ?? Box()
}
// -------------------------------------------------------------------------
// MARK: - Other facets
/// See the documentation of `RenderFunction`.
public private(set) var render: RenderFunction
/// See the documentation of `FilterFunction`.
public let filter: FilterFunction?
/// See the documentation of `WillRenderFunction`.
public let willRender: WillRenderFunction?
/// See the documentation of `DidRenderFunction`.
public let didRender: DidRenderFunction?
// -------------------------------------------------------------------------
// MARK: - Internal
let keyedSubscript: KeyedSubscriptFunction?
let converter: Converter?
init(
value: Any? = nil,
boolValue: Bool? = nil,
converter: Converter? = nil,
keyedSubscript: KeyedSubscriptFunction? = nil,
filter: FilterFunction? = nil,
render: RenderFunction? = nil,
willRender: WillRenderFunction? = nil,
didRender: DidRenderFunction? = nil)
{
let empty = (value == nil) && (keyedSubscript == nil) && (render == nil) && (filter == nil) && (willRender == nil) && (didRender == nil)
self.isEmpty = empty
self.value = value
self.converter = converter
self.boolValue = boolValue ?? !empty
self.keyedSubscript = keyedSubscript
self.filter = filter
self.willRender = willRender
self.didRender = didRender
if let render = render {
self.render = render
} else {
// The default render function: it renders {{variable}} tags as the
// boxed value, and {{#section}}...{{/}} tags by adding the box to
// the context stack.
//
// IMPLEMENTATIN NOTE
//
// We have to set self.render twice in order to avoid the compiler
// error: "variable 'self.render' captured by a closure before being
// initialized"
self.render = { (_) in return Rendering("") }
self.render = { (info: RenderingInfo) in
// Default rendering depends on the tag type:
switch info.tag.type {
case .Variable:
// {{ box }} and {{{ box }}}
if let value = value {
// Use the built-in Swift String Interpolation:
return Rendering("\(value)", .Text)
} else {
return Rendering("", .Text)
}
case .Section:
// {{# box }}...{{/ box }}
// Push the value on the top of the context stack:
let context = info.context.extendedContext(box: self)
// Renders the inner content of the section tag:
return try info.tag.render(context)
}
}
}
}
// Converter wraps all the conversion closures that help MustacheBox expose
// its raw value (typed Any) as useful types.
struct Converter {
let arrayValue: (() -> [MustacheBox]?)
let dictionaryValue: (() -> [String: MustacheBox]?)
init(
@autoclosure(escaping) arrayValue: () -> [MustacheBox]? = nil,
@autoclosure(escaping) dictionaryValue: () -> [String: MustacheBox]? = nil)
{
self.arrayValue = arrayValue
self.dictionaryValue = dictionaryValue
}
}
}
extension MustacheBox: CustomStringConvertible {
public var description: String {
if let value = value {
return "MustacheBox(\(value))"
} else {
return "MustacheBox"
}
}
}
| mit | 0533befc3e12e8ec57738035bb1fde9b | 32.061818 | 144 | 0.572921 | 5.020431 | false | false | false | false |
pisces/UIViewControllerTransitions | Example/UIViewControllerTransitionsExample/Source/NavigationMoveTransitionViewControllers.swift | 1 | 6069 | // BSD 2-Clause License
//
// Copyright (c) 2016 ~ 2021, Steve Kim
// 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.
//
// 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.
//
// NavigationMoveTransitionViewControllers.swift
// UIViewControllerTransitionsExample
//
// Created by pisces on 13/08/2017.
// Copyright © 2017 Steve Kim. All rights reserved.
//
import UIViewControllerTransitions
final class NavigationMoveTransitionFirstViewController: UIViewController {
// MARK: - Lifecycle
override var prefersStatusBarHidden: Bool {
false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
.default
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
.fade
}
override func viewDidLoad() {
super.viewDidLoad()
title = "First View"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "close", style: .plain, target: self, action: #selector(close))
navigationController?.navigationTransition = {
return $0
}(NavigationMoveTransition())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear -> \(type(of: self))")
UIView.animate(withDuration: 0.4, delay: 0, options: UIView.AnimationOptions(rawValue: 0), animations: {
self.setNeedsStatusBarAppearanceUpdate()
}, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear -> \(type(of: self))")
if let navigationController = navigationController {
navigationController.navigationTransition?.interactor?.attach(navigationController, present: secondViewController)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("viewWillDisappear -> \(type(of: self))")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear -> \(type(of: self))")
}
// MARK: - Private
private lazy var secondViewController: NavigationMoveTransitionSecondViewController = {
.init(nibName: "NavigationMoveTransitionSecondView", bundle: .main)
}()
@IBAction private func clicked() {
navigationController?.pushViewController(secondViewController, animated: true)
}
@objc private func close() {
dismiss(animated: true, completion: nil)
}
}
final class NavigationMoveTransitionSecondViewController: UITableViewController {
// MARK: - Lifecycle
override var prefersStatusBarHidden: Bool {
false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
.lightContent
}
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
.fade
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Second View"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear -> \(type(of: self))")
UIView.animate(withDuration: 0.4, delay: 0, options: UIView.AnimationOptions(rawValue: 0), animations: {
self.setNeedsStatusBarAppearanceUpdate()
}, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear -> \(type(of: self))")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("viewWillDisappear -> \(type(of: self))")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear -> \(type(of: self))")
}
// MARK: - Overridden: UITableViewController
override func numberOfSections(in tableView: UITableView) -> Int {
1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
50
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
100
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "UITableViewCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
return cell!
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.textLabel?.text = "\(indexPath.row + 1)"
}
}
| bsd-2-clause | 7fe523f0ae8d3ae943b97b7ab9a1f975 | 35.119048 | 129 | 0.68029 | 5.262793 | false | false | false | false |
r-dent/RGAppVersion | Sources/RGAppVersion.swift | 1 | 6282 | // Copyright (c) 2016 Roman Gille, http://romangille.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 Foundation
open class RGAppVersion {
/**
The current installation state of the app.
- NotDetermined: The current state is not determined. Run determineAppVersionState() to fix this.
- Installed: The app was fresh installed. This could also mean that you´ve run the app with RGAppVersion for the first time.
- Updated: The app ws launched after an update.
- NothingChanged: The app was just launched regular.
*/
enum RGAppVersionState {
case notDetermined, installed, updated, nothingChanged
}
fileprivate static let lastInstalledAppVersionKey = "rg.appVersion.lastInstalledAppVersion"
fileprivate static let lastInstalledBuildKey = "rg.appVersion.lastInstalledAppversion"
fileprivate static var _lastInstalledAppVersion: RGAppVersion?
fileprivate static var _currentAppVersion: RGAppVersion?
fileprivate static var _appVersionState = RGAppVersionState.notDetermined
/// The version string app.
open var appVersion: String?
/// The build number string.
open var buildNumber: String?
/// A combination of version and build. Like 1.7(47).
open var combinedVersion: String {
get {
if let appVersion = appVersion, let buildNumber = buildNumber {
return "\(appVersion)(\(buildNumber))"
}
return ""
}
}
class var defaults: UserDefaults {get {return UserDefaults.standard}}
/**
Initializer.
- Parameter appVersion: The app version string.
- Parameter buildNumber: The build number string.
*/
public init(appVersion: String?, buildNumber: String?) {
self.appVersion = appVersion
self.buildNumber = buildNumber
}
/**
Saves the values of the RGAppVersion object to user defaults.
*/
func setAsCurrentVersion() {
RGAppVersion.defaults.set(appVersion, forKey: RGAppVersion.lastInstalledAppVersionKey)
RGAppVersion.defaults.set(buildNumber, forKey: RGAppVersion.lastInstalledBuildKey)
RGAppVersion.defaults.synchronize()
}
/**
Gets app version and bundle identifier from bundle and user defaults and determines
the current installation state by comparing them.
This also saves the current app version to the user defaults.
*/
open class func determineAppVersionState() {
if _appVersionState != .notDetermined {
return
}
_currentAppVersion = RGAppVersion(
appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,
buildNumber: Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
)
_lastInstalledAppVersion = RGAppVersion(
appVersion: RGAppVersion.defaults.string(forKey: RGAppVersion.lastInstalledAppVersionKey),
buildNumber: RGAppVersion.defaults.string(forKey: RGAppVersion.lastInstalledBuildKey)
)
// App fresh installed.
if _lastInstalledAppVersion?.appVersion == nil {
_currentAppVersion?.setAsCurrentVersion()
_appVersionState = .installed
}
// App updated.
else if _lastInstalledAppVersion?.combinedVersion != _currentAppVersion?.combinedVersion {
_currentAppVersion?.setAsCurrentVersion()
_appVersionState = .updated
}
// Nothing changed.
else {
_appVersionState = .nothingChanged
}
}
/**
The current version of the app.
- Returns: A combination of app version and build number.
*/
open class func currentVersion() -> RGAppVersion {
if _appVersionState == .notDetermined {
RGAppVersion.determineAppVersionState()
}
return _currentAppVersion!
}
/**
The version, with witch the app was started the last time.
- Returns: A combination of app version and build number.
*/
open class func lastVersion() -> RGAppVersion? {
if _appVersionState == .notDetermined {
RGAppVersion.determineAppVersionState()
}
return (_lastInstalledAppVersion?.appVersion == nil) ? nil : _lastInstalledAppVersion
}
/**
Check if the app was newly installed.
A true value could also mean that the app was run the first time with RGAppVersion.
- Returns: A boolean value.
*/
open class func appIsFreshInstalled() -> Bool {
if _appVersionState == .notDetermined {
RGAppVersion.determineAppVersionState()
}
return _appVersionState == .installed
}
/**
Check if the app was launched after an update.
- Returns: A boolean value.
*/
open class func appWasUpdated() -> Bool {
if _appVersionState == .notDetermined {
RGAppVersion.determineAppVersionState()
}
return _appVersionState == .updated
}
}
| mit | 37d804850666f1654f23a35498746dc3 | 36.386905 | 132 | 0.655947 | 5.161052 | false | false | false | false |
GoldRong/LiveProject | LiveDemo/LiveDemo/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 1328 | //
// UIBarButtonItem-Extension.swift
// LiveDemo
//
// Created by Yang on 2017/7/24.
// Copyright © 2017年 Mr.Yang. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
//扩展类方法
/*
class func creatItem (imageName : String , highImageName : String , size : CGSize)->UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
btn.setImage(UIImage(named:highImageName), for: .highlighted)
btn.frame = CGRect.init(origin: CGPoint.zero, size: size)
return UIBarButtonItem.init(customView: btn)
}
*/
//便利构造函数
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero){
//1.创建UIButton
let btn = UIButton()
//2.设置Button图片
btn.setImage(UIImage(named:imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named:highImageName), for: .highlighted)
}
//3.设置图片尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect.init(origin: CGPoint.zero, size: size)
}
//4.创建UIBarButtonItem
self.init(customView: btn)
}
}
| mit | 3255d4300f8008ed13dfc81ef437a66a | 25.5625 | 104 | 0.578039 | 4.23588 | false | false | false | false |
nalexn/ViewInspector | Tests/ViewInspectorTests/Gestures/LongPressGestureTests.swift | 1 | 6184 | import XCTest
import SwiftUI
import Combine
@testable import ViewInspector
// MARK: - Long Press Gesture Tests
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
final class LongPressGestureTests: XCTestCase {
var longPressFinished: Bool?
private var _longPressValue: Any?
@available(tvOS 14.0, *)
private func longPressValue() throws -> LongPressGesture.Value {
return try Inspector.cast(value: _longPressValue!, type: LongPressGesture.Value.self)
}
private var _gestureTests: Any?
@available(tvOS 14.0, *)
private func gestureTests() throws -> CommonGestureTests<LongPressGesture> {
return try Inspector.cast(value: _gestureTests!, type: CommonGestureTests<LongPressGesture>.self)
}
override func setUpWithError() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
longPressFinished = false
_longPressValue = LongPressGesture.Value(finished: longPressFinished!)
_gestureTests = CommonGestureTests<LongPressGesture>(testCase: self,
gesture: LongPressGesture(),
value: try longPressValue(),
assert: assertLongPressValue)
}
override func tearDownWithError() throws {
longPressFinished = nil
_longPressValue = nil
_gestureTests = nil
}
func testCreateLongPressGestureValue() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
XCTAssertNotNil(longPressFinished)
let value = try longPressValue()
assertLongPressValue(value)
}
func testLongPressGestureMask() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().maskTest()
}
#if !os(tvOS)
func testLongPressGesture() throws {
let sut = EmptyView()
.gesture(LongPressGesture(minimumDuration: 5, maximumDistance: 1))
let longPressGesture = try sut.inspect().emptyView().gesture(LongPressGesture.self).actualGesture()
XCTAssertEqual(longPressGesture.minimumDuration, 5)
XCTAssertEqual(longPressGesture.maximumDistance, 1)
}
#endif
func testLongPressGestureWithUpdatingModifier() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().propertiesWithUpdatingModifierTest()
}
func testLongPressGestureWithOnChangedModifier() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().propertiesWithOnChangedModifierTest()
}
func testLongPressGestureWithOnEndedModifier() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().propertiesWithOnEndedModifierTest()
}
#if os(macOS)
func testLongPressGestureWithModifiers() throws {
try gestureTests().propertiesWithModifiersTest()
}
#endif
func testLongPressGestureFailure() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().propertiesFailureTest("LongPressGesture")
}
func testLongPressGestureCallUpdating() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callUpdatingTest()
}
func testLongPressGestureCallUpdatingNotFirst() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callUpdatingNotFirstTest()
}
func testLongPressGestureCallUpdatingMultiple() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callUpdatingMultipleTest()
}
func testLongPressGestureCallUpdatingFailure() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callUpdatingFailureTest()
}
func testLongPressGestureCallOnChanged() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnChangedTest()
}
func testLongPressGestureCallOnChangedNotFirst() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnChangedNotFirstTest()
}
func testLongPressGestureCallOnChangedMultiple() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnChangedMultipleTest()
}
func testLongPressGestureCallOnChangedFailure() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnChangedFailureTest()
}
func testLongPressGestureCallOnEnded() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnEndedTest()
}
func testLongPressGestureCallOnEndedNotFirst() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnEndedNotFirstTest()
}
func testLongPressGestureCallOnEndedMultiple() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnEndedMultipleTest()
}
func testLongPressGestureCallOnEndedFailure() throws {
guard #available(tvOS 14.0, *) else { throw XCTSkip() }
try gestureTests().callOnEndedFailureTest()
}
#if os(macOS)
func testLongPressGestureModifiers() throws {
try gestureTests().modifiersTest()
}
func testLongPressGestureModifiersNotFirst() throws {
try gestureTests().modifiersNotFirstTest()
}
func testLongPressGestureModifiersMultiple() throws {
try gestureTests().modifiersMultipleTest()
}
func testLongPressGestureModifiersNone() throws {
try gestureTests().modifiersNoneTest()
}
#endif
@available(tvOS 14.0, *)
func assertLongPressValue(
_ value: LongPressGesture.Value,
file: StaticString = #filePath,
line: UInt = #line) {
XCTAssertEqual(value, longPressFinished!)
}
}
| mit | 44a602a40a406bcd2601ad7dcfad182e | 34.337143 | 107 | 0.64586 | 4.888538 | false | true | false | false |
hectr/MRLocalNotificationFacade | Example/TableCell.swift | 1 | 578 |
import UIKit
class TableCell: UITableViewCell {
@IBOutlet weak var alertTitleTextfield: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
func setUp(notification: UILocalNotification) {
if (notification.fireDate!.timeIntervalSinceNow > 0) {
alertTitleTextfield.alpha = 1
datePicker.alpha = 1
} else {
alertTitleTextfield.alpha = 0.5
datePicker.alpha = 0.5
}
alertTitleTextfield.text = notification.alertBody
datePicker.date = notification.fireDate!
}
}
| mit | e39206d7089901ba22088de6b1e22ddf | 26.52381 | 62 | 0.641869 | 5.070175 | false | false | false | false |
attackFromCat/LivingTVDemo | LivingTVDemo/LivingTVDemo/Classes/Main/View/PageTitleView.swift | 1 | 6148 | //
// PageTitleView.swift
// LivingTVDemo
//
// Created by 李翔 on 2017/1/9.
// Copyright © 2017年 Lee Xiang. All rights reserved.
//
import UIKit
// MARK: - 代理协议
protocol PageTitleViewDelegate : class {
func titleLabelClick(_ titleView : PageTitleView, selectedIndex : Int)
}
// MARK: - 定义常量
fileprivate let kTitleUnderlineH : CGFloat = 2
fileprivate let kNormalColor : (CGFloat ,CGFloat ,CGFloat) = (85, 85, 85)
fileprivate let kSelectedColor : (CGFloat ,CGFloat ,CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
// MARK: - 属性
fileprivate var titles : [String]
fileprivate var currentIndex : Int = 0
weak var delegate : PageTitleViewDelegate?
// MARK: - 懒加载
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var titleUnderLine :UIView = {
let titleUnderLine = UIView()
titleUnderLine.backgroundColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0)
return titleUnderLine
}()
init(frame: CGRect, titles : [String]) {
self.titles = titles
super.init(frame: frame)
setUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
fileprivate func setUI() {
// 添加滚动视图
addSubview(scrollView)
scrollView.frame = bounds
// 添加滚动视图上面的label
createTitleLabers()
//设置底部分界线和滚动线条
createTitleUnderLine()
}
fileprivate func createTitleLabers() {
let titleLabelW : CGFloat = frame.width / CGFloat(titles.count)
let titleLabelH : CGFloat = frame.height - kTitleUnderlineH
let titleLabelY : CGFloat = 0
for (index, title) in titles.enumerated() {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.textAlignment = .center
label.text = title
label.tag = index
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2, alpha: 1.0)
let titleLabelX : CGFloat = CGFloat(index) * titleLabelW
label.frame = CGRect(x: titleLabelX, y: titleLabelY, width: titleLabelW, height: titleLabelH)
// 创建手势监听点击事件
label.isUserInteractionEnabled = true
let tapGestrue = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelDidClick(_:)))
label.addGestureRecognizer(tapGestrue)
scrollView.addSubview(label)
// 保存创建的label
titleLabels.append(label)
}
}
fileprivate func createTitleUnderLine() {
// 标题模块与滑动内容的分界线
let DividingLine = UIView()
let lineH : CGFloat = 0.5
DividingLine.backgroundColor = UIColor.lightGray
DividingLine.frame = CGRect(x: 0, y: frame.height - lineH, width: scrollView.frame.width, height: lineH)
scrollView.addSubview(DividingLine)
// 滚动滑块
guard let fristBtn = titleLabels.first else {return}
fristBtn.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0)
titleUnderLine.frame = CGRect(x: 0, y: frame.height - kTitleUnderlineH, width: fristBtn.frame.width, height: kTitleUnderlineH)
scrollView.addSubview(titleUnderLine)
}
}
// MARK: - label的点击事件
extension PageTitleView {
@objc func titleLabelDidClick(_ tapGest : UITapGestureRecognizer) {
// 拿到选中的label
guard let selectedLabel = tapGest.view as? UILabel else { return }
let prelabel = titleLabels[currentIndex]
// 变化颜色
prelabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2, alpha: 1.0)
selectedLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0)
// 重新记录当前下标
currentIndex = selectedLabel.tag
// 滑动下划线
let offSetX = CGFloat(currentIndex) * titleUnderLine.frame.width
UIView.animate(withDuration: 0.15) {
self.titleUnderLine.frame.origin.x = offSetX
}
// 代理传值
delegate?.titleLabelClick(self, selectedIndex: currentIndex)
}
}
// MARK: - 暴露的方法
extension PageTitleView {
func setTitleStatus(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
// 取出要进行变化的两个label
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 移动下划线
let offSetX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let lineOffsetX = offSetX * progress
titleUnderLine.frame.origin.x = sourceLabel.frame.origin.x + lineOffsetX
// 改变标题的颜色
// 取出颜色改变的范围
let colorRange = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2)
sourceLabel.textColor = UIColor(r: kSelectedColor.0 - colorRange.0 * progress, g: kSelectedColor.1 - colorRange.1 * progress, b: kSelectedColor.2 - colorRange.2 * progress, alpha: 1.0)
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorRange.0 * progress, g: kNormalColor.1 + colorRange.1 * progress, b: kNormalColor.2 + colorRange.2 * progress, alpha: 1.0)
// 记录最新的下标值
currentIndex = targetIndex
}
}
| mit | 3b665341c08c8760ec5b86af9ffcfd25 | 33.394118 | 192 | 0.624594 | 4.432904 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/Scenes/Menu/MenuViewController.swift | 1 | 3022 | //
// MenuViewController.swift
// Mah Income
//
// Created by Van Luu on 4/18/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import UIKit
class MenuItemModel {
var controllerIdentify: String
var img: String
var name: String
var color: UIColor
var isSelected = false
init(controllerIdentify: String, img: String, name: String, color: UIColor, isSelected: Bool = false) {
self.controllerIdentify = controllerIdentify
self.img = img
self.name = name
self.color = color
self.isSelected = isSelected
}
}
fileprivate let menuData = [
MenuItemModel(controllerIdentify: "ListPaymentViewController", img: "home", name: "Home", color: AppColor.Menu.home, isSelected: true),
MenuItemModel(controllerIdentify: "AddPaymentViewController", img: "plus", name: "Add Bill", color: AppColor.Menu.addBill),
MenuItemModel(controllerIdentify: "CategoryViewController", img: "category", name: "Category", color: AppColor.Menu.category),
MenuItemModel(controllerIdentify: "AnalyzeViewController", img: "analyze", name: "Analyze", color: AppColor.Menu.analyze),
MenuItemModel(controllerIdentify: "SettingViewController", img: "setting", name: "Setting", color: AppColor.Menu.setting),
]
class MenuViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var selectedMenu: MenuItemModel? = nil
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
selectedMenu = menuData.first!
}
@IBAction func handleButton(sender: UIButton) {
if parent! is MenuContainer {
(parent! as! MenuContainer).dismissMenu()
}
}
}
extension MenuViewController: MenuProtocol {
}
extension MenuViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell
let menuItem = menuData[indexPath.row]
cell.configure(menu: menuItem)
return cell
}
}
extension MenuViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let menuItem = menuData[indexPath.row]
if menuItem.isSelected {
return
}
selectedMenu?.isSelected = false
menuItem.isSelected = true
selectedMenu = menuItem
let cell = tableView.cellForRow(at: indexPath) as! MenuTableViewCell
cell.animate {[weak self] colorViewFrame in
guard let this = self else { return }
let colorViewOriginInParent = cell.convert(colorViewFrame.origin, to: this.view)
this.askContainerForPresentingNewScene(sceneIdentify: menuItem.controllerIdentify, menuItemPlace: CGRect(origin: colorViewOriginInParent, size: colorViewFrame.size))
}
}
}
| mit | 2967e8c2047cd24958a0174e4041b699 | 26.715596 | 171 | 0.720622 | 4.563444 | false | false | false | false |
danielpi/Swift-Playgrounds | Swift-Playgrounds/Using Swift With Cocoa And Objective-C/InteractingWithC-APIs.playground/section-1.swift | 1 | 6397 | // Interacting with C APIs
import Foundation
// Primitive Types
// Swift provides equivalents of C primitive integer types—for example, char, int, float, and double.
// However, there is no implicit conversion between these types and core Swift integer types, such as Int. Therefore, use these types if your code specifically requires them, but use Int wherever possible otherwise.
/*
C Type Swift Type
bool CBool
char, signed char CChar
unsigned char CUnsignedChar
short CShort
unsigned short CUnsignedShort
int CInt
unsigned int CUnsignedInt
long CLong
unsigned long CUnsignedLong
long long CLongLong
unsigned long long CUnsignedLongLong
wchar_t CWideChar
char16_t CChar16
char32_t CChar32
float CFloat
double CDouble
*/
// Enumerations
// Swift imports as a Swift enumeration any C-style enumeration marked with the NS_ENUM macro.
/*
Objective-C
typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
UITableViewCellStyleSubtitle
}
*/
enum UITableViewCellStyle: Int {
case Default
case Value1
case Value2
case Subtitle
}
// Swift also imports options marked with the NS_OPTIONS macro. Whereas options behave similarly to imported enumerations, options can also support some bitwise operations, such as &, |, and ~.
// Pointers
/* For Arguments
C Syntax Swift Syntax
------------------ -----------------------
const void * CConstVoidPointer
void * CMutableVoidPointer
const Type * CConstPointer<Type>
Type * CMutablePointer<Type>
*/
/* For return types, variables, and argument types more than one pointer level deep
C Syntax Swift Syntax
------------------ -----------------------
void * COpaquePointer
Type * UnsafePointer<Type>
*/
/* For Class Types
C Syntax Swift Syntax
------------------ -----------------------
Type * const * CConstPointer<Type>
Type * __strong * CMutablePointer<Type>
Type ** AutoreleasingUnsafePointer<Type>
*/
// C Mutable Pointers
// When a function is declared as taking a CMutablePointer<Type> argument, it can accept any of the following
// - nil, which is passed as a null pointer
// - A CMutablePointer<Type> value
// - An in-out expression whose operand is a stored lvalue of type Type, which is passed as the address of the lvalue
// - An in-out Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
func takesAMutablePointer(x: UnsafePointer<Float>) {
// Does something
}
var x: Float = 0.0
var p: UnsafePointer<Float> = nil
var a: [Float] = [1.0, 2.0, 3.0]
takesAMutablePointer(nil)
takesAMutablePointer(p)
takesAMutablePointer(&x)
takesAMutablePointer(&a)
/*
func takesAMutablePointer(x: UnsafePointer<Type>) {
}
var y: Int = 0
var p: UnsafePointer<Float> = nil
var q: UnsafePointer<Int> = nil
var b: [Int] = [1, 2, 3]
*/
// C Const Pointers
// CConstPointer<Type> argument, it can accept any of the following:
// - nil, which is passed as a null pointer
// - A CMutablePointer<Type>, CMutableVoidPointer, CConstPointer<Type>, CConstVoidPointer, or AutoreleasingUnsafePointer<Type> value, which is converted to CConstPointer<Type> if necessary
// - An in-out expression whose operand is an lvalue of type Type, which is passed as the address of the lvalue
// - A Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call
func takesAMutableVoidPointer(x:UnsafeMutablePointer<Void>) {
}
var x2: Float = 0.0, y2: Int = 0
var p2: UnsafeMutablePointer<Float> = nil, q2: UnsafeMutablePointer<Int> = nil
var a2: [Float] = [1.0, 2.0, 3.0], b2: [Int] = [1,2,3]
takesAMutableVoidPointer(nil)
takesAMutableVoidPointer(p2)
takesAMutableVoidPointer(p2)
takesAMutableVoidPointer(&x2)
takesAMutableVoidPointer(&y2)
takesAMutableVoidPointer(&a2)
takesAMutableVoidPointer(&b2)
// AutoreleasingUnsafePointer
// AutoreleasingUnsafePointer<Type>, it can accept any of the following:
// - nil, which is passed as a null pointer
// - An AutoreleasingUnsafePointer<Type> value
// - An in-out expression, whose operand is primitive-copied to a temporary nonowning buffer. The address of that buffer is passed to the callee, and on return, the value in the buffer is loaded, retained, and reassigned into the operand.
func takesAnAutoreleasingPointer(x: AutoreleasingUnsafeMutablePointer<NSDate?>) {
/* ... */
}
var z: NSDate? = nil
var r: AutoreleasingUnsafeMutablePointer<NSDate?> = nil
takesAnAutoreleasingPointer(nil)
takesAnAutoreleasingPointer(r)
takesAnAutoreleasingPointer(&z)
// Global Constants
// Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants.
// Preprocessor Directives
// The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.
// #define FADE_ANIMATION_DURATION 0.35
let FADE_ANIMATION_DURATION = 0.35
// the compiler automatically imports simple macros defined in C and Objective-C source
// Complex Macros are not transferred across.
// Build Configurations
// Swift code can be conditionally compiled based on the evaluation of Build Configurations.
// Build configurations include the literals true and false, command line flags and the platform testing functions listed below.
// You can specify command line flags using -D <#flag#>.
/*
Function Valid Arguments
------------------ -----------------------
os() OSX, iOS
arch() x86_64, arm, arm64, i386
*/
/*
#if <#build configuration#> && !<#build configuration#>
<#statements#>
#elseif <#build configuration#>
<#statements#>
#else
<#statements#>
#endif
*/
// Conditional compilation statements in Swift must completely surround blocks of code that are self-contained and syntactically valid.
| mit | 9305a7afa803b286e5b339d430333c37 | 34.926966 | 261 | 0.695543 | 4.329722 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.