repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
timpalpant/SwiftConstraint | refs/heads/master | ConstraintSolver/Solver.swift | lgpl-2.1 | 1 | //
// ConstraintSolver.swift
// ConstraintSolver
//
// Adapted from Python source by Timothy Palpant on 7/29/14.
//
// Copyright (c) 2005-2014 - Gustavo Niemeyer <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
public protocol Solver {
func solve<T: Hashable>(problem: Problem<T>, single:Bool) -> [[T]]
}
public class BacktrackingSolver : Solver {
let forwardCheck: Bool
public init(forwardCheck: Bool=true) {
self.forwardCheck = forwardCheck
}
public func solve<T: Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] {
problem.preprocess()
var queue: [(variable: Variable<T>, values: [T], pushdomains: [Domain<T>])] = []
var variable: Variable<T>!
var values: [T] = []
var pushdomains: [Domain<T>] = []
while true {
// Mix the Degree and Minimum Remaining Values (MRV) heuristics
var lst = problem.variables.map { variable in
(-variable.constraints.count, variable.domain.count, variable) }
lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 }
variable = nil
for (_, _, v) in lst {
if v.assignment == nil {
// Found unassigned variable
variable = v
values = Array(v.domain)
pushdomains = []
if self.forwardCheck {
for x in problem.variables {
if x.assignment == nil && x !== v {
pushdomains.append(x.domain)
}
}
}
break
}
}
if variable == nil {
// No unassigned variables. We have a solution
// Go back to last variable, if there is one
let sol = problem.variables.map { v in v.assignment! }
problem.solutions.append(sol)
if queue.isEmpty { // last solution
return problem.solutions
}
let t = queue.removeLast()
variable = t.variable
values = t.values
pushdomains = t.pushdomains
for domain in pushdomains {
domain.popState()
}
}
while true {
// We have a variable. Do we have any values left?
if values.count == 0 {
// No. Go back to the last variable, if there is one.
variable.assignment = nil
while !queue.isEmpty {
let t = queue.removeLast()
variable = t.variable
values = t.values
pushdomains = t.pushdomains
for domain in pushdomains {
domain.popState()
}
if !values.isEmpty {
break
}
variable.assignment = nil
}
if values.isEmpty {
return problem.solutions
}
}
// Got a value; check it
variable.assignment = values.removeLast()
for domain in pushdomains {
domain.pushState()
}
var good = true
for constraint in variable.constraints {
if !constraint.evaluate(self.forwardCheck) {
good = false
break // Value is not good
}
}
if good {
break
}
for domain in pushdomains {
domain.popState()
}
}
// Push state before looking for next variable.
queue += [(variable: variable!, values: values, pushdomains: pushdomains)]
}
}
}
public class RecursiveBacktrackingSolver : Solver {
let forwardCheck: Bool
public init(forwardCheck: Bool) {
self.forwardCheck = forwardCheck
}
public convenience init() {
self.init(forwardCheck: true)
}
private func recursiveBacktracking<T: Hashable>(var problem: Problem<T>, single:Bool=false) -> [[T]] {
var pushdomains = [Domain<T>]()
// Mix the Degree and Minimum Remaining Values (MRV) heuristics
var lst = problem.variables.map { variable in
(-variable.constraints.count, variable.domain.count, variable) }
lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 }
var missing: Variable<T>?
for (_, _, variable) in lst {
if variable.assignment == nil {
missing = variable
}
}
if var variable = missing {
pushdomains.removeAll()
if forwardCheck {
for v in problem.variables {
if v.assignment == nil {
pushdomains.append(v.domain)
}
}
}
for value in variable.domain {
variable.assignment = value
for domain in pushdomains {
domain.pushState()
}
var good = true
for constraint in variable.constraints {
if !constraint.evaluate(forwardCheck) {
good = false
break // Value is not good
}
}
if good { // Value is good. Recurse and get next variable
recursiveBacktracking(problem, single: single)
if !problem.solutions.isEmpty && single {
return problem.solutions
}
}
for domain in pushdomains {
domain.popState()
}
}
variable.assignment = nil
return problem.solutions
}
// No unassigned variables. We have a solution
let values = problem.variables.map { variable in variable.assignment! }
problem.solutions.append(values)
return problem.solutions
}
public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] {
problem.preprocess()
return recursiveBacktracking(problem, single: single)
}
}
func random_choice<T>(a: [T]) -> T {
let index = Int(arc4random_uniform(UInt32(a.count)))
return a[index]
}
func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let c = count(list)
for i in 0..<(c - 1) {
let j = Int(arc4random_uniform(UInt32(c - i))) + i
swap(&list[i], &list[j])
}
return list
}
public class MinConflictsSolver : Solver {
let steps: Int
public init(steps: Int=1_000) {
self.steps = steps
}
public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] {
problem.preprocess()
// Initial assignment
for variable in problem.variables {
variable.assignment = random_choice(variable.domain.elements)
}
for _ in 1...self.steps {
var conflicted = false
let lst = shuffle(problem.variables)
for variable in lst {
// Check if variable is not in conflict
var allSatisfied = true
for constraint in variable.constraints {
if !constraint.evaluate(false) {
allSatisfied = false
break
}
}
if allSatisfied {
continue
}
// Variable has conflicts. Find values with less conflicts
var mincount = variable.constraints.count
var minvalues: [T] = []
for value in variable.domain {
variable.assignment = value
var count = 0
for constraint in variable.constraints {
if !constraint.evaluate(false) {
count += 1
}
}
if count == mincount {
minvalues.append(value)
} else if count < mincount {
mincount = count
minvalues.removeAll()
minvalues.append(value)
}
}
// Pick a random one from these values
variable.assignment = random_choice(minvalues)
conflicted = true
}
if !conflicted {
let solution = problem.variables.map { variable in variable.assignment! }
problem.solutions.append(solution)
return problem.solutions
}
}
return problem.solutions
}
} | 27e2b84d08132e96913453bbbdc5d486 | 29.172185 | 104 | 0.585227 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/Views/YesterdailiesDialogView.swift | gpl-3.0 | 1 | //
// YesterdailiesDialogView.swift
// Habitica
//
// Created by Phillip on 08.06.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import PopupDialog
import Habitica_Models
import ReactiveSwift
class YesterdailiesDialogView: UIViewController, UITableViewDelegate, UITableViewDataSource, Themeable {
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var yesterdailiesHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var yesterdailiesTableView: UITableView!
@IBOutlet weak var checkinCountView: UILabel!
@IBOutlet weak var nextCheckinCountView: UILabel!
@IBOutlet weak var headerWrapperView: UIView!
@IBOutlet weak var tableViewWrapper: UIView!
@IBOutlet weak var checkinYesterdaysDailiesLabel: UILabel!
@IBOutlet weak var startDayButton: UIButton!
let taskRepository = TaskRepository()
private let userRepository = UserRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
var tasks: [TaskProtocol]?
override func viewDidLoad() {
super.viewDidLoad()
yesterdailiesTableView.delegate = self
yesterdailiesTableView.dataSource = self
let nib = UINib.init(nibName: "YesterdailyTaskCell", bundle: Bundle.main)
yesterdailiesTableView.register(nib, forCellReuseIdentifier: "Cell")
yesterdailiesTableView.rowHeight = UITableView.automaticDimension
yesterdailiesTableView.estimatedRowHeight = 60
updateTitleBanner()
startDayButton.setTitle(L10n.startMyDay, for: .normal)
ThemeService.shared.addThemeable(themable: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.cornerRadius = 16
view.superview?.superview?.cornerRadius = 16
startDayButton.layer.shadowRadius = 2
startDayButton.layer.shadowOffset = CGSize(width: 1, height: 1)
startDayButton.layer.shadowOpacity = 0.5
startDayButton.layer.masksToBounds = false
}
func applyTheme(theme: Theme) {
view.backgroundColor = theme.contentBackgroundColor
startDayButton.setTitleColor(.white, for: .normal)
startDayButton.backgroundColor = theme.fixedTintColor
tableViewWrapper.backgroundColor = theme.windowBackgroundColor
checkinCountView.textColor = theme.primaryTextColor
nextCheckinCountView.textColor = theme.secondaryTextColor
startDayButton.layer.shadowColor = ThemeService.shared.theme.buttonShadowColor.cgColor
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let window = view.window {
heightConstraint.constant = window.frame.size.height - 300
}
yesterdailiesHeightConstraint.constant = yesterdailiesTableView.contentSize.height
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? YesterdailyTaskCell
if let tasks = tasks {
cell?.configure(task: tasks[indexPath.item])
cell?.checkbox.wasTouched = {[weak self] in
self?.checkedCell(indexPath)
}
cell?.onChecklistItemChecked = {[weak self] item in
self?.checkChecklistItem(indexPath, item: item)
}
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
checkedCell(indexPath)
}
private func checkedCell(_ indexPath: IndexPath) {
if let tasks = tasks {
tasks[indexPath.item].completed = !tasks[indexPath.item].completed
yesterdailiesTableView.reloadRows(at: [indexPath], with: .fade)
}
}
private func checkChecklistItem(_ indexPath: IndexPath, item: ChecklistItemProtocol) {
item.completed = !item.completed
yesterdailiesTableView.reloadRows(at: [indexPath], with: .fade)
}
func updateTitleBanner() {
checkinCountView.text = L10n.welcomeBack
nextCheckinCountView.text = L10n.checkinYesterdaysDalies
}
@IBAction func allDoneTapped(_ sender: Any) {
handleDismiss()
dismiss(animated: true) {}
}
func handleDismiss() {
UserManager.shared.yesterdailiesDialog = nil
var completedTasks = [TaskProtocol]()
if let tasks = tasks {
for task in tasks where task.completed {
completedTasks.append(task)
}
}
userRepository.runCron(tasks: completedTasks)
}
}
| f4dba9e10dd0d99b755fc4406434ef37 | 34.934783 | 112 | 0.681589 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Decimator.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Decimator
//: Decimation is a type of digital distortion like bit crushing,
//: but instead of directly stating what bit depth and sample rate you want,
//: it is done through setting "decimation" and "rounding" parameters.
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
//: Next, we'll connect the audio sources to a decimator
var decimator = AKDecimator(player)
decimator.decimation = 0.5 // Normalized Value 0 - 1
decimator.rounding = 0.5 // Normalized Value 0 - 1
decimator.mix = 0.5 // Normalized Value 0 - 1
AudioKit.output = decimator
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Decimator")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKSlider(property: "Decimation", value: decimator.decimation) { sliderValue in
decimator.decimation = sliderValue
})
addView(AKSlider(property: "Rounding", value: decimator.rounding) { sliderValue in
decimator.rounding = sliderValue
})
addView(AKSlider(property: "Mix", value: decimator.mix) { sliderValue in
decimator.mix = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| 486709d40878b16fac6756413df8446a | 29.58 | 96 | 0.722041 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 24--Iron-Tips/IronTips/IronTips/TipsTableViewController.swift | cc0-1.0 | 1 | //
// TipsTableViewController.swift
// IronTips
//
// Created by Ben Gohlke on 11/5/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
class TipsTableViewController: UITableViewController, UITextFieldDelegate
{
var tips = [PFObject]()
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTip:")
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
if PFUser.currentUser() == nil
{
performSegueWithIdentifier("ShowLoginModalSegue", sender: self)
}
else
{
refreshTips()
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return tips.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TipCell", forIndexPath: indexPath) as! TipCell
let aTip = tips[indexPath.row]
if let comment = aTip["comment"] as? String
{
if comment == ""
{
cell.textField.becomeFirstResponder()
}
else
{
cell.textField.text = comment
}
}
else
{
cell.textField.becomeFirstResponder()
}
return cell
}
// MARK: - Parse Queries
func refreshTips()
{
if PFUser.currentUser() != nil
{
let query = PFQuery(className: "Tip")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil
{
self.tips = objects!
self.tableView.reloadData()
}
else
{
print(error?.localizedDescription)
}
}
}
}
/*
// Override to support conditional editing of the table view.
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 to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Action Handlers
@IBAction func unwindToTipsTableViewController(unwindSegue: UIStoryboardSegue)
{
refreshTips()
}
@IBAction func addTip(sender: UIBarButtonItem)
{
let aTip = PFObject(className: "Tip")
tips.insert(aTip, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - TextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
var rc = false
if textField.text != ""
{
rc = true
textField.resignFirstResponder()
let contentView = textField.superview
let cell = contentView?.superview as? TipCell
let indexPath = tableView.indexPathForCell(cell!)
let aTip = tips[indexPath!.row]
aTip["comment"] = textField.text
aTip.saveInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if succeeded
{
// object was saved to Parse
}
else
{
print(error?.localizedDescription)
}
}
}
return rc
}
}
| 2dfda1dfd15288790215b49511358137 | 28.770833 | 157 | 0.588174 | false | false | false | false |
Xiomara7/cv | refs/heads/master | Xiomara-Figueroa/customMenuView.swift | mit | 1 | //
// customMenu.swift
// Xiomara-Figueroa
//
// Created by Xiomara on 5/6/15.
// Copyright (c) 2015 UPRRP. All rights reserved.
//
import UIKit
class customMenuView: UIView {
var aboutButton: UIButton!
var workButton: UIButton!
var projectsButton: UIButton!
var extraButton: UIButton!
var workTitle: UILabel!
var projectsTitle: UILabel!
var extraTitle: UILabel!
var aboutTitle: UILabel!
var topLeft: UIImageView!
var bottomRigth: UIImageView!
var topRight: UIImageView!
var bottomLeft: UIImageView!
var shouldSetupConstraints = true
init() {
super.init(frame: CGRectZero)
self.backgroundColor = UIColor.whiteColor()
let imageWidth = UIScreen.mainScreen().bounds.width / 2
let imageHeight = UIScreen.mainScreen().bounds.height / 2
topLeft = UIImageView(frame: CGRectMake(0.0,
0.0,
imageWidth,
imageHeight))
bottomRigth = UIImageView(frame: CGRectMake(imageWidth,
imageHeight,
imageWidth,
imageHeight))
topRight = UIImageView(frame: CGRectMake(imageWidth,
0.0,
imageWidth,
imageHeight))
bottomLeft = UIImageView(frame: CGRectMake(0.0,
imageHeight,
imageWidth,
imageHeight))
aboutButton = button(imageName:"button_About")
workButton = button(imageName: "button_Work")
projectsButton = button(imageName: "button_Projects")
extraButton = button(imageName:"button_Extra")
workTitle = label(title:"WORK")
extraTitle = label(title:"OUTREACH")
projectsTitle = label(title:"PROJECTS")
aboutTitle = label(title:"ABOUT")
self.addSubview(aboutButton)
self.addSubview(workButton)
self.addSubview(projectsButton)
self.addSubview(extraButton)
self.addSubview(topLeft)
self.addSubview(topRight)
self.addSubview(bottomRigth)
self.addSubview(bottomLeft)
self.addSubview(workTitle)
self.addSubview(aboutTitle)
self.addSubview(projectsTitle)
self.addSubview(extraTitle)
aboutButton.setTranslatesAutoresizingMaskIntoConstraints(false)
updateConstraints()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class label: UILabel {
init(title: String) {
super.init(frame: CGRectZero)
self.font = UIFont.boldSystemFontOfSize(20.0)
self.textColor = UIColor.grayColor()
self.text = title
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class button: UIButton {
init(imageName: String) {
super.init(frame: CGRectZero)
self.setImage(UIImage(named: imageName), forState: .Normal)
self.backgroundColor = UIColor.whiteColor()
self.sizeToFit()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
override func updateConstraints() {
super.updateConstraints()
if shouldSetupConstraints {
// AutoLayout
workButton.autoAlignAxis(.Horizontal, toSameAxisOfView: topLeft)
workButton.autoAlignAxis(.Vertical, toSameAxisOfView: topLeft)
workTitle.autoPinEdge(.Top, toEdge: .Bottom, ofView: workButton, withOffset: 20.0)
workTitle.autoAlignAxis(.Vertical, toSameAxisOfView: workButton)
aboutButton.autoAlignAxis(.Horizontal, toSameAxisOfView: bottomRigth)
aboutButton.autoAlignAxis(.Vertical, toSameAxisOfView: bottomRigth)
aboutTitle.autoPinEdge(.Bottom, toEdge: .Top, ofView: aboutButton, withOffset: -20.0)
aboutTitle.autoAlignAxis(.Vertical, toSameAxisOfView: aboutButton)
extraButton.autoAlignAxis(.Horizontal, toSameAxisOfView: bottomLeft)
extraButton.autoAlignAxis(.Vertical, toSameAxisOfView: bottomLeft)
extraTitle.autoPinEdge(.Bottom, toEdge: .Top, ofView: extraButton, withOffset: -20.0)
extraTitle.autoAlignAxis(.Vertical, toSameAxisOfView: extraButton)
projectsButton.autoAlignAxis(.Horizontal, toSameAxisOfView: topRight)
projectsButton.autoAlignAxis(.Vertical, toSameAxisOfView: topRight)
projectsTitle.autoPinEdge(.Top, toEdge: .Bottom, ofView: projectsButton, withOffset: 20.0)
projectsTitle.autoAlignAxis(.Vertical, toSameAxisOfView: projectsButton)
shouldSetupConstraints = false
}
}
}
| c789d1d65d8c83380f32a7f88c70d88e | 34.141026 | 102 | 0.55892 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | refs/heads/master | Exercises and Basic Principles/azure-search-basics/azure-search-basics/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// azure-search-basics
//
// Created by Mark Hamilton on 3/10/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.dryverless.azure_search_basics" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("azure_search_basics", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 2c324ead8b50246ec5cbbf88769893f9 | 54.198198 | 291 | 0.720255 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/MagazineLayout-master/MagazineLayout/LayoutCore/Types/ElementLocation.swift | mit | 1 | // Created by bryankeller on 8/13/18.
// Copyright © 2018 Airbnb, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Represents the location of an item in a section.
///
/// Initializing a `ElementLocation` is measurably faster than initializing an `IndexPath`.
/// On an iPhone X, compiled with -Os optimizations, it's about 35x faster to initialize this struct
/// compared to an `IndexPath`.
struct ElementLocation: Hashable {
// MARK: Lifecycle
init(elementIndex: Int, sectionIndex: Int) {
self.elementIndex = elementIndex
self.sectionIndex = sectionIndex
}
init(indexPath: IndexPath) {
if indexPath.count == 2 {
elementIndex = indexPath.item
sectionIndex = indexPath.section
} else {
// `UICollectionViewFlowLayout` is able to work with empty index paths (`IndexPath()`). Per
// the `IndexPath` documntation, an index path that uses `section` or `item` must have exactly
// 2 elements. If not, we default to {0, 0} to prevent crashes.
elementIndex = 0
sectionIndex = 0
}
}
// MARK: Internal
let elementIndex: Int
let sectionIndex: Int
var indexPath: IndexPath {
return IndexPath(item: elementIndex, section: sectionIndex)
}
}
| ade0db4bf1d6161b9d2ce3148dd5f62f | 31.481481 | 100 | 0.710946 | false | false | false | false |
vgorloff/AUHost | refs/heads/master | Vendor/mc/mcxTypes/Sources/Sources/MinMax.swift | mit | 1 | //
// MinMax.swift
// MCA-OSS-AUH
//
// Created by Vlad Gorlov on 06/05/16.
// Copyright © 2016 Vlad Gorlov. All rights reserved.
//
public struct MinMax<T: Comparable> {
public var min: T
public var max: T
public init(min aMin: T, max aMax: T) {
min = aMin
max = aMax
assert(min <= max)
}
public init(valueA: MinMax, valueB: MinMax) {
min = Swift.min(valueA.min, valueB.min)
max = Swift.max(valueA.max, valueB.max)
}
}
extension MinMax where T: Numeric {
public var difference: T {
return max - min
}
}
extension MinMax where T: FloatingPoint {
public var difference: T {
return max - min
}
}
| 4e80fd5715d3b2ee8782f6cf6a325d33 | 17.777778 | 54 | 0.609467 | false | false | false | false |
sawijaya/UIFloatPHTextField | refs/heads/master | UIFloatPHTextField/Item.swift | mit | 1 | //
// Item.swift
//
// Created by Salim Wijaya
// Copyright © 2017. All rights reserved.
//
import Foundation
import UIKit
public protocol ItemConvertible {
associatedtype TypeData
}
public enum ItemImage: ItemConvertible {
public typealias TypeData = ItemImage
case Image(UIImage)
case Data(Data)
case String(String)
public static func dataType(_ dataType: Any?) -> TypeData? {
switch (dataType) {
case let image as UIImage:
return ItemImage.Image(image)
case let data as Data:
return ItemImage.Data(data)
case let string as String:
return ItemImage.String(string)
default:
return nil
}
}
public var image : UIImage! {
switch (self) {
case .Image(let image):
return image
default:
return nil
}
}
public var data : Data! {
switch (self) {
case .Data(let data):
return data
default:
return nil
}
}
public var string : String! {
switch (self) {
case .String(let string):
return string
default:
return nil
}
}
}
public struct Item<T: ItemConvertible> {
public var text: String?
public var value: String?
public var image: T?
public var data:[String:Any]?
public init(data:[String:Any]) {
self.text = data["text"] as? String
self.value = data["value"] as? String
let itemImage = ItemImage.dataType(data["image"])
self.image = itemImage as? T
self.data = data
}
}
| b59a394670338b5d139407495c4ffa3b | 22.105263 | 64 | 0.527904 | false | false | false | false |
AHuaner/Gank | refs/heads/master | Gank/AHMainViewController.swift | mit | 2 | //
// AHMainViewController.swift
// Gank
//
// Created by CoderAhuan on 2016/12/7.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
class AHMainViewController: BaseViewController {
lazy var tabBarVC: TabBarController = {
let tabBarVC = TabBarController()
tabBarVC.delegate = self
return tabBarVC
}()
lazy var LaunchVC: AHLaunchViewController = {
let LaunchVC = AHLaunchViewController(showTime: 3)
LaunchVC.launchComplete = { [unowned self] in
self.view.addSubview(self.tabBarVC.view)
self.addChildViewController(self.tabBarVC)
}
return LaunchVC
}()
override func viewDidLoad() {
super.viewDidLoad()
setupLaunchVC()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupLaunchVC() {
addChildViewController(LaunchVC)
view.addSubview(LaunchVC.view)
}
}
extension AHMainViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
NotificationCenter.default.post(name: NSNotification.Name.AHTabBarDidSelectNotification, object: nil)
}
}
| a762247fe044f0e85a3ead7656b600fb | 26.319149 | 111 | 0.676791 | false | false | false | false |
NjrSea/FlickTransition | refs/heads/master | FlickTransition/DismissAnimationController.swift | mit | 1 | //
// DismissAnimationController.swift
// FlickTransition
//
// Created by paul on 16/9/18.
// Copyright © 2016年 paul. All rights reserved.
//
import UIKit
class DismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate let scaling: CGFloat = 0.95
var dismissDirection: Direction = .Left
var dismissDuration = 0.2
fileprivate var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0, alpha: 0.4)
return view
}()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return dismissDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else {
return
}
let containerView = transitionContext.containerView
guard let snapshot = toVC.view.snapshotView(afterScreenUpdates: true) else {
return
}
snapshot.addSubview(dimmingView)
snapshot.frame = toVC.view.bounds
dimmingView.frame = snapshot.bounds
dimmingView.alpha = 1.0
snapshot.layer.transform = CATransform3DScale(CATransform3DIdentity, self.scaling, self.scaling, 1)
containerView.insertSubview(snapshot, at: 0)
toVC.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: {
snapshot.layer.transform = CATransform3DIdentity
self.dimmingView.alpha = 0.0
var frame = fromVC.view.frame
switch self.dismissDirection {
case .Left:
frame.origin.x = -frame.width
fromVC.view.frame = frame
case .Right:
frame.origin.x = frame.width
fromVC.view.frame = frame
case .Up:
frame.origin.y = -frame.height
fromVC.view.frame = frame
case .Down:
frame.origin.y = frame.height
fromVC.view.frame = frame
}
}) { _ in
snapshot.removeFromSuperview()
self.dimmingView.removeFromSuperview()
toVC.view.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| fdac12463b427ccd6f5e78c81550bd03 | 33.705128 | 111 | 0.623938 | false | false | false | false |
tachun77/todoru2 | refs/heads/master | SwipeTableViewCell/CompleteViewController.swift | mit | 1 | //
// Todoル
// SwipeTableViewCell
//
// Created by 福島達也 on 2016/06/25.
// Copyright © 2016年 福島達也. All rights reserved.
//
import UIKit
import BubbleTransition
class CompleteViewController: UIViewController ,UIViewControllerTransitioningDelegate{
let saveData = NSUserDefaults.standardUserDefaults()
var monsterArray : [UIImage]!
var haikeiArray : [UIImage]!
@IBOutlet var kkeiken : UILabel!
@IBOutlet var monsterImageView : UIImageView!
@IBOutlet var haikeiImageView : UIImageView!
@IBOutlet var sinkagamen : UIButton!
@IBOutlet var serihu : UILabel!
@IBOutlet var hukidasi : UIImageView!
@IBOutlet var tolist : UIButton!
@IBOutlet var tosinka : UIButton!
@IBOutlet var anatano : UILabel!
let transition = BubbleTransition()
var startingPoint = CGPointZero
var duration = 20.0
var transitionMode: BubbleTransitionMode = .Present
var bubbleColor: UIColor = .yellowColor()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController
controller.transitioningDelegate = self
controller.modalPresentationStyle = .Custom
}
func colorWithHexString (hex:String) -> UIColor {
let cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if ((cString as String).characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringWithRange(NSRange(location: 0, length: 2))
let gString = (cString as NSString).substringWithRange(NSRange(location: 2, length: 2))
let bString = (cString as NSString).substringWithRange(NSRange(location: 4, length: 2))
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(
red: CGFloat(Float(r) / 255.0),
green: CGFloat(Float(g) / 255.0),
blue: CGFloat(Float(b) / 255.0),
alpha: CGFloat(Float(1.0))
)
}
// MARK: UIViewControllerTransitioningDelegate
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Present
transition.startingPoint = tolist.center
transition.bubbleColor = UIColor.whiteColor()
return transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Dismiss
transition.startingPoint = tosinka.center
transition.bubbleColor = UIColor.whiteColor()
return transition
}
// @IBAction func modoru(){
//
// self.presentViewController(ListTableViewController,animated:true, completion: nil)
//
// }
override func viewDidLoad() {
super.viewDidLoad()
let keiken : AnyObject = saveData.integerForKey("keikenchi")
let keikenchinow = String(keiken)
kkeiken.text = keikenchinow
let keikenchinow2 = Int(keikenchinow)
monsterArray = [UIImage(named:"anpo_1.png")!,UIImage(named:"rev_1.png")!,UIImage(named:"load.png")!,UIImage(named:"anpo_11.png")!,UIImage(named:"rev_11.png")!]
if keikenchinow2 == 1000{
monsterImageView.image = monsterArray[3]
}
else if keikenchinow2 < 1000 {
monsterImageView.image = monsterArray[0]
} else if keikenchinow2 < 2000 && 1000 < keikenchinow2{
monsterImageView.image = monsterArray[1]
} else if keikenchinow2 == 2000 {
monsterImageView.image = monsterArray[4]
}else{
monsterImageView.image = monsterArray[2]
}
// haikeiArray = [UIImage(named:"[email protected]")!]
//
// if keikenchinow2 > 2000{
// haikeiImageView.image = haikeiArray[0]
// }
if keikenchinow2 == 1000 || keikenchinow2 == 2000 {
self.sinkagamen.hidden = false
serihu.hidden = true
hukidasi.hidden = true
tolist.hidden = true
anatano.hidden = true
self.view.backgroundColor = UIColor.whiteColor()
kkeiken.hidden = true
} else {
self.sinkagamen.hidden = true
serihu.hidden = false
hukidasi.hidden = false
tolist.hidden = false
anatano.hidden = false
kkeiken.hidden = false
}
let serihuArray = ["NICE!","Wonderful!","いいね!","...やるじゃん","Fantastic!!!","oh yeah!","経験値ありがと!"]
let number = Int(rand() % 7)
serihu.text = serihuArray[number]
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
// let keikenchinow : AnyObject = saveData.objectForKey("keiken") as! Int
//
// kkeiken.text = keikenchinow["keiken"]
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let keiken : AnyObject = saveData.integerForKey("keikenchi")
let keikenchinow = String(keiken)
kkeiken.text = keikenchinow
let keikenchinow2 = Int(keikenchinow)
if keikenchinow2 == 1000 || keikenchinow2 == 2000{
UIImageView.animateWithDuration(0.5, delay: 0.0,
options: UIViewAnimationOptions.Repeat, animations: { () -> Void in self.monsterImageView.alpha = 0.0
}, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tosinkagamen(sender : UIButton){
performSegueWithIdentifier("tosinka", sender: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 9b6542161fa005d413a3563814566bc1 | 34.178947 | 217 | 0.62687 | false | false | false | false |
xxxAIRINxxx/ViewPagerController | refs/heads/master | Sources/UIColor+RGBA.swift | mit | 1 | //
// UIColor+RGBA.swift
// ViewPagerController
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
public struct RGBA {
var red : CGFloat = 0.0
var green : CGFloat = 0.0
var blue : CGFloat = 0.0
var alpha : CGFloat = 0.0
}
public extension UIColor {
public func getRGBAStruct() -> RGBA {
let components = self.cgColor.components
let colorSpaceModel = self.cgColor.colorSpace?.model
if colorSpaceModel?.rawValue == CGColorSpaceModel.rgb.rawValue && self.cgColor.numberOfComponents == 4 {
return RGBA(
red: components![0],
green: components![1],
blue: components![2],
alpha: components![3]
)
} else if colorSpaceModel?.rawValue == CGColorSpaceModel.monochrome.rawValue && self.cgColor.numberOfComponents == 2 {
return RGBA(
red: components![0],
green: components![0],
blue: components![0],
alpha: components![1]
)
} else {
return RGBA()
}
}
}
| 8e96bf1caadb512c5e3c6a102aba67bc | 27 | 126 | 0.559801 | false | false | false | false |
mparrish91/gifRecipes | refs/heads/master | test/CAPTCHATest.swift | mit | 1 | //
// CAPTCHATest.swift
// reddift
//
// Created by sonson on 2015/05/07.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import XCTest
#if os(iOS)
import UIKit
#endif
class CAPTCHATest: SessionTestSpec {
func testCheckWhetherCAPTCHAIsNeededOrNot() {
let msg = "is true or false as Bool"
print(msg)
var check_result: Bool? = nil
let documentOpenExpectation = self.expectation(description: msg)
do {
try self.session?.checkNeedsCAPTCHA({(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let check):
check_result = check
}
XCTAssert(check_result != nil, msg)
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
// now, CAPTCHA API does not work.....?
// func testGetIdenForNewCAPTCHA() {
// let msg = "is String"
// print(msg)
// var iden: String? = nil
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let identifier):
// iden = identifier
// }
// XCTAssert(iden != nil, msg)
// documentOpenExpectation.fulfill()
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
// }
// now, CAPTCHA API does not work.....?
// func testSizeOfNewImageGeneratedUsingIden() {
// let msg = "is 120x50"
// print(msg)
//#if os(iOS) || os(tvOS)
// var size: CGSize? = nil
//#elseif os(macOS)
// var size: NSSize? = nil
//#endif
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let string):
// try! self.session?.getCAPTCHA(string, completion: { (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let image):
// size = image.size
// }
// documentOpenExpectation.fulfill()
// })
// }
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
//
// if let size = size {
//#if os(iOS)
// XCTAssert(size == CGSize(width: 120, height: 50), msg)
//#elseif os(macOS)
// XCTAssert(size == NSSize(width: 120, height: 50), msg)
//#endif
// } else {
// XCTFail(msg)
// }
// }
}
| 4d44ef1c895ad7c386cc7f462f66c1e7 | 33.02 | 93 | 0.509112 | false | true | false | false |
MFaarkrog/Apply | refs/heads/master | Example/Apply/simple/SimpleStylesheet.swift | mit | 1 | //
// SimpleStylesheet.swift
// Apply
//
// Created by Morten Faarkrog on 6/7/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
struct Styles {
struct Colors {
static let primary = UIColor.black
static let secondary = UIColor.darkGray
static let button = UIColor.blue
static let background = UIColor.white
}
struct Fonts {
static let h1 = UIFont.systemFont(ofSize: 22)
static let h2 = UIFont.systemFont(ofSize: 17)
static let body = UIFont.systemFont(ofSize: 15)
static let button = UIFont.boldSystemFont(ofSize: 15)
}
}
| 233872ac804986a385eb7f4b1dfc2db2 | 21.111111 | 57 | 0.683417 | false | false | false | false |
macemmi/HBCI4Swift | refs/heads/master | HBCI4Swift/HBCI4Swift/Source/Orders/HBCITanOrder.swift | gpl-2.0 | 1 | //
// HBCITanOrder.swift
// HBCI4Swift
//
// Created by Frank Emminghaus on 02.03.15.
// Copyright (c) 2015 Frank Emminghaus. All rights reserved.
//
import Foundation
class HBCITanOrder : HBCIOrder {
// we only support process variant 2 by now
var process:String?
var orderRef:String?
var listIndex:String?
var tanMediumName:String?
// results
var challenge:String?
var challenge_hhd_uc:Data?
// todo(?)
init?(message:HBCICustomMessage) {
super.init(name: "TAN", message: message);
if self.segment == nil {
return nil;
}
}
func finalize(_ refOrder:HBCIOrder?) ->Bool {
if let process = self.process {
var values:Dictionary<String,Any> = ["process":process, "notlasttan":false];
if tanMediumName != nil {
values["tanmedia"] = tanMediumName!
}
/*
if process == "1" || process == "2" {
values["notlasttan"] = false;
}
*/
if orderRef != nil {
values["orderref"] = orderRef;
}
if let refOrder = refOrder {
values["ordersegcode"] = refOrder.segment.code;
}
if segment.setElementValues(values) {
return true;
} else {
logInfo("Values could not be set for TAN order");
return false;
}
} else {
logInfo("Could not create TAN order - missing process info");
return false;
}
}
func enqueue() ->Bool {
if finalize(nil) {
return msg.addOrder(self);
}
return false;
}
override func updateResult(_ result:HBCIResultMessage) {
super.updateResult(result);
// get challenge information
if let seg = resultSegments.first {
self.challenge = seg.elementValueForPath("challenge") as? String;
self.orderRef = seg.elementValueForPath("orderref") as? String;
if seg.version > 3 {
self.challenge_hhd_uc = seg.elementValueForPath("challenge_hhd_uc") as? Data;
}
}
}
}
| ecb7419c577481390c59e56e14fe3711 | 26.070588 | 93 | 0.515428 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/CryptoAssets/Sources/EthereumKit/Models/Accounts/KeyPair/EthereumKeyPairDeriver.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import WalletCore
public typealias AnyEthereumKeyPairDeriver = AnyKeyPairDeriver<EthereumKeyPair, EthereumKeyDerivationInput, HDWalletError>
public struct EthereumKeyPairDeriver: KeyPairDeriverAPI {
public func derive(input: EthereumKeyDerivationInput) -> Result<EthereumKeyPair, HDWalletError> {
let ethereumCoinType = CoinType.ethereum
// Hardcoding BIP39 passphrase as empty string as it is currently not supported.
guard let hdWallet = HDWallet(mnemonic: input.mnemonic, passphrase: "") else {
return .failure(.walletFailedToInitialise())
}
let privateKey = hdWallet.getKeyForCoin(coin: ethereumCoinType)
let publicKey = hdWallet.getAddressForCoin(coin: ethereumCoinType)
let ethereumPrivateKey = EthereumPrivateKey(
mnemonic: input.mnemonic,
data: privateKey.data
)
let keyPair = EthereumKeyPair(
accountID: publicKey,
privateKey: ethereumPrivateKey
)
return .success(keyPair)
}
}
| 40d55bf071d3dc0b9d7c85f267d8aac7 | 39.321429 | 122 | 0.708592 | false | false | false | false |
inamiy/ReactiveCocoaCatalog | refs/heads/master | ReactiveCocoaCatalog/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2015-09-16.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
import UIKit
import ReactiveSwift
class MasterViewController: UITableViewController
{
let catalogs = Catalog.allCatalogs()
override func awakeFromNib()
{
super.awakeFromNib()
if UIDevice.current.userInterfaceIdiom == .pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad()
{
super.viewDidLoad()
// auto-select
for i in 0..<self.catalogs.count {
if self.catalogs[i].selected {
self.showDetailViewController(at: i)
break
}
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.catalogs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let catalog = self.catalogs[indexPath.row]
cell.textLabel?.text = catalog.title
cell.detailTextLabel?.text = catalog.description
return cell
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
self.showDetailViewController(at: indexPath.row)
}
func showDetailViewController(at index: Int)
{
let catalog = self.catalogs[index]
let newVC = catalog.scene.instantiate()
let newNavC = UINavigationController(rootViewController: newVC)
self.splitViewController?.showDetailViewController(newNavC, sender: self)
// Deinit logging.
let message = deinitMessage(newVC)
newVC.reactive.lifetime.ended.observeCompleted {
print(message)
}
newVC.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
newVC.navigationItem.leftItemsSupplementBackButton = true
}
}
| 3c193a1a6062a872f7bd4c42cb652b85 | 26.091954 | 107 | 0.658888 | false | false | false | false |
chendingcd/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Classes/Tools/Common.swift | mit | 1 | //
// Common.swift
// DouYuZB
//
// Created by 陈鼎 on 2016/11/29.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
let kSatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH: CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
| 5ba5b0a1e3ceb79d515163bd6543f5bb | 14.190476 | 49 | 0.702194 | false | false | false | false |
IngmarStein/swift | refs/heads/master | stdlib/public/core/ObjCMirrors.swift | apache-2.0 | 4 | //===--- ObjCMirrors.swift ------------------------------------------------===//
//
// 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 SwiftShims
#if _runtime(_ObjC)
@_silgen_name("swift_ObjCMirror_count")
func _getObjCCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_ObjCMirror_subscript")
func _getObjCChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
func _getObjCSummary(_ data: _MagicMirrorData) -> String {
let theDescription = _swift_stdlib_objcDebugDescription(data._loadValue(ofType: AnyObject.self)) as AnyObject
return _cocoaStringToSwiftString_NonASCII(theDescription)
}
public // SPI(runtime)
struct _ObjCMirror : _Mirror {
let data: _MagicMirrorData
public var value: Any { return data.objcValue }
public var valueType: Any.Type { return data.objcValueType }
public var objectIdentifier: ObjectIdentifier? {
return data._loadValue(ofType: ObjectIdentifier.self)
}
public var count: Int {
return _getObjCCount(data)
}
public subscript(i: Int) -> (String, _Mirror) {
return _getObjCChild(i, data)
}
public var summary: String {
return _getObjCSummary(data)
}
public var quickLookObject: PlaygroundQuickLook? {
let object = _swift_ClassMirror_quickLookObject(data)
return _getClassPlaygroundQuickLook(object)
}
public var disposition: _MirrorDisposition { return .objCObject }
}
public // SPI(runtime)
struct _ObjCSuperMirror : _Mirror {
let data: _MagicMirrorData
public var value: Any { return data.objcValue }
public var valueType: Any.Type { return data.objcValueType }
// Suppress the value identifier for super mirrors.
public var objectIdentifier: ObjectIdentifier? {
return nil
}
public var count: Int {
return _getObjCCount(data)
}
public subscript(i: Int) -> (String, _Mirror) {
return _getObjCChild(i, data)
}
public var summary: String {
return _getObjCSummary(data)
}
public var quickLookObject: PlaygroundQuickLook? {
let object = _swift_ClassMirror_quickLookObject(data)
return _getClassPlaygroundQuickLook(object)
}
public var disposition: _MirrorDisposition { return .objCObject }
}
#endif
| 2964812288380021c698c3a467de4621 | 31.948052 | 111 | 0.688214 | false | false | false | false |
Beaconstac/iOS-SDK | refs/heads/master | BeaconstacSampleApp/Pods/EddystoneScanner/EddystoneScanner/EddystoneRFC/Models/Telemetry.swift | mit | 1 | //
// Telemetry.swift
// EddystoneScanner
//
// Created by Amit Prabhu on 14/01/18.
// Copyright © 2018 Amit Prabhu. All rights reserved.
//
import Foundation
///
/// Struct that handles the beacon telemtry data
/// Specs https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md
///
@objc public class Telemetry: NSObject {
/// Telemetry data version
@objc public let version: String
/// Battery voltage is the current battery charge in millivolts
@objc public var voltage: UInt = 0
/// Beacon temperature is the temperature in degrees Celsius sensed by the beacon. If not supported the value will be -128.
@objc public var temperature: Float = 0
/// ADV_CNT is the running count of advertisement frames of all types emitted by the beacon since power-up or reboot, useful for monitoring performance metrics that scale per broadcast frame
@objc public var advCount: UInt = 0
/// SEC_CNT is a 0.1 second resolution counter that represents time since beacon power-up or reboot
@objc public var uptime: Float = 0
/// Calculates the advertising interval of the beacon in milliseconds
/// Assumes the beacon is transmitting all 3 eddystone packets (UID, URL and TLM frames)
@objc public var advInt: Float {
guard uptime != 0, uptime != 0 else {
return 0
}
let numberOFFramesPerBeacon = 3
return Float(numberOFFramesPerBeacon * 1000) / (Float(advCount) / uptime)
}
/// Battery percentage
/// Assume the chip requires a 3V battery. Most of the beacons have Nordic chips which support 3V
/// We aaume here that the lower bound is 2000 and upper bound is 3000
/// If the milliVolt is less than 2000, we assume 0% and if it is greater than 3000 we consider it as 100% charged.
/// The formula is % = (read milliVolt - LowerBound) / (UpperBound - LowerBound) * 100
@objc public var batteryPercentage: UInt {
guard voltage > 2000 else {
return 0
}
guard voltage < 3000 else {
return 100
}
let percentage: UInt = UInt(((Float(voltage) - 2000.0) / 1000.0) * 100.0)
return percentage > 100 ? 100 : percentage
}
internal init?(tlmFrameData: Data) {
guard let frameBytes = Telemetry.validateTLMFrameData(tlmFrameData: tlmFrameData) else {
debugPrint("Failed to iniatialize the telemtry object")
return nil
}
self.version = String(format: "%02X", frameBytes[1])
super.init()
self.parseTLMFrameData(frameBytes: frameBytes)
}
/**
Update the telemetry object for the new telemtry frame data
- Parameter tlmFrameData: The raw TLM frame data
*/
internal func update(tlmFrameData: Data) {
guard let frameBytes = Telemetry.validateTLMFrameData(tlmFrameData: tlmFrameData) else {
debugPrint("Failed to update telemetry data")
return
}
self.parseTLMFrameData(frameBytes: frameBytes)
}
/**
Validate the TLM frame data
- Parameter tlmFrameData: The raw TLM frame data
*/
private static func validateTLMFrameData(tlmFrameData: Data) -> [UInt8]? {
let frameBytes = Array(tlmFrameData) as [UInt8]
// The length of the frame should be 14
guard frameBytes.count == 14 else {
debugPrint("Corrupted telemetry frame")
return nil
}
return frameBytes
}
/**
Parse the TLM frame data
- Parameter frameBytes: The `UInt8` byte array
*/
private func parseTLMFrameData(frameBytes: [UInt8]) {
self.voltage = bytesToUInt(byteArray: frameBytes[2..<4])!
self.temperature = Float(frameBytes[4]) + Float(frameBytes[5])/256
self.advCount = bytesToUInt(byteArray: frameBytes[6..<10])!
self.uptime = Float(bytesToUInt(byteArray: frameBytes[10..<14])!) / 10.0
}
}
| 1ecbe6e08727dfa31a6c0a09267ed2f3 | 34.929204 | 194 | 0.637685 | false | false | false | false |
ngominhtrint/Twittient | refs/heads/master | Twittient/TweetDetailViewController.swift | apache-2.0 | 1 | //
// TweetDetailViewController.swift
// Twittient
//
// Created by TriNgo on 3/26/16.
// Copyright © 2016 TriNgo. All rights reserved.
//
import UIKit
class TweetDetailViewController: UIViewController {
@IBOutlet weak var retweetUserLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var tagLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!
@IBOutlet weak var numberRetweetLabel: UILabel!
@IBOutlet weak var numberFavoritesLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var retweetButton: UIButton!
var tweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
avatarImage.layer.cornerRadius = 3.0
showData()
// Do any additional setup after loading the view.
}
func showData(){
nameLabel.text = tweet!.name as? String
tagLabel.text = tweet!.screenName as? String
descriptionLabel.text = tweet!.text as? String
numberRetweetLabel.text = "\(tweet!.retweetCount)"
numberFavoritesLabel.text = "\(tweet!.favoritesCount)"
avatarImage.setImageWithURL((tweet!.profileImageUrl)!)
let timeStamp = dateFromString((tweet?.timeStamp)!, format: "dd/MM/yy HH:mm a")
timeStampLabel.text = "\(timeStamp)"
let isFavorited = tweet!.favorited
if isFavorited {
let image = UIImage(named: "like.png")! as UIImage
likeButton.setImage(image, forState: .Normal)
} else {
let image = UIImage(named: "unlike.png")! as UIImage
likeButton.setImage(image, forState: .Normal)
}
let isRetweeted = tweet!.retweeted
if isRetweeted {
let image = UIImage(named: "retweeted.png")! as UIImage
retweetButton.setImage(image, forState: .Normal)
} else {
let image = UIImage(named: "retweet.png")! as UIImage
retweetButton.setImage(image, forState: .Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onReplyClicked(sender: UIButton) {
}
@IBAction func onRetweetClicked(sender: UIButton) {
let id = tweet?.id as! String
let isRetweeted = (tweet?.retweeted)! as Bool
let retweetEnum: TwitterClient.Retweet
if isRetweeted {
retweetEnum = TwitterClient.Retweet.Unretweet
} else {
retweetEnum = TwitterClient.Retweet.Retweet
}
TwitterClient.shareInstance.retweet(id, retweet: retweetEnum, success: { (tweet: Tweet) -> () in
self.tweet = tweet
self.showData()
}) { (error: NSError) -> () in
print("\(error)")
}
}
@IBAction func onLikeClicked(sender: UIButton) {
let id = tweet?.id as! String
let isFavorite = (tweet?.favorited)! as Bool
let favoriteEnum: TwitterClient.Favorite
if isFavorite {
favoriteEnum = TwitterClient.Favorite.Unlike
} else {
favoriteEnum = TwitterClient.Favorite.Like
}
TwitterClient.shareInstance.favorite(id, favorite: favoriteEnum, success: { (tweet: Tweet) -> () in
self.tweet = tweet
self.showData()
}) { (error: NSError) -> () in
print("\(error)")
}
}
func dateFromString(date: NSDate, format: String) -> String {
let formatter = NSDateFormatter()
let locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.locale = locale
formatter.dateFormat = format
return formatter.stringFromDate(date)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let replyViewController = segue.destinationViewController as! ReplyViewController
replyViewController.tweet = self.tweet
replyViewController.isReplyMessage = true
print("Reply Tweet")
}
}
| 7288b2dfca309f8fe8da2a7392f06799 | 31.659259 | 107 | 0.615786 | false | false | false | false |
mmisesin/particle | refs/heads/master | Particle/ArticleCellTableViewCell.swift | mit | 1 | //
// ArticleCellTableViewCell.swift
// Particle
//
// Created by Artem Misesin on 6/25/17.
// Copyright © 2017 Artem Misesin. All rights reserved.
//
import UIKit
final class ArticleCellTableViewCell: UITableViewCell {
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var secondaryLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setupViews()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configure(with article: ParticleReading, at indexRow: Int, searchStatus: SearchStatus) {
if let articleTitle = article.title {
mainLabel.text = articleTitle
} else {
mainLabel.text = Constants.unknownTitle
}
if let articleURL = article.url {
secondaryLabel.text = crop(url: articleURL)
} else {
secondaryLabel.text = Constants.unknownLink
}
if let imgData = article.thumbnail {
mainImage.image = UIImage(data: imgData as Data)
} else {
mainImage.image = UIImage()
}
if indexRow == 0 {
let height = 1 / UIScreen.main.scale
let line = UIView(frame: CGRect(x: 15, y: 0, width: bounds.width - 30, height: height))
line.backgroundColor = Colors.separatorColor
addSubview(line)
}
setupColors(for: searchStatus)
}
private func setupViews() {
backgroundColor = .white
separatorInset.right = 16
separatorInset.left = 16
//mainImage.layer.cornerRadius = 4
mainImage.contentMode = .scaleAspectFill
mainImage.clipsToBounds = true
mainLabel.textAlignment = .left
secondaryLabel.textAlignment = .left
}
private func setupColors(for searchStatus: SearchStatus) {
switch searchStatus {
case .active(let range):
mainLabel.textColor = Colors.desaturatedHeaderColor
guard let text = mainLabel.text else { return }
let attributedString = NSMutableAttributedString(string: text, attributes:
[NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.bold)])
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: Colors.headerColor, range: range)
mainLabel.attributedText = attributedString
case .nonActive:
mainLabel.textColor = Colors.headerColor
}
secondaryLabel.textColor = Colors.subHeaderColor
}
private func crop(url: String) -> String {
if let startRange = url.range(of: "://") {
let tempString = String(url[startRange.upperBound..<url.endIndex])
if let endRange = tempString.range(of: "/") {
let shortURL = String(tempString[tempString.startIndex..<endRange.lowerBound])
return shortURL
}
}
return url
}
}
| e34f1faad045f64b9779d0a6a5c8dc9b | 33.477778 | 121 | 0.620045 | false | false | false | false |
kishikawakatsumi/TextKitExamples | refs/heads/master | BulletPoint/BulletPoint/ViewController.swift | mit | 1 | //
// ViewController.swift
// BulletPoint
//
// Created by Kishikawa Katsumi on 9/2/16.
// Copyright © 2016 Kishikawa Katsumi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: CGRectInset(view.bounds, 10, 10))
textView.editable = false
textView.textContainerInset = UIEdgeInsetsZero
textView.textContainer.lineFragmentPadding = 0
textView.layoutManager.usesFontLeading = false
view.addSubview(textView)
let headFont = UIFont.boldSystemFontOfSize(20)
let subheadFont = UIFont.boldSystemFontOfSize(16)
let bodyFont = UIFont.systemFontOfSize(12)
let text = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("List", ofType: "txt")!)
let attributedText = NSMutableAttributedString(string: text)
let image = UIImage(named: "bullet")
let attachment = NSTextAttachment(data: nil, ofType: nil)
attachment.image = image
attachment.bounds = CGRect(x: 0, y: -2, width: bodyFont.pointSize, height: bodyFont.pointSize)
let bulletText = NSAttributedString(attachment: attachment)
attributedText.replaceCharactersInRange(NSRange(location: 350, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 502, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 617, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 650, length: 1), withAttributedString: bulletText)
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(headFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(headFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(headFont.pointSize / 2)
let attributes = [
NSFontAttributeName: headFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 0, length: 33))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2)
let attributes = [
NSFontAttributeName: subheadFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 34, length: 20))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.alignment = .Justified
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 55, length: 275))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2)
let attributes = [
NSFontAttributeName: subheadFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 330, length: 19))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.headIndent = bodyFont.pointSize * 2
paragraphStyle.alignment = .Justified
paragraphStyle.tabStops = []
paragraphStyle.defaultTabInterval = bodyFont.pointSize * 2
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 350, length: 472))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.alignment = .Justified
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 822, length: 126))
}
textView.attributedText = attributedText
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| ede5b227282d87cc06423c511dba1fd7 | 40.149351 | 116 | 0.652517 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/struct tables/Battles.swift | gpl-2.0 | 1 | //
// Battles.swift
// GoD Tool
//
// Created by Stars Momodu on 23/03/2021.
//
import Foundation
#if GAME_XD
let battleTrainerStruct = GoDStruct(name: "Battle CD Trainer", format: [
.short(name: "Deck ID", description: "", type: .deckID),
.short(name: "Trainer ID", description: "", type: .uintHex)
])
let BattleCDStruct = GoDStruct(name: "Battle CD", format: [
.byte(name: "Unknown", description: "", type: .uintHex),
.byte(name: "Turn Limit", description: "Set to 0 for no limit", type: .uint),
.byte(name: "Battle Style", description: "Single or Double", type: .battleStyle),
.short(name: "Battle Field", description: "", type: .battleFieldID),
.short(name: "Padding", description: "", type: .null),
.subStruct(name: "Player Deck", description: "", property: battleTrainerStruct),
.subStruct(name: "Opponent Deck", description: "", property: battleTrainerStruct),
.word(name: "Name ID", description: "", type: .msgID(file: .dol)),
.word(name: "Description ID", description: "", type: .msgID(file: .dol)),
.word(name: "Condition Text ID", description: "", type: .msgID(file: .dol)),
.word(name: "Unknown 4", description: "", type: .uintHex),
.array(name: "Unknowns", description: "", property: .byte(name: "Unknown", description: "", type: .uintHex), count: 0x1c),
])
let battleCDsTable = CommonStructTable(index: .BattleCDs, properties: BattleCDStruct)
let battleLayoutsStruct = GoDStruct(name: "Battle Layout", format: [
.byte(name: "Active pokemon per player", description: "", type: .uint),
.byte(name: "Unknown 1", description: "", type: .uintHex),
.byte(name: "Unknown 2", description: "", type: .uintHex),
.word(name: "Unknown", description: "", type: .uintHex)
])
let battleLayoutsTable = CommonStructTable(index: .BattleLayouts, properties: battleLayoutsStruct)
#endif
let battlefieldsStruct = GoDStruct(name: "Battlefield", format: [
.byte(name: "Unknown 1", description: "", type: .uintHex),
.short(name: "Unknown 2", description: "", type: .uintHex),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel)),
.word(name: "Unknown 4", description: "", type: .uintHex),
.word(name: "Unknown 5", description: "", type: .uintHex),
.word(name: "Unknown 6", description: "", type: .uintHex),
.short(name: "Unknown 7", description: "", type: .uintHex),
.short(name: "Unknown 8", description: "", type: .uintHex)
])
let battlefieldsTable = CommonStructTable(index: .BattleFields, properties: battlefieldsStruct)
#if GAME_XD
var battleStruct: GoDStruct {
return GoDStruct(name: "Battle", format: [
.byte(name: "Battle Type", description: "", type: .battleType),
.byte(name: "Trainers per side", description: "", type: .uint),
.byte(name: "Battle Style", description: "", type: .battleStyle),
.byte(name: "Pokemon Per Player", description: "", type: .uint),
.byte(name: "Is Story Battle", description: "", type: .bool),
.short(name: "Battle Field ID", description: "", type: .battleFieldID),
.short(name: "Battle CD ID", description: "Set programmatically at run time so is always set to 0 in the game files", type: .uint),
.word(name: "Battle Identifier String", description: "", type: .msgID(file: .dol)),
.word(name: "BGM ID", description: "", type: .uintHex),
.word(name: "Unknown 2", description: "", type: .uintHex)
]
+ (region == .EU ? [.array(name: "Unknown Values", description: "Only exist in the PAL version", property: .word(name: "", description: "", type: .uintHex), count: 4)] : [])
+ [
.word(name: "Colosseum Round", description: "wzx id for intro text", type: .colosseumRound),
.array(name: "Players", description: "", property: .subStruct(name: "Battle Player", description: "", property: GoDStruct(name: "Battle Player", format: [
.short(name: "Deck ID", description: "", type: .deckID),
.short(name: "Trainer ID", description: "Use deck 0, id 5000 for the player's team", type: .uint),
.word(name: "Controller Index", description: "0 for AI", type: .playerController),
]
)), count: 4)
])
}
#else
let battleStruct = GoDStruct(name: "Battle", format: [
.byte(name: "Battle Type", description: "", type: .battleType),
.byte(name: "Battle Style", description: "", type: .battleStyle),
.byte(name: "Unknown Flag", description: "", type: .bool),
.short(name: "Battle Field ID", description: "", type: .battleFieldID),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel)),
.word(name: "BGM ID", description: "", type: .uintHex),
.word(name: "Unknown 3", description: "", type: .uintHex),
.word(name: "Colosseum Round", description: "", type: .colosseumRound),
.array(name: "Players", description: "", property: .subStruct(name: "Battle Player", description: "", property: GoDStruct(name: "Battle Player", format: [
.short(name: "Trainer ID", description: "id 1 is the player", type: .indexOfEntryInTable(table: trainersTable, nameProperty: nil)),
.word(name: "Controller Index", description: "0 for AI", type: .playerController),
])), count: 4)
])
#endif
var battlesTable: CommonStructTable {
return CommonStructTable(index: .Battles, properties: battleStruct)
}
#if GAME_COLO
let battleStyleStruct = GoDStruct(name: "Battle Styles", format: [
.byte(name: "Trainers per side", description: "", type: .uint),
.byte(name: "Pokemon per trainer", description: "", type: .uint),
.byte(name: "Active pokemon per trainer", description: "", type: .uint),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel))
])
let battleStylesTable = CommonStructTable(index: .BattleStyles, properties: battleStyleStruct) { (index, data) -> String? in
if let trainersPerSide: Int = data.get("Trainers per side"),
let pokemonPerTrainer: Int = data.get("Pokemon per trainer"),
let activePokemonPerTrainer: Int = data.get("Active pokemon per trainer") {
let battleTypeName: String
if trainersPerSide > 1 {
battleTypeName = "Multi"
} else {
battleTypeName = activePokemonPerTrainer == 1 ? "Single" : "Double"
}
return "\(battleTypeName) Battle - \(pokemonPerTrainer) Pokemon Each"
}
return "Battle Style \(index)"
}
let battleTypesStruct = GoDStruct(name: "Battle Types", format: [
.byte(name: "Flag 1", description: "", type: .bool),
.byte(name: "Flag 2", description: "", type: .bool),
.byte(name: "Flag 3", description: "", type: .bool),
.byte(name: "Flag 4", description: "", type: .bool),
.byte(name: "Can Use Items", description: "", type: .bool),
.byte(name: "Flag 6", description: "", type: .bool),
.byte(name: "Flag 7", description: "", type: .bool),
.byte(name: "Flag 8", description: "", type: .bool),
.byte(name: "Flag 9", description: "", type: .bool),
.byte(name: "Flag 10", description: "", type: .bool),
.byte(name: "Flag 11", description: "", type: .bool),
.byte(name: "Flag 12", description: "", type: .bool),
.byte(name: "Flag 13", description: "", type: .bool),
.byte(name: "Flag 14", description: "", type: .bool),
.byte(name: "Flag 15", description: "", type: .bool),
.byte(name: "Flag 16", description: "", type: .bool),
.byte(name: "Flag 17", description: "", type: .bool),
.byte(name: "Flag 18", description: "", type: .bool),
.byte(name: "Flag 19", description: "", type: .bool),
.byte(name: "Flag 20", description: "", type: .bool),
.byte(name: "Flag 21", description: "", type: .bool),
.byte(name: "Flag 22", description: "", type: .bool),
.byte(name: "Flag 23", description: "", type: .bool),
.byte(name: "Flag 24", description: "", type: .bool),
.byte(name: "Flag 25", description: "", type: .bool),
.word(name: "Name ID", description: "", type: .msgID(file: .common_rel))
])
let battleTypesTable = CommonStructTable(index: .BattleTypes, properties: battleTypesStruct) { (index, data) -> String? in
if let type = XGBattleTypes(rawValue: index) {
return type.name
}
return "Battle Type \(index)"
}
#endif
private let aiRolesEnd: [GoDStructProperties] = game == .Colosseum ? [] : [
.byte(name: "Misc 3", description: "", type: .byteRange),
.byte(name: "Misc 4", description: "", type: .byteRange),
]
let pokemonAIRolesStruct = GoDStruct(name: "Pokemon AI Roles", format: [
.word(name: "Name ID", description: "", type: .msgID(file: nil)),
.word(name: "Unknown 1", description: "", type: .uint),
.subStruct(name: "Move Type Weights", description: "How much more/less likely this role is to use a certain type of move", property: GoDStruct(name: "AI Role Weights", format: [
.byte(name: "No Effect", description: "", type: .byteRange),
.byte(name: "Attack", description: "", type: .byteRange),
.byte(name: "Healing", description: "", type: .byteRange),
.byte(name: "Stat Decrease", description: "", type: .byteRange),
.byte(name: "Stat Increase", description: "", type: .byteRange),
.byte(name: "Status", description: "", type: .byteRange),
.byte(name: "Field", description: "", type: .byteRange),
.byte(name: "Affect Opponent's Move", description: "", type: .byteRange),
.byte(name: "OHKO", description: "", type: .byteRange),
.byte(name: "Multi-turn", description: "", type: .byteRange),
.byte(name: "Misc", description: "", type: .byteRange),
.byte(name: "Misc 2", description: "", type: .byteRange)
] + aiRolesEnd))
])
let pokemonAIRolesTable = CommonStructTable(index: .AIPokemonRoles, properties: pokemonAIRolesStruct)
| 7177f762c9fa016c3fed16ac27aee930 | 48.930108 | 178 | 0.667708 | false | false | false | false |
sorenmortensen/SymondsTimetable | refs/heads/master | Sources/Lesson.swift | mit | 1 | //
// Lesson.swift
// SymondsAPI
//
// Created by Søren Mortensen on 20/01/2017.
// Copyright © 2017 Soren Mortensen. All rights reserved.
//
import Foundation
/// A `Lesson` includes all the information provided by the Peter Symonds
/// College Data Service about a single event in a student's timetable.
public class Lesson {
// MARK: - Properties
/// The ID of the lesson.
///
/// - note: Unique among other items of the same type.
public let id: String
/// The title of the lesson.
public let title: String
/// The subtitle of the lesson.
public let subtitle: String?
/// The staff member(s) in charge of the lesson.
public let staff: String?
/// The room in which the lesson takes place.
public let room: String?
/// The start time of the lesson.
public let start: Date
/// The end time of the lesson.
public let end: Date
/// The date at the beginning of the day on which this lesson occurs.
public var dayDate: Date {
let calendar = Calendar.current
return calendar.startOfDay(for: start)
}
/// The type of timetable item this instance represents (such as a lesson,
/// study period, exam, etc.).
public let type: LessonType
/// Whether this lesson is a blank lesson (e.g. a study period or a college
/// holiday).
public let isBlank: Bool
/// Whether this lesson has been marked as cancelled.
///
/// - note: If this property is true, this information should be displayed
/// clearly to the user.
public let isCancelled: Bool
/// Whether this lesson has been marked as taking place in a different room
/// than usual.
///
/// - note: If this property is true, this information should be displayed
/// clearly to the user.
public let isRoomChange: Bool
/// The time range of this lesson, in the format `HH:mm-HH:mm`.
public var timeRange: String {
let startTime = self.timeFormatter.string(from: self.start)
let endTime = self.timeFormatter.string(from: self.end)
return "\(startTime)-\(endTime)"
}
/// The start time of this lesson, in the format `HH:mm`.
public var startTime: String {
return self.timeFormatter.string(from: self.start)
}
/// The end time of this lesson, in the format `HH:mm`.
public var endTime: String {
return self.timeFormatter.string(from: self.end)
}
/// The date on which the lesson occurs, in the user's .long date format.
public var dateString: String {
get {
return dateFormatter.string(from: start)
}
}
/// The length of the lesson (i.e. the length of time between `start` and
/// `end`).
public var length: TimeInterval {
get {
return end.timeIntervalSince(start)
}
}
/// A formatter that can create a date in the format `HH:mm` from a `Date`
/// instance, or vice versa.
private let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
/// A formatter that can create a date in the localised long date format for
/// the user.
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
// MARK: - Types
/// The various types of lessons.
public enum LessonType: String {
/// An extra curricular activity or sports team.
case activity = "activity"
/// A booking made by a student for their art exam.
case artExamBooking = "artexambooking"
/// A national bank holiday.
case bankHoliday = "bankholiday"
/// A period during which a boarding student is on leave from one of the
/// boarding houses.
case boardingLeave = "boardingleave"
/// The morning break period, which occurs from 10:20 to 10:40 each
/// morning for all students.
case morningBreak = "break"
/// An appointment with a Careers adviser.
case careersAppointment = "careersappointment"
/// A careers week talk.
case careersWeek = "careersweek"
/// An exam.
case exam = "exam"
/// One of the college holidays.
case holiday = "holiday"
/// A normal college lesson.
case lesson = "lesson"
/// A blank lunchtime period, which occurs from 13:00 to 13:50 for
/// students who do not have a scheduled lesson during that time.
///
/// - note: This lesson type does not exist in the Symonds Data Service
/// and is manually added to blank events starting at 13:00 and
/// ending at 13:50.
case lunch = "lunch"
/// A period of spare time between lessons.
case study = "studyperiod"
/// A Study Skills appointment.
case studySkills = "studyskills"
/// A Study Support appointment.
case studySupport = "studysupport"
/// A college trip.
case trip = "trip"
/// Tutor time.
case tutorGroup = "tutorgroup"
}
// MARK: - Initialisers
/// Creates a new instance of `Lesson`.
///
/// - Parameters:
/// - id: The lesson's ID.
/// - title: The lesson's title.
/// - subtitle: The lesson's subtitle.
/// - staff: The lesson's staff member.
/// - room: The lesson's room.
/// - start: The lesson's start time.
/// - end: The lesson's end time.
/// - type: The lesson's type.
/// - isBlank: The lesson's blank status.
/// - isCancelled: The lesson's cancelled status.
/// - isRoomChange: The lesson's room change status.
public init(
id: String,
title: String,
subtitle: String,
staff: String?,
room: String?,
start: Date,
end: Date,
type: LessonType,
isBlank: Bool = false,
isCancelled: Bool = false,
isRoomChange: Bool = false
) {
if isBlank {
self.id = "blank"
} else {
self.id = id
}
self.subtitle = subtitle
self.staff = staff
self.room = room
self.start = start
self.end = end
let startTime = self.timeFormatter.string(from: self.start)
let endTime = self.timeFormatter.string(from: self.end)
let timeRange = "\(startTime)-\(endTime)"
if isBlank && timeRange == "13:00-13:50" {
self.type = .lunch
self.title = "Lunch"
} else {
self.type = type
self.title = title
}
self.isBlank = isBlank
self.isCancelled = isCancelled
self.isRoomChange = isRoomChange
}
}
| 10b43086690b4f51d81b761b7d92a85f | 30.854545 | 80 | 0.581336 | false | false | false | false |
wilfreddekok/Antidote | refs/heads/master | Antidote/ChangePasswordController.swift | mpl-2.0 | 1 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
private struct Constants {
static let HorizontalOffset = 40.0
static let ButtonVerticalOffset = 20.0
static let FieldsOffset = 10.0
static let MaxFormWidth = 350.0
}
protocol ChangePasswordControllerDelegate: class {
func changePasswordControllerDidFinishPresenting(controller: ChangePasswordController)
}
class ChangePasswordController: KeyboardNotificationController {
weak var delegate: ChangePasswordControllerDelegate?
private let theme: Theme
private weak var toxManager: OCTManager!
private var scrollView: UIScrollView!
private var containerView: IncompressibleView!
private var oldPasswordField: ExtendedTextField!
private var newPasswordField: ExtendedTextField!
private var repeatPasswordField: ExtendedTextField!
private var button: RoundedButton!
init(theme: Theme, toxManager: OCTManager) {
self.theme = theme
self.toxManager = toxManager
super.init()
edgesForExtendedLayout = .None
addNavigationButtons()
title = String(localized: "change_password")
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(theme.colorForType(.NormalBackground))
createViews()
installConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let old = oldPasswordField {
old.becomeFirstResponder()
}
else if let new = newPasswordField {
new.becomeFirstResponder()
}
}
override func keyboardWillShowAnimated(keyboardFrame frame: CGRect) {
scrollView.contentInset.bottom = frame.size.height
scrollView.scrollIndicatorInsets.bottom = frame.size.height
}
override func keyboardWillHideAnimated(keyboardFrame frame: CGRect) {
scrollView.contentInset.bottom = 0.0
scrollView.scrollIndicatorInsets.bottom = 0.0
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize.width = scrollView.frame.size.width
scrollView.contentSize.height = CGRectGetMaxY(containerView.frame)
}
}
// MARK: Actions
extension ChangePasswordController {
func cancelButtonPressed() {
delegate?.changePasswordControllerDidFinishPresenting(self)
}
func buttonPressed() {
guard validatePasswordFields() else {
return
}
let oldPassword = oldPasswordField.text!
let newPassword = newPasswordField.text!
let hud = JGProgressHUD(style: .Dark)
hud.showInView(view)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [unowned self] in
let result = self.toxManager.changeEncryptPassword(newPassword, oldPassword: oldPassword)
if result {
let keychainManager = KeychainManager()
if keychainManager.toxPasswordForActiveAccount != nil {
keychainManager.toxPasswordForActiveAccount = newPassword
}
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
hud.dismiss()
if result {
self.delegate?.changePasswordControllerDidFinishPresenting(self)
}
else {
handleErrorWithType(.WrongOldPassword)
}
}
}
}
}
extension ChangePasswordController: ExtendedTextFieldDelegate {
func loginExtendedTextFieldReturnKeyPressed(field: ExtendedTextField) {
if field === oldPasswordField {
newPasswordField!.becomeFirstResponder()
}
else if field === newPasswordField {
repeatPasswordField!.becomeFirstResponder()
}
else if field === repeatPasswordField {
buttonPressed()
}
}
}
private extension ChangePasswordController {
func addNavigationButtons() {
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .Cancel,
target: self,
action: #selector(ChangePasswordController.cancelButtonPressed))
}
func createViews() {
scrollView = UIScrollView()
view.addSubview(scrollView)
containerView = IncompressibleView()
containerView.backgroundColor = .clearColor()
scrollView.addSubview(containerView)
button = RoundedButton(theme: theme, type: .RunningPositive)
button.setTitle(String(localized: "change_password_done"), forState: .Normal)
button.addTarget(self, action: #selector(ChangePasswordController.buttonPressed), forControlEvents: .TouchUpInside)
containerView.addSubview(button)
oldPasswordField = createPasswordFieldWithTitle(String(localized: "old_password"))
newPasswordField = createPasswordFieldWithTitle(String(localized: "new_password"))
repeatPasswordField = createPasswordFieldWithTitle(String(localized: "repeat_password"))
oldPasswordField.returnKeyType = .Next
newPasswordField.returnKeyType = .Next
repeatPasswordField.returnKeyType = .Done
}
func createPasswordFieldWithTitle(title: String) -> ExtendedTextField {
let field = ExtendedTextField(theme: theme, type: .Normal)
field.delegate = self
field.title = title
field.secureTextEntry = true
containerView.addSubview(field)
return field
}
func installConstraints() {
scrollView.snp_makeConstraints {
$0.edges.equalTo(view)
}
containerView.customIntrinsicContentSize.width = CGFloat(Constants.MaxFormWidth)
containerView.snp_makeConstraints {
$0.top.equalTo(scrollView)
$0.centerX.equalTo(scrollView)
$0.width.lessThanOrEqualTo(Constants.MaxFormWidth)
$0.width.lessThanOrEqualTo(scrollView).offset(-2 * Constants.HorizontalOffset)
}
var topConstraint = containerView.snp_top
if installConstraintsForField(oldPasswordField, topConstraint: topConstraint) {
topConstraint = oldPasswordField!.snp_bottom
}
if installConstraintsForField(newPasswordField, topConstraint: topConstraint) {
topConstraint = newPasswordField!.snp_bottom
}
if installConstraintsForField(repeatPasswordField, topConstraint: topConstraint) {
topConstraint = repeatPasswordField!.snp_bottom
}
button.snp_makeConstraints {
$0.top.equalTo(topConstraint).offset(Constants.ButtonVerticalOffset)
$0.leading.trailing.equalTo(containerView)
$0.bottom.equalTo(containerView)
}
}
/**
Returns true if field exists, no otherwise.
*/
func installConstraintsForField(field: ExtendedTextField?, topConstraint: ConstraintItem) -> Bool {
guard let field = field else {
return false
}
field.snp_makeConstraints {
$0.top.equalTo(topConstraint).offset(Constants.FieldsOffset)
$0.leading.trailing.equalTo(containerView)
}
return true
}
func validatePasswordFields() -> Bool {
guard let oldText = oldPasswordField.text where !oldText.isEmpty else {
handleErrorWithType(.PasswordIsEmpty)
return false
}
guard let newText = newPasswordField.text where !newText.isEmpty else {
handleErrorWithType(.PasswordIsEmpty)
return false
}
guard let repeatText = repeatPasswordField.text where !repeatText.isEmpty else {
handleErrorWithType(.PasswordIsEmpty)
return false
}
guard newText == repeatText else {
handleErrorWithType(.PasswordsDoNotMatch)
return false
}
return true
}
}
| 01d0c3156ab825ab578df813c0b45779 | 31.559055 | 123 | 0.662999 | false | false | false | false |
apple/swift-nio-http2 | refs/heads/main | IntegrationTests/tests_01_allocation_counters/test_01_resources/test_get_100000_headers_canonical_form.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOHPACK
func run(identifier: String) {
measure(identifier: identifier) {
let headers: HPACKHeaders = ["key": "no,trimming"]
var count = 0
for _ in 0..<100_000 {
count &+= headers[canonicalForm: "key"].count
}
return count
}
measure(identifier: identifier + "_trimming_whitespace") {
let headers: HPACKHeaders = ["key": " some , trimming "]
var count = 0
for _ in 0..<100_000 {
count &+= headers[canonicalForm: "key"].count
}
return count
}
measure(identifier: identifier + "_trimming_whitespace_from_short_string") {
// first components has length > 15 with whitespace and <= 15 without.
let headers: HPACKHeaders = ["key": " smallString ,whenStripped"]
var count = 0
for _ in 0..<100_000 {
count &+= headers[canonicalForm: "key"].count
}
return count
}
measure(identifier: identifier + "_trimming_whitespace_from_long_string") {
let headers: HPACKHeaders = ["key": " moreThan15CharactersWithAndWithoutWhitespace ,anotherValue"]
var count = 0
for _ in 0..<100_000 {
count &+= headers[canonicalForm: "key"].count
}
return count
}
}
| fbe98b310664bf8625b807c0336daeda | 33.018868 | 106 | 0.546312 | false | false | false | false |
jarocht/iOS-AlarmDJ | refs/heads/master | AlarmDJ/AlarmDJ/SettingsTableViewController.swift | mit | 1 | //
// SettingsTableViewController.swift
// AlarmDJ
//
// Created by X Code User on 7/22/15.
// Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var snoozeTimeTextField: UITextField!
@IBOutlet weak var zipcodeTextField: UITextField!
@IBOutlet weak var twentyFourHourSwitch: UISwitch!
@IBOutlet weak var newsQueryTextField: UITextField!
@IBOutlet weak var musicGenreDataPicker: UIPickerView!
let ldm = LocalDataManager()
var settings = SettingsContainer()
var genres: [String] = ["Alternative","Blues","Country","Dance","Electronic","Hip-Hop/Rap","Jazz","Klassik","Pop","Rock", "Soundtracks"]
override func viewDidLoad() {
super.viewDidLoad()
snoozeTimeTextField.delegate = self
snoozeTimeTextField.tag = 0
zipcodeTextField.delegate = self
zipcodeTextField.tag = 1
newsQueryTextField.delegate = self
newsQueryTextField.tag = 2
musicGenreDataPicker.dataSource = self
musicGenreDataPicker.delegate = self
}
override func viewWillAppear(animated: Bool) {
settings = ldm.loadSettings()
snoozeTimeTextField.text! = "\(settings.snoozeInterval)"
zipcodeTextField.text! = settings.weatherZip
twentyFourHourSwitch.on = settings.twentyFourHour
newsQueryTextField.text! = settings.newsQuery
var index = 0
for var i = 0; i < genres.count; i++ {
if genres[i] == settings.musicGenre{
index = i
}
}
musicGenreDataPicker.selectRow(index, inComponent: 0, animated: true)
}
override func viewWillDisappear(animated: Bool) {
if count(zipcodeTextField.text!) == 5 {
settings.weatherZip = zipcodeTextField.text!
}
if count(snoozeTimeTextField.text!) > 0 {
var timeVal: Int = (snoozeTimeTextField.text!).toInt()!
if timeVal > 0 {
settings.snoozeInterval = timeVal
//ldm.saveSettings(settingsContainer: settings)
}
}
if count (newsQueryTextField.text!) > 0 {
settings.newsQuery = newsQueryTextField.text!
}
ldm.saveSettings(settingsContainer: settings)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func twentyFourHourSwitchClicked(sender: AnyObject) {
settings.twentyFourHour = twentyFourHourSwitch.on
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField.tag < 2 {
if count(textField.text!) + count(string) <= 5 {
return true;
}
return false
} else {
if count(textField.text!) + count(string) <= 25 {
return true;
}
return false
}
}
func textFieldDidBeginEditing(textField: UITextField) {
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return genres.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return genres[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
settings.musicGenre = genres[row]
}
} | d207e8ac6ca5ea9328b8425b5d580525 | 32.809917 | 140 | 0.632274 | false | false | false | false |
lorentey/GlueKit | refs/heads/master | Sources/ArrayGatheringSource.swift | mit | 1 | //
// ArrayGatheringSource.swift
// GlueKit
//
// Created by Károly Lőrentey on 2017-09-05.
// Copyright © 2017 Károly Lőrentey. All rights reserved.
//
extension ObservableArrayType where Element: SourceType {
public func gather() -> AnySource<Element.Value> {
return ArrayGatheringSource(self).anySource
}
}
private class ArrayGatheringSource<Origin: ObservableArrayType, Value>: _AbstractSource<Value>
where Origin.Element: SourceType, Origin.Element.Value == Value {
let origin: Origin
var sinks: Set<AnySink<Value>> = []
private struct GatherSink: UniqueOwnedSink {
typealias Owner = ArrayGatheringSource
unowned let owner: Owner
func receive(_ value: ArrayUpdate<Origin.Element>) {
guard case let .change(change) = value else { return }
change.forEachOld { source in
for sink in owner.sinks {
source.remove(sink)
}
}
change.forEachNew { source in
for sink in owner.sinks {
source.add(sink)
}
}
}
}
init(_ origin: Origin) {
self.origin = origin
}
override func add<Sink: SinkType>(_ sink: Sink) where Sink.Value == Value {
if sinks.isEmpty {
origin.add(GatherSink(owner: self))
}
let new = sinks.insert(sink.anySink).inserted
precondition(new)
for source in origin.value {
source.add(sink)
}
}
@discardableResult
override func remove<Sink: SinkType>(_ sink: Sink) -> Sink where Sink.Value == Value {
let result = sinks.remove(sink.anySink)!
for source in origin.value {
source.remove(result)
}
if sinks.isEmpty {
origin.remove(GatherSink(owner: self))
}
return result.opened()!
}
}
| 8627840d6d1edb8144d512475bb3f5a6 | 27.893939 | 94 | 0.585737 | false | false | false | false |
catloafsoft/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Filters/High Shelf Filter/AKHighShelfFilter.swift | mit | 1 | //
// AKHighShelfFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's HighShelfFilter Audio Unit
///
/// - parameter input: Input node to process
/// - parameter cutOffFrequency: Cut Off Frequency (Hz) ranges from 10000 to 22050 (Default: 10000)
/// - parameter gain: Gain (dB) ranges from -40 to 40 (Default: 0)
///
public class AKHighShelfFilter: AKNode, AKToggleable {
private let cd = AudioComponentDescription(
componentType: kAudioUnitType_Effect,
componentSubType: kAudioUnitSubType_HighShelfFilter,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0)
internal var internalEffect = AVAudioUnitEffect()
internal var internalAU = AudioUnit()
private var mixer: AKMixer
/// Cut Off Frequency (Hz) ranges from 10000 to 22050 (Default: 10000)
public var cutOffFrequency: Double = 10000 {
didSet {
if cutOffFrequency < 10000 {
cutOffFrequency = 10000
}
if cutOffFrequency > 22050 {
cutOffFrequency = 22050
}
AudioUnitSetParameter(
internalAU,
kHighShelfParam_CutOffFrequency,
kAudioUnitScope_Global, 0,
Float(cutOffFrequency), 0)
}
}
/// Gain (dB) ranges from -40 to 40 (Default: 0)
public var gain: Double = 0 {
didSet {
if gain < -40 {
gain = -40
}
if gain > 40 {
gain = 40
}
AudioUnitSetParameter(
internalAU,
kHighShelfParam_Gain,
kAudioUnitScope_Global, 0,
Float(gain), 0)
}
}
/// Dry/Wet Mix (Default 100)
public var dryWetMix: Double = 100 {
didSet {
if dryWetMix < 0 {
dryWetMix = 0
}
if dryWetMix > 100 {
dryWetMix = 100
}
inputGain?.volume = 1 - dryWetMix / 100
effectGain?.volume = dryWetMix / 100
}
}
private var lastKnownMix: Double = 100
private var inputGain: AKMixer?
private var effectGain: AKMixer?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
/// Initialize the high shelf filter node
///
/// - parameter input: Input node to process
/// - parameter cutOffFrequency: Cut Off Frequency (Hz) ranges from 10000 to 22050 (Default: 10000)
/// - parameter gain: Gain (dB) ranges from -40 to 40 (Default: 0)
///
public init(
_ input: AKNode,
cutOffFrequency: Double = 10000,
gain: Double = 0) {
self.cutOffFrequency = cutOffFrequency
self.gain = gain
inputGain = AKMixer(input)
inputGain!.volume = 0
mixer = AKMixer(inputGain!)
effectGain = AKMixer(input)
effectGain!.volume = 1
internalEffect = AVAudioUnitEffect(audioComponentDescription: cd)
super.init()
AudioKit.engine.attachNode(internalEffect)
internalAU = internalEffect.audioUnit
AudioKit.engine.connect((effectGain?.avAudioNode)!, to: internalEffect, format: AudioKit.format)
AudioKit.engine.connect(internalEffect, to: mixer.avAudioNode, format: AudioKit.format)
avAudioNode = mixer.avAudioNode
AudioUnitSetParameter(internalAU, kHighShelfParam_CutOffFrequency, kAudioUnitScope_Global, 0, Float(cutOffFrequency), 0)
AudioUnitSetParameter(internalAU, kHighShelfParam_Gain, kAudioUnitScope_Global, 0, Float(gain), 0)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
if isStopped {
dryWetMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
if isPlaying {
lastKnownMix = dryWetMix
dryWetMix = 0
isStarted = false
}
}
}
| 08da1d785540fbd59c9126435b5ccfa3 | 30.811594 | 132 | 0.585421 | false | false | false | false |
nomothetis/SemverKit | refs/heads/master | Common/Increment.swift | mit | 1 | //
// VersionBump.swift
// SemverKit
//
// Created by Salazar, Alexandros on 9/15/14.
// Copyright (c) 2014 nomothetis. All rights reserved.
//
import Foundation
/**
An extension to allow semantic incrementation of versions, including support for alpha and beta
versions.
*/
extension Version {
/**
Bumps the major number by one; zeros and nils out the rest.
:return: a new version with a bumped major version.
*/
public func nextMajorVersion() -> Version {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: PreReleaseInfo.None)
}
/**
Bumps the minor number by one; zeros and nils out all less-significant values.
:return: a new version with a bumped minor version.
*/
public func nextMinorVersion() -> Version {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease: nil, metadata: nil)
}
/**
Bumps the patch number by one; zeros and nils out all less-significant values.
:return: a new version with a bumped patch version.
*/
public func nextPatchVersion() -> Version {
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease: nil)
}
/**
Returns the next major alpha version.
The next major alpha version of version `v1` is defined as the smallest version `v2 > v1` with
- A patch number of 0
- A minor number of 0
- A pre-release of alpha.X, where X is an integer
Examples:
- 2.3.5 -> 3.0.0-alpha.0
- 2.0.5 -> 3.0.0-alpha.0
- 3.0.0 -> 4.0.0-alpha.0
- 3.0.0-alpha.0 -> 3.0.0-alpha.1
- 3.0.0-beta.1 -> 4.0.0-alpha.0
- 3.0.0-alpha -> 3.0.0-alpha.0
- 3.0.0-234 -> 3.0.0-alpha.0
- 3.0.0-tim -> 4.0.0-alpha.0
:return: a new version with bumped major version, and an alpha prerelease of 0.
*/
public func nextMajorAlphaVersion() -> Version {
switch self.preRelease {
case PreReleaseInfo.None:
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0))
case PreReleaseInfo.Alpha(let alpha):
if (self.patch == 0) && (self.minor == 0) {
return Version(major: self.major, minor: 0, patch: 0, preRelease:.Alpha(alpha + 1))
} else {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0))
}
case PreReleaseInfo.Beta(_):
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0))
case .Arbitrary(let info):
if (self.preRelease < PreReleaseInfo.Alpha(0)) {
return Version(major: self.major, minor: 0, patch: 0, preRelease: .Alpha(0))
} else {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Alpha(0))
}
}
}
/**
Returns the next minor alpha version.
The next minor alpha version of a version `v1` is defined as the smallest version `v2 > v1` with
- A patch number of 0.
- An pre-release of alpha.X, where X is an integer.
Examples:
- 2.3.5 -> 2.4.0-alpha.0
- 2.3.0 -> 2.4.0-alpha.0
- 2.3.5-alpha.3 -> 2.4.0-alpha.0
- 2.3.0-alpha.3 -> 2.3.0-alpha.4
- 2.3.0-alpha.a -> 2.4.0-alpha.0 (digits have lower priority than strings)
- 2.3.0-12 -> 2.3.0-alpha.0
- 2.3.0-beta.3 -> 2.4.0-alpha.0
- 2.3.0-alpha -> 2.3.0-alpha.0
:return: the next minor alpha version.
*/
public func nextMinorAlphaVersion() -> Version {
switch self.preRelease {
case PreReleaseInfo.None:
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0))
case PreReleaseInfo.Alpha(let alpha):
if (self.patch == 0) {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(alpha + 1))
} else {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0))
}
case PreReleaseInfo.Beta(_):
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0))
case .Arbitrary(let info):
if (self.patch != 0) {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(0))
} else if (self.preRelease < PreReleaseInfo.Alpha(0)) {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Alpha(0))
} else {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease: .Alpha(0))
}
}
}
/**
Returns the next patch alpha version.
The next patch alpha version of a version `v1` is defined as the smallest version `v2 > v1`
with:
- A pre-release in the form alpha.X where X is an integer
Examples:
- 2.0.0 -> 2.0.1-alpha.0
- 2.0.1-alpha.0 -> 2.0.1-alpha.2
- 2.0.1-beta.3 -> 2.0.2-alpha.0
- 2.0.1-alpha -> 2.0.2-alpha.0
:return: the next patch alpha version.
*/
public func nextPatchAlphaVersion() -> Version {
switch self.preRelease {
case PreReleaseInfo.None:
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Alpha(0))
case PreReleaseInfo.Alpha(let alpha):
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(alpha + 1))
case PreReleaseInfo.Beta(_):
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Alpha(0))
case .Arbitrary(let info):
if (self.preRelease < PreReleaseInfo.Alpha(0)) {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Alpha(0))
} else {
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease: .Alpha(0))
}
}
}
/**
Returns the next major beta version.
The next major beta version of a version `v1` is defined as the smallest version `v2 > v1` with:
- A minor number of 0
- A patch number of 0
- A pre-release of beta.X, where X is an integer
Examples:
2.3.5 -> 3.0.0-beta.0
2.3.5-alpha.0 -> 3.0.0-beta.0
3.0.0-alpha.7 -> 3.0.0-beta.0
3.0.0-beta.7 -> 3.0.0-beta.8
3.0.0-tim -> 4.0.0-beta.0
3.0.0-123 -> 3.0.0-beta0
:return: the next major beta version.
*/
public func nextMajorBetaVersion() -> Version {
switch self.preRelease {
case .None:
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Beta(0))
case .Alpha(_):
if self.minor == 0 && self.patch == 0 {
return Version(major: self.major, minor: 0, patch: 0, preRelease:.Beta(0))
} else {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Beta(0))
}
case .Beta(let int):
if (self.minor == 0 && self.patch == 0) {
return Version(major: self.major, minor: 0, patch: 0, preRelease:.Beta(int + 1))
} else {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Beta(0))
}
case .Arbitrary(let arr):
if (self.preRelease < .Beta(0)) {
return Version(major: self.major, minor: 0, patch: 0, preRelease: .Beta(0))
} else {
return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Beta(0))
}
}
}
/**
Returns the next minor beta version.
The next minor beta version of a version `v1` is defined as the smallest version `v2 > v1` with:
- A patch number of 0
- A pre-release of beta.X, where X is an integer
Examples:
- 2.3.5 -> 2.4.0-beta.0
- 2.2.0 -> 2.3.0-beta.0
- 2.5.0-alpha.3 -> 2.5.0-beta.0
- 2.7.0-beta.3 -> 2.7.0-beta.4
- 8.3.0-final -> 8.4.0-beta.0
- 8.4.0-45 -> 8.4.0-beta.0
:return: the next minor beta version.
*/
public func nextMinorBetaVersion() -> Version {
switch self.preRelease {
case .None:
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0))
case .Alpha(_):
if self.patch == 0 {
return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(0))
} else {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0))
}
case .Beta(let int):
if self.patch == 0 {
return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(int + 1))
} else {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0))
}
case .Arbitrary(let info):
if self.preRelease < PreReleaseInfo.Beta(0) {
return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(0))
} else {
return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0))
}
}
}
/**
Returns the next patch beta version.
The next patch beta version of a version `v1` is defined as the smallest version `v2 > v1` where:
- A pre-release in the form beta.X where X is an integer
Examples:
- 2.3.5 -> 2.3.6-beta.0
- 3.4.0-alpha.0 -> 3.4.0-beta.0
- 3.0.0 -> 3.0.1-beta.0
- 3.1.0 -> 3.1.1-beta.0
- 3.1.0-beta.1 -> 3.1.1-beta.2
- 3.1.0-123 -> 3.1.0-beta.0
:return: the next patch beta version.
*/
public func nextPatchBetaVersion() -> Version {
switch self.preRelease {
case .None:
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Beta(0))
case .Alpha(_):
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Beta(0))
case .Beta(let num):
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Beta(num + 1))
case .Arbitrary(let info):
if self.preRelease < .Beta(0) {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Beta(0))
} else {
return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Beta(0))
}
}
}
/**
Gets the stable version.
A stabilized version `v1` is the smallest version `v2 > v1` such that there is no prerelease
or metadata info.
Examples:
- 3.0.0-alpha.2 -> 3.0.0
- 3.4.3-beta.0 -> 3.4.3
:return: the stabilized version.
*/
public func nextStableVersion() -> Version {
return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: PreReleaseInfo.None)
}
} | 8a550ab9f3b901cc64b0ce628ab5b559 | 37.753425 | 117 | 0.563588 | false | false | false | false |
CoolCodeFactory/ViperWeather | refs/heads/master | ViperWeather/RootContainer.swift | apache-2.0 | 1 | //
// RootContainer.swift
// Architecture
//
// Created Dmitri Utmanov on 20/02/16.
// Copyright © 2016 Dmitriy Utmanov. All rights reserved.
//
// Generated by Swift-Viper templates. Find latest version at https://github.com/Nikita2k/SwiftViper
//
import UIKit
import Swinject
class RootContainer: AssemblyType {
func assemble(container: Container) {
container.registerForStoryboard(RootViewController.self) { (r, c) -> () in
container.register(RootPresenterProtocol.self) { [weak c] r in
guard let c = c else { fatalError("Contoller is nil") }
let interface = c
let interactor = r.resolve(RootInteractorInputProtocol.self)!
let router = r.resolve(RootRouterInputProtocol.self)!
let presenter = RootPresenter(interface: interface, interactor: interactor, router: router)
interactor.presenter = presenter
return presenter
}
c.presenter = r.resolve(RootPresenterProtocol.self)
}
container.register(RootInteractorInputProtocol.self) { r in
return RootInteractor()
}
container.register(RootRouterInputProtocol.self) { r in
let router = RootRouter()
router.listAssembler = r.resolve(ListAssembler.self)!
return router
}
container.register(ListAssembler.self) { r in
let parentAssembler = r.resolve(RootAssembler.self)!
return ListAssembler(parentAssembler: parentAssembler)
}
}
}
| 72477183fde18dc28f6d4d4a246781fa | 32.44898 | 107 | 0.612569 | false | false | false | false |
BoltApp/bolt-ios | refs/heads/master | BoltExample/BoltExample/BoltAPI/Model/BLTShippingAddress.swift | mit | 1 | //
// BLTShippingAddress.swift
// BoltAPI
//
// Created by Bolt.
// Copyright © 2018 Bolt. All rights reserved.
//
import Foundation
public enum BLTShippingAddressError: Error {
case wrongCountryCode(_ countryCode: String)
}
struct BLTShippingAddressConstants {
static let countryCodeCharactersCount = 2
}
/// Shipping address object within shipment
public class BLTShippingAddress: Decodable {
// MARK: Required
/// First name
public var firstName: String
/// Last Name
public var lastName: String
/// Street address line 1
public var streetAddress1: String
/// Refers to a city or something similar
public var locality: String
/// Refers to a state or something similar
public var region: String
/// Postal or ZIP code
public var postalCode: String
/// 2 letter ISO country code
public private(set) var countryCode: String
/// Full name of the country
public var country: String
// MARK: Optional
/// Company
public var company: String?
/// Phone number
public var phone: String?
/// Email address
public var email: String?
/// Street address line 2
public var streetAddress2: String?
/// Street address line 3
public var streetAddress3: String?
/// Street address line 4
public var streetAddress4: String?
// MARK: Initialization
/**
Initializes a Shipping address object within shipment.
- Parameter firstName: First name.
- Parameter lastName: Last name.
- Parameter streetAddress1: Street address line 1.
- Parameter locality: Refers to a city or something similar.
- Parameter region: Refers to a state or something similar.
- Parameter postalCode: Postal or ZIP code.
- Parameter countryCode: 2 letter ISO country code.
- Parameter country: Full name of the country.
- Returns: A new shipping address instance.
*/
public init(firstName: String,
lastName: String,
streetAddress1: String,
locality: String,
region: String,
postalCode: String,
countryCode: String,
country: String) throws {
self.firstName = firstName
self.lastName = lastName
self.streetAddress1 = streetAddress1
self.locality = locality
self.region = region
self.postalCode = postalCode
if countryCode.count == BLTShippingAddressConstants.countryCodeCharactersCount {
self.countryCode = countryCode
} else {
throw BLTShippingAddressError.wrongCountryCode(countryCode)
}
self.country = country
}
// MARK: Additional
public func change(countryCode: String) throws {
if countryCode.count == BLTShippingAddressConstants.countryCodeCharactersCount {
self.countryCode = countryCode
} else {
throw BLTShippingAddressError.wrongCountryCode(countryCode)
}
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
case streetAddress1 = "street_address1"
case streetAddress2 = "street_address2"
case streetAddress3 = "street_address3"
case streetAddress4 = "street_address4"
case locality
case region
case postalCode = "postal_code"
case countryCode = "country_code"
case country
case company
case phone
case email
}
required public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
firstName = try values.decode(String.self, forKey: .firstName)
lastName = try values.decode(String.self, forKey: .lastName)
streetAddress1 = try values.decode(String.self, forKey: .streetAddress1)
locality = try values.decode(String.self, forKey: .locality)
region = try values.decode(String.self, forKey: .region)
postalCode = try values.decode(String.self, forKey: .postalCode)
countryCode = try values.decode(String.self, forKey: .countryCode)
country = try values.decode(String.self, forKey: .country)
if let value = try? values.decode(String.self, forKey: .company) {
company = value
}
if let value = try? values.decode(String.self, forKey: .phone) {
phone = value
}
if let value = try? values.decode(String.self, forKey: .email) {
email = value
}
if let value = try? values.decode(String.self, forKey: .streetAddress2) {
streetAddress2 = value
}
if let value = try? values.decode(String.self, forKey: .streetAddress3) {
streetAddress3 = value
}
if let value = try? values.decode(String.self, forKey: .streetAddress4) {
streetAddress4 = value
}
}
}
// MARK: Encode
extension BLTShippingAddress: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(firstName, forKey: .firstName)
try container.encode(lastName, forKey: .lastName)
try container.encode(streetAddress1, forKey: .streetAddress1)
try container.encode(locality, forKey: .locality)
try container.encode(region, forKey: .region)
try container.encode(postalCode, forKey: .postalCode)
try container.encode(countryCode, forKey: .countryCode)
try container.encode(country, forKey: .country)
if let value = company {
try container.encode(value, forKey: .company)
}
if let value = phone {
try container.encode(value, forKey: .phone)
}
if let value = email {
try container.encode(value, forKey: .email)
}
if let value = streetAddress2 {
try container.encode(value, forKey: .streetAddress2)
}
if let value = streetAddress3 {
try container.encode(value, forKey: .streetAddress3)
}
if let value = streetAddress4 {
try container.encode(value, forKey: .streetAddress4)
}
}
}
| 57644556860454580c3db5ab2f60842f | 31.179104 | 88 | 0.618429 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/WalletAuthentication/Repositories/WalletRecovery/AccountRecoveryRepository.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Errors
import FeatureAuthenticationDomain
final class AccountRecoveryRepository: AccountRecoveryRepositoryAPI {
// MARK: - Properties
private let userCreationClient: NabuUserCreationClientAPI
private let userResetClient: NabuResetUserClientAPI
private let userRecoveryClient: NabuUserRecoveryClientAPI
// MARK: - Setup
init(
userCreationClient: NabuUserCreationClientAPI = resolve(),
userResetClient: NabuResetUserClientAPI = resolve(),
userRecoveryClient: NabuUserRecoveryClientAPI = resolve()
) {
self.userCreationClient = userCreationClient
self.userResetClient = userResetClient
self.userRecoveryClient = userRecoveryClient
}
// MARK: - API
func createOrGetNabuUser(
jwtToken: String
) -> AnyPublisher<(NabuOfflineToken, jwtToken: String), AccountRecoveryServiceError> {
userCreationClient
.createUser(for: jwtToken)
.map(NabuOfflineToken.init)
.map { ($0, jwtToken) }
.mapError(AccountRecoveryServiceError.network)
.eraseToAnyPublisher()
}
func resetUser(
offlineToken: NabuOfflineToken,
jwtToken: String
) -> AnyPublisher<Void, AccountRecoveryServiceError> {
let response = NabuOfflineTokenResponse(from: offlineToken)
return userResetClient
.resetUser(offlineToken: response, jwt: jwtToken)
.mapError(AccountRecoveryServiceError.network)
.eraseToAnyPublisher()
}
func recoverUser(
jwtToken: String,
userId: String,
recoveryToken: String
) -> AnyPublisher<NabuOfflineToken, AccountRecoveryServiceError> {
userRecoveryClient
.recoverUser(
jwt: jwtToken,
userId: userId,
recoveryToken: recoveryToken
)
.map(NabuOfflineToken.init)
.mapError(AccountRecoveryServiceError.network)
.eraseToAnyPublisher()
}
}
| 21034b80b8be35136a93d1843e41719f | 30.641791 | 90 | 0.666981 | false | false | false | false |
argent-os/argent-ios | refs/heads/master | app-ios/ProfileMenuViewController.swift | mit | 1 | //
// ProfileMenuViewController.swift
// argent-ios
//
// Created by Sinan Ulkuatam on 3/19/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import UIKit
import Foundation
import SafariServices
import CWStatusBarNotification
import StoreKit
import Crashlytics
import Whisper
import MZFormSheetPresentationController
import KeychainSwift
class ProfileMenuViewController: UITableViewController, SKStoreProductViewControllerDelegate {
@IBOutlet weak var shareCell: UITableViewCell!
@IBOutlet weak var rateCell: UITableViewCell!
@IBOutlet weak var inviteCell: UITableViewCell!
private var menuSegmentBar: UISegmentedControl = UISegmentedControl(items: ["Account", "More"])
private var shouldShowSection1: Bool? = true
private var shouldShowSection2: Bool? = false
private var maskHeaderView = UIView()
private var verifiedLabel = UILabel()
private var verifiedImage = UIImageView()
private var verifiedButton:UIButton = UIButton()
private var userImageView: UIImageView = UIImageView()
private var scrollView: UIScrollView!
private var notification = CWStatusBarNotification()
private var locationLabel = UILabel()
private let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 40, width: UIScreen.mainScreen().bounds.size.width, height: 50))
private let refreshControlView = UIRefreshControl()
private var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureHeader()
validateAccount()
}
func validateAccount() {
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let app: UIApplication = UIApplication.sharedApplication()
let statusBarHeight: CGFloat = app.statusBarFrame.size.height
let statusBarView: UIView = UIView(frame: CGRectMake(0, -statusBarHeight, UIScreen.mainScreen().bounds.size.width, statusBarHeight))
statusBarView.backgroundColor = UIColor.clearColor()
self.navigationController?.navigationBar.addSubview(statusBarView)
self.verifiedLabel.contentMode = .Center
self.verifiedLabel.textAlignment = .Center
self.verifiedLabel.textColor = UIColor.darkBlue()
self.verifiedLabel.font = UIFont(name: "SFUIText-Regular", size: 14)
self.verifiedLabel.layer.cornerRadius = 5
self.verifiedLabel.layer.borderColor = UIColor.darkBlue().CGColor
self.verifiedLabel.layer.borderWidth = 0
let verifyTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.showTutorialModal(_:)))
self.verifiedLabel.addGestureRecognizer(verifyTap)
self.verifiedLabel.userInteractionEnabled = true
self.view.addSubview(self.verifiedLabel)
self.view.bringSubviewToFront(self.verifiedLabel)
Account.getStripeAccount { (acct, err) in
let fields = acct?.verification_fields_needed
let _ = fields.map { (unwrappedOptionalArray) -> Void in
// if array has values
if !unwrappedOptionalArray.isEmpty {
self.verifiedLabel.text = "How to Verify?"
self.verifiedLabel.textColor = UIColor.iosBlue()
self.verifiedLabel.frame = CGRect(x: 110, y: 82, width: screenWidth-220, height: 30)
self.locationLabel.textAlignment = NSTextAlignment.Center
var fields_required: [String] = unwrappedOptionalArray
if let indexOfExternalAccount = fields_required.indexOf("external_account") {
fields_required[indexOfExternalAccount] = "Bank"
}
if let indexOfFirstName = fields_required.indexOf("legal_entity.first_name") {
fields_required[indexOfFirstName] = "First Name"
}
if let indexOfLastName = fields_required.indexOf("legal_entity.last_name") {
fields_required[indexOfLastName] = "Last Name"
}
if let indexOfBusinessName = fields_required.indexOf("legal_entity.business_name") {
fields_required[indexOfBusinessName] = "Business Name"
}
if let indexOfAddressCity = fields_required.indexOf("legal_entity.address.city") {
fields_required[indexOfAddressCity] = "City"
}
if let indexOfAddressState = fields_required.indexOf("legal_entity.address.state") {
fields_required[indexOfAddressState] = "State"
}
if let indexOfAddressZip = fields_required.indexOf("legal_entity.address.postal_code") {
fields_required[indexOfAddressZip] = "ZIP"
}
if let indexOfAddressLine1 = fields_required.indexOf("legal_entity.address.line1") {
fields_required[indexOfAddressLine1] = "Address"
}
if let indexOfPIN = fields_required.indexOf("legal_entity.personal_id_number") {
fields_required[indexOfPIN] = "SSN or Personal ID Number"
}
if let indexOfSSNLast4 = fields_required.indexOf("legal_entity.ssn_last_4") {
fields_required[indexOfSSNLast4] = "SSN Information"
}
if let indexOfEIN = fields_required.indexOf("legal_entity.business_tax_id") {
fields_required[indexOfEIN] = "Business Tax ID (EIN)"
}
if let indexOfVerificationDocument = fields_required.indexOf("legal_entity.verification.document") {
fields_required[indexOfVerificationDocument] = "Verification Document"
}
let fields_list = fields_required.dropLast().reduce("") { $0 + $1 + ", " } + fields_required.last!
// regex to replace legal.entity in the future
var announcement = Announcement(title: "Identity verification incomplete", subtitle:
fields_list, image: UIImage(named: "IconAlertCalm"))
announcement.duration = 7
// Shout(announcement, to: self)
let _ = Timeout(10) {
if acct?.transfers_enabled == false {
//showGlobalNotification("Transfers disabled until more account information is provided", duration: 10.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.oceanBlue())
}
}
} else if let disabled_reason = acct?.verification_disabled_reason where acct?.verification_disabled_reason != "" {
self.locationLabel.removeFromSuperview()
self.verifiedLabel.layer.borderWidth = 0
self.verifiedLabel.frame = CGRect(x: 30, y: 100, width: screenWidth-60, height: 30)
self.view.addSubview(self.verifiedLabel)
if disabled_reason == "rejected.fraud" {
self.verifiedButton.removeFromSuperview()
self.verifiedLabel.text = "Account rejected: Fraud detected"
} else if disabled_reason == "rejected.terms_of_service" {
self.verifiedButton.removeFromSuperview()
self.verifiedLabel.text = "Account rejected: Terms of Service"
} else if disabled_reason == "rejected.other" {
self.verifiedButton.removeFromSuperview()
self.verifiedLabel.text = "Account rejected | Reason: Other"
} else if disabled_reason == "other" {
self.verifiedButton.removeFromSuperview()
self.verifiedLabel.text = "System maintenance, transfers disabled"
}
}
}
}
}
func checkIfVerified(completionHandler: (Bool, NSError?) -> ()){
Account.getStripeAccount { (acct, err) in
let fields = acct?.verification_fields_needed
let _ = fields.map { (unwrappedOptionalArray) -> Void in
// if array has values
if !unwrappedOptionalArray.isEmpty {
// print("checking if empty... false")
completionHandler(false, nil)
} else {
// print("checking if empty... true")
completionHandler(true, nil)
}
}
}
}
func refresh(sender:AnyObject) {
self.configureView()
self.validateAccount()
self.loadProfile()
self.configureHeader()
// self.tableView.tableHeaderView = ParallaxHeaderView.init(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 220));
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 180))
self.view.sendSubviewToBack(self.tableView.tableHeaderView!)
let _ = Timeout(0.3) {
self.refreshControlView.endRefreshing()
}
}
func configureView() {
self.view.backgroundColor = UIColor.clearColor()
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
self.view.bringSubviewToFront(tableView)
// self.tableView.tableHeaderView = ParallaxHeaderView.init(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 220));
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 180))
refreshControlView.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControlView.addTarget(self, action: #selector(ProfileMenuViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControlView) // not required when using UITableViewController
configureHeader()
loadProfile()
// Add action to share cell to return to activity menu
shareCell.targetForAction(Selector("share:"), withSender: self)
// Add action to rate cell to return to activity menu
let rateGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.openStoreProductWithiTunesItemIdentifier(_:)))
rateCell.addGestureRecognizer(rateGesture)
// Add action to invite user
let inviteGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.inviteUser(_:)))
inviteCell.addGestureRecognizer(inviteGesture)
maskHeaderView.frame = CGRect(x: 0, y: 90, width: screenWidth, height: 60)
maskHeaderView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(maskHeaderView)
menuSegmentBar.addTarget(self, action: #selector(self.toggleSegment(_:)), forControlEvents: .ValueChanged)
menuSegmentBar.selectedSegmentIndex = 0
menuSegmentBar.frame = CGRect(x: 30, y: 120, width: screenWidth-60, height: 30)
self.view.addSubview(menuSegmentBar)
self.view.bringSubviewToFront(menuSegmentBar)
}
func inviteUser(sender: AnyObject) {
self.presentViewController(AddCustomerViewController(), animated: true, completion: nil)
}
func openStoreProductWithiTunesItemIdentifier(sender: AnyObject) {
showGlobalNotification("Loading App Store", duration: 1, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.pastelBlue())
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
let parameters = [ SKStoreProductParameterITunesItemIdentifier : APP_ID]
storeViewController.loadProductWithParameters(parameters) { [weak self] (loaded, error) -> Void in
if loaded {
// Parent class of self is UIViewController
self?.presentViewController(storeViewController, animated: true, completion: nil)
}
}
}
func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
viewController.dismissViewControllerAnimated(true, completion: nil)
}
func configureHeader() {
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let attachment: NSTextAttachment = NSTextAttachment()
attachment.image = UIImage(named: "IconPinWhiteTiny")
let attachmentString: NSAttributedString = NSAttributedString(attachment: attachment)
Account.getStripeAccount { (acct, err) in
self.checkIfVerified({ (bool, err) in
if bool == true {
// the account does not require information, display location
if let address_city = acct?.address_city where address_city != "", let address_country = acct?.address_country {
let locationStr = adjustAttributedStringNoLineSpacing(address_city.uppercaseString + ", " + address_country.uppercaseString, spacing: 0.5, fontName: "SFUIText-Regular", fontSize: 11, fontColor: UIColor.darkBlue())
// locationStr.appendAttributedString(attachmentString)
self.locationLabel.attributedText = locationStr
} else {
let locationStr: NSMutableAttributedString = NSMutableAttributedString(string: "")
locationStr.appendAttributedString(attachmentString)
self.locationLabel.attributedText = locationStr
}
self.view.addSubview(self.locationLabel)
} else {
// profile information is required, show tutorial button
}
})
}
self.locationLabel.frame = CGRectMake(0, 62, screenWidth, 70)
self.locationLabel.textAlignment = NSTextAlignment.Center
self.locationLabel.font = UIFont(name: "SFUIText-Regular", size: 12)
self.locationLabel.numberOfLines = 0
self.locationLabel.textColor = UIColor.darkBlue()
}
// Sets up nav
func configureNav(user: User) {
let navItem = UINavigationItem()
// TODO: do a check for first name, and business name
let f_name = user.first_name
let l_name = user.last_name
let u_name = user.username
let b_name = user.business_name
if b_name != "" {
navItem.title = b_name
} else if f_name != "" {
navItem.title = f_name + " " + l_name
} else {
navItem.title = u_name
}
self.navBar.titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.darkBlue(),
NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 17.0)!
]
self.navBar.setItems([navItem], animated: false)
let _ = Timeout(0.1) {
self.view.addSubview(self.navBar)
}
}
//Changing Status Bar
override func prefersStatusBarHidden() -> Bool {
return false
}
//Changing Status Bar
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
// Handles share and logout action controller
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(tableView.cellForRowAtIndexPath(indexPath)!.tag == 865) {
// share action controller
let activityViewController = UIActivityViewController(
activityItems: ["Check out this app! https://www.argentapp.com/home" as NSString],
applicationActivities: nil)
if activityViewController.userActivity?.activityType == UIActivityTypePostToFacebook {
let uuid = NSUUID().UUIDString
Answers.logShareWithMethod("FaceBook",
contentName: "User sharing to Facebook",
contentType: "facebook",
contentId: uuid,
customAttributes: nil)
} else if activityViewController.userActivity?.activityType == UIActivityTypePostToTwitter {
let uuid = NSUUID().UUIDString
Answers.logShareWithMethod("Twitter",
contentName: "User sharing to Twitter",
contentType: "twitter",
contentId: uuid,
customAttributes: nil)
} else if activityViewController.userActivity?.activityType == UIActivityTypeMessage {
let uuid = NSUUID().UUIDString
Answers.logShareWithMethod("Message",
contentName: "User sharing through message",
contentType: "message",
contentId: uuid,
customAttributes: nil)
} else if activityViewController.userActivity?.activityType == UIActivityTypeMail {
let uuid = NSUUID().UUIDString
Answers.logShareWithMethod("Mail",
contentName: "User sharing through mail",
contentType: "mail",
contentId: uuid,
customAttributes: nil)
}
activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
presentViewController(activityViewController, animated: true, completion: nil)
activityViewController.popoverPresentationController?.sourceView = UIView()
activityViewController.popoverPresentationController?.sourceRect = UIView().bounds
}
if(tableView.cellForRowAtIndexPath(indexPath)!.tag == 534) {
// 1
let optionMenu = UIAlertController(title: nil, message: "Are you sure you want to logout?", preferredStyle: .ActionSheet)
optionMenu.popoverPresentationController?.sourceView = UIView()
optionMenu.popoverPresentationController?.sourceRect = UIView().bounds
// 2
let logoutAction = UIAlertAction(title: "Logout", style: .Destructive, handler: {
(alert: UIAlertAction!) -> Void in
NSUserDefaults.standardUserDefaults().setValue("", forKey: "userAccessToken")
NSUserDefaults.standardUserDefaults().synchronize();
Answers.logCustomEventWithName("User logged out from profile",
customAttributes: [:])
// go to login view
// let sb = UIStoryboard(name: "Main", bundle: nil)
// let loginVC = sb.instantiateViewControllerWithIdentifier("LoginViewController")
// loginVC.modalTransitionStyle = .CrossDissolve
// let root = UIApplication.sharedApplication().keyWindow?.rootViewController
// root!.presentViewController(loginVC, animated: true, completion: { () -> Void in })
self.performSegueWithIdentifier("loginView", sender: self)
})
//
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
// 4
optionMenu.addAction(logoutAction)
optionMenu.addAction(cancelAction)
// 5
self.presentViewController(optionMenu, animated: true, completion: nil)
}
}
// Loads profile and sets picture
func loadProfile() {
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(ProfileMenuViewController.goToEditPicture(_:)))
userImageView.frame = CGRectMake(screenWidth / 2, -64, 60, 60)
userImageView.layer.cornerRadius = 30
userImageView.userInteractionEnabled = true
userImageView.addGestureRecognizer(tapGestureRecognizer)
userImageView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin]
// centers user profile image
userImageView.center = CGPointMake(self.view.bounds.size.width / 2, 10)
userImageView.backgroundColor = UIColor.groupTableViewBackgroundColor()
userImageView.layer.masksToBounds = true
userImageView.clipsToBounds = true
userImageView.layer.borderWidth = 3
userImageView.layer.borderColor = UIColor(rgba: "#fff").colorWithAlphaComponent(0.3).CGColor
User.getProfile({ (user, error) in
let acv = UIActivityIndicatorView(activityIndicatorStyle: .White)
acv.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
acv.startAnimating()
self.activityIndicator.center = self.userImageView.center
self.userImageView.addSubview(acv)
addActivityIndicatorView(acv, view: self.userImageView, color: .White)
self.userImageView.bringSubviewToFront(acv)
if error != nil {
let alert = UIAlertController(title: "Error", message: "Could not load profile \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
self.configureNav(user!)
if user!.picture != "" {
let img = UIImage(data: NSData(contentsOfURL: NSURL(string: (user!.picture))!)!)!
self.userImageView.image = img
addSubviewWithFade(self.userImageView, parentView: self, duration: 0.8)
} else {
let img = UIImage(named: "IconAnonymous")
self.userImageView.image = img
addSubviewWithFade(self.userImageView, parentView: self, duration: 0.8)
}
})
}
// Opens edit picture
func goToEditPicture(sender: AnyObject) {
self.performSegueWithIdentifier("profilePictureView", sender: sender)
}
// Opens edit picture
func goToEdit(sender: AnyObject) {
self.performSegueWithIdentifier("editProfileView", sender: sender)
}
}
extension ProfileMenuViewController {
// MARK: Tutorial modal
func showTutorialModal(sender: AnyObject) {
let navigationController = self.storyboard!.instantiateViewControllerWithIdentifier("accountVerificationModalNavigationController") as! UINavigationController
let formSheetController = MZFormSheetPresentationViewController(contentViewController: navigationController)
// Initialize and style the terms and conditions modal
formSheetController.presentationController?.contentViewSize = CGSizeMake(300, UIScreen.mainScreen().bounds.height-130)
formSheetController.presentationController?.shouldUseMotionEffect = true
formSheetController.presentationController?.containerView?.backgroundColor = UIColor.blackColor()
formSheetController.presentationController?.containerView?.sizeToFit()
formSheetController.presentationController?.shouldApplyBackgroundBlurEffect = true
formSheetController.presentationController?.blurEffectStyle = UIBlurEffectStyle.Dark
formSheetController.presentationController?.shouldDismissOnBackgroundViewTap = true
formSheetController.presentationController?.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppears.CenterVertically
formSheetController.presentationController?.shouldCenterVertically = true
formSheetController.presentationController?.shouldCenterHorizontally = true
formSheetController.contentViewControllerTransitionStyle = MZFormSheetPresentationTransitionStyle.SlideFromBottom
formSheetController.contentViewCornerRadius = 15
formSheetController.allowDismissByPanningPresentedView = true
formSheetController.interactivePanGestureDismissalDirection = .All;
// Blur will be applied to all MZFormSheetPresentationControllers by default
MZFormSheetPresentationController.appearance().shouldApplyBackgroundBlurEffect = true
let presentedViewController = navigationController.viewControllers.first as! AccountVerificationTutorialViewController
// keep passing along user data to modal
presentedViewController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
presentedViewController.navigationItem.leftItemsSupplementBackButton = true
// Be sure to update current module on storyboard
self.presentViewController(formSheetController, animated: true, completion: nil)
}
}
extension ProfileMenuViewController {
func toggleSegment(sender: UISegmentedControl) {
self.tableView.beginUpdates()
// change boolean conditions for what to show/hide
if menuSegmentBar.selectedSegmentIndex == 0 {
self.view.bringSubviewToFront(menuSegmentBar)
self.view.bringSubviewToFront(verifiedLabel)
self.shouldShowSection1 = true
self.shouldShowSection2 = false
} else if menuSegmentBar.selectedSegmentIndex == 1 {
self.view.bringSubviewToFront(menuSegmentBar)
self.view.bringSubviewToFront(verifiedLabel)
self.shouldShowSection1 = false
self.shouldShowSection2 = true
}
self.tableView.endUpdates()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
if self.shouldShowSection1 == true {
return 44.0
} else {
return 0.0
}
}
else if indexPath.section == 1 {
if self.shouldShowSection2 == true {
return 44.0
} else {
return 0.0
}
} else {
return 44.0
}
}
}
extension ProfileMenuViewController {
override func scrollViewDidScroll(scrollView: UIScrollView) {
if self.tableView.contentOffset.y > 90 {
self.view.bringSubviewToFront(menuSegmentBar)
self.menuSegmentBar.frame.origin.y = self.tableView.contentOffset.y+30
self.maskHeaderView.frame.origin.y = self.tableView.contentOffset.y+20
}
}
}
| 3dc60beb65ea3a4f2567ce71572987ec | 48.691358 | 310 | 0.619556 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/NCNPCPickerGroupsViewController.swift | lgpl-2.1 | 2 | //
// NCNPCPickerGroupsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 21.07.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCNPCPickerGroupsViewController: NCTreeViewController, NCSearchableViewController {
var parentGroup: NCDBNpcGroup?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCHeaderTableViewCell.default,
Prototype.NCDefaultTableViewCell.compact])
setupSearchController(searchResultsController: self.storyboard!.instantiateViewController(withIdentifier: "NCNPCPickerTypesViewController"))
title = parentGroup?.npcGroupName ?? NSLocalizedString("NPC", comment: "")
}
override func didReceiveMemoryWarning() {
if !isViewLoaded || view.window == nil {
treeController?.content = nil
}
}
override func content() -> Future<TreeNode?> {
let request = NSFetchRequest<NCDBNpcGroup>(entityName: "NpcGroup")
request.sortDescriptors = [NSSortDescriptor(key: "npcGroupName", ascending: true)]
if let parent = parentGroup {
request.predicate = NSPredicate(format: "parentNpcGroup == %@", parent)
}
else {
request.predicate = NSPredicate(format: "parentNpcGroup == NULL")
}
let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: nil, cacheName: nil)
try? results.performFetch()
return .init(FetchedResultsNode(resultsController: results, sectionNode: nil, objectNode: NCNPCGroupRow.self))
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
guard let row = node as? NCNPCGroupRow else {return}
if row.object.group != nil {
Router.Database.NPCPickerTypes(npcGroup: row.object).perform(source: self, sender: treeController.cell(for: node))
}
else {
Router.Database.NPCPickerGroups(parentGroup: row.object).perform(source: self, sender: treeController.cell(for: node))
}
}
//MARK: UISearchResultsUpdating
var searchController: UISearchController?
func updateSearchResults(for searchController: UISearchController) {
let predicate: NSPredicate
guard let controller = searchController.searchResultsController as? NCNPCPickerTypesViewController else {return}
if let text = searchController.searchBar.text, text.count > 2 {
predicate = NSPredicate(format: "group.category.categoryID == 11 AND typeName CONTAINS[C] %@", text)
}
else {
predicate = NSPredicate(value: false)
}
controller.predicate = predicate
controller.reloadData()
}
}
| 213495c2985ef793bb7220a3d0424eba | 32.240964 | 168 | 0.757521 | false | false | false | false |
danwatco/mega-liker | refs/heads/master | MegaLiker/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// MegaLiker
//
// Created by Dan Watkinson on 27/11/2015.
// Copyright © 2015 Dan Watkinson. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
var clientID = "[INSTAGRAM_CLIENT_ID]"
var defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
let accessCode = defaults.objectForKey("accessCode")
if(accessCode != nil){
statusLabel.text = "You are now signed in."
}
}
@IBAction func signInBtn(sender: UIButton) {
let userScope = "&scope=likes"
let instagramURL = "https://instagram.com/oauth/authorize/?client_id=" + clientID + "&redirect_uri=megaliker://callback&response_type=token" + userScope
UIApplication.sharedApplication().openURL(NSURL(string: instagramURL)!)
}
@IBAction func signOutBtn(sender: UIButton) {
defaults.removeObjectForKey("accessCode")
statusLabel.textColor = UIColor.redColor()
statusLabel.text = "You are now signed out."
let navController:CustomNavigationController = self.parentViewController as! CustomNavigationController
let viewController:ViewController = navController.viewControllers.first as! ViewController
viewController.userStatus = false
viewController.accessCode = nil
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 0d313230912efdd6ce04e547934067de | 32.587302 | 160 | 0.681474 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/ContextMenu/RoomContextPreviewViewController.swift | apache-2.0 | 1 | // File created from ScreenTemplate
// $ createScreen.sh Spaces/SpaceRoomList/SpaceChildRoomDetail ShowSpaceChildRoomDetail
/*
Copyright 2021 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
import MatrixSDK
/// `RoomContextPreviewViewController` is used to dsplay room preview data within a `UIContextMenuContentPreviewProvider`
final class RoomContextPreviewViewController: UIViewController {
// MARK: - Constants
private enum Constants {
static let popoverWidth: CGFloat = 300
}
// MARK: Outlets
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var avatarView: RoomAvatarView!
@IBOutlet private weak var spaceAvatarView: SpaceAvatarView!
@IBOutlet private weak var userIconView: UIImageView!
@IBOutlet private weak var membersLabel: UILabel!
@IBOutlet private weak var roomsIconView: UIImageView!
@IBOutlet private weak var roomsLabel: UILabel!
@IBOutlet private weak var topicLabel: UILabel!
@IBOutlet private weak var topicLabelBottomMargin: NSLayoutConstraint!
@IBOutlet private weak var spaceTagView: UIView!
@IBOutlet private weak var spaceTagLabel: UILabel!
@IBOutlet private weak var stackView: UIStackView!
@IBOutlet private weak var inviteHeaderView: UIView!
@IBOutlet private weak var inviterAvatarView: UserAvatarView!
@IBOutlet private weak var inviteTitleLabel: UILabel!
@IBOutlet private weak var inviteDetailLabel: UILabel!
@IBOutlet private weak var inviteSeparatorView: UIView!
// MARK: Private
private var theme: Theme!
private var viewModel: RoomContextPreviewViewModelProtocol!
private var mediaManager: MXMediaManager?
// MARK: - Setup
class func instantiate(with viewModel: RoomContextPreviewViewModelProtocol, mediaManager: MXMediaManager?) -> RoomContextPreviewViewController {
let viewController = StoryboardScene.RoomContextPreviewViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.mediaManager = mediaManager
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
viewModel.viewDelegate = self
setupView()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.process(viewAction: .loadData)
}
override var preferredContentSize: CGSize {
get {
return CGSize(width: Constants.popoverWidth, height: self.intrisicHeight(with: Constants.popoverWidth))
}
set {
super.preferredContentSize = newValue
}
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.titleLabel.textColor = theme.textPrimaryColor
self.titleLabel.font = theme.fonts.title3SB
self.membersLabel.font = theme.fonts.caption1
self.membersLabel.textColor = theme.colors.tertiaryContent
self.topicLabel.font = theme.fonts.caption1
self.topicLabel.textColor = theme.colors.tertiaryContent
self.userIconView.tintColor = theme.colors.tertiaryContent
self.roomsIconView.tintColor = theme.colors.tertiaryContent
self.roomsLabel.font = theme.fonts.caption1
self.roomsLabel.textColor = theme.colors.tertiaryContent
self.spaceTagView.backgroundColor = theme.colors.quinaryContent
self.spaceTagLabel.font = theme.fonts.caption1
self.spaceTagLabel.textColor = theme.colors.tertiaryContent
self.inviteTitleLabel.textColor = theme.colors.tertiaryContent
self.inviteTitleLabel.font = theme.fonts.calloutSB
self.inviteDetailLabel.textColor = theme.colors.tertiaryContent
self.inviteDetailLabel.font = theme.fonts.caption1
self.inviteSeparatorView.backgroundColor = theme.colors.quinaryContent
self.inviterAvatarView.alpha = 0.7
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func renderLoaded(with parameters: RoomContextPreviewLoadedParameters) {
self.titleLabel.text = parameters.displayName
self.spaceTagView.isHidden = parameters.roomType != .space
self.avatarView.isHidden = parameters.roomType == .space
self.spaceAvatarView.isHidden = parameters.roomType != .space
let avatarViewData = AvatarViewData(matrixItemId: parameters.roomId,
displayName: parameters.displayName,
avatarUrl: parameters.avatarUrl,
mediaManager: mediaManager,
fallbackImage: .matrixItem(parameters.roomId, parameters.displayName))
if !self.avatarView.isHidden {
self.avatarView.fill(with: avatarViewData)
}
if !self.spaceAvatarView.isHidden {
self.spaceAvatarView.fill(with: avatarViewData)
}
if parameters.membership != .invite {
self.stackView.removeArrangedSubview(self.inviteHeaderView)
self.inviteHeaderView.isHidden = true
}
self.membersLabel.text = parameters.membersCount == 1 ? VectorL10n.roomTitleOneMember : VectorL10n.roomTitleMembers("\(parameters.membersCount)")
if let inviterId = parameters.inviterId {
if let inviter = parameters.inviter {
let avatarData = AvatarViewData(matrixItemId: inviterId,
displayName: inviter.displayname,
avatarUrl: inviter.avatarUrl,
mediaManager: mediaManager,
fallbackImage: .matrixItem(inviterId, inviter.displayname))
self.inviterAvatarView.fill(with: avatarData)
if let inviterName = inviter.displayname {
self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterName)
self.inviteDetailLabel.text = inviterId
} else {
self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId)
}
} else {
self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId)
}
}
self.topicLabel.text = parameters.topic
topicLabelBottomMargin.constant = self.topicLabel.text.isEmptyOrNil ? 0 : 16
self.roomsIconView.isHidden = parameters.roomType != .space
self.roomsLabel.isHidden = parameters.roomType != .space
self.view.layoutIfNeeded()
}
private func setupView() {
self.spaceTagView.layer.masksToBounds = true
self.spaceTagView.layer.cornerRadius = 2
self.spaceTagLabel.text = VectorL10n.spaceTag
}
private func intrisicHeight(with width: CGFloat) -> CGFloat {
if self.topicLabel.text.isEmptyOrNil {
return self.topicLabel.frame.minY
}
let topicHeight = self.topicLabel.sizeThatFits(CGSize(width: width - self.topicLabel.frame.minX * 2, height: 0)).height
return self.topicLabel.frame.minY + topicHeight + 16
}
}
// MARK: - RoomContextPreviewViewModelViewDelegate
extension RoomContextPreviewViewController: RoomContextPreviewViewModelViewDelegate {
func roomContextPreviewViewModel(_ viewModel: RoomContextPreviewViewModelProtocol, didUpdateViewState viewSate: RoomContextPreviewViewState) {
switch viewSate {
case .loaded(let parameters):
self.renderLoaded(with: parameters)
}
}
}
| c386e7ef56e9edb214c2a72bc4dcc680 | 40.031963 | 153 | 0.670376 | false | false | false | false |
LockLight/Weibo_Demo | refs/heads/master | SinaWeibo/SinaWeibo/Classes/View/NewFeature(新特性与欢迎页)/WBWelcomeView.swift | mit | 1 | //
// WBWelcomeView.swift
// SinaWeibo
//
// Created by locklight on 17/4/5.
// Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
import SDWebImage
class WBWelcomeView: UIView {
lazy var iconView:UIImageView = {
let iconView = UIImageView()
iconView.sd_setImage(with: URL(string: WBUserAccount.shared.avatar_large!)!, placeholderImage: UIImage(named: "avatar_default_big")!)
return iconView
}()
lazy var welcomeLabel:UILabel = UILabel(title: "欢迎回来,\(WBUserAccount.shared.screen_name!)", fontSize: 15, alignment: .center)
override init(frame: CGRect) {
super.init(frame: screenBounds)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//动画要在控件部署完后添加
override func didMoveToWindow() {
super.didMoveToWindow()
addAnimation()
}
}
extension WBWelcomeView{
func setupUI() {
self.backgroundColor = UIColor.white
//添加控件
addSubview(iconView)
addSubview(welcomeLabel)
//头像圆角
iconView.layer.cornerRadius = 45
iconView.layer.masksToBounds = true
//自动布局
iconView.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-100)
make.size.equalTo(CGSize(width: 90, height: 90))
}
welcomeLabel.snp.makeConstraints { (make ) in
make.centerX.equalTo(self)
make.bottom.equalTo(self).offset(-150)
}
//动画添加前,强制更新UI布局
layoutIfNeeded()
}
func addAnimation(){
iconView.snp.updateConstraints { (make ) in
make.centerY.equalTo(self).offset(-130)
}
UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 9.8, options: [], animations: {
self.layoutIfNeeded()
}) { (isFinish) in
self.removeFromSuperview()
}
}
}
| f8f255b5288c86d09bc8e80f53b90d55 | 25.897436 | 141 | 0.591516 | false | false | false | false |
CodaFi/swiftz | refs/heads/master | Sources/Swiftz/Those.swift | apache-2.0 | 3 | //
// These.swift
// Swiftz
//
// Created by Robert Widmann on 11/25/14.
// Copyright (c) 2014-2016 Maxwell Swadling. Lll rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// Represents a value with three possiblities: a left value, a right value, or
/// both a left and right value (This, That, and These respectively).
public enum Those<L, R> {
case This(L)
case That(R)
case These(L, R)
/// Returns whether the receiver contains a left value.
public func isThis() -> Bool {
switch self {
case .This(_):
return true
default:
return false
}
}
/// Returns whether the receiver contains a right value.
public func isThat() -> Bool {
switch self {
case .That(_):
return true
default:
return false
}
}
/// Returns whether the receiver contains both a left and right value.
public func isThese() -> Bool {
switch self {
case .These(_, _):
return true
default:
return false
}
}
/// Case analysis for the Those type. If there is a left value the first
/// function is applied to it to yield a result. If there is a right value
/// the middle function is applied. If there is both a left and right value
/// the last function is applied to both.
public func fold<C>(this : (L) -> C, that : (R) -> C, these : (L, R) -> C) -> C {
switch self {
case let .This(x):
return this(x)
case let .That(x):
return that(x)
case let .These(x, y):
return these(x, y)
}
}
/// Extracts values from the receiver filling in any missing values with
/// given default ones.
public func toTuple(_ l : L, _ r : R) -> (L, R) {
switch self {
case let .This(x):
return (x, r)
case let .That(x):
return (l, x)
case let .These(x, y):
return (x, y)
}
}
}
/// Merges a those with the same type on the Left and Right into a singular
/// value of that same type.
public func merge<L>(_ f : @escaping (L) -> (L) -> L) -> (Those<L, L>) -> L {
return { $0.fold(this: identity, that: identity, these: uncurry(f)) }
}
/// MARK: Equatable
public func ==<L : Equatable, R : Equatable>(lhs: Those<L, R>, rhs: Those<L, R>) -> Bool {
switch (lhs, rhs) {
case let (.This(l), .This(r)):
return l == r
case let (.That(l), .That(r)):
return l == r
case let (.These(la, ra), .These(lb, rb)):
return (la == lb) && (ra == rb)
default:
return false
}
}
public func !=<L : Equatable, R : Equatable>(lhs: Those<L, R>, rhs: Those<L, R>) -> Bool {
return !(lhs == rhs)
}
/// MARK: Bifunctor
extension Those /*: Bifunctor*/ {
public typealias A = L
public typealias B = Any
public typealias C = R
public typealias D = Any
public typealias PAC = Those<A, C>
public typealias PAD = Those<A, D>
public typealias PBC = Those<B, C>
public typealias PBD = Those<B, D>
public func bimap<B, D>(_ f : (A) -> B, _ g : (C) -> D) -> Those<B, D> {
switch self {
case let .This(x):
return .This(f(x))
case let .That(x):
return .That(g(x))
case let .These(x, y):
return .These(f(x), g(y))
}
}
public func leftMap<B>(_ f : (A) -> B) -> Those<B, C> {
return self.bimap(f, identity)
}
public func rightMap(g : @escaping (C) -> D) -> Those<A, D> {
return self.bimap(identity, g)
}
}
| fa008ac9a623248ef08a0f52751501ee | 22.807407 | 90 | 0.613877 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/Serialization/serialize_attr.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -parse-as-library -o %t %s
// RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-sil-opt -enable-sil-verify-all -disable-sil-linking %t/serialize_attr.swiftmodule | %FileCheck %s
// BCANALYZER-NOT: UnknownCode
// @_semantics
// -----------------------------------------------------------------------------
//CHECK-DAG: @_semantics("crazy") func foo()
@_inlineable
@_versioned
@_semantics("crazy") func foo() -> Int { return 5}
// @_specialize
// -----------------------------------------------------------------------------
// These lines should be contiguous.
// CHECK-DAG: @_specialize(exported: false, kind: full, where T == Int, U == Float)
// CHECK-DAG: func specializeThis<T, U>(_ t: T, u: U)
@_inlineable
@_versioned
@_specialize(where T == Int, U == Float)
func specializeThis<T, U>(_ t: T, u: U) {}
public protocol PP {
associatedtype PElt
}
public protocol QQ {
associatedtype QElt
}
public struct RR : PP {
public typealias PElt = Float
}
public struct SS : QQ {
public typealias QElt = Int
}
public struct GG<T : PP> {}
// These three lines should be contiguous, however, there is no way to
// sequence FileCheck directives while using CHECK-DAG as the outer
// label, and the declaration order is unpredictable.
//
// CHECK-DAG: class CC<T> where T : PP {
// CHECK-DAG: @_specialize(exported: false, kind: full, where T == RR, U == SS)
// CHECK-DAG: @inline(never) func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ
public class CC<T : PP> {
@_inlineable
@_versioned
@inline(never)
@_specialize(where T==RR, U==SS)
func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-DAG: sil [serialized] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-DAG: sil [serialized] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
| 0478ea7b257b8b4df210ed8eb755a651 | 35.370968 | 283 | 0.608869 | false | false | false | false |
nuclearace/SwiftDiscord | refs/heads/master | Sources/SwiftDiscord/Rest/DiscordEndpointGateway.swift | mit | 1 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without
// limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import Foundation
import Dispatch
struct DiscordEndpointGateway {
static var gatewayURL = getURL()
private static var gatewaySemaphore = DispatchSemaphore(value: 0)
static func getURL() -> String {
// Linux's urlsession is busted
#if os(Linux)
return "wss://gateway.discord.gg"
#else
var request = URLRequest(url: URL(string: "https://discordapp.com/api/gateway")!)
request.httpMethod = "GET"
var url = "wss://gateway.discord.gg"
URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data, let stringData = String(data: data, encoding: .utf8),
case let .object(info)? = JSON.decodeJSON(stringData),
let gateway = info["url"] as? String else {
gatewaySemaphore.signal()
return
}
url = gateway
gatewaySemaphore.signal()
}.resume()
gatewaySemaphore.wait()
return url
#endif
}
}
| 65910564b19d3dd06ef164f7e9cc14a8 | 39 | 119 | 0.681481 | false | false | false | false |
rudkx/swift | refs/heads/main | test/Interop/Cxx/class/inheritance/type-aliases-module-interface.swift | apache-2.0 | 1 | // RUN: %target-swift-ide-test -print-module -module-to-print=TypeAliases -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s
// CHECK: struct Base {
// CHECK-NEXT: init()
// CHECK-NEXT: struct Struct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias T = Int32
// CHECK-NEXT: typealias U = Base.Struct
// CHECK-NEXT: }
// CHECK-NEXT: struct Derived {
// CHECK-NEXT: init()
// CHECK-NEXT: typealias Struct = Base.Struct.Type
// CHECK-NEXT: typealias T = Int32
// CHECK-NEXT: typealias U = Base.Struct
// CHECK-NEXT: }
| 44d171780a403af808e84aa62121fb1c | 33 | 141 | 0.645329 | false | true | false | false |
lp1994428/TextKitch | refs/heads/master | TextKitchen/TextKitchen/classes/Common/MainTabBarViewController.swift | mit | 1 | //
// MainTabBarViewController.swift
// TextKitchen
//
// Created by 罗平 on 16/10/21.
// Copyright © 2016年 罗平. All rights reserved.
//
import UIKit
import SnapKit
class MainTabBarViewController: UITabBarController {
var bgView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
tabBar.hidden = true
createViewController()
// myTabBar()
}
func createViewController(){
//10.24从文件里面读取数据
let path = NSBundle.mainBundle().pathForResource("Controllers", ofType: "json")
let data = NSData(contentsOfFile: path!)
//视图控制器名字的数组
var ctrNameArray = [String]()
var images = [String]()
var titles = [String]()
do {
// 可能抛异常
let array = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
if array.isKindOfClass(NSArray){
let tmp = array as![[String:String]]
for dic in tmp{
let name = dic["ctrname"]
let imageName = dic["image"]
let title = dic["title"]
ctrNameArray.append(name!)
images.append(imageName!)
titles.append(title!)
}
}
}catch(let error){
//捕获错误信息
print(error)
}
// 如果获取的数组为空
if ctrNameArray.count == 0{
ctrNameArray = ["TextKitchen.IngredientsViewController","TextKitchen.CommunityViewController","TextKitchen.MallViewController","TextKitchen.FoodViewController","TextKitchen.ProfileViewController"]
titles = ["食材","社区","商城","食客","我的"]
images = ["home","community","shop","shike","mine"]
}
var ctrlArray = [UINavigationController]()
for i in 0..<ctrNameArray.count{
let ctrl = NSClassFromString(ctrNameArray[i]) as! UIViewController.Type
let vc = ctrl.init()
let navCtrl = UINavigationController(rootViewController: vc)
ctrlArray.append(navCtrl)
}
viewControllers = ctrlArray
myTabBar(images, titles: titles)
}
func myTabBar(imagesName:[String],titles:[String]) {
bgView = UIView.createView()
bgView?.backgroundColor = UIColor.whiteColor()
bgView?.layer.borderColor = UIColor.orangeColor().CGColor
bgView?.layer.borderWidth = 1
view.addSubview(bgView!)
bgView?.snp_makeConstraints(closure: { [weak self](make) in
make.left.right.bottom.equalTo(self!.view)
make.height.equalTo(49)
})
let width = lpScreenWd/CGFloat(imagesName.count)
for i in 0..<imagesName.count{
let btn = UIButton.createButton(nil, bgImageName: "\(imagesName[i])_normal", highLightImageName: "\(imagesName[i])_select" , selectImageName: "\(imagesName[i])_select", target: self, action: #selector(btnClick(_:)))
btn.tag = 300 + i
bgView?.addSubview(btn)
btn.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(self.bgView!)
make.width.equalTo(width)
make.left.equalTo(width*CGFloat(i))
})
if btn.tag == 300{
btn.selected = true
}
let textLabel = UILabel.createLabel(titles[i], textAlignment: NSTextAlignment.Center, font: UIFont.systemFontOfSize(10))
//10.24
textLabel.textColor = UIColor.lightGrayColor()
textLabel.tag = 400
btn.addSubview(textLabel)
textLabel.snp_makeConstraints(closure: { (make) in
make.left.right.bottom.equalTo(btn)
make.height.equalTo(20)
})
if i == 0{
btn.selected = true
textLabel.textColor = UIColor.brownColor()
}
}
}
func btnClick(btn:UIButton) {
let index = btn.tag - 300
//选中当前的按钮,取消选中之前的,切换视图控制器
if selectedIndex != index{
let lastBtn = bgView?.viewWithTag(300+selectedIndex) as! UIButton
lastBtn.selected = false
lastBtn.userInteractionEnabled = true
let lastlabel = lastBtn.viewWithTag(400) as! UILabel
lastlabel.textColor = UIColor.lightGrayColor()
btn.selected = true
btn.userInteractionEnabled = false
selectedIndex = index
let curLabel = btn.viewWithTag(400) as! UILabel
curLabel.textColor = UIColor.brownColor()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 8715331bc074efa0e144e137e0dd6b0b | 36.413043 | 227 | 0.574085 | false | false | false | false |
broccolii/SingleBarNavigationController | refs/heads/master | SingleBarNavigationController/SingleBarNavigationController/Resouce/ExclusiveNavigationController.swift | mit | 1 | //
// ExclusiveNavigationController.swift
// SingleBarNavigationController
//
// Created by Broccoli on 2016/10/27.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
import UIKit
fileprivate func SafeWrapViewController(_ viewController: UIViewController,
navigationBarClass: AnyClass? = nil,
useSystemBackBarButtonItem: Bool = false,
backBarButtonItem: UIBarButtonItem? = nil,
backTitle: String? = nil) -> UIViewController {
if !(viewController is WrapperViewController) {
return WrapperViewController(viewController,
navigationBarClass: navigationBarClass,
backBarButtonItem: backBarButtonItem,
useSystemBackBarButtonItem: useSystemBackBarButtonItem,
backTitle: backTitle)
}
return viewController
}
fileprivate func SafeUnwrapViewController(_ viewController: UIViewController) -> UIViewController {
if (viewController is WrapperViewController) {
return (viewController as! WrapperViewController).contentViewController
}
return viewController
}
open class ExclusiveNavigationController: UINavigationController, UINavigationControllerDelegate {
fileprivate weak var exclusiveDelegate: UINavigationControllerDelegate?
fileprivate var animationBlock: ((Bool) -> Void)?
@IBInspectable var isUseSystemBackBarButtonItem = false
@IBInspectable var isTransferNavigationBarAttributes = true
var exclusiveTopViewController: UIViewController {
return SafeUnwrapViewController(super.topViewController!)
}
var exclusiveVisibleViewController: UIViewController {
return SafeUnwrapViewController(super.visibleViewController!)
}
var exclusiveViewControllers: [UIViewController] {
return super.viewControllers.map{ (viewController) -> UIViewController in
return SafeUnwrapViewController(viewController)
}
}
func onBack(_ sender: Any) {
_ = popViewController(animated: true)
}
// MARK: - Overrides
override open func awakeFromNib() {
viewControllers = super.viewControllers
}
required public init() {
super.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: SafeWrapViewController(rootViewController, navigationBarClass: rootViewController.navigationBarClass))
}
convenience init(rootViewControllerNoWrapping rootViewController: UIViewController) {
self.init()
super.pushViewController(rootViewController, animated: false)
}
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
super.delegate = self
super.setNavigationBarHidden(true, animated: false)
}
@available(iOS, introduced: 6.0, deprecated: 9.0)
func forUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> UIViewController? {
var viewController = super.forUnwindSegueAction(action, from: fromViewController, withSender: sender)
if viewController == nil {
if let index = viewControllers.index(of: fromViewController) {
for i in 0..<index {
if let _ = viewControllers[i].forUnwindSegueAction(action, from: fromViewController, withSender: sender) {
viewController = viewControllers[i].forUnwindSegueAction(action, from: fromViewController, withSender: sender)
break
}
}
}
}
return viewController
}
override open func setNavigationBarHidden(_ hidden: Bool, animated: Bool) {}
override open func pushViewController(_ viewController: UIViewController, animated: Bool) {
if viewControllers.count > 0 {
let currentLast = SafeUnwrapViewController(viewControllers.last!)
super.pushViewController(SafeWrapViewController(viewController,
navigationBarClass: viewController.navigationBarClass,
useSystemBackBarButtonItem: isUseSystemBackBarButtonItem,
backBarButtonItem: currentLast.navigationItem.backBarButtonItem,
backTitle: currentLast.title),
animated: animated)
} else {
super.pushViewController(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass), animated: animated)
}
}
override open func popViewController(animated: Bool) -> UIViewController {
return SafeUnwrapViewController(super.popViewController(animated: animated)!)
}
override open func popToRootViewController(animated: Bool) -> [UIViewController]? {
if let viewControllers = super.popToRootViewController(animated: animated) {
return viewControllers.map{ (viewController) -> UIViewController in
SafeUnwrapViewController(viewController)
}
} else {
return nil
}
}
override open func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
var controllerToPop: UIViewController? = nil
for item in super.viewControllers {
if SafeUnwrapViewController(item) == viewController {
controllerToPop = item
break
}
}
if controllerToPop != nil {
if let viewControllers = super.popToRootViewController(animated: animated) {
return viewControllers.map{ (viewController) -> UIViewController in
return SafeUnwrapViewController(viewController)
}
}
return nil
}
return nil
}
override open func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
var wrapViewControllers = [UIViewController]()
for (index, viewController) in viewControllers.enumerated() {
if isUseSystemBackBarButtonItem && index > 0 {
wrapViewControllers.append(SafeWrapViewController(viewController,
navigationBarClass: viewController.navigationBarClass,
useSystemBackBarButtonItem: isUseSystemBackBarButtonItem,
backBarButtonItem: viewControllers[index - 1].navigationItem.backBarButtonItem,
backTitle: viewControllers[index - 1].title))
} else {
wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass))
}
}
super.setViewControllers(wrapViewControllers, animated: animated)
}
open override var viewControllers: [UIViewController] {
set {
var wrapViewControllers = [UIViewController]()
for (index, viewController) in newValue.enumerated() {
if isUseSystemBackBarButtonItem && index > 0 {
wrapViewControllers.append(SafeWrapViewController(viewController,
navigationBarClass: viewController.navigationBarClass,
useSystemBackBarButtonItem: isUseSystemBackBarButtonItem,
backBarButtonItem: newValue[index - 1].navigationItem.backBarButtonItem,
backTitle: newValue[index - 1].title))
} else {
wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass))
}
}
super.viewControllers = wrapViewControllers
}
get {
let unwrapViewControllers = super.viewControllers.map { (viewController) -> UIViewController in
return SafeUnwrapViewController(viewController)
}
return unwrapViewControllers
}
}
open override var childViewControllers: [UIViewController] {
let unwrapViewControllers = super.childViewControllers.map { (viewController) -> UIViewController in
return SafeUnwrapViewController(viewController)
}
return unwrapViewControllers
}
override open var delegate: UINavigationControllerDelegate? {
set {
exclusiveDelegate = newValue
}
get {
return super.delegate
}
}
override open var shouldAutorotate: Bool {
return topViewController?.shouldAutorotate ?? false
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return topViewController?.supportedInterfaceOrientations ?? .portrait
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return topViewController?.preferredInterfaceOrientationForPresentation ?? .unknown
}
@available(iOS, introduced: 2.0, deprecated: 8.0, message: "Header views are animated along with the rest of the view hierarchy")
override open func rotatingHeaderView() -> UIView? {
return topViewController?.rotatingHeaderView()
}
@available(iOS, introduced: 2.0, deprecated: 8.0, message: "Footer views are animated along with the rest of the view hierarchy")
override open func rotatingFooterView() -> UIView? {
return topViewController?.rotatingFooterView()
}
override open func responds(to aSelector: Selector) -> Bool {
if super.responds(to: aSelector) {
return true
}
return exclusiveDelegate?.responds(to: aSelector) ?? false
}
override open func forwardingTarget(for aSelector: Selector) -> Any? {
return exclusiveDelegate
}
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
var viewController = viewController
let isRootVC = SafeUnwrapViewController(viewController) == navigationController.viewControllers.first!
if !isRootVC {
viewController = SafeUnwrapViewController(viewController)
if !isUseSystemBackBarButtonItem && viewController.navigationItem.leftBarButtonItem == nil {
viewController.navigationItem.leftBarButtonItem = viewController.customBackItem(withTarget: self, action: #selector(onBack))
}
}
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))){
exclusiveDelegate!.navigationController!(navigationController, willShow: viewController, animated: animated)
}
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
let isRootVC = viewController == navigationController.viewControllers.first!
let unwrappedViewController = SafeUnwrapViewController(viewController)
if unwrappedViewController.disableInteractivePopGesture {
interactivePopGestureRecognizer?.delegate = nil
interactivePopGestureRecognizer?.isEnabled = false
} else {
interactivePopGestureRecognizer?.delaysTouchesBegan = true
interactivePopGestureRecognizer?.delegate = self
interactivePopGestureRecognizer?.isEnabled = !isRootVC
}
ExclusiveNavigationController.attemptRotationToDeviceOrientation()
if (animationBlock != nil) {
animationBlock!(true)
animationBlock = nil
}
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))){
exclusiveDelegate?.navigationController!(navigationController, didShow: unwrappedViewController, animated: animated)
}
}
public func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationControllerSupportedInterfaceOrientations(_:))){
return exclusiveDelegate!.navigationControllerSupportedInterfaceOrientations!(navigationController)
}
return .all
}
public func navigationControllerPreferredInterfaceOrientationForPresentation(_ navigationController: UINavigationController) -> UIInterfaceOrientation {
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationControllerPreferredInterfaceOrientationForPresentation(_:))){
return exclusiveDelegate!.navigationControllerPreferredInterfaceOrientationForPresentation!(navigationController)
}
return .portrait
}
public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:interactionControllerFor:))){
return exclusiveDelegate!.navigationController!(navigationController, interactionControllerFor: animationController)!
}
return nil
}
public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let _ = exclusiveDelegate,
exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:animationControllerFor:from:to:))){
return exclusiveDelegate!.navigationController!(navigationController, animationControllerFor: operation, from: fromVC, to: toVC)
}
return nil
}
}
public extension ExclusiveNavigationController {
// MARK: - Methods
func remove(_ controller: UIViewController) {
remove(controller, animated: false)
}
func remove(_ controller: UIViewController, animated flag: Bool) {
var controllers = viewControllers
var controllerToRemove: UIViewController? = nil
controllers.forEach { (viewController) in
if SafeUnwrapViewController(viewController) == controller {
controllerToRemove = viewController
}
}
if controllerToRemove != nil {
controllers.remove(at: controllers.index(of: controllerToRemove!)!)
super.setViewControllers(controllers, animated: flag)
}
}
func push(_ viewController: UIViewController, animated: Bool, complete block: @escaping (Bool) -> Void) {
if (animationBlock != nil) {
animationBlock!(false)
}
animationBlock = block
pushViewController(viewController, animated: animated)
}
func popToViewController(viewController: UIViewController, animated: Bool, complete block: @escaping (Bool) -> Void) -> [UIViewController]? {
if (animationBlock != nil) {
animationBlock!(false)
}
animationBlock = block
let array = popToViewController(viewController, animated: animated)
if let _ = array,
array!.count > 0 {
if (animationBlock != nil) {
animationBlock = nil
}
}
return array
}
func popToRootViewController(animated: Bool, complete block: @escaping (Bool) -> Void) -> [UIViewController]? {
if (animationBlock != nil) {
animationBlock!(false)
}
animationBlock = block
let array = popToRootViewController(animated: animated)
if let _ = array,
array!.count > 0 {
if (animationBlock != nil) {
animationBlock = nil
}
}
return array
}
}
extension ExclusiveNavigationController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return (gestureRecognizer == interactivePopGestureRecognizer)
}
}
| aa784a2060ece4d9be80837461b1c306 | 44.468193 | 253 | 0.652247 | false | false | false | false |
chris-wood/reveiller | refs/heads/master | Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisYHighLayerDefault.swift | gpl-2.0 | 3 | //
// ChartAxisYHighLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisYHighLayerDefault: ChartAxisYLayerDefault {
override var low: Bool {return false}
override var lineP1: CGPoint {
return self.p1
}
override var lineP2: CGPoint {
return self.p2
}
override func initDrawers() {
self.lineDrawer = self.generateLineDrawer(offset: 0)
let labelsOffset = self.settings.labelsToAxisSpacingY + self.settings.axisStrokeWidth
self.labelDrawers = self.generateLabelDrawers(offset: labelsOffset)
let axisTitleLabelsOffset = labelsOffset + self.labelsMaxWidth + self.settings.axisTitleLabelsToLabelsSpacing
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: axisTitleLabelsOffset)
}
override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer {
let halfStrokeWidth = self.settings.axisStrokeWidth / 2 // we want that the stroke begins at the beginning of the frame, not in the middle of it
let x = self.p1.x + offset + halfStrokeWidth
let p1 = CGPointMake(x, self.p1.y)
let p2 = CGPointMake(x, self.p2.y)
return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor)
}
override func labelsX(offset offset: CGFloat, labelWidth: CGFloat) -> CGFloat {
return self.p1.x + offset
}
}
| 0794f92e37edf5ff8c9c46ea98f78b85 | 33.681818 | 152 | 0.686107 | false | false | false | false |
PANDA-Guide/PandaGuideApp | refs/heads/master | Carthage/Checkouts/APIKit/Carthage/Checkouts/OHHTTPStubs/Examples/Swift/MainViewController.swift | gpl-3.0 | 6 | //
// ViewController.swift
// OHHTTPStubsDemo
//
// Created by Olivier Halligon on 18/04/2015.
// Copyright (c) 2015 AliSoftware. All rights reserved.
//
import UIKit
import OHHTTPStubs
class MainViewController: UIViewController {
////////////////////////////////////////////////////////////////////////////////
// MARK: - Outlets
@IBOutlet var delaySwitch: UISwitch!
@IBOutlet var textView: UITextView!
@IBOutlet var installTextStubSwitch: UISwitch!
@IBOutlet var imageView: UIImageView!
@IBOutlet var installImageStubSwitch: UISwitch!
////////////////////////////////////////////////////////////////////////////////
// MARK: - Init & Dealloc
override func viewDidLoad() {
super.viewDidLoad()
installTextStub(self.installTextStubSwitch)
installImageStub(self.installImageStubSwitch)
OHHTTPStubs.onStubActivation { (request: NSURLRequest, stub: OHHTTPStubsDescriptor, response: OHHTTPStubsResponse) in
print("[OHHTTPStubs] Request to \(request.URL!) has been stubbed with \(stub.name)")
}
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Global stubs activation
@IBAction func toggleStubs(sender: UISwitch) {
OHHTTPStubs.setEnabled(sender.on)
self.delaySwitch.enabled = sender.on
self.installTextStubSwitch.enabled = sender.on
self.installImageStubSwitch.enabled = sender.on
let state = sender.on ? "and enabled" : "but disabled"
print("Installed (\(state)) stubs: \(OHHTTPStubs.allStubs)")
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Text Download and Stub
@IBAction func downloadText(sender: UIButton) {
sender.enabled = false
self.textView.text = nil
let urlString = "http://www.opensource.apple.com/source/Git/Git-26/src/git-htmldocs/git-commit.txt?txt"
let req = NSURLRequest(URL: NSURL(string: urlString)!)
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue()) { (_, data, _) in
sender.enabled = true
if let receivedData = data, receivedText = NSString(data: receivedData, encoding: NSASCIIStringEncoding) {
self.textView.text = receivedText as String
}
}
}
weak var textStub: OHHTTPStubsDescriptor?
@IBAction func installTextStub(sender: UISwitch) {
if sender.on {
// Install
textStub = stub(isExtension("txt")) { _ in
let stubPath = OHPathForFile("stub.txt", self.dynamicType)
return fixture(stubPath!, headers: ["Content-Type":"text/plain"])
.requestTime(self.delaySwitch.on ? 2.0 : 0.0, responseTime:OHHTTPStubsDownloadSpeedWifi)
}
textStub?.name = "Text stub"
} else {
// Uninstall
OHHTTPStubs.removeStub(textStub!)
}
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Image Download and Stub
@IBAction func downloadImage(sender: UIButton) {
sender.enabled = false
self.imageView.image = nil
let urlString = "http://images.apple.com/support/assets/images/products/iphone/hero_iphone4-5_wide.png"
let req = NSURLRequest(URL: NSURL(string: urlString)!)
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue.mainQueue()) { (_, data, _) in
sender.enabled = true
if let receivedData = data {
self.imageView.image = UIImage(data: receivedData)
}
}
}
weak var imageStub: OHHTTPStubsDescriptor?
@IBAction func installImageStub(sender: UISwitch) {
if sender.on {
// Install
imageStub = stub(isExtension("png") || isExtension("jpg") || isExtension("gif")) { _ in
let stubPath = OHPathForFile("stub.jpg", self.dynamicType)
return fixture(stubPath!, headers: ["Content-Type":"image/jpeg"])
.requestTime(self.delaySwitch.on ? 2.0 : 0.0, responseTime: OHHTTPStubsDownloadSpeedWifi)
}
imageStub?.name = "Image stub"
} else {
// Uninstall
OHHTTPStubs.removeStub(imageStub!)
}
}
////////////////////////////////////////////////////////////////////////////////
// MARK: - Cleaning
@IBAction func clearResults() {
self.textView.text = ""
self.imageView.image = nil
}
}
| 6ab32474c62b05f8eab8590eb5260b86 | 34.870229 | 125 | 0.54501 | false | false | false | false |
blakemerryman/Swift-Scripts | refs/heads/master | Intro Examples/6-AppleScriptExample.swift | mit | 1 | #!/usr/bin/env xcrun swift
import Foundation
enum Options: String {
case ShutDown = "--off"
case Restart = "--restart"
case Sleep = "--sleep"
case Lock = "--lock"
}
if Process.arguments.count > 1 {
let flag = Process.arguments[1]
let userInput = Options(rawValue: flag)
var scriptToPerform: NSAppleScript?
// WARNING - Needs much better error handling here ( non-Options from user == CRASH!!! )
// Also,
switch userInput! {
case .ShutDown:
let shutDownSource = "tell app \"loginwindow\" to «event aevtrsdn»"
scriptToPerform = NSAppleScript(source:shutDownSource)
case .Restart:
let restartSource = "tell app \"loginwindow\" to «event aevtrrst»"
scriptToPerform = NSAppleScript(source:restartSource)
case .Sleep:
let sleepSource = "tell app \"System Events\" to sleep"
scriptToPerform = NSAppleScript(source: sleepSource)
case .Lock:
let lockSource = "tell application \"System Events\" to tell process \"SystemUIServer\" to click (first menu item of menu 1 of ((click (first menu bar item whose description is \"Keychain menu extra\")) of menu bar 1) whose title is \"Lock Screen\")"
scriptToPerform = NSAppleScript(source:lockSource)
}
if let script = scriptToPerform {
var possibleError: NSDictionary?
print("Performing some script... \(userInput!.rawValue)")
//script.executeAndReturnError(&possibleError)
if let error = possibleError {
print("ERROR: \(error)")
}
}
}
| 238f1301b15a3ebe4073790e56b82898 | 29.921569 | 258 | 0.6487 | false | false | false | false |
Ferrari-lee/firefox-ios | refs/heads/master | Storage/SQL/SQLiteLogins.swift | mpl-2.0 | 18 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let AllLoginTables: Args = [TableLoginsMirror, TableLoginsLocal]
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 2 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
// We ignore the version.
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local])
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db, version: to)
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db, version: to)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
let protectionSpace = NSURLProtectionSpace(host: row["hostname"] as! String,
port: 0,
`protocol`: nil,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? " +
"ORDER BY timeLastUsed DESC"
let args: Args = [protectionSpace.host, protectionSpace.host]
log.debug("Looking for login: \(protectionSpace.host)")
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [protectionSpace.host, username, protectionSpace.host, username]
usernameMatch = "username = ?"
} else {
args = [protectionSpace.host, protectionSpace.host]
usernameMatch = "username IS NULL"
}
log.debug("Looking for login: \(username), \(args[0])")
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND username IS ? " +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func addLogin(login: LoginData) -> Success {
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(whereClause whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared =
"guid " +
", hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", timesUsed" +
", username" +
", password "
let local =
", local_modified " +
", is_deleted " +
", sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(\(shared)\(local)) " +
"SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status " +
"FROM \(TableLoginsMirror) " +
(whereClause ?? "")
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
public func removeLoginByGUID(guid: GUID) -> Success {
let nowMillis = NSDate.now()
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid = ? AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid = ?"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(delete, withArgs: args)
>>> { self.db.run(update, withArgs: args) }
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(insert, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
private func resolveConflictBetween(local local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(local local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
/**
* Clean up any metadata.
*/
public func onRemovedAccount() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
| e9dfb334eda975b45dbc516d7bf5ac66 | 41.718714 | 198 | 0.605864 | false | false | false | false |
dabainihao/MapProject | refs/heads/master | MapProject/MapProject/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// MapProject
//
// Created by 杨少锋 on 16/4/13.
// Copyright © 2016年 杨少锋. All rights reserved.
// 地图定位, 编码, 插大头针
import UIKit
class ViewController: UIViewController,BMKMapViewDelegate,UITextFieldDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKRouteSearchDelegate {
lazy var map : BMKMapView? = {
BMKMapView()
}()
lazy var locService : BMKLocationService? = {
BMKLocationService()
}()
lazy var geo: BMKGeoCodeSearch? = {
BMKGeoCodeSearch()
}()
lazy var expectAddress: UITextField! = {
UITextField()
}()
// route搜索服务
lazy var routeSearch: BMKRouteSearch! = {
BMKRouteSearch()
}()
lazy var titleView : UIView! = {
UIView()
}()
var loginButton : UIButton!
var sureButton: UIButton!
var routePlannButton : UIButton!
var userLocation :CLLocation?
var expectLocation : String?
var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "路线规划"
if (!CLLocationManager.locationServicesEnabled()) {
print("定位服务当前可能尚未打开,请设置打开!")
return;
}
self.locService?.allowsBackgroundLocationUpdates = false;
self.locService?.distanceFilter = 100
self.locService?.desiredAccuracy = 100
self.locService?.startUserLocationService();
self.map?.frame = CGRectMake(0, 0, self.view.bounds.size.width,self.view.bounds.size.height)
self.map?.delegate = self
self.map?.showsUserLocation = true
self.map?.mapType = 1;
// 地图比例尺级别,在手机上当前可使用的级别为3-21级
self.map?.zoomLevel = 19;
self.map?.userTrackingMode = BMKUserTrackingModeNone; // 设置定位状态
self.view.addSubview(self.map!)
self.titleView.frame = CGRectMake(20, 40, self.view.frame.size.width - 40, 50)
self.titleView.backgroundColor = UIColor.whiteColor()
self.titleView.layer.cornerRadius = 2;
self.titleView.layer.masksToBounds = true
self.view.addSubview(self.titleView)
self.loginButton = UIButton(type: UIButtonType.System)
self.loginButton.frame = CGRectMake(5, 10, 30, 30)
self.loginButton.addTarget(self, action: "loginOrregist", forControlEvents: UIControlEvents.TouchUpInside)
self.titleView.addSubview(self.loginButton)
self.label = UILabel(frame: CGRectMake(39, 10, 1, 30))
self.label?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15)
self.titleView.addSubview(self.label!)
self.expectAddress.frame = CGRectMake(50, 0, 170, 50)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "expectAddressChang", name: UITextFieldTextDidChangeNotification, object: nil)
self.expectAddress.borderStyle = UITextBorderStyle.None
self.expectAddress.placeholder = "请输入详细的地址"
self.expectAddress.delegate = self
self.titleView.addSubview(self.expectAddress)
self.sureButton = UIButton(type: UIButtonType.System)
self.sureButton.enabled = false
self.sureButton.setTitle("确定", forState: UIControlState.Normal)
self.sureButton.frame = CGRectMake(225, 10, 30, 30)
self.sureButton .addTarget(self, action: "sureButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
self.sureButton.enabled = false
self.titleView.addSubview(self.sureButton)
self.routePlannButton = UIButton(type: UIButtonType.System)
self.routePlannButton.setTitle("路线规划", forState: UIControlState.Normal)
self.routePlannButton.frame = CGRectMake(260, 10, 70, 30)
self.routePlannButton .addTarget(self, action: "routePlannButtonAction", forControlEvents: UIControlEvents.TouchUpInside)
self.routePlannButton.enabled = false;
self.titleView.addSubview(self.routePlannButton)
}
func loginOrregist() {
if (LO_loginHelper().isLogin()) {
let alter = UIAlertView(title: "提示", message: "已登录", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定")
alter.show() //
} else {
let nav : UINavigationController = UINavigationController(rootViewController: LO_LoginController())
self.presentViewController(nav, animated: true) { () -> Void in
}
}
}
//BMKMapView新增viewWillAppear、viewWillDisappear方法来控制BMKMapView的生命周期,并且在一个时刻只能有一个BMKMapView接受回调消息,因此在使用BMKMapView的viewController中需要在viewWillAppear、viewWillDisappear方法中调用BMKMapView的对应的方法,并处理delegat
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
if (!LO_loginHelper().isLogin()) {
self.loginButton.setImage(UIImage(named:"person") , forState:UIControlState.Normal)
self.loginButton.setImage(UIImage(named:"person") , forState:UIControlState.Selected)
} else {
self.loginButton.setImage(UIImage(named:"person_all") , forState:UIControlState.Normal)
self.loginButton.setImage(UIImage(named:"person_all") , forState:UIControlState.Selected)
}
self.locService?.delegate = self
self.map?.delegate = self
self.geo?.delegate = self
self.routeSearch.delegate = self
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.locService?.delegate = nil
self.map?.delegate = nil
self.geo?.delegate = nil
self.routeSearch.delegate = nil
}
func expectAddressChang() {
if self.expectAddress.text == "" {
self.sureButton.enabled = false
} else {
self.sureButton.enabled = true
}
}
// 确定按钮的事件
func sureButtonAction() {
self.sureButton.enabled = false;
self.expectAddress.resignFirstResponder()
if (self.expectAddress.text == nil) {
print("您输入的位置为空")
return
}
let addressInformation: BMKGeoCodeSearchOption = BMKGeoCodeSearchOption()
addressInformation.address = self.expectAddress.text
self.geo?.geoCode(addressInformation)
}
// 路线规划的事件
func routePlannButtonAction() {
if (self.userLocation == nil || self.expectAddress.text == nil) {
return
}
let reverseGeoCodeOption : BMKReverseGeoCodeOption = BMKReverseGeoCodeOption();
reverseGeoCodeOption.reverseGeoPoint = (self.userLocation?.coordinate)!
self.geo?.reverseGeoCode(reverseGeoCodeOption)
}
//*返回地址信息搜索结果(用户输入转化坐标)
func onGetGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
if result.address == nil {
let alter = UIAlertView(title: "提示", message: "没有这个位置", delegate: nil, cancelButtonTitle: "确定", otherButtonTitles: "取消")
alter .show()
return;
}
self.expectLocation = result.address
self.sureButton.enabled = true;
if (error != BMK_SEARCH_NO_ERROR || searcher != self.geo || result == nil) { // 如果没有正常返回结果直接返回
print("编码错误")
return;
}
self.map?.setCenterCoordinate(result.location, animated: true)
// 移除地图上添加的标注
self.map?.removeAnnotations(self.map?.annotations)
let annotation = LO_Annotation()
annotation.coordinate = result.location
annotation.pointImage = UIImage(named: "exAddress")
annotation.title = result.address
self.map?.addAnnotation(annotation)
}
/*返回反地理编码搜索结果*/
func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
let from = BMKPlanNode()
from.name = result.addressDetail.district + result.addressDetail.streetName;
from.name = "上地三街"
from.cityName = result.addressDetail.city
let to = BMKPlanNode()
// 终点
to.name = self.expectAddress.text!;
to.name = "清河中街"
to.cityName = result.addressDetail.city
let transitRouteSearchOption = BMKTransitRoutePlanOption()
transitRouteSearchOption.city = result.addressDetail.city
transitRouteSearchOption.from = from
transitRouteSearchOption.to = to
print("frame = \(from.name) to = \(to.name)")
// 发起公交检索
let flag = routeSearch.transitSearch(transitRouteSearchOption)
if flag {
print("公交检索发送成功")
}else {
print("公交检索发送失败")
}
}
//
/***返回公交搜索结果*/
func onGetTransitRouteResult(searcher: BMKRouteSearch!, result: BMKTransitRouteResult!, errorCode error: BMKSearchErrorCode) {
print("onGetTransitRouteResult: \(error)")
if error != BMK_SEARCH_NO_ERROR {
print("%d",error)
let alter = UIAlertView(title: "提示", message: "\(error)", delegate: nil, cancelButtonTitle: "确定", otherButtonTitles: "取消")
alter .show()
}
self.map!.removeAnnotations(self.map!.annotations)
self.map!.removeOverlays(self.map!.overlays)
if error == BMK_SEARCH_NO_ERROR {
let plan = result.routes[0] as! BMKTransitRouteLine
let size = plan.steps.count
var planPointCounts = 0
for i in 0..<size {
let transitStep = plan.steps[i] as! BMKTransitStep
if i == 0 {
let item = LO_RouteAnnotation()
item.coordinate = plan.starting.location
item.title = "起点"
item.type = 0
self.map!.addAnnotation(item) // 添加起点标注
}else if i == size - 1 {
let item = LO_RouteAnnotation()
item.coordinate = plan.terminal.location
item.title = "终点"
item.type = 1
self.map!.addAnnotation(item) // 添加终点标注
}
let item = LO_RouteAnnotation()
item.coordinate = transitStep.entrace.location
item.title = transitStep.instruction
item.type = 3
self.map!.addAnnotation(item)
// 轨迹点总数累计
planPointCounts = Int(transitStep.pointsCount) + planPointCounts
}
// 轨迹点
var tempPoints = Array(count: planPointCounts, repeatedValue: BMKMapPoint(x: 0, y: 0))
var i = 0
for j in 0..<size {
let transitStep = plan.steps[j] as! BMKTransitStep
for k in 0..<Int(transitStep.pointsCount) {
tempPoints[i].x = transitStep.points[k].x
tempPoints[i].y = transitStep.points[k].y
i++
}
}
// 通过 points 构建 BMKPolyline
let polyLine = BMKPolyline(points: &tempPoints, count: UInt(planPointCounts))
// 添加路线 overlay
self.map!.addOverlay(polyLine)
mapViewFitPolyLine(polyLine)
}
}
// 添加覆盖物
func mapView(mapView: BMKMapView!, viewForOverlay overlay: BMKOverlay!) -> BMKOverlayView! {
if overlay as! BMKPolyline? != nil {
let polylineView = BMKPolylineView(overlay: overlay as! BMKPolyline)
polylineView.strokeColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.7)
polylineView.lineWidth = 3
return polylineView
}
return nil
}
//根据polyline设置地图范围
func mapViewFitPolyLine(polyline: BMKPolyline!) {
if polyline.pointCount < 1 {
return
}
let pt = polyline.points[0]
var ltX = pt.x
var rbX = pt.x
var ltY = pt.y
var rbY = pt.y
for i in 1..<polyline.pointCount {
let pt = polyline.points[Int(i)]
if pt.x < ltX {
ltX = pt.x
}
if pt.x > rbX {
rbX = pt.x
}
if pt.y > ltY {
ltY = pt.y
}
if pt.y < rbY {
rbY = pt.y
}
}
let rect = BMKMapRectMake(ltX, ltY, rbX - ltX, rbY - ltY)
self.map!.visibleMapRect = rect
self.map!.zoomLevel = self.map!.zoomLevel - 0.3
}
// 添加大头针的代理
func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! {
if annotation is LO_RouteAnnotation {
if let routeAnnotation = annotation as! LO_RouteAnnotation? {
return getViewForRouteAnnotation(routeAnnotation)
}
}
if annotation is BMKUserLocation {
self.routePlannButton.enabled = false
return nil;
}
let AnnotationViewID = "renameMark"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! BMKPinAnnotationView?
if annotationView == nil {
annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
}
annotationView?.annotation = annotation
let lo_annotation = annotation as! LO_Annotation
annotationView?.image = lo_annotation.pointImage
annotationView?.canShowCallout = true
self.routePlannButton.enabled = true;
return annotationView
}
//
func getViewForRouteAnnotation(routeAnnotation: LO_RouteAnnotation!) -> BMKAnnotationView? {
var view: BMKAnnotationView?
let imageName = "nav_bus"
let identifier = "\(imageName)_annotation"
view = self.map!.dequeueReusableAnnotationViewWithIdentifier(identifier)
if view == nil {
view = BMKAnnotationView(annotation: routeAnnotation, reuseIdentifier: identifier)
view?.centerOffset = CGPointMake(0, -(view!.frame.size.height * 0.5))
view?.canShowCallout = true
}
view?.annotation = routeAnnotation
let bundlePath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("/mapapi.bundle/")
let bundle = NSBundle(path: bundlePath!)
if let imagePath = bundle?.resourcePath?.stringByAppendingString("/images/icon_\(imageName).png") {
let image = UIImage(contentsOfFile: imagePath)
if image != nil {
view?.image = image
}
}
return view
}
// 用户位置更新
func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
print("didUpdateUserLocation lat:\(userLocation.location.coordinate.latitude) lon:\(userLocation.location.coordinate.longitude)")
self.userLocation = userLocation.location;
self.map?.updateLocationData(userLocation)
// 设置用户位置为地图的中心点
self.map?.setCenterCoordinate(userLocation.location.coordinate, animated: true)
}
// 定位失败
func didFailToLocateUserWithError(error: NSError!) {
print("定位失败")
}
// 大头针的点击事件
func mapView(mapView: BMKMapView!, didSelectAnnotationView view: BMKAnnotationView!) {
self.map?.setCenterCoordinate(view.annotation.coordinate, animated: true);
}
// 控制键盘回收
func mapView(mapView: BMKMapView!, regionWillChangeAnimated animated: Bool) {
self.expectAddress.resignFirstResponder()
}
func mapView(mapView: BMKMapView!, onClickedBMKOverlayView overlayView: BMKOverlayView!) {
self.expectAddress.resignFirstResponder()
}
func mapview(mapView: BMKMapView!, onDoubleClick coordinate: CLLocationCoordinate2D) {
self.expectAddress.resignFirstResponder()
}
func mapview(mapView: BMKMapView!, onLongClick coordinate: CLLocationCoordinate2D) {
self.expectAddress.resignFirstResponder()
}
func mapView(mapView: BMKMapView!, onClickedMapBlank coordinate: CLLocationCoordinate2D) {
self.expectAddress.resignFirstResponder()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.expectAddress.resignFirstResponder()
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if string == "\n" {
self.expectAddress.resignFirstResponder()
return false
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.expectAddress.resignFirstResponder()
return true
}
}
| 15646c0c6f90ddfe5d66b754d02bc30d | 38.725537 | 198 | 0.622049 | false | false | false | false |
carping/Postal | refs/heads/master | PostalDemo/PostalDemo/LoginTableViewController.swift | mit | 1 | //
// LoginTableViewController.swift
// PostalDemo
//
// Created by Kevin Lefevre on 24/05/2016.
// Copyright © 2017 Snips. All rights reserved.
//
import UIKit
import Postal
enum LoginError: Error {
case badEmail
case badPassword
case badHostname
case badPort
}
extension LoginError: CustomStringConvertible {
var description: String {
switch self {
case .badEmail: return "Bad mail"
case .badPassword: return "Bad password"
case .badHostname: return "Bad hostname"
case .badPort: return "Bad port"
}
}
}
final class LoginTableViewController: UITableViewController {
fileprivate let mailsSegueIdentifier = "mailsSegue"
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var hostnameTextField: UITextField!
@IBOutlet weak var portTextField: UITextField!
var provider: MailProvider?
}
// MARK: - View lifecycle
extension LoginTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let provider = provider, let configuration = provider.preConfiguration {
emailTextField.placeholder = "exemple@\(provider.hostname)"
hostnameTextField.isUserInteractionEnabled = false
hostnameTextField.text = configuration.hostname
portTextField.isUserInteractionEnabled = false
portTextField.text = "\(configuration.port)"
}
}
}
// MARK: - Navigation management
extension LoginTableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch (segue.identifier, segue.destination) {
case (.some(mailsSegueIdentifier), let vc as MailsTableViewController):
do {
vc.configuration = try createConfiguration()
} catch let error as LoginError {
showAlertError("Error login", message: (error as NSError).localizedDescription)
} catch {
fatalError()
}
break
default: break
}
}
}
// MARK: - Helpers
private extension LoginTableViewController {
func createConfiguration() throws -> Configuration {
guard let email = emailTextField.text , !email.isEmpty else { throw LoginError.badEmail }
guard let password = passwordTextField.text , !password.isEmpty else { throw LoginError.badPassword }
if let configuration = provider?.preConfiguration {
return Configuration(hostname: configuration.hostname, port: configuration.port, login: email, password: .plain(password), connectionType: configuration.connectionType, checkCertificateEnabled: configuration.checkCertificateEnabled)
} else {
guard let hostname = hostnameTextField.text , !hostname.isEmpty else { throw LoginError.badHostname }
guard let portText = portTextField.text , !portText.isEmpty else { throw LoginError.badPort }
guard let port = UInt16(portText) else { throw LoginError.badPort }
return Configuration(hostname: hostname, port: port, login: email, password: .plain(""), connectionType: .tls, checkCertificateEnabled: true)
}
}
}
| c0fc2fa852cd3a965980486c678e2f13 | 33.291667 | 244 | 0.671324 | false | true | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/PageHistoryComparisonSelectionViewController.swift | mit | 2 | import UIKit
protocol PageHistoryComparisonSelectionViewControllerDelegate: AnyObject {
func pageHistoryComparisonSelectionViewController(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController, selectionOrder: SelectionOrder)
func pageHistoryComparisonSelectionViewControllerDidTapCompare(_ pageHistoryComparisonSelectionViewController: PageHistoryComparisonSelectionViewController)
}
class PageHistoryComparisonSelectionViewController: UIViewController {
@IBOutlet private weak var firstSelectionButton: AlignedImageButton!
@IBOutlet private weak var secondSelectionButton: AlignedImageButton!
@IBOutlet private weak var compareButton: UIButton!
private var theme = Theme.standard
public weak var delegate: PageHistoryComparisonSelectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setup(button: firstSelectionButton)
setup(button: secondSelectionButton)
compareButton.setTitle(CommonStrings.compareTitle, for: .normal)
compareButton.addTarget(self, action: #selector(performCompareButtonAction(_:)), for: .touchUpInside)
resetSelectionButtons()
updateFonts()
}
private func setup(button: AlignedImageButton) {
button.cornerRadius = 8
button.clipsToBounds = true
button.backgroundColor = theme.colors.paperBackground
button.imageView?.tintColor = theme.colors.link
button.setTitleColor(theme.colors.link, for: .normal)
button.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
button.horizontalSpacing = 10
button.contentHorizontalAlignment = .leading
button.leftPadding = 10
button.rightPadding = 10
button.addTarget(self, action: #selector(performSelectionButtonAction(_:)), for: .touchUpInside)
}
@objc private func performSelectionButtonAction(_ sender: AlignedImageButton) {
guard let selectionOrder = SelectionOrder(rawValue: sender.tag) else {
return
}
delegate?.pageHistoryComparisonSelectionViewController(self, selectionOrder: selectionOrder)
}
@objc private func performCompareButtonAction(_ sender: UIButton) {
delegate?.pageHistoryComparisonSelectionViewControllerDidTapCompare(self)
}
private func reset(button: AlignedImageButton?) {
button?.setTitle(nil, for: .normal)
button?.setImage(nil, for: .normal)
button?.backgroundColor = theme.colors.paperBackground
button?.borderWidth = 1
button?.borderColor = theme.isDark ? UIColor.wmf_gray : theme.colors.border
}
public func resetSelectionButton(_ selectionOrder: SelectionOrder) {
reset(button: button(selectionOrder))
}
public func resetSelectionButtons() {
reset(button: firstSelectionButton)
reset(button: secondSelectionButton)
}
public func setCompareButtonEnabled(_ enabled: Bool) {
compareButton.isEnabled = enabled
}
private func button(_ selectionOrder: SelectionOrder) -> AlignedImageButton? {
switch selectionOrder {
case .first:
return firstSelectionButton
case .second:
return secondSelectionButton
}
}
public func updateSelectionButton(_ selectionOrder: SelectionOrder, with themeModel: PageHistoryViewController.SelectionThemeModel, cell: PageHistoryCollectionViewCell) {
let button = self.button(selectionOrder)
UIView.performWithoutAnimation {
button?.setTitle(cell.time, for: .normal)
button?.setImage(cell.authorImage, for: .normal)
button?.backgroundColor = themeModel.backgroundColor
button?.imageView?.tintColor = themeModel.authorColor
button?.setTitleColor(themeModel.authorColor, for: .normal)
button?.tintColor = themeModel.authorColor
button?.borderWidth = 1
button?.borderColor = themeModel.borderColor
}
}
private func updateFonts() {
compareButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
firstSelectionButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
secondSelectionButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
}
}
extension PageHistoryComparisonSelectionViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.midBackground
compareButton.tintColor = theme.colors.link
}
}
| aea302e37bcc6e9bd5b9d98d4768d5f7 | 41.787611 | 179 | 0.725957 | false | false | false | false |
marinehero/DominantColor | refs/heads/master | DominantColor/Shared/DominantColors.swift | mit | 2 | //
// DominantColors.swift
// DominantColor
//
// Created by Indragie on 12/20/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
#if os(OSX)
import Foundation
#elseif os(iOS)
import UIKit
#endif
// MARK: Bitmaps
private struct RGBAPixel {
let r: UInt8
let g: UInt8
let b: UInt8
let a: UInt8
}
extension RGBAPixel: Hashable {
private var hashValue: Int {
return (((Int(r) << 8) | Int(g)) << 8) | Int(b)
}
}
private func ==(lhs: RGBAPixel, rhs: RGBAPixel) -> Bool {
return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b
}
private func createRGBAContext(width: Int, height: Int) -> CGContext {
return CGBitmapContextCreate(
nil,
width,
height,
8, // bits per component
width * 4, // bytes per row
CGColorSpaceCreateDeviceRGB(),
CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
)
}
// Enumerates over all of the pixels in an RGBA bitmap context
// in the order that they are stored in memory, for faster access.
//
// From: https://www.mikeash.com/pyblog/friday-qa-2012-08-31-obtaining-and-interpreting-image-data.html
private func enumerateRGBAContext(context: CGContext, handler: (Int, Int, RGBAPixel) -> Void) {
let (width, height) = (CGBitmapContextGetWidth(context), CGBitmapContextGetHeight(context))
let data = unsafeBitCast(CGBitmapContextGetData(context), UnsafeMutablePointer<RGBAPixel>.self)
for y in 0..<height {
for x in 0..<width {
handler(x, y, data[Int(x + y * width)])
}
}
}
// MARK: Conversions
private func RGBVectorToCGColor(rgbVector: INVector3) -> CGColor {
return CGColorCreate(CGColorSpaceCreateDeviceRGB(), [CGFloat(rgbVector.x), CGFloat(rgbVector.y), CGFloat(rgbVector.z), 1.0])
}
private extension RGBAPixel {
func toRGBVector() -> INVector3 {
return INVector3(
x: Float(r) / Float(UInt8.max),
y: Float(g) / Float(UInt8.max),
z: Float(b) / Float(UInt8.max)
)
}
}
// MARK: Clustering
extension INVector3 : ClusteredType {}
// MARK: Main
public enum GroupingAccuracy {
case Low // CIE 76 - Euclidian distance
case Medium // CIE 94 - Perceptual non-uniformity corrections
case High // CIE 2000 - Additional corrections for neutral colors, lightness, chroma, and hue
}
struct DefaultParameterValues {
static var maxSampledPixels: Int = 1000
static var accuracy: GroupingAccuracy = .Medium
static var seed: UInt32 = 3571
static var memoizeConversions: Bool = false
}
/**
Computes the dominant colors in an image
:param: image The image
:param: maxSampledPixels Maximum number of pixels to sample in the image. If
the total number of pixels in the image exceeds this
value, it will be downsampled to meet the constraint.
:param: accuracy Level of accuracy to use when grouping similar colors.
Higher accuracy will come with a performance tradeoff.
:param: seed Seed to use when choosing the initial points for grouping
of similar colors. The same seed is guaranteed to return
the same colors every time.
:param: memoizeConversions Whether to memoize conversions from RGB to the LAB color
space (used for grouping similar colors). Memoization
will only yield better performance for large values of
`maxSampledPixels` in images that are primarily comprised
of flat colors. If this information about the image is
not known beforehand, it is best to not memoize.
:returns: A list of dominant colors in the image sorted from most dominant to
least dominant.
*/
public func dominantColorsInImage(
image: CGImage,
maxSampledPixels: Int = DefaultParameterValues.maxSampledPixels,
accuracy: GroupingAccuracy = DefaultParameterValues.accuracy,
seed: UInt32 = DefaultParameterValues.seed,
memoizeConversions: Bool = DefaultParameterValues.memoizeConversions
) -> [CGColor] {
let (width, height) = (CGImageGetWidth(image), CGImageGetHeight(image))
let (scaledWidth, scaledHeight) = scaledDimensionsForPixelLimit(maxSampledPixels, width, height)
// Downsample the image if necessary, so that the total number of
// pixels sampled does not exceed the specified maximum.
let context = createRGBAContext(scaledWidth, scaledHeight)
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: Int(scaledWidth), height: Int(scaledHeight)), image)
// Get the RGB colors from the bitmap context, ignoring any pixels
// that have alpha transparency.
// Also convert the colors to the LAB color space
var labValues = [INVector3]()
labValues.reserveCapacity(Int(scaledWidth * scaledHeight))
let RGBToLAB: RGBAPixel -> INVector3 = {
let f: RGBAPixel -> INVector3 = { IN_RGBToLAB($0.toRGBVector()) }
return memoizeConversions ? memoize(f) : f
}()
enumerateRGBAContext(context) { (_, _, pixel) in
if pixel.a == UInt8.max {
labValues.append(RGBToLAB(pixel))
}
}
// Cluster the colors using the k-means algorithm
let k = selectKForElements(labValues)
var clusters = kmeans(labValues, k, seed, distanceForAccuracy(accuracy))
// Sort the clusters by size in descending order so that the
// most dominant colors come first.
clusters.sort { $0.size > $1.size }
return clusters.map { RGBVectorToCGColor(IN_LABToRGB($0.centroid)) }
}
private func distanceForAccuracy(accuracy: GroupingAccuracy) -> (INVector3, INVector3) -> Float {
switch accuracy {
case .Low:
return CIE76SquaredColorDifference
case .Medium:
return CIE94SquaredColorDifference()
case .High:
return CIE2000SquaredColorDifference()
}
}
// Computes the proportionally scaled dimensions such that the
// total number of pixels does not exceed the specified limit.
private func scaledDimensionsForPixelLimit(limit: Int, width: Int, height: Int) -> (Int, Int) {
if (width * height > limit) {
let ratio = Float(width) / Float(height)
let maxWidth = sqrtf(ratio * Float(limit))
return (Int(maxWidth), Int(Float(limit) / maxWidth))
}
return (width, height)
}
private func selectKForElements<T>(elements: [T]) -> Int {
// Seems like a magic number...
return 16
}
| 13dc168f41ed7ea1f6614246ea75687d | 35.027174 | 128 | 0.658923 | false | false | false | false |
tkremenek/swift | refs/heads/master | test/IRGen/async/class_resilience.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-experimental-concurrency -disable-availability-checking -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class %S/Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-experimental-concurrency -disable-availability-checking -enable-library-evolution %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-cpu %s
// REQUIRES: concurrency
import resilient_class
open class MyBaseClass<T> {
var value: T
open func wait() async -> Int {
return 0
}
open func wait() async -> T {
return value
}
open func waitThrows() async throws -> Int {
return 0
}
open func waitThrows() async throws -> T {
return value
}
// FIXME
// open func waitGeneric<T>(_: T) async -> T
// open func waitGenericThrows<T>(_: T) async throws -> T
public init(_ value: T) {
self.value = value
}
}
// CHECK-LABEL: @"$s16class_resilience11MyBaseClassC4waitxyYaFTjTu" = {{(dllexport )?}}{{(protected )?}}global %swift.async_func_pointer
// CHECK-LABEL: @"$s16class_resilience11MyBaseClassCMn" = {{(dllexport )?}}{{(protected )?}}constant
// CHECK-SAME: %swift.async_func_pointer* @"$s16class_resilience11MyBaseClassC4waitxyYaFTu"
// CHECK-LABEL: @"$s16class_resilience9MyDerivedCMn" = hidden constant
// CHECK-SAME: %swift.async_func_pointer* @"$s16class_resilience9MyDerivedC4waitSiyYaF010resilient_A09BaseClassCADxyYaFTVTu"
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swift{{(tail)?}}cc void @"$s16class_resilience14callsAwaitableyx010resilient_A09BaseClassCyxGYalF"(%swift.opaque* noalias nocapture %0, %swift.context* swiftasync %1{{.*}})
// CHECK: %swift.async_func_pointer* @"$s15resilient_class9BaseClassC4waitxyYaFTjTu"
// CHECK: ret void
public func callsAwaitable<T>(_ c: BaseClass<T>) async -> T {
return await c.wait()
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swift{{(tail)?}}cc void @"$s16class_resilience11MyBaseClassC4waitxyYaFTj"(%swift.opaque* noalias nocapture %0, %swift.context* swiftasync %1, %T16class_resilience11MyBaseClassC* swiftself %2) {{#([0-9]+)}} {
class MyDerived : BaseClass<Int> {
override func wait() async -> Int {
return await super.wait()
}
}
| a19052d0cdd48936b83d46e0a0be92a8 | 39.666667 | 264 | 0.713546 | false | false | false | false |
joalbright/Gameboard | refs/heads/master | Gameboards.playground/Pages/Minesweeper.xcplaygroundpage/Contents.swift | apache-2.0 | 1 | import UIKit
enum MoveType { case Guess, Mark }
var minesweeper = Gameboard(.Minesweeper, testing: true)
// setup colors
var colors = BoardColors()
colors.background = UIColor(red:0.5, green:0.5, blue:0.5, alpha:1)
colors.foreground = UIColor(red:0.6, green:0.6, blue:0.6, alpha:1)
colors.player1 = UIColor.yellowColor()
colors.player2 = UIColor.blackColor()
colors.highlight = UIColor.blueColor()
colors.selected = UIColor.redColor()
minesweeper.boardColors = colors
// collection of guesses
let guesses: [(Square,MoveType)] = [
((4,3),.Guess), // guess
((9,0),.Mark), // mark
((7,4),.Mark), // mark
((4,1),.Mark), // mark
((4,0),.Guess), // guess
((0,9),.Guess), // guess
((2,7),.Mark), // guess
((6,9),.Guess), // guess
((1,0),.Guess), // game over
]
// loop guesses
for guess in guesses {
do {
switch guess.1 {
case .Guess: try minesweeper.guess(toSquare: guess.0)
case .Mark: try minesweeper.mark(toSquare: guess.0)
}
} catch {
print(error)
}
}
minesweeper.visualize(CGRect(x: 0, y: 0, width: 199, height: 199))
| 27df155cfda7bd3d1d179406827c1b19 | 19.389831 | 66 | 0.571904 | false | false | false | false |
alblue/swift | refs/heads/master | test/expr/primary/literal/collection_upcast_opt.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift -dump-ast 2> %t.ast
// RUN: %FileCheck %s < %t.ast
// Verify that upcasts of array literals upcast the individual elements in place
// rather than introducing a collection_upcast_expr.
protocol P { }
struct X : P { }
struct TakesArray<T> {
init(_: [(T) -> Void]) { }
}
// CHECK-LABEL: func_decl{{.*}}"arrayUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: array_expr type='[(X) -> Void]'
// CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x1}}
// CHECK-NEXT: function_conversion_expr implicit type='(X) -> Void'
// CHECK-NEXT: {{declref_expr.*x2}}
func arrayUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesArray<X>([x1, x2])
}
struct TakesDictionary<T> {
init(_: [Int : (T) -> Void]) { }
}
// CHECK-LABEL: func_decl{{.*}}"dictionaryUpcast(_:_:)"
// CHECK: assign_expr
// CHECK-NOT: collection_upcast_expr
// CHECK: paren_expr type='([Int : (X) -> Void])'
// CHECK-NOT: collection_upcast_expr
// CHECK: (dictionary_expr type='[Int : (X) -> Void]'
func dictionaryUpcast(_ x1: @escaping (P) -> Void, _ x2: @escaping (P) -> Void) {
_ = TakesDictionary<X>(([1: x1, 2: x2]))
}
| ae0963d08f1913a58c2819199367bc4c | 31.447368 | 81 | 0.626115 | false | false | false | false |
Jpadilla1/react-native-ios-charts | refs/heads/master | RNiOSCharts/PieRadarChartViewBaseExtension.swift | mit | 1 | //
// PieRadarChartViewBase.swift
// PoliRank
//
// Created by Jose Padilla on 2/8/16.
// Copyright © 2016 Facebook. All rights reserved.
//
import Charts
import SwiftyJSON
extension PieRadarChartViewBase {
func setPieRadarChartViewBaseProps(_ config: String!) {
setChartViewBaseProps(config);
var json: JSON = nil;
if let data = config.data(using: String.Encoding.utf8) {
json = JSON(data: data);
};
if json["rotationEnabled"].exists() {
self.rotationEnabled = json["rotationEnabled"].boolValue;
}
if json["rotationAngle"].exists() {
self.rotationAngle = CGFloat(json["rotationAngle"].floatValue);
}
if json["rotationWithTwoFingers"].exists() {
self.rotationWithTwoFingers = json["rotationWithTwoFingers"].boolValue;
}
if json["minOffset"].exists() {
self.minOffset = CGFloat(json["minOffset"].floatValue);
}
}
}
| de46b7610510b3e355fb1484055beaea | 22.923077 | 77 | 0.652733 | false | true | false | false |
crsmithdev/hint | refs/heads/master | HintLauncher/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// HintLauncher
//
// Created by Christopher Smith on 12/31/16.
// Copyright © 2016 Chris Smith. All rights reserved.
//
import Cocoa
import Foundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let applications = NSWorkspace.shared().runningApplications
let running = applications.filter({$0.bundleIdentifier == "com.crsmithdev.Hint"}).count > 0
if !running {
let launcherPath = Bundle.main.bundlePath as NSString
var components = launcherPath.pathComponents
components.removeLast()
components.removeLast()
components.removeLast()
components.append("MacOS")
components.append("Hint")
let appPath = NSString.path(withComponents: components)
NSWorkspace.shared().launchApplication(appPath)
}
NSApp.terminate(nil)
}
}
| 535d4041450496c484b45d0decaad366 | 28.027778 | 99 | 0.636364 | false | false | false | false |
inamiy/ReactiveCocoaCatalog | refs/heads/master | ReactiveCocoaCatalog/Samples/BadgeManager.swift | mit | 1 | //
// BadgeManager.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-09.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import Foundation
import Result
import ReactiveSwift
/// Singleton class for on-memory badge persistence.
final class BadgeManager
{
// Singleton.
static let badges = BadgeManager()
private var _badges: [MenuId : MutableProperty<Badge>] = [:]
subscript(menuId: MenuId) -> MutableProperty<Badge>
{
if let property = self._badges[menuId] {
return property
}
else {
let property = MutableProperty<Badge>(.none)
self._badges[menuId] = property
return property
}
}
/// - FIXME: This should be created NOT from current `_badges`-dictionary but from combined MutableProperties of badges.
var mergedSignal: Signal<(MenuId, Badge), NoError>
{
let signals = self._badges.map { menuId, property in
return property.signal.map { (menuId, $0) }
}
return Signal.merge(signals)
}
private init() {}
}
// MARK: Badge
enum Badge: RawRepresentable
{
case none
case new // "N" mark
case number(Int)
case string(Swift.String)
var rawValue: Swift.String?
{
switch self {
case .none: return nil
case .new: return "N"
case .number(let int): return int > 999 ? "999+" : int > 0 ? "\(int)" : nil
case .string(let str): return str
}
}
var number: Int?
{
guard case .number(let int) = self else { return nil }
return int
}
init(_ intValue: Int)
{
self = .number(intValue)
}
init(rawValue: Swift.String?)
{
switch rawValue {
case .none, .some("0"), .some(""):
self = .none
case .some("N"):
self = .new
case let .some(str):
self = Int(str).map { .number($0) } ?? .string(str)
}
}
}
| 5cff30114cfdb9a071712ab2e0261504 | 23.05814 | 124 | 0.545191 | false | false | false | false |
RMizin/PigeonMessenger-project | refs/heads/main | FalconMessenger/ChatsControllers/InputContainerView.swift | gpl-3.0 | 1 | //
// InputContainerView.swift
// Avalon-print
//
// Created by Roman Mizin on 3/25/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import AVFoundation
final class InputContainerView: UIControl {
var audioPlayer: AVAudioPlayer!
weak var mediaPickerController: MediaPickerControllerNew?
weak var trayDelegate: ImagePickerTrayControllerDelegate?
var attachedMedia = [MediaObject]()
fileprivate var tap = UITapGestureRecognizer()
static let commentOrSendPlaceholder = "Comment or Send"
static let messagePlaceholder = "Message"
weak var chatLogController: ChatLogViewController? {
didSet {
sendButton.addTarget(chatLogController, action: #selector(ChatLogViewController.sendMessage), for: .touchUpInside)
}
}
lazy var inputTextView: InputTextView = {
let textView = InputTextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.delegate = self
return textView
}()
lazy var attachCollectionView: AttachCollectionView = {
let attachCollectionView = AttachCollectionView()
return attachCollectionView
}()
let placeholderLabel: UILabel = {
let placeholderLabel = UILabel()
placeholderLabel.text = messagePlaceholder
placeholderLabel.sizeToFit()
placeholderLabel.textColor = ThemeManager.currentTheme().generalSubtitleColor
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
return placeholderLabel
}()
var attachButton: MediaPickerRespondingButton = {
var attachButton = MediaPickerRespondingButton()
attachButton.addTarget(self, action: #selector(togglePhoto), for: .touchDown)
return attachButton
}()
var recordVoiceButton: VoiceRecorderRespondingButton = {
var recordVoiceButton = VoiceRecorderRespondingButton()
recordVoiceButton.addTarget(self, action: #selector(toggleVoiceRecording), for: .touchDown)
return recordVoiceButton
}()
let sendButton: UIButton = {
let sendButton = UIButton(type: .custom)
sendButton.setImage(UIImage(named: "send"), for: .normal)
sendButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.isEnabled = false
sendButton.backgroundColor = .white
return sendButton
}()
private var heightConstraint: NSLayoutConstraint!
private func addHeightConstraints() {
heightConstraint = heightAnchor.constraint(equalToConstant: InputTextViewLayout.minHeight)
heightConstraint.isActive = true
}
func confirugeHeightConstraint() {
let size = inputTextView.sizeThatFits(CGSize(width: inputTextView.bounds.size.width, height: .infinity))
let height = size.height + 12
heightConstraint.constant = height < InputTextViewLayout.maxHeight() ? height : InputTextViewLayout.maxHeight()
let maxHeight: CGFloat = InputTextViewLayout.maxHeight()
guard height >= maxHeight else { inputTextView.isScrollEnabled = false; return }
inputTextView.isScrollEnabled = true
}
func handleRotation() {
attachCollectionView.collectionViewLayout.invalidateLayout()
DispatchQueue.main.async { [weak self] in
guard let width = self?.inputTextView.frame.width else { return }
self?.attachCollectionView.frame.size.width = width//self?.inputTextView.frame.width
self?.attachCollectionView.reloadData()
self?.confirugeHeightConstraint()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
NotificationCenter.default.addObserver(self, selector: #selector(changeTheme),
name: .themeUpdated, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inputViewResigned),
name: .inputViewResigned, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(inputViewResponded),
name: .inputViewResponded, object: nil)
addHeightConstraints()
backgroundColor = ThemeManager.currentTheme().barBackgroundColor
// sendButton.tintColor = ThemeManager.generalTintColor
addSubview(attachButton)
addSubview(recordVoiceButton)
addSubview(inputTextView)
addSubview(sendButton)
addSubview(placeholderLabel)
inputTextView.addSubview(attachCollectionView)
sendButton.layer.cornerRadius = 15
sendButton.clipsToBounds = true
tap = UITapGestureRecognizer(target: self, action: #selector(toggleTextView))
tap.delegate = self
if #available(iOS 11.0, *) {
attachButton.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 5).isActive = true
inputTextView.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true
} else {
attachButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
inputTextView.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true
}
attachButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
attachButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
attachButton.widthAnchor.constraint(equalToConstant: 35).isActive = true
recordVoiceButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
recordVoiceButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
recordVoiceButton.widthAnchor.constraint(equalToConstant: 35).isActive = true
recordVoiceButton.leftAnchor.constraint(equalTo: attachButton.rightAnchor, constant: 0).isActive = true
inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true
inputTextView.leftAnchor.constraint(equalTo: recordVoiceButton.rightAnchor, constant: 3).isActive = true
inputTextView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6).isActive = true
placeholderLabel.font = UIFont.systemFont(ofSize: (inputTextView.font!.pointSize))
placeholderLabel.isHidden = !inputTextView.text.isEmpty
placeholderLabel.leftAnchor.constraint(equalTo: inputTextView.leftAnchor, constant: 12).isActive = true
placeholderLabel.rightAnchor.constraint(equalTo: inputTextView.rightAnchor).isActive = true
placeholderLabel.topAnchor.constraint(equalTo: attachCollectionView.bottomAnchor,
constant: inputTextView.font!.pointSize / 2.3).isActive = true
placeholderLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
sendButton.rightAnchor.constraint(equalTo: inputTextView.rightAnchor, constant: -4).isActive = true
sendButton.bottomAnchor.constraint(equalTo: inputTextView.bottomAnchor, constant: -4).isActive = true
sendButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
sendButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
configureAttachCollectionView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func changeTheme() {
backgroundColor = ThemeManager.currentTheme().barBackgroundColor
inputTextView.changeTheme()
attachButton.changeTheme()
recordVoiceButton.changeTheme()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
@objc func toggleTextView () {
print("toggling")
inputTextView.inputView = nil
inputTextView.reloadInputViews()
UIView.performWithoutAnimation {
inputTextView.resignFirstResponder()
inputTextView.becomeFirstResponder()
}
}
@objc fileprivate func inputViewResigned() {
inputTextView.removeGestureRecognizer(tap)
}
@objc fileprivate func inputViewResponded() {
guard let recognizers = inputTextView.gestureRecognizers else { return }
guard !recognizers.contains(tap) else { return }
inputTextView.addGestureRecognizer(tap)
}
@objc func togglePhoto () {
checkAuthorisationStatus()
UIView.performWithoutAnimation {
_ = recordVoiceButton.resignFirstResponder()
}
if attachButton.isFirstResponder {
_ = attachButton.resignFirstResponder()
} else {
if attachButton.controller == nil {
attachButton.controller = MediaPickerControllerNew()
mediaPickerController = attachButton.controller
mediaPickerController?.mediaPickerDelegate = self
}
_ = attachButton.becomeFirstResponder()
// inputTextView.addGestureRecognizer(tap)
}
}
@objc func toggleVoiceRecording () {
UIView.performWithoutAnimation {
_ = attachButton.resignFirstResponder()
}
if recordVoiceButton.isFirstResponder {
_ = recordVoiceButton.resignFirstResponder()
} else {
if recordVoiceButton.controller == nil {
recordVoiceButton.controller = VoiceRecordingViewController()
recordVoiceButton.controller?.mediaPickerDelegate = self
}
_ = recordVoiceButton.becomeFirstResponder()
// inputTextView.addGestureRecognizer(tap)
}
}
func resignAllResponders() {
inputTextView.resignFirstResponder()
_ = attachButton.resignFirstResponder()
_ = recordVoiceButton.resignFirstResponder()
}
}
extension InputContainerView {
func prepareForSend() {
inputTextView.text = ""
sendButton.isEnabled = false
placeholderLabel.isHidden = false
inputTextView.isScrollEnabled = false
attachedMedia.removeAll()
attachCollectionView.reloadData()
resetChatInputConntainerViewSettings()
}
func resetChatInputConntainerViewSettings() {
guard attachedMedia.isEmpty else { return }
attachCollectionView.frame = CGRect(x: 0, y: 0, width: inputTextView.frame.width, height: 0)
inputTextView.textContainerInset = InputTextViewLayout.defaultInsets
placeholderLabel.text = InputContainerView.messagePlaceholder
sendButton.isEnabled = !inputTextView.text.isEmpty
confirugeHeightConstraint()
}
func expandCollection() {
sendButton.isEnabled = (!inputTextView.text.isEmpty || !attachedMedia.isEmpty)
placeholderLabel.text = InputContainerView.commentOrSendPlaceholder
attachCollectionView.frame = CGRect(x: 0, y: 3,
width: inputTextView.frame.width, height: AttachCollectionView.height)
inputTextView.textContainerInset = InputTextViewLayout.extendedInsets
confirugeHeightConstraint()
}
}
extension InputContainerView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard attachCollectionView.bounds.contains(touch.location(in: attachCollectionView)) else { return true }
return false
}
}
extension InputContainerView: UITextViewDelegate {
private func handleSendButtonState() {
let whiteSpaceIsEmpty = inputTextView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty
if (attachedMedia.count > 0 && !whiteSpaceIsEmpty) || (inputTextView.text != "" && !whiteSpaceIsEmpty) {
sendButton.isEnabled = true
} else {
sendButton.isEnabled = false
}
}
func textViewDidChange(_ textView: UITextView) {
confirugeHeightConstraint()
placeholderLabel.isHidden = !textView.text.isEmpty
chatLogController?.isTyping = !textView.text.isEmpty
handleSendButtonState()
}
func textViewDidEndEditing(_ textView: UITextView) {
if chatLogController?.chatLogAudioPlayer != nil {
chatLogController?.chatLogAudioPlayer.stop()
chatLogController?.chatLogAudioPlayer = nil
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text == "\n", let chatLogController = self.chatLogController else { return true }
if chatLogController.isScrollViewAtTheBottom() {
chatLogController.collectionView.scrollToBottom(animated: false)
}
return true
}
}
| 9b53abe0b1b07909fd066557aaed5a11 | 36.548287 | 155 | 0.743466 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Toolbox/Colleague/Composing/Controller/ColleagueComposeViewController.swift | mit | 2 | //
// ColleagueComposeViewController.swift
// DereGuide
//
// Created by zzk on 2017/8/2.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import CoreData
import EasyTipView
import AudioToolbox
protocol ColleagueComposeViewControllerDelegate: class {
func didPost(_ colleagueComposeViewController: ColleagueComposeViewController)
func didSave(_ colleagueComposeViewController: ColleagueComposeViewController)
func didRevoke(_ colleagueComposeViewController: ColleagueComposeViewController)
}
class ColleagueComposeViewController: BaseTableViewController {
weak var delegate: ColleagueComposeViewControllerDelegate?
var remote: ProfileRemote = ProfileRemote()
lazy var context: NSManagedObjectContext = self.parentContext.newChildContext()
fileprivate var parentContext: NSManagedObjectContext {
return CoreDataStack.default.viewContext
}
lazy var cardSelectionViewController: UnitCardSelectTableViewController = {
let vc = UnitCardSelectTableViewController()
vc.delegate = self
return vc
}()
fileprivate var cells = [UITableViewCell]()
var lastSelectedMyCenterItem: MyCenterItemView?
var lastSelectedCenterWantedItem: CenterWantedItemView?
fileprivate var profile: Profile!
fileprivate struct Row: CustomStringConvertible {
var type: UITableViewCell.Type
var description: String {
return type.description()
}
var title: String
}
fileprivate var rows: [Row] = [
Row(type: ColleagueInputCell.self, title: NSLocalizedString("游戏ID", comment: "")),
Row(type: ColleagueInputCell.self, title: NSLocalizedString("昵称", comment: "")),
Row(type: ColleagueMyCentersCell.self, title: NSLocalizedString("我的队长", comment: "")),
// Row(type: ColleagueCentersWantedCell.self, title: NSLocalizedString("希望征集的队长", comment: "")),
Row(type: ColleagueMessageCell.self, title: NSLocalizedString("留言", comment: "")),
Row(type: ColleagueButtonsCell.self, title: "")
]
var postItem: UIBarButtonItem!
var indicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
prepareStaticCells()
setupStaticCells()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.allowsSelection = false
tableView.tableFooterView = UIView(frame: .zero)
navigationItem.title = NSLocalizedString("我的信息", comment: "")
postItem = UIBarButtonItem(title: NSLocalizedString("发布", comment: ""), style: .done, target: self, action: #selector(postAction))
navigationItem.rightBarButtonItem = postItem
if UIDevice.current.userInterfaceIdiom == .pad {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAction))
}
indicator = UIActivityIndicatorView(style: .white)
indicator.color = .parade
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if UserDefaults.standard.firstTimeComposingMyProfile {
showTip1((cells[2] as! ColleagueMyCentersCell).infoButton)
showTip2()
UserDefaults.standard.firstTimeComposingMyProfile = false
}
}
var tip1: EasyTipView?
var tip2: EasyTipView?
var maskView: UIView?
private func showMaskView() {
if maskView == nil {
maskView = UIView()
}
navigationController?.view.addSubview(maskView!)
maskView?.snp.remakeConstraints { (make) in
make.edges.equalToSuperview()
}
maskView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hideHelpTips)))
}
@objc func showTip1(_ button: UIButton) {
if tip1 == nil {
var preferences = EasyTipView.Preferences()
preferences.drawing.font = UIFont.boldSystemFont(ofSize: 14)
preferences.drawing.foregroundColor = .white
preferences.drawing.backgroundColor = .cute
tip1 = EasyTipView(text: NSLocalizedString("双击从全部卡片中选择,长按编辑潜能或者移除偶像,我的队长中至少要填一个位置才能发布", comment: ""), preferences: preferences, delegate: nil)
}
if maskView?.superview == nil {
showMaskView()
}
tip1?.show(forView: button)
}
@objc func showTip2() {
if tip2 == nil {
var preferences = EasyTipView.Preferences()
preferences.drawing.font = UIFont.boldSystemFont(ofSize: 14)
preferences.drawing.foregroundColor = .white
preferences.drawing.backgroundColor = .cool
tip2 = EasyTipView(text: NSLocalizedString("向所有用户公开您的信息,重复发布会自动覆盖之前的内容并刷新更新时间", comment: ""), preferences: preferences, delegate: nil)
}
if maskView?.superview == nil {
showMaskView()
}
tip2?.show(forItem: navigationItem.rightBarButtonItem!)
}
@objc func hideHelpTips() {
tip1?.dismiss()
tip2?.dismiss()
maskView?.removeFromSuperview()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
hideHelpTips()
context.saveOrRollback()
}
// @objc func resetAction() {
// profile.reset()
// setupStaticCells()
// }
@objc func postAction() {
guard validateInput() else { return }
saveProfileFromInput()
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicator)
indicator.startAnimating()
if let _ = profile.remoteIdentifier {
remote.modify([profile], modification: { (records, commit) in
self.context.perform {
if let record = records.first {
let localRecord = self.profile.toCKRecord()
localRecord.allKeys().forEach {
record[$0] = localRecord[$0]
}
// call commit to modify remote record, only when remote has the record.
commit()
} else {
// there is no matched record in remote, upload again
self.upload()
}
}
}, completion: { (remoteProfiles, error) in
self.postDidCompleted(error, remoteProfiles)
})
} else {
upload()
}
}
fileprivate func dismissOrPop() {
if UIDevice.current.userInterfaceIdiom == .pad {
dismiss(animated: true, completion: nil)
} else {
navigationController?.popViewController(animated: true)
}
}
@objc func cancelAction() {
dismiss(animated: true, completion: nil)
}
func setup(parentProfile: Profile) {
self.profile = context.object(with: parentProfile.objectID) as? Profile
}
fileprivate func validateInput() -> Bool {
guard let _ = (cells[0] as! ColleagueInputCell).input.text?.match(pattern: "^[0-9]{9}$").first else {
UIAlertController.showHintMessage(NSLocalizedString("您输入的游戏ID不合法", comment: ""), in: self)
return false
}
guard let count = (cells[1] as! ColleagueInputCell).input.text?.count, count <= 10 else {
UIAlertController.showHintMessage(NSLocalizedString("昵称不能超过10个文字", comment: ""), in: self)
return false
}
guard (cells[2] as! ColleagueMyCentersCell).centers.contains(where: { $0.0 != 0 }) else {
UIAlertController.showHintMessage(NSLocalizedString("至少添加一名自己的队长", comment: ""), in: self)
return false
}
return true
}
fileprivate func postDidCompleted(_ error: RemoteError?, _ remoteProfiles: [ProfileRemote.R]) {
context.perform {
self.indicator.stopAnimating()
self.navigationItem.rightBarButtonItem = self.postItem
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("发布失败,请确保iCloud已登录并且网络状态正常", comment: ""), in: self)
} else {
self.profile.remoteIdentifier = remoteProfiles.first?.id
self.profile.creatorID = remoteProfiles.first?.creatorID
self.context.saveOrRollback()
self.parentContext.saveOrRollback()
UIAlertController.showHintMessage(NSLocalizedString("发布成功", comment: ""), in: self) {
self.dismissOrPop()
self.delegate?.didPost(self)
}
}
}
}
fileprivate func upload() {
remote.upload([profile], completion: { (remoteProfiles, error) in
self.postDidCompleted(error, remoteProfiles)
})
}
fileprivate func saveProfileFromInput() {
profile.nickName = (cells[1] as! ColleagueInputCell).input.text ?? ""
profile.gameID = (cells[0] as! ColleagueInputCell).input.text ?? ""
profile.myCenters = (cells[2] as! ColleagueMyCentersCell).centers
// profile.centersWanted = (cells[3] as! ColleagueCentersWantedCell).centers
profile.message = (cells[3] as! ColleagueMessageCell).messageView.text.trimmingCharacters(in: ["\n", " "])
context.saveOrRollback()
parentContext.saveOrRollback()
}
private func prepareStaticCells() {
for index in 0..<rows.count {
let row = rows[index]
let cell = row.type.init()
cells.append(cell)
(cell as? ColleagueBaseCell)?.setTitle(row.title)
switch cell {
case let cell as ColleagueInputCell where index == 0:
cell.checkPattern = "^[0-9]{9}$"
case let cell as ColleagueInputCell where index == 1:
cell.checkPattern = "^.{0,10}$"
case let cell as ColleagueMyCentersCell:
cell.delegate = self
cell.infoButton.addTarget(self, action: #selector(showTip1(_:)), for: .touchUpInside)
// case let cell as ColleagueCentersWantedCell:
// cell.delegate = self
// cell.infoButton.addTarget(self, action: #selector(showTip2(_:)), for: .touchUpInside)
case let cell as ColleagueButtonsCell:
cell.delegate = self
default:
break
}
}
}
private func setupStaticCells() {
for index in 0..<rows.count {
let cell = cells[index]
switch index {
case 0:
(cell as! ColleagueInputCell).setup(with: profile.gameID, keyboardType: .numberPad)
case 1:
(cell as! ColleagueInputCell).setup(with: profile.nickName, keyboardType: .default)
case 2:
(cell as! ColleagueMyCentersCell).setup(profile)
// case 3:
// (cell as! ColleagueCentersWantedCell).setup(profile)
case 3:
(cell as! ColleagueMessageCell).setup(with: profile.message ?? "")
default:
break
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cells[indexPath.row]
}
}
extension ColleagueComposeViewController: CenterWantedGroupViewDelegate {
func centerWantedGroupView(_ centerWantedGroupView: CenterWantedGroupView, didDoubleTap item: CenterWantedItemView) {
lastSelectedCenterWantedItem = item
lastSelectedMyCenterItem = nil
navigationController?.pushViewController(cardSelectionViewController, animated: true)
}
func centerWantedGroupView(_ centerWantedGroupView: CenterWantedGroupView, didLongPressAt item: CenterWantedItemView) {
guard let id = item.cardID, let card = CGSSDAO.shared.findCardById(id) else {
return
}
let vc = CenterWantedEditingViewController()
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 240, height: 140)
vc.delegate = self
lastSelectedCenterWantedItem = item
vc.setupWith(card: card, minLevel: item.minLevel)
let pc = vc.popoverPresentationController
pc?.delegate = self
pc?.sourceView = item
pc?.sourceRect = CGRect(x: item.fwidth / 2, y: item.fheight / 2, width: 0, height: 0)
present(vc, animated: true, completion: nil)
// play sound like peek(3d touch)
AudioServicesPlaySystemSound(1519)
}
}
extension ColleagueComposeViewController: MyCenterGroupViewDelegate {
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didLongPressAt item: MyCenterItemView) {
guard let id = item.cardID, let card = CGSSDAO.shared.findCardById(id) else {
return
}
let vc = MyCenterEditingViewController()
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 240, height: 290)
vc.delegate = self
lastSelectedMyCenterItem = item
vc.setupWith(card: card, potential: item.potential)
let pc = vc.popoverPresentationController
pc?.delegate = self
pc?.sourceView = item
pc?.sourceRect = CGRect(x: item.fwidth / 2, y: item.fheight / 2, width: 0, height: 0)
present(vc, animated: true, completion: nil)
// play sound like peek(3d touch)
AudioServicesPlaySystemSound(1519)
}
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didDoubleTap item: MyCenterItemView) {
lastSelectedMyCenterItem = item
lastSelectedCenterWantedItem = nil
navigationController?.pushViewController(cardSelectionViewController, animated: true)
}
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didTap item: MyCenterItemView) {
}
}
extension ColleagueComposeViewController: MyCenterEditingViewControllerDelegate {
func didDelete(myCenterEditingViewController: MyCenterEditingViewController) {
lastSelectedMyCenterItem?.setupWith(cardID: 0)
}
}
extension ColleagueComposeViewController: CenterWantedEditingViewControllerDelegate {
func didDelete(centerWantedEditingViewController: CenterWantedEditingViewController) {
lastSelectedCenterWantedItem?.setupWith(cardID: 0)
}
}
extension ColleagueComposeViewController: BaseCardTableViewControllerDelegate {
func selectCard(_ card: CGSSCard) {
lastSelectedCenterWantedItem?.setupWith(cardID: card.id, minLevel: 0)
lastSelectedMyCenterItem?.setupWith(cardID: card.id, potential: .zero)
}
}
extension ColleagueComposeViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
if let vc = popoverPresentationController.presentedViewController as? MyCenterEditingViewController {
if let view = popoverPresentationController.sourceView as? MyCenterItemView {
view.setupWith(cardID: view.cardID, potential: vc.potential)
}
} else if let vc = popoverPresentationController.presentedViewController as? CenterWantedEditingViewController {
if let view = popoverPresentationController.sourceView as? CenterWantedItemView {
view.setupWith(cardID: view.cardID, minLevel: vc.editingView.minLevel)
}
}
}
}
extension ColleagueComposeViewController: ColleaColleagueButtonsCellDelegate {
func didSave(_ colleagueButtonsCell: ColleagueButtonsCell) {
saveProfileFromInput()
dismissOrPop()
delegate?.didSave(self)
}
func didRevoke(_ colleagueButtonsCell: ColleagueButtonsCell) {
colleagueButtonsCell.setRevoking(true)
remote.removeAll { (remoteIdentifiers, errors) in
DispatchQueue.main.async {
colleagueButtonsCell.setRevoking(false)
if errors.count > 0 {
UIAlertController.showHintMessage(NSLocalizedString("撤销失败,请确保iCloud已登录并且网络状态正常", comment: ""), in: self)
} else {
UIAlertController.showHintMessage(NSLocalizedString("撤销成功", comment: ""), in: self)
self.delegate?.didRevoke(self)
}
}
}
}
}
| 1539eb9fee72c6cae116084850e14214 | 37.421875 | 154 | 0.634637 | false | false | false | false |
rockbruno/swiftshield | refs/heads/master | Tests/SwiftShieldTests/FeatureTestUtils.swift | gpl-3.0 | 1 | import Foundation
@testable import SwiftShieldCore
var modifiableFilePath: String {
path(forResource: "FeatureTestProject/FeatureTestProject/File.swift").relativePath
}
func modifiableFileContents() throws -> String {
try File(path: modifiableFilePath).read()
}
var modifiablePlistPath: String {
path(forResource: "FeatureTestProject/FeatureTestProject/CustomPlist.plist").relativePath
}
func modifiablePlistContents() throws -> String {
try File(path: modifiablePlistPath).read()
}
func testModule(
withContents contents: String = "",
withPlist plistContents: String =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>
"""
) throws -> Module {
let projectPath = path(forResource: "FeatureTestProject/FeatureTestProject.xcodeproj").relativePath
let projectFile = File(path: projectPath)
let provider = SchemeInfoProvider(
projectFile: projectFile,
schemeName: "FeatureTestProject",
taskRunner: TaskRunner(),
logger: DummyLogger(),
modulesToIgnore: []
)
try File(path: modifiableFilePath).write(contents: contents)
try File(path: modifiablePlistPath).write(contents: plistContents)
return try provider.getModulesFromProject().first!
}
func baseTestData(ignorePublic: Bool = false,
namesToIgnore: Set<String> = []) -> (SourceKitObfuscator, SourceKitObfuscatorDataStore, ObfuscatorDelegateSpy) {
let logger = Logger()
let sourceKit = SourceKit(logger: logger)
let dataStore = SourceKitObfuscatorDataStore()
let obfuscator = SourceKitObfuscator(
sourceKit: sourceKit,
logger: logger,
dataStore: dataStore,
namesToIgnore: namesToIgnore,
ignorePublic: ignorePublic
)
let delegateSpy = ObfuscatorDelegateSpy()
obfuscator.delegate = delegateSpy
return (obfuscator, dataStore, delegateSpy)
}
| f41eee9c12a7ee248ed4c6316584e412 | 32 | 130 | 0.693122 | false | true | false | false |
delannoyk/SoundcloudSDK | refs/heads/master | sources/SoundcloudSDK/model/APIResponse.swift | mit | 1 | //
// APIResponse.swift
// Soundcloud
//
// Created by Kevin DELANNOY on 21/10/15.
// Copyright © 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
public protocol APIResponse {
associatedtype U
var response: Result<U, SoundcloudError> { get }
}
public struct SimpleAPIResponse<T>: APIResponse {
public typealias U = T
public let response: Result<T, SoundcloudError>
// MARK: Initialization
init(result: Result<T, SoundcloudError>) {
response = result
}
init(error: SoundcloudError) {
response = .failure(error)
}
init(value: T) {
response = .success(value)
}
}
public struct PaginatedAPIResponse<T>: APIResponse {
public typealias U = [T]
public let response: Result<[T], SoundcloudError>
private let nextPageURL: URL?
private let parse: (JSONObject) -> Result<[T], SoundcloudError>
// MARK: Initialization
init(response: Result<[T], SoundcloudError>,
nextPageURL: URL?,
parse: @escaping (JSONObject) -> Result<[T], SoundcloudError>) {
self.response = response
self.nextPageURL = nextPageURL
self.parse = parse
}
// MARK: Next page
public var hasNextPage: Bool {
return (nextPageURL != nil)
}
@discardableResult
public func fetchNextPage(completion: @escaping (PaginatedAPIResponse<T>) -> Void) -> CancelableOperation? {
if let nextPageURL = nextPageURL {
let request = Request(
url: nextPageURL,
method: .get,
parameters: nil,
headers: SoundcloudClient.accessToken.map { ["Authorization": "OAuth \($0)" ] },
parse: { JSON -> Result<PaginatedAPIResponse, SoundcloudError> in
return .success(PaginatedAPIResponse(JSON: JSON, parse: self.parse))
}) { result in
completion(result.recover { PaginatedAPIResponse(error: $0) })
}
request.start()
return request
}
return nil
}
}
| bf93ea6da64ad0fa147815a60c23589d | 26.077922 | 112 | 0.604317 | false | false | false | false |
AliSoftware/SwiftGen | refs/heads/develop | Tests/SwiftGenKitTests/ColorsTests.swift | mit | 1 | //
// SwiftGenKit UnitTests
// Copyright © 2020 SwiftGen
// MIT Licence
//
import PathKit
@testable import SwiftGenKit
import TestUtils
import XCTest
private final class TestFileParser1: ColorsFileTypeParser {
init(options: ParserOptionValues) {}
static let extensions = ["test1"]
func parseFile(at path: Path) throws -> Colors.Palette {
Colors.Palette(name: "test1", colors: [:])
}
}
private final class TestFileParser2: ColorsFileTypeParser {
init(options: ParserOptionValues) {}
static let extensions = ["test2"]
func parseFile(at path: Path) throws -> Colors.Palette {
Colors.Palette(name: "test2", colors: [:])
}
}
private final class TestFileParser3: ColorsFileTypeParser {
init(options: ParserOptionValues) {}
static let extensions = ["test1"]
func parseFile(at path: Path) throws -> Colors.Palette {
Colors.Palette(name: "test3", colors: [:])
}
}
final class ColorParserTests: XCTestCase {
func testEmpty() throws {
let parser = try Colors.Parser()
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "empty", sub: .colors)
}
// MARK: - Dispatch
func testDispatchKnowExtension() throws {
let parser = try Colors.Parser()
parser.register(parser: TestFileParser1.self)
parser.register(parser: TestFileParser2.self)
let filter = try Filter(pattern: ".*\\.(test1|test2)$")
try parser.searchAndParse(path: "someFile.test1", filter: filter)
XCTAssertEqual(parser.palettes.first?.name, "test1")
}
func testDispatchUnknownExtension() throws {
let parser = try Colors.Parser()
parser.register(parser: TestFileParser1.self)
parser.register(parser: TestFileParser2.self)
do {
let filter = try Filter(pattern: ".*\\.unknown$")
try parser.searchAndParse(path: "someFile.unknown", filter: filter)
XCTFail("Code did succeed while it was expected to fail for unknown extension")
} catch Colors.ParserError.unsupportedFileType {
// That's the expected exception we want to happen
} catch let error {
XCTFail("Unexpected error occured while parsing: \(error)")
}
}
func testDuplicateExtensionWarning() throws {
var warned = false
let parser = try Colors.Parser()
parser.warningHandler = { _, _, _ in
warned = true
}
parser.register(parser: TestFileParser1.self)
XCTAssert(!warned, "No warning should have been triggered")
parser.register(parser: TestFileParser3.self)
XCTAssert(warned, "Warning should have been triggered for duplicate extension")
}
// MARK: - Multiple palettes
func testParseMultipleFiles() throws {
let parser = try Colors.Parser()
try parser.searchAndParse(path: Fixtures.resource(for: "colors.clr", sub: .colors))
try parser.searchAndParse(path: Fixtures.resource(for: "extra.txt", sub: .colors))
let result = parser.stencilContext()
XCTDiffContexts(result, expected: "multiple", sub: .colors)
}
// MARK: - String parsing
func testStringNoPrefix() throws {
let color = try Colors.parse(hex: "FFFFFF", path: #file)
XCTAssertEqual(color, 0xFFFFFFFF)
}
func testStringWithHash() throws {
let color = try Colors.parse(hex: "#FFFFFF", path: #file)
XCTAssertEqual(color, 0xFFFFFFFF)
}
func testStringWith0x() throws {
let color = try Colors.parse(hex: "0xFFFFFF", path: #file)
XCTAssertEqual(color, 0xFFFFFFFF)
}
func testStringWithAlpha() throws {
let color = try Colors.parse(hex: "FFFFFFCC", path: #file)
XCTAssertEqual(color, 0xFFFFFFCC)
}
func testStringWithAlphaArgb() throws {
let color = try Colors.parse(hex: "CCFFFFFF", path: #file, format: .argb)
XCTAssertEqual(color, 0xFFFFFFCC)
}
// MARK: - Hex Value
func testHexValues() {
let colors: [NSColor: UInt32] = [
NSColor(red: 0, green: 0, blue: 0, alpha: 0): 0x00000000,
NSColor(red: 1, green: 1, blue: 1, alpha: 1): 0xFFFFFFFF,
NSColor(red: 0.973, green: 0.973, blue: 0.973, alpha: 1): 0xF8F8F8FF,
NSColor(red: 0.969, green: 0.969, blue: 0.969, alpha: 1): 0xF7F7F7FF
]
for (color, value) in colors {
XCTAssertEqual(color.hexValue, value)
}
}
// MARK: - Custom options
func testUnknownOption() throws {
do {
_ = try Colors.Parser(options: ["SomeOptionThatDoesntExist": "foo"])
XCTFail("Parser successfully created with an invalid option")
} catch ParserOptionList.Error.unknownOption(let key, _) {
// That's the expected exception we want to happen
XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)")
} catch let error {
XCTFail("Unexpected error occured: \(error)")
}
}
}
| 1929b76ea941678460b0c36d7a79dcb4 | 29.907895 | 93 | 0.684972 | false | true | false | false |
Majki92/SwiftEmu | refs/heads/master | SwiftBoy/GameBoyJoypad.swift | gpl-2.0 | 2 | //
// GameBoyJoypad.swift
// SwiftBoy
//
// Created by Michal Majczak on 27.09.2015.
// Copyright © 2015 Michal Majczak. All rights reserved.
//
import Foundation
class GameBoyJoypad {
static let BTN_UP: UInt8 = 0x40
static let BTN_DOWN: UInt8 = 0x80
static let BTN_LEFT: UInt8 = 0x20
static let BTN_RIGHT: UInt8 = 0x10
static let BTN_A: UInt8 = 0x01
static let BTN_B: UInt8 = 0x02
static let BTN_START: UInt8 = 0x08
static let BTN_SELECT: UInt8 = 0x04
var state: UInt8
var memory: GameBoyRAM?
init() {
state = 0xFF
}
func registerRAM(_ ram: GameBoyRAM) {
memory = ram
}
func getKeyValue(_ mask: UInt8) -> UInt8 {
switch mask & 0x30 {
case 0x10:
return 0xD0 | (state & 0x0F)
case 0x20:
return 0xE0 | ((state >> 4) & 0x0F)
default:
return 0xFF
}
}
func pressButton(_ flag: UInt8) {
if(state & flag != 0) {
state &= ~flag
memory?.requestInterrupt(GameBoyRAM.I_P10P13)
}
}
func releaseButton(_ flag: UInt8) {
state |= flag
}
}
| 28fa9cd61f135f11e41fefdecb3e3f97 | 20.636364 | 57 | 0.543697 | false | false | false | false |
mogstad/Delta | refs/heads/master | tests/processor_spec.swift | mit | 1 | import Foundation
import Quick
import Nimble
@testable import Delta
struct Model: DeltaItem, Equatable {
var identifier: Int
var count: Int
var deltaIdentifier: Int { return self.identifier }
init(identifier: Int, count: Int = 0) {
self.identifier = identifier
self.count = count
}
}
func ==(lhs: Model, rhs: Model) -> Bool {
return lhs.identifier == rhs.identifier && lhs.count == rhs.count
}
class DeltaProcessorSpec: QuickSpec {
override func spec() {
describe("changes(from, to)") {
var records: [DeltaChange]!
describe("Adding nodes") {
beforeEach {
let from = [Model(identifier: 1)]
let to = [Model(identifier: 1), Model(identifier: 2)]
records = self.records(from, to: to)
expect(records.count).to(equal(1))
}
it("creates “add” record") {
let record = DeltaChange.add(index: 1)
expect(records[0]).to(equal(record))
}
}
describe("Removing nodes") {
beforeEach {
let from = [Model(identifier: 1), Model(identifier: 2)]
let to = [Model(identifier: 1)]
records = self.records(from, to: to)
expect(records.count).to(equal(1))
}
it("creates “remove” record") {
let record = DeltaChange.remove(index: 1)
expect(records[0]).to(equal(record))
}
}
describe("Changing nodes") {
beforeEach {
let from = [Model(identifier: 1, count: 10)]
let to = [Model(identifier: 1, count: 5)]
records = self.records(from, to: to)
expect(records.count).to(equal(1))
}
it("creates “change” record") {
let record = DeltaChange.change(index: 0, from: 0)
expect(records[0]).to(equal(record))
}
}
describe("Changing a node and removing a node") {
beforeEach {
let from = [
Model(identifier: 0),
Model(identifier: 1, count: 10)
]
let to = [
Model(identifier: 1, count: 5)
]
records = self.records(from, to: to)
expect(records.count).to(equal(2))
}
it("creates “remove” record") {
let record = DeltaChange.remove(index: 0)
expect(records[0]).to(equal(record))
}
it("creates “change” record") {
let record = DeltaChange.change(index: 0, from: 1)
expect(records[1]).to(equal(record))
}
}
describe("Removing and adding") {
beforeEach {
let from = [Model(identifier: 16) ,Model(identifier: 64), Model(identifier: 32)]
let to = [Model(identifier: 16), Model(identifier: 256), Model(identifier: 32)]
records = self.records(from, to: to)
expect(records.count).to(equal(2))
}
it("creates “remove” record") {
let record = DeltaChange.remove(index: 1)
expect(records[0]).to(equal(record))
}
it("creates “add” record") {
let record = DeltaChange.add(index: 1)
expect(records[1]).to(equal(record))
}
}
describe("Moving a record in a set") {
beforeEach {
let from = [Model(identifier: 1), Model(identifier: 3), Model(identifier: 2)]
let to = [Model(identifier: 1), Model(identifier: 2), Model(identifier: 3)]
records = self.records(from, to: to)
expect(records.count).to(equal(1))
}
it("creates “move” record") {
let record = DeltaChange.move(index: 2, from: 1)
expect(records[0]).to(equal(record))
}
}
describe("Moving multiple items in a set set") {
beforeEach {
let from = [
Model(identifier: 1),
Model(identifier: 3),
Model(identifier: 6),
Model(identifier: 2),
Model(identifier: 5),
Model(identifier: 4)
]
let to = [
Model(identifier: 1),
Model(identifier: 2),
Model(identifier: 3),
Model(identifier: 4),
Model(identifier: 5),
Model(identifier: 6)
]
records = self.records(from, to: to)
expect(records.count).to(equal(3))
}
it("moves the record") {
let record = DeltaChange.move(index: 2, from: 1)
let record1 = DeltaChange.move(index: 5, from: 2)
let record2 = DeltaChange.move(index: 4, from: 4)
expect(records[0]).to(equal(record))
expect(records[1]).to(equal(record1))
expect(records[2]).to(equal(record2))
}
}
describe("Moving an item and appending an item") {
beforeEach {
let from = [
Model(identifier: 1),
Model(identifier: 3),
Model(identifier: 6)
]
let to = [
Model(identifier: 4),
Model(identifier: 1),
Model(identifier: 6),
Model(identifier: 3)
]
records = self.records(from, to: to)
expect(records.count).to(equal(2))
}
it("moves the record") {
let record = DeltaChange.move(index: 3, from: 1)
expect(records[1]).to(equal(record))
}
}
describe("Removing an item and appending another item") {
beforeEach {
let from = [
Model(identifier: 4),
Model(identifier: 1),
Model(identifier: 3),
Model(identifier: 6)
]
let to = [
Model(identifier: 1),
Model(identifier: 6),
Model(identifier: 3)
]
records = self.records(from, to: to)
expect(records.count).to(equal(2))
}
it("moves the record") {
let record = DeltaChange.move(index: 2, from: 2)
expect(records[1]).to(equal(record))
}
}
describe("Removing an item while moving another") {
beforeEach {
let from = [
Model(identifier: 0),
Model(identifier: 1),
Model(identifier: 2),
]
let to = [
Model(identifier: 2),
Model(identifier: 1),
]
records = self.records(from, to: to)
expect(records.count).to(equal(2))
}
it("moves the record") {
let removeRecord = DeltaChange.remove(index: 0)
expect(records[0]).to(equal(removeRecord))
let moveRecord = DeltaChange.move(index: 0, from: 2)
expect(records[1]).to(equal(moveRecord))
}
}
}
}
fileprivate func records(_ from: [Model], to: [Model]) -> [DeltaChange] {
return changes(from: from, to: to)
}
}
| 0e6289dc420cbfabad5f78cbc5c81753 | 27.214876 | 90 | 0.521236 | false | false | false | false |
icylydia/PlayWithLeetCode | refs/heads/master | 67. Add Binary/solution.swift | mit | 1 | class Solution {
func addBinary(a: String, _ b: String) -> String {
let x = String(a.characters.reverse())
let y = String(b.characters.reverse())
let maxLength = max(x.characters.count, y.characters.count)
var carry = false
var sum = false
var r_ans = ""
var idx = x.startIndex, idy = y.startIndex
for _ in 0..<maxLength {
sum = carry
carry = false
if idx < x.endIndex {
carry = (sum && (x[idx] == "1"))
sum = (sum != (x[idx] == "1"))
idx = idx.advancedBy(1)
}
if idy < y.endIndex {
carry = carry || (sum && y[idy] == "1")
sum = (sum != (y[idy] == "1"))
idy = idy.advancedBy(1)
}
r_ans += sum ? "1" : "0"
}
if carry {
r_ans += "1"
}
return String(r_ans.characters.reverse())
}
} | 7ca4cdf358f0238b5ef31d1135e95d2a | 29.5 | 67 | 0.45186 | false | false | false | false |
leizh007/HiPDA | refs/heads/master | HiPDA/HiPDA/General/Protocols/StoryboardLoadable.swift | mit | 1 | //
// StoryboardLoadable.swift
// HiPDA
//
// Created by leizh007 on 16/9/3.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import Foundation
enum StoryBoard: String {
case main = "Main"
case login = "Login"
case views = "Views"
case me = "Me"
case home = "Home"
case message = "Message"
case search = "Search"
}
/// 可以从storyboard中加载
protocol StoryboardLoadable {
}
extension StoryboardLoadable where Self: UIViewController {
static var identifier: String {
return "\(self)"
}
static func load(from storyboard: StoryBoard) -> Self {
return UIStoryboard(name: storyboard.rawValue, bundle: nil)
.instantiateViewController(withIdentifier: Self.identifier) as! Self
}
}
| 0c1e69ad0ff887f2b8caa47fdded3bc4 | 20.742857 | 80 | 0.651774 | false | false | false | false |
marcusellison/lil-twitter | refs/heads/master | lil-twitter/ReplyViewController.swift | mit | 1 | //
// ReplyViewController.swift
// lil-twitter
//
// Created by Marcus J. Ellison on 5/24/15.
// Copyright (c) 2015 Marcus J. Ellison. All rights reserved.
//
import UIKit
class ReplyViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screennameLabel: UILabel!
@IBOutlet weak var thumbLabel: UIImageView!
@IBOutlet weak var tweetField: UITextField!
var tweet: Tweet!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var imageURL = NSURL(string: User.currentUser!.profileImageURL!)
nameLabel.text = User.currentUser?.name
screennameLabel.text = User.currentUser?.screenname
thumbLabel.setImageWithURL(imageURL)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onReply(sender: AnyObject) {
println("replying now")
var tweetID = tweet.tweetIDString
var text = "@" + tweet.user!.screenname! + " " + tweetField.text
TwitterClient.sharedInstance.replyTweet(tweetField.text, tweetID: tweetID) { (tweet, error) -> () in
self.navigationController?.popViewControllerAnimated(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 7ff2da969db25f9f4c6e61884415729e | 25.859375 | 108 | 0.678301 | false | false | false | false |
fhchina/firefox-ios | refs/heads/master | Sync/State.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
/*
* This file includes types that manage intra-sync and inter-sync metadata
* for the use of synchronizers and the state machine.
*
* See docs/sync.md for details on what exactly we need to persist.
*/
public struct Fetched<T: Equatable>: Equatable {
let value: T
let timestamp: Timestamp
}
public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value
}
/*
* Persistence pref names.
* Note that syncKeyBundle isn't persisted by us.
*
* Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"),
* and we keep a 'label'. This label is used to find the real fetched keys in the Keychain.
*/
private let PrefVersion = "_v"
private let PrefGlobal = "global"
private let PrefGlobalTS = "globalTS"
private let PrefKeyLabel = "keyLabel"
private let PrefKeysTS = "keysTS"
private let PrefLastFetched = "lastFetched"
private let PrefClientName = "clientName"
private let PrefClientGUID = "clientGUID"
class PrefsBackoffStorage: BackoffStorage {
let prefs: Prefs
private let key = "timestamp"
init(prefs: Prefs) {
self.prefs = prefs
}
var serverBackoffUntilLocalTimestamp: Timestamp? {
get {
return self.prefs.unsignedLongForKey(self.key)
}
set(value) {
if let value = value {
self.prefs.setLong(value, forKey: self.key)
} else {
self.prefs.removeObjectForKey(self.key)
}
}
}
func clearServerBackoff() {
self.prefs.removeObjectForKey(self.key)
}
func isInBackoff(now: Timestamp) -> Timestamp? {
if let ts = self.serverBackoffUntilLocalTimestamp where now < ts {
return ts
}
return nil
}
}
/**
* The scratchpad consists of the following:
*
* 1. Cached records. We cache meta/global and crypto/keys until they change.
* 2. Metadata like timestamps, both for cached records and for server fetches.
* 3. User preferences -- engine enablement.
* 4. Client record state.
*
* Note that the scratchpad itself is immutable, but is a class passed by reference.
* Its mutable fields can be mutated, but you can't accidentally e.g., switch out
* meta/global and get confused.
*
* TODO: the Scratchpad needs to be loaded from persistent storage, and written
* back at certain points in the state machine (after a replayable action is taken).
*/
public class Scratchpad {
public class Builder {
var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too!
private var global: Fetched<MetaGlobal>?
private var keys: Fetched<Keys>?
private var keyLabel: String
var collectionLastFetched: [String: Timestamp]
var engineConfiguration: EngineConfiguration?
var clientGUID: String
var clientName: String
var prefs: Prefs
init(p: Scratchpad) {
self.syncKeyBundle = p.syncKeyBundle
self.prefs = p.prefs
self.global = p.global
self.keys = p.keys
self.keyLabel = p.keyLabel
self.collectionLastFetched = p.collectionLastFetched
self.engineConfiguration = p.engineConfiguration
self.clientGUID = p.clientGUID
self.clientName = p.clientName
}
public func setKeys(keys: Fetched<Keys>?) -> Builder {
self.keys = keys
if let keys = keys {
self.collectionLastFetched["crypto"] = keys.timestamp
}
return self
}
public func setGlobal(global: Fetched<MetaGlobal>?) -> Builder {
self.global = global
if let global = global {
self.collectionLastFetched["meta"] = global.timestamp
}
return self
}
public func clearFetchTimestamps() -> Builder {
self.collectionLastFetched = [:]
return self
}
public func build() -> Scratchpad {
return Scratchpad(
b: self.syncKeyBundle,
m: self.global,
k: self.keys,
keyLabel: self.keyLabel,
fetches: self.collectionLastFetched,
engines: self.engineConfiguration,
clientGUID: self.clientGUID,
clientName: self.clientName,
persistingTo: self.prefs
)
}
}
public lazy var backoffStorage: BackoffStorage = {
return PrefsBackoffStorage(prefs: self.prefs.branch("backoff.storage"))
}()
public func evolve() -> Scratchpad.Builder {
return Scratchpad.Builder(p: self)
}
// This is never persisted.
let syncKeyBundle: KeyBundle
// Cached records.
// This cached meta/global is what we use to add or remove enabled engines. See also
// engineConfiguration, below.
// We also use it to detect when meta/global hasn't changed -- compare timestamps.
//
// Note that a Scratchpad held by a Ready state will have the current server meta/global
// here. That means we don't need to track syncIDs separately (which is how desktop and
// Android are implemented).
// If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't
// synced with this server before, and we'll do a fresh sync.
let global: Fetched<MetaGlobal>?
// We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs.
// Instead, we store a label, which is seeded when you first create a Scratchpad.
// This label is used to retrieve the real keys from your Keychain.
//
// Note that we also don't store the syncKeyBundle here. That's always created from kB,
// provided by the Firefox Account.
//
// Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to
// clean up without having your key. Secondly, we don't want to accidentally load keys
// from the Keychain just because the Sync Key is the same -- e.g., after a node
// reassignment. Randomly generating a label offers all of the benefits with none of the
// problems, with only the cost of persisting that label alongside the rest of the state.
let keys: Fetched<Keys>?
let keyLabel: String
// Collection timestamps.
var collectionLastFetched: [String: Timestamp]
// Enablement states.
let engineConfiguration: EngineConfiguration?
// What's our client name?
let clientName: String
let clientGUID: String
// Where do we persist when told?
let prefs: Prefs
init(b: KeyBundle,
m: Fetched<MetaGlobal>?,
k: Fetched<Keys>?,
keyLabel: String,
fetches: [String: Timestamp],
engines: EngineConfiguration?,
clientGUID: String,
clientName: String,
persistingTo prefs: Prefs
) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = k
self.keyLabel = keyLabel
self.global = m
self.engineConfiguration = engines
self.collectionLastFetched = fetches
self.clientGUID = clientGUID
self.clientName = clientName
}
// This should never be used in the end; we'll unpickle instead.
// This should be a convenience initializer, but... Swift compiler bug?
init(b: KeyBundle, persistingTo prefs: Prefs) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = nil
self.keyLabel = Bytes.generateGUID()
self.global = nil
self.engineConfiguration = nil
self.collectionLastFetched = [String: Timestamp]()
self.clientGUID = Bytes.generateGUID()
self.clientName = DeviceInfo.defaultClientName()
}
// For convenience.
func withGlobal(m: Fetched<MetaGlobal>?) -> Scratchpad {
return self.evolve().setGlobal(m).build()
}
func freshStartWithGlobal(global: Fetched<MetaGlobal>) -> Scratchpad {
// TODO: I *think* a new keyLabel is unnecessary.
return self.evolve()
.setGlobal(global)
.setKeys(nil)
.clearFetchTimestamps()
.build()
}
func applyEngineChoices(old: MetaGlobal?) -> (Scratchpad, MetaGlobal?) {
log.info("Applying engine choices from inbound meta/global.")
log.info("Old meta/global syncID: \(old?.syncID)")
log.info("New meta/global syncID: \(self.global?.value.syncID)")
log.info("HACK: ignoring engine choices.")
// TODO: detect when the sets of declined or enabled engines have changed, and update
// our preferences and generate a new meta/global if necessary.
return (self, nil)
}
private class func unpickleV1FromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad {
let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve()
// Do this first so that the meta/global and crypto/keys unpickling can overwrite the timestamps.
if let lastFetched: [String: AnyObject] = prefs.dictionaryForKey(PrefLastFetched) {
b.collectionLastFetched = optFilter(mapValues(lastFetched, { ($0 as? NSNumber)?.unsignedLongLongValue }))
}
if let mg = prefs.stringForKey(PrefGlobal) {
if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) {
if let global = MetaGlobal.fromPayload(mg) {
b.setGlobal(Fetched(value: global, timestamp: mgTS))
} else {
log.error("Malformed meta/global in prefs. Ignoring.")
}
} else {
// This should never happen.
log.error("Found global in prefs, but not globalTS!")
}
}
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
b.keyLabel = keyLabel
if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) {
if let keys = KeychainWrapper.stringForKey("keys." + keyLabel) {
// We serialize as JSON.
let keys = Keys(payload: KeysPayload(keys))
if keys.valid {
log.debug("Read keys from Keychain with label \(keyLabel).")
b.setKeys(Fetched(value: keys, timestamp: ckTS))
} else {
log.error("Invalid keys extracted from Keychain. Discarding.")
}
} else {
log.error("Found keysTS in prefs, but didn't find keys in Keychain!")
}
}
}
b.clientGUID = prefs.stringForKey(PrefClientGUID) ?? {
log.error("No value found in prefs for client GUID! Generating one.")
return Bytes.generateGUID()
}()
b.clientName = prefs.stringForKey(PrefClientName) ?? {
log.error("No value found in prefs for client name! Using default.")
return DeviceInfo.defaultClientName()
}()
// TODO: engineConfiguration
return b.build()
}
/**
* Remove anything that might be left around after prefs is wiped.
*/
public class func clearFromPrefs(prefs: Prefs) {
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
log.debug("Removing saved key from keychain.")
KeychainWrapper.removeObjectForKey(keyLabel)
} else {
log.debug("No key label; nothing to remove from keychain.")
}
}
public class func restoreFromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? {
if let ver = prefs.intForKey(PrefVersion) {
switch (ver) {
case 1:
return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle)
default:
return nil
}
}
log.debug("No scratchpad found in prefs.")
return nil
}
/**
* Persist our current state to our origin prefs.
* Note that calling this from multiple threads with either mutated or evolved
* scratchpads will cause sadness — individual writes are thread-safe, but the
* overall pseudo-transaction is not atomic.
*/
public func checkpoint() -> Scratchpad {
return pickle(self.prefs)
}
func pickle(prefs: Prefs) -> Scratchpad {
prefs.setInt(1, forKey: PrefVersion)
if let global = global {
prefs.setLong(global.timestamp, forKey: PrefGlobalTS)
prefs.setString(global.value.toPayload().toString(), forKey: PrefGlobal)
} else {
prefs.removeObjectForKey(PrefGlobal)
prefs.removeObjectForKey(PrefGlobalTS)
}
// We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs.
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
if let keys = self.keys {
let payload = keys.value.asPayload().toString(pretty: false)
let label = "keys." + self.keyLabel
log.debug("Storing keys in Keychain with label \(label).")
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
prefs.setLong(keys.timestamp, forKey: PrefKeysTS)
// TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here.
KeychainWrapper.setString(payload, forKey: label)
} else {
log.debug("Removing keys from Keychain.")
KeychainWrapper.removeObjectForKey(self.keyLabel)
}
// TODO: engineConfiguration
prefs.setString(clientName, forKey: PrefClientName)
prefs.setString(clientGUID, forKey: PrefClientGUID)
// Thanks, Swift.
let dict = mapValues(collectionLastFetched, { NSNumber(unsignedLongLong: $0) }) as NSDictionary
prefs.setObject(dict, forKey: PrefLastFetched)
return self
}
}
| 06997edf048485aabe650bb517ed4e48 | 35.30303 | 117 | 0.618809 | false | false | false | false |
bsmith11/ScoreReporter | refs/heads/master | ScoreReporter/Teams/TeamsViewModel.swift | mit | 1 | //
// TeamsViewModel.swift
// ScoreReporter
//
// Created by Bradley Smith on 11/22/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import ScoreReporterCore
class TeamsViewModel: NSObject {
fileprivate let teamService = TeamService(client: APIClient.sharedInstance)
fileprivate(set) dynamic var loading = false
fileprivate(set) dynamic var error: NSError? = nil
}
// MARK: - Public
extension TeamsViewModel {
func downloadTeams() {
loading = true
teamService.downloadTeamList { [weak self] result in
self?.loading = false
self?.error = result.error
}
}
}
| 53e44d805fe24f9ed4ac59b449811b2a | 21.1 | 79 | 0.6727 | false | false | false | false |
PayNoMind/iostags | refs/heads/master | Tags/Models/TagContainer.swift | mit | 2 | import Foundation
public class TagContainer {
private var saveTag: Tag = Tag.tag("")
var set: ((_ tags: OrderedSet<Tag>) -> Void)? {
didSet {
self.set?(self.tags)
}
}
public var tags: OrderedSet<Tag> = [] {
didSet {
self.set?(self.tags)
}
}
var currentTag: Tag = Tag.tag("")
init(tags: [Tag]) {
let final: [Tag] = [Tag.addTag] + (tags.contains(Tag.addTag) ? [] : tags)
self.tags = OrderedSet<Tag>(final)
}
func startEditing(AtIndex index: Int) {
saveTag = tags[index]
currentTag = tags[index]
// if saveTag == .addTag {
// tags.insert(Tag.tag(""), atIndex: index)
// }
}
func doneEditing(AtIndex index: Int) {
if currentTag.value.isEmpty {
// do nothing
// reload
}
if saveTag.value != currentTag.value {
// self.tags = self.removeAddTag()
//todo handle this safer
// tags.insert(currentTag, at: 0)
tags.insert(currentTag, atIndex: index)
// tags[index] = currentTag
let final: [Tag] = [Tag.addTag] + tags //(tags.contains(Tag.addTag) ? [] : tags)
let orderedSet = OrderedSet<Tag>(final)
self.set?(orderedSet)
}
}
func remove(AtIndex index: Int) {
_ = tags.remove(At: index)
self.set?(self.tags)
}
func removeAddTag() -> [Tag] {
return self.tags.filter { $0 != Tag.addTag }
}
func insert(Tag tag: Tag) {
tags.insert(tag, atIndex: 0)
tags.insert(Tag.addTag, atIndex: 0)
self.set?(self.tags)
}
}
| 7edc549f69ecb9b6c2da658a5bc860c7 | 21.636364 | 86 | 0.584337 | false | false | false | false |
coppercash/Anna | refs/heads/master | CoreJS/CoreJS.swift | mit | 1 | //
// CoreJS.swift
// Anna_iOS
//
// Created by William on 2018/4/19.
//
import Foundation
import JavaScriptCore
public struct
CoreJS
{
public typealias
Context = JSContext
public typealias
FileManaging = Anna.FileManaging
public typealias
FileHandling = Anna.FileHandling
@objc(CJSDependency) @objcMembers
public class
Dependency : NSObject
{
public typealias
ExceptionHandler = (JSContext?, Error?) -> Void
public var
moduleURL :URL? = nil,
fileManager :FileManaging? = nil,
standardOutput :FileHandling? = nil,
exceptionHandler :ExceptionHandler? = nil,
nodePathURLs :Set<URL>? = nil
}
}
@objc(CJSFileManaging)
public protocol
FileManaging
{
@objc(contentsAtPath:)
func
contents(atPath path: String) -> Data?
@objc(fileExistsAtPath:)
func
fileExists(atPath path: String) -> Bool
@objc(fileExistsAtPath:isDirectory:)
func
fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool
}
extension FileManager : CoreJS.FileManaging {}
@objc(CJSFileHandling)
public protocol
FileHandling
{
@objc(writeData:)
func
write(_ data: Data) -> Void
}
extension FileHandle : CoreJS.FileHandling {}
class
Native : NSObject, NativeJSExport
{
weak var
context :JSContext?
let
module :Module,
fileManager :FileManaging,
standardOutput :FileHandling
init(
context :JSContext,
fileManager :FileManaging,
standardOutput :FileHandling,
paths :Set<URL>
) {
self.module = Module(
fileManager: fileManager,
core: [],
global: paths
)
self.context = context
self.fileManager = fileManager
self.standardOutput = standardOutput
}
func
contains(
_ id :JSValue
) -> NSNumber {
return (false as NSNumber)
}
func
moduleExports(
_ id :JSValue
) -> JSExport! {
return nil
}
func
resolvedPath(
_ id :JSValue,
_ parent :JSValue,
_ main :JSValue
) -> String! {
guard let id = id.string() else { return nil }
let
module = (parent.url() ?? main.url())?.deletingLastPathComponent()
return try? self.module.resolve(
x: id, from:
module
)
}
func
load(
_ jspath :JSValue,
_ exports :JSValue,
_ require :JSValue,
_ module :JSValue
) {
guard
let
context = self.context,
let
url = jspath.url()
else { return }
self.module.loadScript(
at: url,
to: context,
exports: exports,
require: require,
module: module
)
}
func
log(
_ string :String
) {
guard let data = (string + "\n").data(using: .utf8) else { return }
self.standardOutput.write(data)
}
}
@objc protocol
NativeJSExport : JSExport
{
func
contains(
_ id :JSValue
) -> NSNumber
func
moduleExports(
_ id :JSValue
) -> JSExport!
func
resolvedPath(
_ id :JSValue,
_ parent :JSValue,
_ main :JSValue
) -> String!
func
load(
_ path :JSValue,
_ exports :JSValue,
_ require :JSValue,
_ module :JSValue
)
func
log(
_ string :String
)
}
extension
JSContext
{
func
setup(
with dependency :CoreJS.Dependency? = nil
) throws {
let
context = self
context.name = "CoreJS"
if let handle = dependency?.exceptionHandler {
context.exceptionHandler = { handle( $0, $1?.error()) }
}
context.globalObject.setValue(
context.globalObject,
forProperty: "global"
)
let
fileManager = dependency?.fileManager ?? FileManager.default,
standardOutput = dependency?.standardOutput ?? FileHandle.standardOutput,
moduleURL = dependency?.moduleURL ??
Bundle.main
.bundleURL
.appendingPathComponent("corejs")
.appendingPathExtension("bundle"),
paths = dependency?.nodePathURLs ?? Set(),
native = Native(
context: context,
fileManager: fileManager,
standardOutput: standardOutput,
paths: paths
)
let
mainScriptPath = try native.module.resolve(
x: moduleURL.path,
from: nil
),
require = context.evaluateScript("""
(function() { return function () {}; })();
""") as JSValue,
module = context.evaluateScript("""
(function() { return { exports: {} }; })();
""") as JSValue,
exports = module.forProperty("exports") as JSValue
native.module.loadScript(
at: URL(fileURLWithPath: mainScriptPath),
to: context,
exports: exports,
require: require,
module: module
)
exports
.forProperty("setup")
.call(withArguments: [native])
}
func
require(
_ identifier :String
) -> JSValue! {
return self
.globalObject
.forProperty("require")
.call(withArguments: [identifier])
}
}
extension
JSValue
{
func
error() -> Error? {
let
jsValue = self
guard
let
name = jsValue.forProperty("name").toString(),
let
message = jsValue.forProperty("message").toString(),
let
stack = jsValue.forProperty("stack").toString()
else { return nil }
return NSError(
domain: name,
code: -1,
userInfo: [
NSLocalizedDescriptionKey: message,
NSLocalizedFailureReasonErrorKey: stack,
]
)
}
func
string() -> String? {
let
value = self
guard value.isString else { return nil }
return value.toString()
}
func
url() -> URL? {
let
value = self
guard value.isString else { return nil }
return URL(fileURLWithPath: value.toString())
}
}
| d198a0adc2a4c99b73b770ad31d014a8 | 22.606498 | 93 | 0.528215 | false | false | false | false |
Witcast/witcast-ios | refs/heads/develop | Pods/PullToRefreshKit/Source/Classes/Footer.swift | apache-2.0 | 1 | //
// Footer.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/7/11.
// I refer a lot logic for MJRefresh https://github.com/CoderMJLee/MJRefresh ,thanks to this lib and all contributors.
// Copyright © 2016年 Leo. All rights reserved.
import Foundation
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
public enum RefreshKitFooterText{
case pullToRefresh
case tapToRefresh
case scrollAndTapToRefresh
case refreshing
case noMoreData
}
public enum RefreshMode{
/// 只有Scroll才会触发
case scroll
/// 只有Tap才会触发
case tap
/// Scroll和Tap都会触发
case scrollAndTap
}
open class DefaultRefreshFooter:UIView, RefreshableFooter, Tintable{
open let spinner:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
open let textLabel:UILabel = UILabel(frame: CGRect(x: 0,y: 0,width: 140,height: 40)).SetUp {
$0.font = UIFont.systemFont(ofSize: 14)
$0.textAlignment = .center
}
/// 触发刷新的模式
open var refreshMode = RefreshMode.scrollAndTap{
didSet{
tap.isEnabled = (refreshMode != .scroll)
udpateTextLabelWithMode(refreshMode)
}
}
fileprivate func udpateTextLabelWithMode(_ refreshMode:RefreshMode){
switch refreshMode {
case .scroll:
textLabel.text = textDic[.pullToRefresh]
case .tap:
textLabel.text = textDic[.tapToRefresh]
case .scrollAndTap:
textLabel.text = textDic[.scrollAndTapToRefresh]
}
}
fileprivate var tap:UITapGestureRecognizer!
fileprivate var textDic = [RefreshKitFooterText:String]()
/**
This function can only be called before Refreshing
*/
open func setText(_ text:String,mode:RefreshKitFooterText){
textDic[mode] = text
textLabel.text = textDic[.pullToRefresh]
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(spinner)
addSubview(textLabel)
textDic[.pullToRefresh] = PullToRefreshKitFooterString.pullUpToRefresh
textDic[.refreshing] = PullToRefreshKitFooterString.refreshing
textDic[.noMoreData] = PullToRefreshKitFooterString.noMoreData
textDic[.tapToRefresh] = PullToRefreshKitFooterString.tapToRefresh
textDic[.scrollAndTapToRefresh] = PullToRefreshKitFooterString.scrollAndTapToRefresh
udpateTextLabelWithMode(refreshMode)
tap = UITapGestureRecognizer(target: self, action: #selector(DefaultRefreshFooter.catchTap(_:)))
self.addGestureRecognizer(tap)
}
open override func layoutSubviews() {
super.layoutSubviews()
textLabel.center = CGPoint(x: frame.size.width/2, y: frame.size.height/2);
spinner.center = CGPoint(x: frame.width/2 - 70 - 20, y: frame.size.height/2)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func catchTap(_ tap:UITapGestureRecognizer){
let scrollView = self.superview?.superview as? UIScrollView
scrollView?.beginFooterRefreshing()
}
// MARK: - Refreshable -
open func heightForRefreshingState() -> CGFloat {
return PullToRefreshKitConst.defaultFooterHeight
}
open func didBeginRefreshing() {
textLabel.text = textDic[.refreshing];
spinner.startAnimating()
}
open func didEndRefreshing() {
udpateTextLabelWithMode(refreshMode)
spinner.stopAnimating()
}
open func didUpdateToNoMoreData(){
textLabel.text = textDic[.noMoreData]
}
open func didResetToDefault() {
udpateTextLabelWithMode(refreshMode)
}
open func shouldBeginRefreshingWhenScroll()->Bool {
return refreshMode != .tap
}
// MARK: - Handle touch -
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard refreshMode != .scroll else{
return
}
self.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard refreshMode != .scroll else{
return
}
self.backgroundColor = UIColor.white
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
guard refreshMode != .scroll else{
return
}
self.backgroundColor = UIColor.white
}
// MARK: Tintable
open func setThemeColor(themeColor: UIColor) {
textLabel.textColor = themeColor
spinner.color = themeColor
}
}
class RefreshFooterContainer:UIView{
enum RefreshFooterState {
case idle
case refreshing
case willRefresh
case noMoreData
}
// MARK: - Propertys -
var refreshAction:(()->())?
var attachedScrollView:UIScrollView!
weak var delegate:RefreshableFooter?
fileprivate var _state:RefreshFooterState = .idle
var state:RefreshFooterState{
get{
return _state
}
set{
guard newValue != _state else{
return
}
_state = newValue
if newValue == .refreshing{
DispatchQueue.main.async(execute: {
self.delegate?.didBeginRefreshing()
self.refreshAction?()
})
}else if newValue == .noMoreData{
self.delegate?.didUpdateToNoMoreData()
}else if newValue == .idle{
self.delegate?.didResetToDefault()
}
}
}
// MARK: - Init -
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
self.isUserInteractionEnabled = true
self.backgroundColor = UIColor.clear
self.autoresizingMask = .flexibleWidth
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life circle -
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.state == .willRefresh {
self.state = .refreshing
}
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
guard newSuperview != nil else{ //remove from superview
if !self.isHidden{
var inset = attachedScrollView.contentInset
inset.bottom = inset.bottom - self.frame.height
attachedScrollView.contentInset = inset
}
return
}
guard newSuperview is UIScrollView else{
return;
}
attachedScrollView = newSuperview as? UIScrollView
attachedScrollView.alwaysBounceVertical = true
if !self.isHidden {
var contentInset = attachedScrollView.contentInset
contentInset.bottom = contentInset.bottom + self.frame.height
attachedScrollView.contentInset = contentInset
}
self.frame = CGRect(x: 0,y: attachedScrollView.contentSize.height,width: self.frame.width, height: self.frame.height)
addObservers()
}
deinit{
removeObservers()
}
// MARK: - Private -
fileprivate func addObservers(){
attachedScrollView?.addObserver(self, forKeyPath:PullToRefreshKitConst.KPathOffSet, options: [.old,.new], context: nil)
attachedScrollView?.addObserver(self, forKeyPath:PullToRefreshKitConst.KPathContentSize, options:[.old,.new] , context: nil)
attachedScrollView?.panGestureRecognizer.addObserver(self, forKeyPath:PullToRefreshKitConst.KPathPanState, options:[.old,.new] , context: nil)
}
fileprivate func removeObservers(){
attachedScrollView?.removeObserver(self, forKeyPath: PullToRefreshKitConst.KPathContentSize,context: nil)
attachedScrollView?.removeObserver(self, forKeyPath: PullToRefreshKitConst.KPathOffSet,context: nil)
attachedScrollView?.panGestureRecognizer.removeObserver(self, forKeyPath: PullToRefreshKitConst.KPathPanState,context: nil)
}
func handleScrollOffSetChange(_ change: [NSKeyValueChangeKey : Any]?){
if state != .idle && self.frame.origin.y != 0{
return
}
let insetTop = attachedScrollView.contentInset.top
let contentHeight = attachedScrollView.contentSize.height
let scrollViewHeight = attachedScrollView.frame.size.height
if insetTop + contentHeight > scrollViewHeight{
let offSetY = attachedScrollView.contentOffset.y
if offSetY > self.frame.origin.y - scrollViewHeight + attachedScrollView.contentInset.bottom{
let oldOffset = (change?[NSKeyValueChangeKey.oldKey] as AnyObject).cgPointValue
let newOffset = (change?[NSKeyValueChangeKey.newKey] as AnyObject).cgPointValue
guard newOffset?.y > oldOffset?.y else{
return
}
let shouldStart = self.delegate?.shouldBeginRefreshingWhenScroll()
guard shouldStart! else{
return
}
beginRefreshing()
}
}
}
func handlePanStateChange(_ change: [NSKeyValueChangeKey : Any]?){
guard state == .idle else{
return
}
if attachedScrollView.panGestureRecognizer.state == .ended {
let scrollInset = attachedScrollView.contentInset
let scrollOffset = attachedScrollView.contentOffset
let contentSize = attachedScrollView.contentSize
if scrollInset.top + contentSize.height <= attachedScrollView.frame.height{
if scrollOffset.y >= -1 * scrollInset.top {
let shouldStart = self.delegate?.shouldBeginRefreshingWhenScroll()
guard shouldStart! else{
return
}
beginRefreshing()
}
}else{
if scrollOffset.y > contentSize.height + scrollInset.bottom - attachedScrollView.frame.height {
let shouldStart = self.delegate?.shouldBeginRefreshingWhenScroll()
guard shouldStart! else{
return
}
beginRefreshing()
}
}
}
}
func handleContentSizeChange(_ change: [NSKeyValueChangeKey : Any]?){
self.frame = CGRect(x: 0,y: self.attachedScrollView.contentSize.height,width: self.frame.size.width,height: self.frame.size.height)
}
// MARK: - KVO -
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard self.isUserInteractionEnabled else{
return;
}
if keyPath == PullToRefreshKitConst.KPathOffSet {
handleScrollOffSetChange(change)
}
guard !self.isHidden else{
return;
}
if keyPath == PullToRefreshKitConst.KPathPanState{
handlePanStateChange(change)
}
if keyPath == PullToRefreshKitConst.KPathContentSize {
handleContentSizeChange(change)
}
}
// MARK: - API -
func beginRefreshing(){
if self.window != nil {
self.state = .refreshing
}else{
if state != .refreshing{
self.state = .willRefresh
}
}
}
func endRefreshing(){
self.state = .idle
self.delegate?.didEndRefreshing()
}
func resetToDefault(){
self.state = .idle
}
func updateToNoMoreData(){
self.state = .noMoreData
}
}
| 9bb4d823f8037619eb840b4db8e79742 | 34.751462 | 151 | 0.625256 | false | false | false | false |
LeeWongSnail/Swift | refs/heads/master | DesignBox/DesignBox/App/Publish/ViewController/View/ArtPublishMenuViewController.swift | mit | 1 | //
// ArtPublishMenuViewController.swift
// DesignBox
//
// Created by LeeWong on 2017/9/11.
// Copyright © 2017年 LeeWong. All rights reserved.
//
import UIKit
class ArtPublishMenuViewController: UIViewController {
var rootNaviController:UINavigationController?
var topAlphaView: UIView?
var menuView: ArtPublishChoiceView?
//MARK: - ADD TAP Gesture
func publishWorkDidClick() -> Void {
dismissMenu()
let vc = ArtPublishWorkViewController()
vc.hidesBottomBarWhenPushed = true
let nav = UINavigationController(rootViewController: vc)
self.navigationController?.present(nav, animated: true, completion: nil)
}
func publishRequirementDidClick() -> Void {
dismissMenu()
let vc = ArtPublishWorkViewController()
vc.hidesBottomBarWhenPushed = true
let nav = UINavigationController(rootViewController: vc)
self.navigationController?.present(nav, animated: true, completion: nil)
}
func dismissMenu() -> Void {
dismissMenuAnimated(animated: true)
}
func dismissMenuAnimated(animated:Bool) -> Void {
if animated {
UIView.animate(withDuration: 0.2, animations: {
self.menuView?.center = CGPoint(x: self.view.frame.size.width/2, y: -((self.menuView?.frame.size.height)!/2))
self.view.backgroundColor = UIColor.init(white: 0, alpha: 0)
}, completion: { (finish) in
self.view.removeFromSuperview()
self.removeTopAlphaView()
self.removeFromParentViewController()
})
} else {
self.view.removeFromSuperview()
self.removeFromParentViewController()
removeTopAlphaView()
}
}
func showInViewController(viewController:UIViewController) -> Void {
if viewController.isKind(of: UITabBarController.self) {
self.rootNaviController = (viewController as! UITabBarController).selectedViewController as? UINavigationController
} else if (viewController.isKind(of: UINavigationController.self)) {
self.rootNaviController = viewController as? UINavigationController
} else {
self.rootNaviController = viewController.navigationController
}
AppDelegate.getRootWindow()?.addSubview(self.view)
self.rootNaviController?.addChildViewController(self)
self.view.snp.makeConstraints { (make) in
make.edges.equalTo(AppDelegate.getRootWindow()!)
}
self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.title = nil
self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "publish_menu_close")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.showTopAlphaView()
self.showMenuView()
}
}
func addTapGesture() -> Void {
self.view.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.view.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(ArtPublishMenuViewController.dismissMenu))
self.view.addGestureRecognizer(tap)
}
//MARK: - LOAD VIEW
func buildUI() -> Void {
}
func showTopAlphaView() -> Void {
self.topAlphaView = self.rootNaviController?.view.resizableSnapshotView(from: CGRect.init(x: 0, y: 0, width: SCREEN_W, height: 64), afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
let tap = UITapGestureRecognizer(target: self, action: #selector(ArtPublishMenuViewController.dismissMenu))
self.topAlphaView?.addGestureRecognizer(tap)
AppDelegate.getRootWindow()?.addSubview(self.topAlphaView!)
self.topAlphaView?.snp.makeConstraints({ (make) in
make.top.left.right.equalTo(AppDelegate.getRootWindow()!)
make.bottom.equalTo((AppDelegate.getRootWindow()?.snp.top)!).offset(64)
})
}
func removeTopAlphaView() -> Void {
self.topAlphaView?.removeFromSuperview()
self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "icon_publish")
}
func showMenuView() -> Void {
let menuView = UINib(nibName: "ArtPublishChoiceView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! ArtPublishChoiceView
menuView.frame = CGRect.init(x: 0, y: 64, width: SCREEN_W, height: 260)
self.view.addSubview(menuView)
self.view.insertSubview(menuView, belowSubview: self.topAlphaView!)
menuView.center = CGPoint.init(x: SCREEN_W/2, y: -menuView.frame.size.height/2)
UIView.animate(withDuration: 0.2) {
self.view.backgroundColor = UIColor(white: 0, alpha: 0.5)
menuView.center = CGPoint.init(x: SCREEN_W/2, y: menuView.frame.size.height/2 + 64)
}
self.menuView = menuView
self.menuView?.publishRequirement.addTarget(self, action: #selector(ArtPublishMenuViewController.publishRequirementDidClick), for: UIControlEvents.touchUpInside)
self.menuView?.publishWork.addTarget(self, action: #selector(ArtPublishMenuViewController.publishWorkDidClick), for: UIControlEvents.touchUpInside)
}
//MARK:- LIFE CYCLE
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addTapGesture()
buildUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 630680d752bb1238a091492369efc23c | 36.202532 | 200 | 0.649711 | false | false | false | false |
gejingguo/NavMesh2D | refs/heads/master | Sources/Triangle.swift | apache-2.0 | 1 | //
// Triangle.swift
// NavMesh2D
//
// Created by andyge on 16/6/25.
//
//
import Foundation
/// 三角形
public class Triangle {
public var id = -1
public var groupId = -1
public var points = [Vector2D](repeating: Vector2D(), count: 3)
public var neighbors = [Int](repeating: -1, count: 3)
var center = Vector2D()
var box = Rect()
var wallDistances = [Double](repeating: 0.0, count: 3)
public init() {
}
public init(id: Int, groupId: Int, point1: Vector2D, point2: Vector2D, point3: Vector2D) {
self.id = id
self.groupId = groupId
self.points[0] = point1
self.points[1] = point2
self.points[2] = point3
// 计算中心点
center.x = (points[0].x + points[1].x + points[2].x)/3
center.y = (points[0].y + points[1].y + points[2].y)/3
// 计算相邻俩点中点距离
var wallMidPoints = [Vector2D](repeating: Vector2D(), count: 3)
wallMidPoints[0] = Vector2D(x: (points[0].x + points[1].x)/2, y: (points[0].y + points[1].y)/2)
wallMidPoints[1] = Vector2D(x: (points[1].x + points[2].x)/2, y: (points[1].y + points[2].y)/2)
wallMidPoints[2] = Vector2D(x: (points[2].x + points[0].x)/2, y: (points[2].y + points[0].y)/2)
wallDistances[0] = (wallMidPoints[0] - wallMidPoints[1]).length
wallDistances[1] = (wallMidPoints[1] - wallMidPoints[2]).length
wallDistances[2] = (wallMidPoints[2] - wallMidPoints[0]).length
// 计算包围盒
calcBoxCollider()
}
/// 计算包围盒
func calcBoxCollider() {
if points[0] == points[1] || points[1] == points[2] || points[2] == points[0] {
fatalError("triangle not valid.")
//return
}
var xMin = points[0].x
var xMax = xMin
var yMin = points[0].y
var yMax = yMin
for i in 1..<3 {
if points[i].x < xMin {
xMin = points[i].x
}
else if points[i].x > xMax {
xMax = points[i].x
}
else if points[i].y < yMin {
yMin = points[i].y
}
else if points[i].y > yMax {
yMax = points[i].y
}
}
self.box.origin = Vector2D(x: xMin, y: yMin)
self.box.size.width = xMax - xMin
self.box.size.height = yMax - yMin
}
/// 获取索引对应的边
public func getSide(index: Int) -> Line? {
switch index {
case 0:
return Line(start: points[0], end: points[1])
case 1:
return Line(start: points[1], end: points[2])
case 2:
return Line(start: points[2], end: points[0])
default:
return nil
}
}
/// 检查点是否在三角形中(边上也算)
public func contains(point: Vector2D) -> Bool {
if !self.box.contains(point: point) {
return false;
}
guard let resultA = getSide(index: 0)?.classifyPoint(point: point) else {
return false
}
guard let resultB = getSide(index: 1)?.classifyPoint(point: point) else {
return false
}
guard let resultC = getSide(index: 2)?.classifyPoint(point: point) else {
return false
}
if resultA == PointSide.Online || resultB == PointSide.Online || resultC == PointSide.Online {
return true
}
else if resultA == PointSide.Right && resultB == PointSide.Right && resultC == PointSide.Right {
return true
}
else {
return false
}
}
/// 检查是否是邻居三角形
public func isNeighbor(triangle: Triangle) -> Bool {
for i in 0..<3 {
if neighbors[i] == triangle.id {
return true;
}
}
return false;
}
/// 获取邻居三角形边索引
public func getWallIndex(neighborId: Int) -> Int {
for i in 0..<3 {
if neighbors[i] == neighborId {
return i
}
}
return -1
}
}
| 180769f80c177993a4558af81e7835ff | 27.985915 | 104 | 0.500243 | false | false | false | false |
XCEssentials/UniFlow | refs/heads/master | Sources/6_InternalBindings/InternalBindingBDD_GivenOrThenContext.swift | mit | 1 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([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 Combine
//---
public
extension InternalBindingBDD
{
struct GivenOrThenContext<W: Publisher> // W - When
{
public
let description: String
//internal
let when: (AnyPublisher<Dispatcher.AccessReport, Never>) -> W
public
func given<G>(
_: G.Type = G.self,
_ given: @escaping (Dispatcher, W.Output) throws -> G?
) -> ThenContext<W, G> {
.init(
description: description,
when: when,
given: given
)
}
public
func givenIf(
_ given: @escaping (Dispatcher, W.Output) throws -> Bool
) -> ThenContext<W, Void> {
.init(
description: description,
when: when,
given: { try given($0, $1) ? () : nil }
)
}
public
func given<G>(
_: G.Type = G.self,
_ outputOnlyHandler: @escaping (W.Output) throws -> G?
) -> ThenContext<W, G> {
given { _, output in
try outputOnlyHandler(output)
}
}
public
func givenIf(
_ outputOnlyHandler: @escaping (W.Output) throws -> Bool
) -> ThenContext<W, Void> {
given { _, output in
try outputOnlyHandler(output) ? () : nil
}
}
public
func given<G>(
_: G.Type = G.self,
_ dispOnlyHandler: @escaping (Dispatcher) throws -> G?
) -> ThenContext<W, G> {
given { disp, _ in
try dispOnlyHandler(disp)
}
}
public
func givenIf(
_ dispOnlyHandler: @escaping (Dispatcher) throws -> Bool
) -> ThenContext<W, Void> {
given { disp, _ in
try dispOnlyHandler(disp) ? () : nil
}
}
public
func then(
scope: String = #file,
location: Int = #line,
_ then: @escaping (Dispatcher, W.Output) -> Void
) -> InternalBinding {
.init(
source: S.self,
description: description,
scope: scope,
location: location,
when: when,
given: { $1 }, /// just pass `when` clause output straight through as is
then: then
)
}
public
func then(
scope: String = #file,
location: Int = #line,
_ dispatcherOnlyHandler: @escaping (Dispatcher) -> Void
) -> InternalBinding {
then(scope: scope, location: location) { dispatcher, _ in
dispatcherOnlyHandler(dispatcher)
}
}
}
}
| f8e5f73af88d07fc3dd143ddf5d38f95 | 28.194444 | 88 | 0.510466 | false | false | false | false |
bourdakos1/Visual-Recognition-Tool | refs/heads/master | iOS/Visual Recognition/PulleyViewController.swift | mit | 1 | //
// PulleyViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
// Copyright © 2016 52inc. All rights reserved.
//
import UIKit
/**
* The base delegate protocol for Pulley delegates.
*/
@objc public protocol PulleyDelegate: class {
@objc optional func drawerPositionDidChange(drawer: PulleyViewController)
@objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat)
@objc optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat)
}
/**
* View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions.
*/
public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate {
func collapsedDrawerHeight() -> CGFloat
func partialRevealDrawerHeight() -> CGFloat
func supportedDrawerPositions() -> [PulleyPosition]
}
/**
* View controllers that are the main content can implement this to receive changes in state.
*/
public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate {
// Not currently used for anything, but it's here for parity with the hopes that it'll one day be used.
}
/**
Represents a Pulley drawer position.
- collapsed: When the drawer is in its smallest form, at the bottom of the screen.
- partiallyRevealed: When the drawer is partially revealed.
- open: When the drawer is fully open.
- closed: When the drawer is off-screen at the bottom of the view. Note: Users cannot close or reopen the drawer on their own. You must set this programatically
*/
public enum PulleyPosition: Int {
case collapsed = 0
case partiallyRevealed = 1
case open = 2
case closed = 3
public static let all: [PulleyPosition] = [
.collapsed,
.partiallyRevealed,
.open,
.closed
]
public static func positionFor(string: String?) -> PulleyPosition {
guard let positionString = string?.lowercased() else {
return .closed
}
switch positionString {
case "collapsed":
return .collapsed
case "partiallyrevealed":
return .partiallyRevealed
case "open":
return .open
case "closed":
return .closed
default:
print("PulleyViewController: Position for string '\(positionString)' not found. Available values are: collapsed, partiallyRevealed, open, and closed. Defaulting to collapsed.")
return .closed
}
}
}
private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0
private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0
open class PulleyViewController: UIViewController {
// Interface Builder
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet public var primaryContentContainerView: UIView!
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet public var drawerContentContainerView: UIView!
// Internal
fileprivate let primaryContentContainer: UIView = UIView()
fileprivate let drawerContentContainer: UIView = UIView()
fileprivate let drawerShadowView: UIView = UIView()
let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView() /// Change
fileprivate let backgroundDimmingView: UIView = UIView()
fileprivate var dimmingViewTapRecognizer: UITapGestureRecognizer?
fileprivate var lastDragTargetContentOffset: CGPoint = CGPoint.zero
/// The current content view controller (shown behind the drawer).
public fileprivate(set) var primaryContentViewController: UIViewController! {
willSet {
guard let controller = primaryContentViewController else {
return;
}
controller.view.removeFromSuperview()
controller.willMove(toParentViewController: nil)
controller.removeFromParentViewController()
}
didSet {
guard let controller = primaryContentViewController else {
return;
}
controller.view.translatesAutoresizingMaskIntoConstraints = true
self.primaryContentContainer.addSubview(controller.view)
self.addChildViewController(controller)
controller.didMove(toParentViewController: self)
if self.isViewLoaded
{
self.view.setNeedsLayout()
self.setNeedsSupportedDrawerPositionsUpdate()
}
}
}
/// The current drawer view controller (shown in the drawer).
public fileprivate(set) var drawerContentViewController: UIViewController! {
willSet {
guard let controller = drawerContentViewController else {
return;
}
controller.view.removeFromSuperview()
controller.willMove(toParentViewController: nil)
controller.removeFromParentViewController()
}
didSet {
guard let controller = drawerContentViewController else {
return;
}
controller.view.translatesAutoresizingMaskIntoConstraints = true
self.drawerContentContainer.addSubview(controller.view)
self.addChildViewController(controller)
controller.didMove(toParentViewController: self)
if self.isViewLoaded
{
self.view.setNeedsLayout()
self.setNeedsSupportedDrawerPositionsUpdate()
}
}
}
/// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed.
public weak var delegate: PulleyDelegate?
/// The current position of the drawer.
public fileprivate(set) var drawerPosition: PulleyPosition = .closed {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
/// The background visual effect layer for the drawer. By default this is the extraLight effect. You can change this if you want, or assign nil to remove it.
public var drawerBackgroundVisualEffectView: UIVisualEffectView? = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) {
willSet {
drawerBackgroundVisualEffectView?.removeFromSuperview()
}
didSet {
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView, self.isViewLoaded
{
drawerScrollView.insertSubview(drawerBackgroundVisualEffectView, aboveSubview: drawerShadowView)
drawerBackgroundVisualEffectView.clipsToBounds = true
drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius
}
}
}
/// The inset from the top of the view controller when fully open.
@IBInspectable public var topInset: CGFloat = 50.0 {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The corner radius for the drawer.
@IBInspectable public var drawerCornerRadius: CGFloat = 13.0 {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
drawerBackgroundVisualEffectView?.layer.cornerRadius = drawerCornerRadius
}
}
}
/// The opacity of the drawer shadow.
@IBInspectable public var shadowOpacity: Float = 0.1 {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The radius of the drawer shadow.
@IBInspectable public var shadowRadius: CGFloat = 3.0 {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The opaque color of the background dimming view.
@IBInspectable public var backgroundDimmingColor: UIColor = UIColor.black {
didSet {
if self.isViewLoaded
{
backgroundDimmingView.backgroundColor = backgroundDimmingColor
}
}
}
/// The maximum amount of opacity when dimming.
@IBInspectable public var backgroundDimmingOpacity: CGFloat = 0.5 {
didSet {
if self.isViewLoaded
{
self.scrollViewDidScroll(drawerScrollView)
}
}
}
/// The starting position for the drawer when it first loads
public var initialDrawerPosition: PulleyPosition = .closed
/// This is here exclusively to support IBInspectable in Interface Builder because Interface Builder can't deal with enums. If you're doing this in code use the -initialDrawerPosition property instead. Available strings are: open, closed, partiallyRevealed, collapsed
@IBInspectable public var initialDrawerPositionFromIB: String? {
didSet {
initialDrawerPosition = PulleyPosition.positionFor(string: initialDrawerPositionFromIB)
}
}
/// The drawer positions supported by the drawer
fileprivate var supportedDrawerPositions: [PulleyPosition] = PulleyPosition.all {
didSet {
guard self.isViewLoaded else {
return
}
guard supportedDrawerPositions.count > 0 else {
supportedDrawerPositions = PulleyPosition.all
return
}
self.view.setNeedsLayout()
if supportedDrawerPositions.contains(drawerPosition)
{
setDrawerPosition(position: drawerPosition)
}
else
{
let lowestDrawerState: PulleyPosition = supportedDrawerPositions.min { (pos1, pos2) -> Bool in
return pos1.rawValue < pos2.rawValue
} ?? .collapsed
setDrawerPosition(position: lowestDrawerState, animated: false)
}
drawerScrollView.isScrollEnabled = supportedDrawerPositions.count > 1
}
}
/**
Initialize the drawer controller programmtically.
- parameter contentViewController: The content view controller. This view controller is shown behind the drawer.
- parameter drawerViewController: The view controller to display inside the drawer.
- note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account.
- returns: A newly created Pulley drawer.
*/
required public init(contentViewController: UIViewController, drawerViewController: UIViewController) {
super.init(nibName: nil, bundle: nil)
({
self.primaryContentViewController = contentViewController
self.drawerContentViewController = drawerViewController
})()
}
/**
Initialize the drawer controller from Interface Builder.
- note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container.
- parameter aDecoder: The NSCoder to decode from.
- returns: A newly created Pulley drawer.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func loadView() {
super.loadView()
// IB Support
if primaryContentContainerView != nil
{
primaryContentContainerView.removeFromSuperview()
}
if drawerContentContainerView != nil
{
drawerContentContainerView.removeFromSuperview()
}
// Setup
primaryContentContainer.backgroundColor = UIColor.white
definesPresentationContext = true
drawerScrollView.bounces = false
drawerScrollView.delegate = self
drawerScrollView.clipsToBounds = false
drawerScrollView.showsVerticalScrollIndicator = false
drawerScrollView.showsHorizontalScrollIndicator = false
// drawerScrollView.delaysContentTouches = true
// drawerScrollView.canCancelContentTouches = true
drawerScrollView.backgroundColor = UIColor.clear
drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast
drawerScrollView.scrollsToTop = false
drawerScrollView.touchDelegate = self
drawerShadowView.layer.shadowOpacity = shadowOpacity
drawerShadowView.layer.shadowRadius = shadowRadius
drawerShadowView.backgroundColor = UIColor.clear
drawerContentContainer.backgroundColor = UIColor.clear
backgroundDimmingView.backgroundColor = backgroundDimmingColor
backgroundDimmingView.isUserInteractionEnabled = false
backgroundDimmingView.alpha = 0.0
drawerBackgroundVisualEffectView?.clipsToBounds = true
dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizerAction(gestureRecognizer:)))
backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!)
drawerScrollView.addSubview(drawerShadowView)
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView
{
drawerScrollView.addSubview(drawerBackgroundVisualEffectView)
drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius
}
drawerScrollView.addSubview(drawerContentContainer)
primaryContentContainer.backgroundColor = UIColor.white
self.view.backgroundColor = UIColor.white
self.view.addSubview(primaryContentContainer)
self.view.addSubview(backgroundDimmingView)
self.view.addSubview(drawerScrollView)
}
override open func viewDidLoad() {
super.viewDidLoad()
// IB Support
if primaryContentViewController == nil || drawerContentViewController == nil
{
assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.")
// Locate main content VC
for child in self.childViewControllers
{
if child.view == primaryContentContainerView.subviews.first
{
primaryContentViewController = child
}
if child.view == drawerContentContainerView.subviews.first
{
drawerContentViewController = child
}
}
assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.")
}
setDrawerPosition(position: initialDrawerPosition, animated: false)
scrollViewDidScroll(drawerScrollView)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.drawerScrollView.isHidden = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
let rect = CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0/UIScreen.main.scale))
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.navigationController?.navigationBar.shadowImage = image
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.barStyle = .black
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 1)
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.10
setNeedsSupportedDrawerPositionsUpdate()
}
let v = UIView(frame: CGRect(x: 0, y: 0, width: UIWindow().frame.width, height: 64))
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.drawerScrollView.isHidden = false
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
let rect = CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0/UIScreen.main.scale))
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.navigationController?.navigationBar.shadowImage = image
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.barStyle = .black
self.v.removeFromSuperview()
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 1)
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.10
self.navigationController?.toolbar.isHidden = true
self.setDrawerPosition(position: .closed, animated: false)
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.drawerScrollView.isHidden = true
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.barStyle = .default
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 0)
self.navigationController?.navigationBar.layer.shadowColor = UIColor.clear.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.0
self.setDrawerPosition(position: .closed, animated: false)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.drawerScrollView.isHidden = true
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.barStyle = .default
self.v.backgroundColor = UIColor.white
self.navigationController?.view.insertSubview(self.v, belowSubview: (self.navigationController?.navigationBar)!)
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 0)
self.navigationController?.navigationBar.layer.shadowColor = UIColor.clear.cgColor
self.navigationController?.navigationBar.layer.shadowOpacity = 0.0
self.setDrawerPosition(position: .closed, animated: false)
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout main content
primaryContentContainer.frame = self.view.bounds
backgroundDimmingView.frame = self.view.bounds
// Layout container
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].min() ?? 0
let bounceOverflowMargin: CGFloat = 20.0
if supportedDrawerPositions.contains(.open)
{
// Layout scrollview
drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset)
}
else
{
// Layout scrollview
let adjustedTopInset: CGFloat = supportedDrawerPositions.contains(.partiallyRevealed) ? partialRevealHeight : collapsedHeight
drawerScrollView.frame = CGRect(x: 0, y: self.view.bounds.height - adjustedTopInset, width: self.view.bounds.width, height: adjustedTopInset)
}
drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin)
drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame
drawerShadowView.frame = drawerContentContainer.frame
drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height)
// Update rounding mask and shadows
let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).cgPath
let cardMaskLayer = CAShapeLayer()
cardMaskLayer.path = borderPath
cardMaskLayer.frame = drawerContentContainer.bounds
cardMaskLayer.fillColor = UIColor.white.cgColor
cardMaskLayer.backgroundColor = UIColor.clear.cgColor
drawerContentContainer.layer.mask = cardMaskLayer
drawerShadowView.layer.shadowPath = borderPath
// Make VC views match frames
primaryContentViewController?.view.frame = primaryContentContainer.bounds
drawerContentViewController?.view.frame = CGRect(x: drawerContentContainer.bounds.minX, y: drawerContentContainer.bounds.minY, width: drawerContentContainer.bounds.width, height: drawerContentContainer.bounds.height)
setDrawerPosition(position: drawerPosition, animated: false)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Configuration Updates
/**
Set the drawer position, with an option to animate.
- parameter position: The position to set the drawer to.
- parameter animated: Whether or not to animate the change. (Default: true)
*/
public func setDrawerPosition(position: PulleyPosition, animated: Bool = true)
{
guard supportedDrawerPositions.contains(position) else {
print("PulleyViewController: You can't set the drawer position to something not supported by the current view controller contained in the drawer. If you haven't already, you may need to implement the PulleyDrawerViewControllerDelegate.")
return
}
drawerPosition = position
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let stopToMoveTo: CGFloat
switch drawerPosition {
case .collapsed:
stopToMoveTo = collapsedHeight
case .partiallyRevealed:
stopToMoveTo = partialRevealHeight
case .open:
stopToMoveTo = (self.view.bounds.size.height - topInset)
case .closed:
stopToMoveTo = 0
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.min() ?? 0
if animated
{
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { [weak self] () -> Void in
self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
if let drawer = self
{
drawer.delegate?.drawerPositionDidChange?(drawer: drawer)
(drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer)
(drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer)
drawer.view.layoutIfNeeded()
}
}, completion: nil)
}
else
{
drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
delegate?.drawerPositionDidChange?(drawer: self)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self)
}
}
/**
Change the current primary content view controller (The one behind the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change. Defaults to true.
*/
public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true)
{
if animated
{
UIView.transition(with: primaryContentContainer, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.primaryContentViewController = controller
}, completion: nil)
}
else
{
primaryContentViewController = controller
}
}
/**
Change the current drawer content view controller (The one inside the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change.
*/
public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true)
{
if animated
{
UIView.transition(with: drawerContentContainer, duration: 0.5, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.drawerContentViewController = controller
self?.setDrawerPosition(position: self?.drawerPosition ?? .closed, animated: false)
}, completion: nil)
}
else
{
drawerContentViewController = controller
setDrawerPosition(position: drawerPosition, animated: false)
}
}
/**
Update the supported drawer positions allows by the Pulley Drawer
*/
public func setNeedsSupportedDrawerPositionsUpdate()
{
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
supportedDrawerPositions = drawerVCCompliant.supportedDrawerPositions()
}
else
{
supportedDrawerPositions = PulleyPosition.all
}
}
// MARK: Actions
func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer)
{
if gestureRecognizer == dimmingViewTapRecognizer
{
if gestureRecognizer.state == .ended
{
self.setDrawerPosition(position: .collapsed, animated: true)
}
}
}
// MARK: Propogate child view controller style / status bar presentation based on drawer state
override open var childViewControllerForStatusBarStyle: UIViewController? {
get {
if drawerPosition == .open {
return drawerContentViewController
}
return primaryContentViewController
}
}
override open var childViewControllerForStatusBarHidden: UIViewController? {
get {
if drawerPosition == .open {
return drawerContentViewController
}
return primaryContentViewController
}
}
}
extension PulleyViewController: PulleyPassthroughScrollViewDelegate {
func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool
{
let contentDrawerLocation = drawerContentContainer.frame.origin.y
if point.y < contentDrawerLocation
{
return true
}
return false
}
func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView
{
if drawerPosition == .open
{
return backgroundDimmingView
}
return primaryContentContainer
}
}
extension PulleyViewController: UIScrollViewDelegate {
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == drawerScrollView
{
// Find the closest anchor point and snap there.
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
var drawerStops: [CGFloat] = [CGFloat]()
if supportedDrawerPositions.contains(.open)
{
drawerStops.append((self.view.bounds.size.height - topInset))
}
if supportedDrawerPositions.contains(.partiallyRevealed)
{
drawerStops.append(partialRevealHeight)
}
if supportedDrawerPositions.contains(.collapsed)
{
drawerStops.append(collapsedHeight)
}
let lowestStop = drawerStops.min() ?? 0
let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y
var currentClosestStop = lowestStop
for currentStop in drawerStops
{
if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView)
{
currentClosestStop = currentStop
}
}
if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= .ulpOfOne && supportedDrawerPositions.contains(.open)
{
setDrawerPosition(position: .open, animated: true)
} else if abs(Float(currentClosestStop - collapsedHeight)) <= .ulpOfOne && supportedDrawerPositions.contains(.collapsed)
{
setDrawerPosition(position: .collapsed, animated: true)
} else if supportedDrawerPositions.contains(.partiallyRevealed){
setDrawerPosition(position: .partiallyRevealed, animated: true)
}
}
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if scrollView == drawerScrollView
{
lastDragTargetContentOffset = targetContentOffset.pointee
// Halt intertia
targetContentOffset.pointee = scrollView.contentOffset
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == drawerScrollView
{
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
var drawerStops: [CGFloat] = [CGFloat]()
if supportedDrawerPositions.contains(.open)
{
drawerStops.append((self.view.bounds.size.height - topInset))
}
if supportedDrawerPositions.contains(.partiallyRevealed)
{
drawerStops.append(partialRevealHeight)
}
if supportedDrawerPositions.contains(.collapsed)
{
drawerStops.append(collapsedHeight)
}
let lowestStop = drawerStops.min() ?? 0
if scrollView.contentOffset.y > partialRevealHeight - lowestStop
{
// Calculate percentage between partial and full reveal
let fullRevealHeight = (self.view.bounds.size.height - topInset)
let progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight))
delegate?.makeUIAdjustmentsForFullscreen?(progress: progress)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress)
backgroundDimmingView.alpha = progress * backgroundDimmingOpacity
backgroundDimmingView.isUserInteractionEnabled = true
}
else
{
if backgroundDimmingView.alpha >= 0.001
{
backgroundDimmingView.alpha = 0.0
delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0)
backgroundDimmingView.isUserInteractionEnabled = false
}
}
delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop)
}
}
}
| eb4acd845b45c88fe523160a39244a40 | 38.788441 | 271 | 0.640026 | false | false | false | false |
LYM-mg/MGDS_Swift | refs/heads/master | MGDS_Swift/MGDS_Swift/Class/Home/Miao/ViewModel/MGNewViewModel.swift | mit | 1 | //
// MGNewViewModel.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/1/19.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class MGNewViewModel: NSObject {
/** 当前页 */
var currentPage: Int = 1
/** 用户 */
var anchors = [MGAnchor]()
}
extension MGNewViewModel {
func getHotData(finishedCallBack: @escaping (_ err: Error?) -> ()) {
NetWorkTools.requestData(type: .get, urlString: "http://live.9158.com/Room/GetNewRoomOnline?page=\(self.currentPage)", succeed: { [unowned self] (result, err) in
guard let result = result as? [String: Any] else { return }
guard let data = result["data"] as? [String: Any] else { return }
guard let dictArr = data["list"] as? [[String: Any]] else { return }
for anchorDict in dictArr {
let anchor = MGAnchor(dict: anchorDict)
self.anchors.append(anchor)
}
finishedCallBack(nil)
}) { (err) in
finishedCallBack(err)
}
}
}
| 409da9fb897eff9c4e5472f6d6d6946e | 29.685714 | 169 | 0.568901 | false | false | false | false |
KinoAndWorld/Meizhi-Swift | refs/heads/master | Meizhi-Swift/Scene/CoverController.swift | apache-2.0 | 1 | //
// CoverController.swift
// Meizhi-Swift
//
// Created by kino on 14/11/26.
// Copyright (c) 2014年 kino. All rights reserved.
//
import UIKit
extension Array {
func find(includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
class CoverController: BaseController , UITableViewDelegate , UITableViewDataSource{
var coverID = ""
var covers:Array<Cover> = []
var loadingView:LoadingView? = nil
@IBOutlet weak var coverTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
prepareData()
}
func prepareData(){
loadingView = LoadingView()
loadingView!.showMe()
if coverID != ""{
CoverManager.fetchCovers(coverID: coverID, andComplete:{
[weak self] covers in
if let strongSelf = self{
strongSelf.loadingView?.hideMe()
if covers.count != 0{
strongSelf.covers = covers
strongSelf.observerCoverSize()
strongSelf.reloadCoversData()
}else{
//handle blank data
}
}
})
}
}
func observerCoverSize(){
for cover in covers{
cover.obseverImageSize = {
[weak self] newSizeCover in
if let sgSelf = self{
let index = sgSelf.covers.find{ $0 == newSizeCover}
if index != nil {
sgSelf.reloadTableByRow(index!)
}
}
}
}
}
func reloadTableByRow(row:Int){
dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in
let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let sgSelf = self{
sgSelf.coverTableView.beginUpdates()
sgSelf.coverTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
sgSelf.coverTableView.endUpdates()
}
})
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return heightForIndexPath(indexPath)
}
func heightForIndexPath(indexPath:NSIndexPath) -> CGFloat{
let model = self.covers[indexPath.row] as Cover
if model.imageSize.height != 0 {
return model.imageSize.height
}else{
return 500
}
}
func reloadCoversData(){
coverTableView.reloadData()
}
//MARK: TableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.covers.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let coverCell = tableView.dequeueReusableCellWithIdentifier("CoverTableCell", forIndexPath: indexPath) as CoverTableCell
let model = self.covers[indexPath.row] as Cover
coverCell.configureCellWithCover(model)
coverCell.touchCellCall = {[weak self] covCell in
if let sSelf = self{
let model = covCell.model! as Cover
let imageInfo = JTSImageInfo()
imageInfo.image = covCell.coverImageView.image
imageInfo.imageURL = NSURL(string: model.imageUrl)
imageInfo.referenceRect = covCell.coverImageView.frame;
imageInfo.referenceView = covCell.coverImageView.superview;
let imageViewer = JTSImageViewController(imageInfo: imageInfo,
mode: JTSImageViewControllerMode.Image,
backgroundStyle: JTSImageViewControllerBackgroundOptions.Blurred)
imageViewer.showFromViewController(self,
transition: JTSImageViewControllerTransition._FromOriginalPosition)
}
}
return coverCell
}
}
| 238a7d7aaa7b3264911776b96519d2a5 | 31.511278 | 128 | 0.555273 | false | false | false | false |
hooman/swift | refs/heads/main | test/AutoDiff/stdlib/anydifferentiable.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off)
// REQUIRES: executable_test
import _Differentiation
import StdlibUnittest
var TypeErasureTests = TestSuite("DifferentiableTypeErasure")
struct Vector: Differentiable, Equatable {
var x, y: Float
}
struct Generic<T: Differentiable & Equatable>: Differentiable, Equatable {
var x: T
}
extension AnyDerivative {
// This exists only to faciliate testing.
func moved(along offset: TangentVector) -> Self {
var result = self
result.move(by: offset)
return result
}
}
TypeErasureTests.test("AnyDifferentiable operations") {
do {
var any = AnyDifferentiable(Vector(x: 1, y: 1))
let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
any.move(by: tan)
expectEqual(Vector(x: 2, y: 2), any.base as? Vector)
}
do {
var any = AnyDifferentiable(Generic<Float>(x: 1))
let tan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
any.move(by: tan)
expectEqual(Generic<Float>(x: 2), any.base as? Generic<Float>)
}
}
TypeErasureTests.test("AnyDerivative operations") {
do {
var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
tan += tan
expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan + tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 0, y: 0)), tan - tan)
expectEqual(AnyDerivative(Vector.TangentVector(x: 4, y: 4)), tan.moved(along: tan))
expectEqual(AnyDerivative(Vector.TangentVector(x: 2, y: 2)), tan)
}
do {
var tan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
tan += tan
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 2)), tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan + tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 0)), tan - tan)
expectEqual(AnyDerivative(Generic<Float>.TangentVector(x: 4)), tan.moved(along: tan))
}
}
TypeErasureTests.test("AnyDerivative.zero") {
var zero = AnyDerivative.zero
zero += zero
zero -= zero
expectEqual(zero, zero + zero)
expectEqual(zero, zero - zero)
expectEqual(zero, zero.moved(along: zero))
var tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
expectEqual(zero, zero)
expectEqual(AnyDerivative(Vector.TangentVector.zero), tan - tan)
expectNotEqual(AnyDerivative(Vector.TangentVector.zero), zero)
expectNotEqual(AnyDerivative.zero, tan - tan)
tan += zero
tan -= zero
expectEqual(tan, tan + zero)
expectEqual(tan, tan - zero)
expectEqual(tan, tan.moved(along: zero))
expectEqual(tan, zero.moved(along: tan))
expectEqual(zero, zero)
expectEqual(tan, tan)
}
TypeErasureTests.test("AnyDifferentiable casting") {
let any = AnyDifferentiable(Vector(x: 1, y: 1))
expectEqual(Vector(x: 1, y: 1), any.base as? Vector)
let genericAny = AnyDifferentiable(Generic<Float>(x: 1))
expectEqual(Generic<Float>(x: 1),
genericAny.base as? Generic<Float>)
expectEqual(nil, genericAny.base as? Generic<Double>)
}
TypeErasureTests.test("AnyDifferentiable reflection") {
let originalVector = Vector(x: 1, y: 1)
let vector = AnyDifferentiable(originalVector)
let mirror = Mirror(reflecting: vector)
let children = Array(mirror.children)
expectEqual(2, children.count)
expectEqual(["x", "y"], children.map(\.label))
expectEqual([originalVector.x, originalVector.y], children.map { $0.value as! Float })
}
TypeErasureTests.test("AnyDerivative casting") {
let tan = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
expectEqual(Vector.TangentVector(x: 1, y: 1), tan.base as? Vector.TangentVector)
let genericTan = AnyDerivative(Generic<Float>.TangentVector(x: 1))
expectEqual(Generic<Float>.TangentVector(x: 1),
genericTan.base as? Generic<Float>.TangentVector)
expectEqual(nil, genericTan.base as? Generic<Double>.TangentVector)
let zero = AnyDerivative.zero
expectEqual(nil, zero.base as? Float)
expectEqual(nil, zero.base as? Vector.TangentVector)
expectEqual(nil, zero.base as? Generic<Float>.TangentVector)
}
TypeErasureTests.test("AnyDerivative reflection") {
let originalTan = Vector.TangentVector(x: 1, y: 1)
let tan = AnyDerivative(originalTan)
let mirror = Mirror(reflecting: tan)
let children = Array(mirror.children)
expectEqual(2, children.count)
expectEqual(["x", "y"], children.map(\.label))
expectEqual([originalTan.x, originalTan.y], children.map { $0.value as! Float })
}
TypeErasureTests.test("AnyDifferentiable differentiation") {
// Test `AnyDifferentiable` initializer.
do {
let x: Float = 3
let v = AnyDerivative(Float(2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP: Float = 2
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Vector(x: 4, y: 5)
let v = AnyDerivative(Vector.TangentVector(x: 2, y: 2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP = Vector.TangentVector(x: 2, y: 2)
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Generic<Double>(x: 4)
let v = AnyDerivative(Generic<Double>.TangentVector(x: 2))
let 𝛁x = pullback(at: x, of: { AnyDifferentiable($0) })(v)
let expectedVJP = Generic<Double>.TangentVector(x: 2)
expectEqual(expectedVJP, 𝛁x)
}
}
TypeErasureTests.test("AnyDerivative differentiation") {
// Test `AnyDerivative` operations.
func tripleSum(_ x: AnyDerivative, _ y: AnyDerivative) -> AnyDerivative {
let sum = x + y
return sum + sum + sum
}
do {
let x = AnyDerivative(Float(4))
let y = AnyDerivative(Float(-2))
let v = AnyDerivative(Float(1))
let expectedVJP: Float = 3
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Float)
expectEqual(expectedVJP, 𝛁y.base as? Float)
}
do {
let x = AnyDerivative(Vector.TangentVector(x: 4, y: 5))
let y = AnyDerivative(Vector.TangentVector(x: -2, y: -1))
let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
let expectedVJP = Vector.TangentVector(x: 3, y: 3)
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Vector.TangentVector)
expectEqual(expectedVJP, 𝛁y.base as? Vector.TangentVector)
}
do {
let x = AnyDerivative(Generic<Double>.TangentVector(x: 4))
let y = AnyDerivative(Generic<Double>.TangentVector(x: -2))
let v = AnyDerivative(Generic<Double>.TangentVector(x: 1))
let expectedVJP = Generic<Double>.TangentVector(x: 3)
let (𝛁x, 𝛁y) = pullback(at: x, y, of: tripleSum)(v)
expectEqual(expectedVJP, 𝛁x.base as? Generic<Double>.TangentVector)
expectEqual(expectedVJP, 𝛁y.base as? Generic<Double>.TangentVector)
}
// Test `AnyDerivative` initializer.
func typeErased<T>(_ x: T) -> AnyDerivative
where T: Differentiable, T.TangentVector == T {
let any = AnyDerivative(x)
return any + any
}
do {
let x: Float = 3
let v = AnyDerivative(Float(1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP: Float = 2
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Vector.TangentVector(x: 4, y: 5)
let v = AnyDerivative(Vector.TangentVector(x: 1, y: 1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP = Vector.TangentVector(x: 2, y: 2)
expectEqual(expectedVJP, 𝛁x)
}
do {
let x = Generic<Double>.TangentVector(x: 4)
let v = AnyDerivative(Generic<Double>.TangentVector(x: 1))
let 𝛁x = pullback(at: x, of: { x in typeErased(x) })(v)
let expectedVJP = Generic<Double>.TangentVector(x: 2)
expectEqual(expectedVJP, 𝛁x)
}
}
runAllTests()
| b35004fd5b5ff1cd104409aa35175203 | 32.471616 | 89 | 0.683757 | false | true | false | false |
CPRTeam/CCIP-iOS | refs/heads/master | Pods/Nuke/Sources/ImageProcessing.swift | gpl-3.0 | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015-2020 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
#if os(watchOS)
import WatchKit
#endif
#if os(macOS)
import Cocoa
#endif
// MARK: - ImageProcessing
/// Performs image processing.
///
/// For basic processing needs, implement the following method:
///
/// ```
/// func process(image: PlatformImage) -> PlatformImage?
/// ```
///
/// If your processor needs to manipulate image metadata (`ImageContainer`), or
/// get access to more information via the context (`ImageProcessingContext`),
/// there is an additional method that allows you to do that:
///
/// ```
/// func process(image container: ImageContainer, context: ImageProcessingContext) -> ImageContainer?
/// ```
///
/// You must implement either one of those methods.
public protocol ImageProcessing {
/// Returns a processed image. By default, returns `nil`.
///
/// - note: Gets called a background queue managed by the pipeline.
func process(_ image: PlatformImage) -> PlatformImage?
/// Returns a processed image. By default, this calls the basic `process(image:)` method.
///
/// - note: Gets called a background queue managed by the pipeline.
func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer?
/// Returns a string that uniquely identifies the processor.
///
/// Consider using the reverse DNS notation.
var identifier: String { get }
/// Returns a unique processor identifier.
///
/// The default implementation simply returns `var identifier: String` but
/// can be overridden as a performance optimization - creating and comparing
/// strings is _expensive_ so you can opt-in to return something which is
/// fast to create and to compare. See `ImageProcessors.Resize` for an example.
///
/// - note: A common approach is to make your processor `Hashable` and return `self`
/// from `hashableIdentifier`.
var hashableIdentifier: AnyHashable { get }
}
public extension ImageProcessing {
/// The default implementation simply calls the basic
/// `process(_ image: PlatformImage) -> PlatformImage?` method.
func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? {
container.map(process)
}
/// The default impleemntation simply returns `var identifier: String`.
var hashableIdentifier: AnyHashable { identifier }
}
/// Image processing context used when selecting which processor to use.
public struct ImageProcessingContext {
public let request: ImageRequest
public let response: ImageResponse
public let isFinal: Bool
public init(request: ImageRequest, response: ImageResponse, isFinal: Bool) {
self.request = request
self.response = response
self.isFinal = isFinal
}
}
// MARK: - ImageProcessors
/// A namespace for all processors that implement `ImageProcessing` protocol.
public enum ImageProcessors {}
// MARK: - ImageProcessors.Resize
extension ImageProcessors {
/// Scales an image to a specified size.
public struct Resize: ImageProcessing, Hashable, CustomStringConvertible {
private let size: CGSize
private let contentMode: ContentMode
private let crop: Bool
private let upscale: Bool
/// An option for how to resize the image.
public enum ContentMode: CustomStringConvertible {
/// Scales the image so that it completely fills the target area.
/// Maintains the aspect ratio of the original image.
case aspectFill
/// Scales the image so that it fits the target size. Maintains the
/// aspect ratio of the original image.
case aspectFit
public var description: String {
switch self {
case .aspectFill: return ".aspectFill"
case .aspectFit: return ".aspectFit"
}
}
}
/// Initializes the processor with the given size.
///
/// - parameter size: The target size.
/// - parameter unit: Unit of the target size, `.points` by default.
/// - parameter contentMode: `.aspectFill` by default.
/// - parameter crop: If `true` will crop the image to match the target size.
/// Does nothing with content mode .aspectFill. `false` by default.
/// - parameter upscale: `false` by default.
public init(size: CGSize, unit: ImageProcessingOptions.Unit = .points, contentMode: ContentMode = .aspectFill, crop: Bool = false, upscale: Bool = false) {
self.size = CGSize(size: size, unit: unit)
self.contentMode = contentMode
self.crop = crop
self.upscale = upscale
}
/// Resizes the image to the given width preserving aspect ratio.
///
/// - parameter unit: Unit of the target size, `.points` by default.
public init(width: CGFloat, unit: ImageProcessingOptions.Unit = .points, crop: Bool = false, upscale: Bool = false) {
self.init(size: CGSize(width: width, height: 4096), unit: unit, contentMode: .aspectFit, crop: crop, upscale: upscale)
}
/// Resizes the image to the given height preserving aspect ratio.
///
/// - parameter unit: Unit of the target size, `.points` by default.
public init(height: CGFloat, unit: ImageProcessingOptions.Unit = .points, crop: Bool = false, upscale: Bool = false) {
self.init(size: CGSize(width: 4096, height: height), unit: unit, contentMode: .aspectFit, crop: crop, upscale: upscale)
}
public func process(_ image: PlatformImage) -> PlatformImage? {
if crop && contentMode == .aspectFill {
return image.processed.byResizingAndCropping(to: size)
} else {
return image.processed.byResizing(to: size, contentMode: contentMode, upscale: upscale)
}
}
public var identifier: String {
"com.github.kean/nuke/resize?s=\(size),cm=\(contentMode),crop=\(crop),upscale=\(upscale)"
}
public var hashableIdentifier: AnyHashable { self }
public var description: String {
"Resize(size: \(size) pixels, contentMode: \(contentMode), crop: \(crop), upscale: \(upscale))"
}
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
// MARK: - ImageProcessors.Circle
extension ImageProcessors {
/// Rounds the corners of an image into a circle. If the image is not a square,
/// crops it to a square first.
public struct Circle: ImageProcessing, Hashable, CustomStringConvertible {
private let border: ImageProcessingOptions.Border?
public init(border: ImageProcessingOptions.Border? = nil) {
self.border = border
}
public func process(_ image: PlatformImage) -> PlatformImage? {
image.processed.byDrawingInCircle(border: border)
}
public var identifier: String {
if let border = self.border {
return "com.github.kean/nuke/circle?border=\(border)"
} else {
return "com.github.kean/nuke/circle"
}
}
public var hashableIdentifier: AnyHashable { self }
public var description: String {
"Circle(border: \(border?.description ?? "nil"))"
}
}
}
// MARK: - ImageProcessors.RoundedCorners
extension ImageProcessors {
/// Rounds the corners of an image to the specified radius.
///
/// - warning: In order for the corners to be displayed correctly, the image must exactly match the size
/// of the image view in which it will be displayed. See `ImageProcessor.Resize` for more info.
public struct RoundedCorners: ImageProcessing, Hashable, CustomStringConvertible {
private let radius: CGFloat
private let border: ImageProcessingOptions.Border?
/// Initializes the processor with the given radius.
///
/// - parameter radius: The radius of the corners.
/// - parameter unit: Unit of the radius, `.points` by default.
/// - parameter border: An optional border drawn around the image.
public init(radius: CGFloat, unit: ImageProcessingOptions.Unit = .points, border: ImageProcessingOptions.Border? = nil) {
self.radius = radius.converted(to: unit)
self.border = border
}
public func process(_ image: PlatformImage) -> PlatformImage? {
image.processed.byAddingRoundedCorners(radius: radius, border: border)
}
public var identifier: String {
if let border = self.border {
return "com.github.kean/nuke/rounded_corners?radius=\(radius),border=\(border)"
} else {
return "com.github.kean/nuke/rounded_corners?radius=\(radius)"
}
}
public var hashableIdentifier: AnyHashable { self }
public var description: String {
"RoundedCorners(radius: \(radius) pixels, border: \(border?.description ?? "nil"))"
}
}
}
#if os(iOS) || os(tvOS)
// MARK: - ImageProcessors.CoreImageFilter
import CoreImage
extension ImageProcessors {
/// Applies Core Image filter (`CIFilter`) to the image.
///
/// # Performance Considerations.
///
/// Prefer chaining multiple `CIFilter` objects using `Core Image` facilities
/// instead of using multiple instances of `ImageProcessors.CoreImageFilter`.
///
/// # References
///
/// - [Core Image Programming Guide](https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_intro/ci_intro.html)
/// - [Core Image Filter Reference](https://developer.apple.com/library/prerelease/ios/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html)
public struct CoreImageFilter: ImageProcessing, CustomStringConvertible {
private let name: String
private let parameters: [String: Any]
public let identifier: String
/// - parameter identifier: Uniquely identifies the processor.
public init(name: String, parameters: [String: Any], identifier: String) {
self.name = name
self.parameters = parameters
self.identifier = identifier
}
public init(name: String) {
self.name = name
self.parameters = [:]
self.identifier = "com.github.kean/nuke/core_image?name=\(name))"
}
public func process(_ image: PlatformImage) -> PlatformImage? {
let filter = CIFilter(name: name, parameters: parameters)
return CoreImageFilter.apply(filter: filter, to: image)
}
// MARK: - Apply Filter
/// A default context shared between all Core Image filters. The context
/// has `.priorityRequestLow` option set to `true`.
public static var context = CIContext(options: [.priorityRequestLow: true])
public static func apply(filter: CIFilter?, to image: UIImage) -> UIImage? {
guard let filter = filter else {
return nil
}
return applyFilter(to: image) {
filter.setValue($0, forKey: kCIInputImageKey)
return filter.outputImage
}
}
static func applyFilter(to image: UIImage, context: CIContext = context, closure: (CoreImage.CIImage) -> CoreImage.CIImage?) -> UIImage? {
let ciImage: CoreImage.CIImage? = {
if let image = image.ciImage {
return image
}
if let image = image.cgImage {
return CoreImage.CIImage(cgImage: image)
}
return nil
}()
guard let inputImage = ciImage, let outputImage = closure(inputImage) else {
return nil
}
guard let imageRef = context.createCGImage(outputImage, from: outputImage.extent) else {
return nil
}
return UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
}
public var description: String {
"CoreImageFilter(name: \(name), parameters: \(parameters))"
}
}
}
// MARK: - ImageProcessors.GaussianBlur
extension ImageProcessors {
/// Blurs an image using `CIGaussianBlur` filter.
public struct GaussianBlur: ImageProcessing, Hashable, CustomStringConvertible {
private let radius: Int
/// Initializes the receiver with a blur radius.
public init(radius: Int = 8) {
self.radius = radius
}
/// Applies `CIGaussianBlur` filter to the image.
public func process(_ image: PlatformImage) -> PlatformImage? {
let filter = CIFilter(name: "CIGaussianBlur", parameters: ["inputRadius": radius])
return CoreImageFilter.apply(filter: filter, to: image)
}
public var identifier: String {
"com.github.kean/nuke/gaussian_blur?radius=\(radius)"
}
public var hashableIdentifier: AnyHashable { self }
public var description: String {
"GaussianBlur(radius: \(radius))"
}
}
}
#endif
// MARK: - ImageDecompression (Internal)
struct ImageDecompression {
func decompress(image: UIImage) -> UIImage {
let output = image.decompressed() ?? image
ImageDecompression.setDecompressionNeeded(false, for: output)
return output
}
// MARK: Managing Decompression State
static var isDecompressionNeededAK = "ImageDecompressor.isDecompressionNeeded.AssociatedKey"
static func setDecompressionNeeded(_ isDecompressionNeeded: Bool, for image: UIImage) {
objc_setAssociatedObject(image, &isDecompressionNeededAK, isDecompressionNeeded, .OBJC_ASSOCIATION_RETAIN)
}
static func isDecompressionNeeded(for image: UIImage) -> Bool? {
objc_getAssociatedObject(image, &isDecompressionNeededAK) as? Bool
}
}
#endif
// MARK: - ImageProcessors.Composition
extension ImageProcessors {
/// Composes multiple processors.
public struct Composition: ImageProcessing, Hashable, CustomStringConvertible {
let processors: [ImageProcessing]
/// Composes multiple processors.
public init(_ processors: [ImageProcessing]) {
// note: multiple compositions are not flatten by default.
self.processors = processors
}
public func process(_ image: PlatformImage) -> PlatformImage? {
processors.reduce(image) { image, processor in
autoreleasepool {
image.flatMap { processor.process($0) }
}
}
}
/// Processes the given image by applying each processor in an order in
/// which they were added. If one of the processors fails to produce
/// an image the processing stops and `nil` is returned.
public func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? {
processors.reduce(container) { container, processor in
autoreleasepool {
container.flatMap { processor.process($0, context: context) }
}
}
}
public var identifier: String {
processors.map({ $0.identifier }).joined()
}
public var hashableIdentifier: AnyHashable { self }
public func hash(into hasher: inout Hasher) {
for processor in processors {
hasher.combine(processor.hashableIdentifier)
}
}
public static func == (lhs: Composition, rhs: Composition) -> Bool {
lhs.processors == rhs.processors
}
public var description: String {
"Composition(processors: \(processors))"
}
}
}
// MARK: - ImageProcessors.Anonymous
extension ImageProcessors {
/// Processed an image using a specified closure.
public struct Anonymous: ImageProcessing, CustomStringConvertible {
public let identifier: String
private let closure: (PlatformImage) -> PlatformImage?
public init(id: String, _ closure: @escaping (PlatformImage) -> PlatformImage?) {
self.identifier = id
self.closure = closure
}
public func process(_ image: PlatformImage) -> PlatformImage? {
self.closure(image)
}
public var description: String {
"AnonymousProcessor(identifier: \(identifier)"
}
}
}
// MARK: - Image Processing (Internal)
extension PlatformImage {
/// Draws the image in a `CGContext` in a canvas with the given size using
/// the specified draw rect.
///
/// For example, if the canvas size is `CGSize(width: 10, height: 10)` and
/// the draw rect is `CGRect(x: -5, y: 0, width: 20, height: 10)` it would
/// draw the input image (which is horizontal based on the known draw rect)
/// in a square by centering it in the canvas.
///
/// - parameter drawRect: `nil` by default. If `nil` will use the canvas rect.
func draw(inCanvasWithSize canvasSize: CGSize, drawRect: CGRect? = nil) -> PlatformImage? {
guard let cgImage = cgImage else {
return nil
}
// For more info see:
// - Quartz 2D Programming Guide
// - https://github.com/kean/Nuke/issues/35
// - https://github.com/kean/Nuke/issues/57
let alphaInfo: CGImageAlphaInfo = cgImage.isOpaque ? .noneSkipLast : .premultipliedLast
guard let ctx = CGContext(
data: nil,
width: Int(canvasSize.width), height: Int(canvasSize.height),
bitsPerComponent: 8, bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: alphaInfo.rawValue) else {
return nil
}
ctx.draw(cgImage, in: drawRect ?? CGRect(origin: .zero, size: canvasSize))
guard let outputCGImage = ctx.makeImage() else {
return nil
}
return PlatformImage.make(cgImage: outputCGImage, source: self)
}
/// Decompresses the input image by drawing in the the `CGContext`.
func decompressed() -> PlatformImage? {
guard let cgImage = cgImage else {
return nil
}
return draw(inCanvasWithSize: cgImage.size, drawRect: CGRect(origin: .zero, size: cgImage.size))
}
}
// MARK: - ImageProcessingExtensions
extension PlatformImage {
var processed: ImageProcessingExtensions {
ImageProcessingExtensions(image: self)
}
}
struct ImageProcessingExtensions {
let image: PlatformImage
func byResizing(to targetSize: CGSize,
contentMode: ImageProcessors.Resize.ContentMode,
upscale: Bool) -> PlatformImage? {
guard let cgImage = image.cgImage else {
return nil
}
let scale = contentMode == .aspectFill ?
cgImage.size.scaleToFill(targetSize) :
cgImage.size.scaleToFit(targetSize)
guard scale < 1 || upscale else {
return image // The image doesn't require scaling
}
let size = cgImage.size.scaled(by: scale).rounded()
return image.draw(inCanvasWithSize: size)
}
/// Crops the input image to the given size and resizes it if needed.
/// - note: this method will always upscale.
func byResizingAndCropping(to targetSize: CGSize) -> PlatformImage? {
guard let cgImage = image.cgImage else {
return nil
}
let imageSize = cgImage.size
let scaledSize = imageSize.scaled(by: cgImage.size.scaleToFill(targetSize))
let drawRect = scaledSize.centeredInRectWithSize(targetSize)
return image.draw(inCanvasWithSize: targetSize, drawRect: drawRect)
}
#if os(iOS) || os(tvOS) || os(watchOS)
func byDrawingInCircle(border: ImageProcessingOptions.Border?) -> UIImage? {
guard let squared = byCroppingToSquare(), let cgImage = squared.cgImage else {
return nil
}
let radius = CGFloat(cgImage.width) / 2.0 // Can use any dimension since image is a square
return squared.processed.byAddingRoundedCorners(radius: radius, border: border)
}
/// Draws an image in square by preserving an aspect ratio and filling the
/// square if needed. If the image is already a square, returns an original image.
func byCroppingToSquare() -> UIImage? {
guard let cgImage = image.cgImage else {
return nil
}
guard cgImage.width != cgImage.height else {
return image // Already a square
}
let imageSize = cgImage.size
let side = min(cgImage.width, cgImage.height)
let targetSize = CGSize(width: side, height: side)
let cropRect = CGRect(origin: .zero, size: targetSize).offsetBy(
dx: max(0, (imageSize.width - targetSize.width) / 2),
dy: max(0, (imageSize.height - targetSize.height) / 2)
)
guard let cropped = cgImage.cropping(to: cropRect) else {
return nil
}
return UIImage(cgImage: cropped, scale: image.scale, orientation: image.imageOrientation)
}
/// Adds rounded corners with the given radius to the image.
/// - parameter radius: Radius in pixels.
/// - parameter border: Optional stroke border.
func byAddingRoundedCorners(radius: CGFloat, border: ImageProcessingOptions.Border? = nil) -> UIImage? {
guard let cgImage = image.cgImage else {
return nil
}
let imageSize = cgImage.size
UIGraphicsBeginImageContextWithOptions(imageSize, false, 1.0)
defer { UIGraphicsEndImageContext() }
let rect = CGRect(origin: CGPoint.zero, size: imageSize)
let clippingPath = UIBezierPath(roundedRect: rect, cornerRadius: radius)
clippingPath.addClip()
image.draw(in: CGRect(origin: CGPoint.zero, size: imageSize))
if let border = border, let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(border.color.cgColor)
let path = UIBezierPath(roundedRect: rect, cornerRadius: radius)
path.lineWidth = border.width
path.stroke()
}
guard let roundedImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
return nil
}
return UIImage(cgImage: roundedImage, scale: image.scale, orientation: image.imageOrientation)
}
#endif
}
// MARK: - CoreGraphics Helpers (Internal)
#if os(macOS)
extension NSImage {
var cgImage: CGImage? {
cgImage(forProposedRect: nil, context: nil, hints: nil)
}
static func make(cgImage: CGImage, source: NSImage) -> NSImage {
NSImage(cgImage: cgImage, size: .zero)
}
}
#else
extension UIImage {
static func make(cgImage: CGImage, source: UIImage) -> UIImage {
UIImage(cgImage: cgImage, scale: source.scale, orientation: source.imageOrientation)
}
}
#endif
extension CGImage {
/// Returns `true` if the image doesn't contain alpha channel.
var isOpaque: Bool {
let alpha = alphaInfo
return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast
}
var size: CGSize {
CGSize(width: width, height: height)
}
}
extension CGFloat {
func converted(to unit: ImageProcessingOptions.Unit) -> CGFloat {
switch unit {
case .pixels: return self
case .points: return self * Screen.scale
}
}
}
extension CGSize: Hashable { // For some reason `CGSize` isn't `Hashable`
public func hash(into hasher: inout Hasher) {
hasher.combine(width)
hasher.combine(height)
}
}
extension CGSize {
/// Creates the size in pixels by scaling to the input size to the screen scale
/// if needed.
init(size: CGSize, unit: ImageProcessingOptions.Unit) {
switch unit {
case .pixels: self = size // The size is already in pixels
case .points: self = size.scaled(by: Screen.scale)
}
}
func scaled(by scale: CGFloat) -> CGSize {
CGSize(width: width * scale, height: height * scale)
}
func rounded() -> CGSize {
CGSize(width: CGFloat(round(width)), height: CGFloat(round(height)))
}
}
extension CGSize {
func scaleToFill(_ targetSize: CGSize) -> CGFloat {
let scaleHor = targetSize.width / width
let scaleVert = targetSize.height / height
return max(scaleHor, scaleVert)
}
func scaleToFit(_ targetSize: CGSize) -> CGFloat {
let scaleHor = targetSize.width / width
let scaleVert = targetSize.height / height
return min(scaleHor, scaleVert)
}
/// Calculates a rect such that the output rect will be in the center of
/// the rect of the input size (assuming origin: .zero)
func centeredInRectWithSize(_ targetSize: CGSize) -> CGRect {
// First, resize the original size to fill the target size.
CGRect(origin: .zero, size: self).offsetBy(
dx: -(width - targetSize.width) / 2,
dy: -(height - targetSize.height) / 2
)
}
}
// MARK: - ImageProcessing Extensions (Internal)
func == (lhs: [ImageProcessing], rhs: [ImageProcessing]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
// Lazily creates `hashableIdentifiers` because for some processors the
// identifiers might be expensive to compute.
return zip(lhs, rhs).allSatisfy {
$0.hashableIdentifier == $1.hashableIdentifier
}
}
// MARK: - ImageProcessingOptions
public enum ImageProcessingOptions {
public enum Unit: CustomStringConvertible {
case points
case pixels
public var description: String {
switch self {
case .points: return "points"
case .pixels: return "pixels"
}
}
}
#if os(iOS) || os(tvOS) || os(watchOS)
/// Draws a border.
///
/// - warning: To make sure that the border looks the way you expect,
/// make sure that the images you display exactly match the size of the
/// views in which they get displayed. If you can't guarantee that, pleasee
/// consider adding border to a view layer. This should be your primary
/// option regardless.
public struct Border: Hashable, CustomStringConvertible {
public let color: UIColor
public let width: CGFloat
/// - parameter color: Border color.
/// - parameter width: Border width. 1 points by default.
/// - parameter unit: Unit of the width, `.points` by default.
public init(color: UIColor, width: CGFloat = 1, unit: Unit = .points) {
self.color = color
self.width = width.converted(to: unit)
}
public var description: String {
"Border(color: \(color.hex), width: \(width) pixels)"
}
}
#endif
}
// MARK: - Misc (Internal)
struct Screen {
#if os(iOS) || os(tvOS)
/// Returns the current screen scale.
static var scale: CGFloat { UIScreen.main.scale }
#elseif os(watchOS)
/// Returns the current screen scale.
static var scale: CGFloat { WKInterfaceDevice.current().screenScale }
#elseif os(macOS)
/// Always returns 1.
static var scale: CGFloat { 1 }
#endif
}
#if os(iOS) || os(tvOS) || os(watchOS)
extension UIColor {
/// Returns a hex representation of the color, e.g. "#FFFFAA".
var hex: String {
var (r, g, b, a) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))
getRed(&r, green: &g, blue: &b, alpha: &a)
let components = [r, g, b, a < 1 ? a : nil]
return "#" + components
.compactMap { $0 }
.map { String(format: "%02lX", lroundf(Float($0) * 255)) }
.joined()
}
}
#endif
| 0cd82e29b8257c32888ba4faac1fd3cf | 34.21 | 167 | 0.627734 | false | false | false | false |
jens-maus/Frameless | refs/heads/master | Frameless/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Unframed
//
// Created by Jay Stakelon on 10/23/14.
// Copyright (c) 2014 Jay Stakelon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
setUserSettingsDefaults()
if let lastIntro: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.IntroVersionSeen.rawValue) {
setupAppViewController(false)
} else {
self.window!.rootViewController = createIntroViewController()
self.window!.makeKeyAndVisible()
}
UIButton.appearance().tintColor = UIColorFromHex(0x9178E2)
return true
}
func setUserSettingsDefaults() {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ShakeGesture.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(true, forKey: AppDefaultKeys.ShakeGesture.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.PanFromBottomGesture.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(true, forKey: AppDefaultKeys.PanFromBottomGesture.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.TripleTapGesture.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(true, forKey: AppDefaultKeys.TripleTapGesture.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ForwardBackGesture.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(true, forKey: AppDefaultKeys.ForwardBackGesture.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.NoBounceAnimation.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(false, forKey: AppDefaultKeys.NoBounceAnimation.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.FramerBonjour.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(true, forKey: AppDefaultKeys.FramerBonjour.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.KeepAwake.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(false, forKey: AppDefaultKeys.KeepAwake.rawValue)
} else {
let isIdleTimer = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.KeepAwake.rawValue) as? Bool
UIApplication.sharedApplication().idleTimerDisabled = isIdleTimer!
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.HomePage.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue("", forKey: AppDefaultKeys.HomePage.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ScreenIdleTimeout.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue("", forKey: AppDefaultKeys.ScreenIdleTimeout.rawValue)
}
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.MotionDetection.rawValue) == nil {
NSUserDefaults.standardUserDefaults().setValue(false, forKey: AppDefaultKeys.MotionDetection.rawValue)
}
}
func createIntroViewController() -> OnboardingViewController {
let page01: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Frameless is a chromeless,\nfull-screen web browser. Load a\npage and everything else hides", image: UIImage(named: "introimage01"), buttonText: nil) {
}
page01.iconWidth = 158
page01.iconHeight = 258.5
let page02: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Swipe up, tap with three fingers\nor shake the device to show\nthe browser bar and keyboard", image: UIImage(named: "introimage02"), buttonText: nil) {
}
page02.iconWidth = 158
page02.iconHeight = 258.5
let page03: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Swipe left and right to go\nforward and back in your\nsession history", image: UIImage(named: "introimage03"), buttonText: nil) {
self.introCompletion()
}
page03.iconWidth = 158
page03.iconHeight = 258.5
let page04: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "And disable any of the gestures\nif they get in your way", image: UIImage(named: "introimage04"), buttonText: "LET'S GO!") {
self.introCompletion()
}
page04.iconWidth = 158
page04.iconHeight = 258.5
let bgImage = UIImage.withColor(UIColorFromHex(0x9178E2))
let onboardingViewController = PortraitOnboardingViewController(
backgroundImage: bgImage,
contents: [page01, page02, page03, page04])
onboardingViewController.fontName = "ClearSans"
onboardingViewController.bodyFontSize = 16
onboardingViewController.titleFontName = "ClearSans-Bold"
onboardingViewController.titleFontSize = 22
onboardingViewController.buttonFontName = "ClearSans-Bold"
onboardingViewController.buttonFontSize = 20
onboardingViewController.topPadding = 60+(self.window!.frame.height/12)
onboardingViewController.underTitlePadding = 8
onboardingViewController.shouldMaskBackground = false
return onboardingViewController
}
func introCompletion() {
NSUserDefaults.standardUserDefaults().setValue(1, forKey: AppDefaultKeys.IntroVersionSeen.rawValue)
setupAppViewController(true)
}
func setupAppViewController(animated : Bool) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appViewController = storyboard.instantiateViewControllerWithIdentifier("mainViewController") as! UIViewController
if animated {
UIView.transitionWithView(self.window!, duration: 0.5, options:UIViewAnimationOptions.TransitionFlipFromBottom, animations: { () -> Void in
self.window!.rootViewController = appViewController
}, completion:nil)
}
else {
self.window?.rootViewController = appViewController
}
self.window!.makeKeyAndVisible()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
if let appViewController = self.window?.rootViewController as? ViewController {
appViewController.resetScreenIdleTimer(fadeScreen: false)
}
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
if let appViewController = self.window?.rootViewController as? ViewController {
appViewController.resetScreenIdleTimer(fadeScreen: false)
}
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
if let appViewController = self.window?.rootViewController as? ViewController {
appViewController.resetScreenIdleTimer(fadeScreen: false)
}
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if let appViewController = self.window?.rootViewController as? ViewController {
appViewController.resetScreenIdleTimer(fadeScreen: false)
}
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
if let appViewController = self.window?.rootViewController as? ViewController {
appViewController.resetScreenIdleTimer(fadeScreen: false)
}
}
}
| d1b8779afffcf86ca7bfe0448c97ffd7 | 53.656977 | 285 | 0.715562 | false | false | false | false |
JGiola/swift | refs/heads/main | test/IRGen/MachO-objc-sections.swift | apache-2.0 | 10 | // RUN: %swift -target arm64-apple-ios8.0 -disable-legacy-type-info -parse-stdlib -enable-objc-interop -disable-objc-attr-requires-foundation-module -I %S/Inputs/usr/include -emit-ir %s -o - | %FileCheck %s -check-prefix CHECK-MACHO
// REQUIRES: OS=ios
import ObjCInterop
@objc
class C {
}
extension C : P {
public func method() {
f(I())
}
}
@_objc_non_lazy_realization
class D {
}
// CHECK-MACHO: @"$s4main1CCMf" = {{.*}}, section "__DATA,__objc_data, regular"
// CHECK-MACHO: @"\01l_OBJC_LABEL_PROTOCOL_$_P" = {{.*}}, section "__DATA,__objc_protolist,coalesced,no_dead_strip"
// CHECK-MACHO: @"\01l_OBJC_PROTOCOL_REFERENCE_$_P" = {{.*}}, section "__DATA,__objc_protorefs,coalesced,no_dead_strip"
// CHECK-MACHO: @"objc_classes_$s4main1CCN" = {{.*}}, section "__DATA,__objc_classlist,regular,no_dead_strip"
// CHECK-MACHO: @"objc_classes_$s4main1DCN" = {{.*}}, section "__DATA,__objc_classlist,regular,no_dead_strip"
// CHECK-MACHO: @objc_categories = {{.*}}, section "__DATA,__objc_catlist,regular,no_dead_strip"
// CHECK-MACHO: @objc_non_lazy_classes = {{.*}}, section "__DATA,__objc_nlclslist,regular,no_dead_strip"
| 5736349c0eb46315538e7f4437c55eb0 | 39.535714 | 232 | 0.662555 | false | false | false | false |
SugarRecord/SugarRecord | refs/heads/master | Example/SugarRecord/Source/Main/ViewController.swift | mit | 6 | import UIKit
import SnapKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Attributes
lazy var tableView: UITableView = {
let _tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
_tableView.translatesAutoresizingMaskIntoConstraints = false
_tableView.delegate = self
_tableView.dataSource = self
_tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "default-cell")
return _tableView
}()
// MARK: - Init
init() {
super.init(nibName: nil, bundle: nil)
self.title = "SugarRecord Examples"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: - Setup
fileprivate func setup() {
setupView()
setupTableView()
}
fileprivate func setupView() {
self.view.backgroundColor = UIColor.white
}
fileprivate func setupTableView() {
self.view.addSubview(tableView)
self.tableView.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.view)
}
}
// MARK: - UITableViewDataSource / UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "default-cell")!
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "CoreData Basic"
default:
cell.textLabel?.text = ""
}
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch (indexPath as NSIndexPath).row {
case 0:
self.navigationController?.pushViewController(CoreDataBasicView(), animated: true)
default:
break
}
}
}
| a6c2017158e2e0e0b3923f965253462d | 27.345238 | 100 | 0.624528 | false | false | false | false |
nearfri/Strix | refs/heads/main | Sources/Strix/Error/RunError.swift | mit | 1 | import Foundation
public struct RunError: LocalizedError, CustomStringConvertible {
public var input: String
public var position: String.Index
public var underlyingErrors: [ParseError]
public init(input: String, position: String.Index, underlyingErrors: [ParseError]) {
self.input = input
self.position = position
self.underlyingErrors = underlyingErrors
}
public var errorDescription: String? {
var buffer = ErrorOutputBuffer()
ErrorMessageWriter(input: input, position: position, errors: underlyingErrors)
.write(to: &buffer)
return buffer.text.trimmingCharacters(in: .newlines)
}
public var failureReason: String? {
var buffer = ErrorOutputBuffer()
ErrorMessageWriter(errors: underlyingErrors).write(to: &buffer)
return buffer.text.trimmingCharacters(in: .newlines)
}
public var description: String {
return "line: \(textPosition.line), column: \(textPosition.column), "
+ "underlyingErrors: \(underlyingErrors)"
}
public var textPosition: TextPosition {
return TextPosition(string: input, index: position)
}
}
| f8099b82515240d8418a1b580089493b | 30.794872 | 88 | 0.65 | false | false | false | false |
caicai0/ios_demo | refs/heads/master | load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/Attribute.swift | mit | 1 | //
// Attribute.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Attribute {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
static let booleanAttributes: [String] = [
"allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize",
"noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected",
"sortable", "truespeed", "typemustmatch"
]
var key: String
var value: String
public init(key: String, value: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
self.value = value
}
/**
Get the attribute key.
@return the attribute key
*/
open func getKey() -> String {
return key
}
/**
Set the attribute key; case is preserved.
@param key the new key; must not be null
*/
open func setKey(key: String) throws {
try Validate.notEmpty(string: key)
self.key = key.trim()
}
/**
Get the attribute value.
@return the attribute value
*/
open func getValue() -> String {
return value
}
/**
Set the attribute value.
@param value the new attribute value; must not be null
*/
@discardableResult
open func setValue(value: String) -> String {
let old = self.value
self.value = value
return old
}
/**
Get the HTML representation of this attribute; e.g. {@code href="index.html"}.
@return HTML
*/
public func html() -> String {
let accum = StringBuilder()
html(accum: accum, out: (Document("")).outputSettings())
return accum.toString()
}
public func html(accum: StringBuilder, out: OutputSettings ) {
accum.append(key)
if (!shouldCollapseAttribute(out: out)) {
accum.append("=\"")
Entities.escape(accum, value, out, true, false, false)
accum.append("\"")
}
}
/**
Get the string representation of this attribute, implemented as {@link #html()}.
@return string
*/
open func toString() -> String {
return html()
}
/**
* Create a new Attribute from an unencoded key and a HTML attribute encoded value.
* @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars.
* @param encodedValue HTML attribute encoded value
* @return attribute
*/
open static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute {
let value = try Entities.unescape(string: encodedValue, strict: true)
return try Attribute(key: unencodedKey, value: value)
}
public func isDataAttribute() -> Bool {
return key.startsWith(Attributes.dataPrefix) && key.characters.count > Attributes.dataPrefix.characters.count
}
/**
* Collapsible if it's a boolean attribute and value is empty or same as name
*
* @param out Outputsettings
* @return Returns whether collapsible or not
*/
public final func shouldCollapseAttribute(out: OutputSettings) -> Bool {
return ("" == value || value.equalsIgnoreCase(string: key))
&& out.syntax() == OutputSettings.Syntax.html
&& isBooleanAttribute()
}
public func isBooleanAttribute() -> Bool {
return (Attribute.booleanAttributes.binarySearch(Attribute.booleanAttributes, key) != -1)
}
public func hashCode() -> Int {
var result = key.hashValue
result = 31 * result + value.hashValue
return result
}
public func clone() -> Attribute {
do {
return try Attribute(key: key, value: value)
} catch Exception.Error( _, let msg) {
print(msg)
} catch {
}
return try! Attribute(key: "", value: "")
}
}
extension Attribute : Equatable {
static public func == (lhs: Attribute, rhs: Attribute) -> Bool {
return lhs.value == rhs.value && lhs.key == rhs.key
}
}
| 13cd73e1f1a20c58c54b5f56fc319e08 | 28.25 | 117 | 0.603835 | false | false | false | false |
MukeshKumarS/Swift | refs/heads/master | validation-test/stdlib/GameplayKit.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
import GameplayKit
// GameplayKit is only available on iOS 9.0 and above, OS X 10.11 and above, and
// tvOS 9.0 and above.
var GamePlayKitTests = TestSuite("GameplayKit")
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) {
class TestComponent : GKComponent {}
class OtherTestComponent : GKComponent {}
class TestState1 : GKState {}
class TestState2 : GKState {}
GamePlayKitTests.test("GKEntity.componentForClass()") {
let entity = GKEntity()
entity.addComponent(TestComponent())
do {
var componentForTestComponent =
entity.componentForClass(TestComponent.self)
var componentForOtherTestComponent_nil =
entity.componentForClass(OtherTestComponent.self)
expectNotEmpty(componentForTestComponent)
expectType(Optional<TestComponent>.self, &componentForTestComponent)
expectEmpty(componentForOtherTestComponent_nil)
}
entity.removeComponentForClass(TestComponent.self)
entity.addComponent(OtherTestComponent())
do {
var componentForOtherTestComponent =
entity.componentForClass(OtherTestComponent.self)
var componentForTestComponent_nil =
entity.componentForClass(TestComponent.self)
expectNotEmpty(componentForOtherTestComponent)
expectType(Optional<OtherTestComponent>.self, &componentForOtherTestComponent)
expectEmpty(componentForTestComponent_nil)
}
}
GamePlayKitTests.test("GKStateMachine.stateForClass()") {
do {
// Construct a state machine with a custom subclass as the only state.
let stateMachine = GKStateMachine(
states: [TestState1()])
var stateForTestState1 =
stateMachine.stateForClass(TestState1.self)
var stateForTestState2_nil =
stateMachine.stateForClass(TestState2.self)
expectNotEmpty(stateForTestState1)
expectType(Optional<TestState1>.self, &stateForTestState1)
expectEmpty(stateForTestState2_nil)
}
do {
// Construct a state machine with a custom subclass as the only state.
let stateMachine = GKStateMachine(
states: [TestState2()])
var stateForTestState2 =
stateMachine.stateForClass(TestState2.self)
var stateForTestState1_nil =
stateMachine.stateForClass(TestState1.self)
expectNotEmpty(stateForTestState2)
expectType(Optional<TestState2>.self, &stateForTestState2)
expectEmpty(stateForTestState1_nil)
}
}
} // if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *)
runAllTests()
| de13bb78357107b297fe462d8fb6f935 | 26.565217 | 82 | 0.751972 | false | true | false | false |
macc704/iKF | refs/heads/master | iKF/KFLabelNoteRefView.swift | gpl-2.0 | 1 | //
// KFLabelNoteRefView.swift
// iKF
//
// Created by Yoshiaki Matsuzawa on 2014-08-01.
// Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved.
//
import UIKit
class KFLabelNoteRefView: UIView {
var model:KFReference!;
var icon: KFPostRefIconView!;
var titleLabel: UILabel!;
var authorLabel: UILabel!;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(ref: KFReference) {
self.model = ref;
icon = KFPostRefIconView(frame: CGRectMake(5, 5, 25, 25));
titleLabel = UILabel(frame: CGRectMake(40, 7, 200, 20));
authorLabel = UILabel(frame: CGRectMake(50, 23, 120, 10));
super.init(frame: KFAppUtils.DEFAULT_RECT());
self.layer.cornerRadius = 5;
self.layer.masksToBounds = true;
self.backgroundColor = UIColor.clearColor();
self.frame = CGRectMake(0, 0, 230, 40);
self.addSubview(icon);
titleLabel.font = UIFont.systemFontOfSize(13);
self.addSubview(titleLabel);
authorLabel.font = UIFont.systemFontOfSize(10);
self.addSubview(authorLabel);
self.layer.cornerRadius = 5;
self.layer.masksToBounds = true;
self.updateFromModel();
}
func updateFromModel(){
icon.beenRead = (self.model.post as KFNote).beenRead;
icon.update();
titleLabel.text = (self.model.post as KFNote).title;
titleLabel.sizeToFit();
authorLabel.text = (self.model.post as KFNote).primaryAuthor?.getFullName();
authorLabel.sizeToFit();
//self.sizeToFit(); //does not work
let titleRight = 45+titleLabel.frame.size.width;
let authorRight = 55+authorLabel.frame.size.width;
let tmp = titleRight > authorRight;
let newWidth = tmp ? titleRight : authorRight;
let r = self.frame;
self.frame = CGRectMake(0, 0, newWidth, r.size.height);
}
func getRelativeReference() -> CGPoint{
return icon.center;
}
}
| cc8951a6617441ee5b3c117b35a9d5a9 | 28.402778 | 84 | 0.601323 | false | false | false | false |
dekatotoro/FluxWithRxSwiftSample | refs/heads/master | FluxWithRxSwiftSample/Models/GitHub/GitHubLinkHeader.swift | mit | 1 | //
// GitHubLinkHeader.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
import Foundation
// https://developer.github.com/v3/#pagination
struct GitHubLinkHeader {
let first: Element?
let prev: Element?
let next: Element?
let last: Element?
var hasFirstPage: Bool {
return first != nil
}
var hasPrevPage: Bool {
return prev != nil
}
var hasNextPage: Bool {
return next != nil
}
var hasLastPage: Bool {
return last != nil
}
init?(string: String) {
let elements = string.components(separatedBy: ", ").flatMap { Element(string: $0) }
first = elements.filter { $0.rel == "first" }.first
prev = elements.filter { $0.rel == "prev" }.first
next = elements.filter { $0.rel == "next" }.first
last = elements.filter { $0.rel == "last" }.first
if first == nil && prev == nil && next == nil && last == nil {
return nil
}
}
}
extension GitHubLinkHeader {
public struct Element {
let uri: URL
let rel: String
let page: Int
init?(string: String) {
let attributes = string.components(separatedBy: "; ")
guard attributes.count == 2 else {
return nil
}
func trimString(_ string: String) -> String {
guard string.characters.count > 2 else {
return ""
}
return string[string.characters.index(after: string.startIndex)..<string.characters.index(before: string.endIndex)]
}
func value(_ field: String) -> String? {
let pair = field.components(separatedBy: "=")
guard pair.count == 2 else {
return nil
}
return trimString(pair.last!)
}
let uriString = attributes[0]
guard let uri = URL(string: trimString(uriString)) else {
return nil
}
self.uri = uri
guard let rel = value(attributes[1]) else {
return nil
}
self.rel = rel
guard let queryItems = NSURLComponents(url: uri, resolvingAgainstBaseURL: true)?.queryItems else {
return nil
}
guard queryItems.count > 0 else { return nil }
let pageQueryItem = queryItems.filter({ $0.name == "page" }).first
guard let value = pageQueryItem?.value,
let page = Int(value) else {
return nil
}
self.page = page
}
}
}
| d61cca8c45ee215a58fd9ea6fef2eae3 | 28.142857 | 131 | 0.497899 | false | false | false | false |
spritekitbook/spritekitbook-swift | refs/heads/master | Chapter 6/Finish/SpaceRunner/SpaceRunner/GameScene.swift | apache-2.0 | 2 | //
// GameScene.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/18/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
// MARK: - Private instance constants
private let background = Background()
private let player = Player()
private let meteorController = MeteorController()
// MARK: - Private class variables
private var lastUpdateTime:TimeInterval = 0.0
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
}
override func didMove(to view: SKView) {
self.setup()
}
// MARK: - Setup
private func setup() {
self.backgroundColor = Colors.colorFromRGB(rgbvalue: Colors.background)
self.addChild(background)
self.addChild(player)
self.addChild(meteorController)
}
// MARK: - Update
override func update(_ currentTime: TimeInterval) {
let delta = currentTime - self.lastUpdateTime
self.lastUpdateTime = currentTime
player.update()
meteorController.update(delta: delta)
}
// MARK: - Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let touchLocation = touch.location(in: self)
player.updateTargetPosition(position: touchLocation)
}
// MARK: - Load Scene
private func loadScene() {
let scene = GameOverScene(size: kViewSize)
let transition = SKTransition.fade(with: SKColor.black, duration: 0.5)
self.view?.presentScene(scene, transition: transition)
}
}
| 513a16af5177d487fd8a2aba0155a4c7 | 25.347826 | 79 | 0.622112 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/UI/UserFlowViewController.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// swiftlint:disable file_length
import UIKit
import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs
import third_party_objective_c_material_components_ios_components_Dialogs_ColorThemer
protocol UserFlowViewControllerDelegate: class {
/// Tells the delegate to present the account selector so a user can change or remove accounts.
func presentAccountSelector()
}
// swiftlint:disable type_body_length
// TODO: Consider breaking this class into multiple classes for each delegate.
/// Manages the navigation of the user flow which begins after a user has signed in and includes
/// all management of data such as viewing, creating, and adding to experiments.
class UserFlowViewController: UIViewController, ExperimentsListViewControllerDelegate,
ExperimentCoordinatorViewControllerDelegate, PermissionsGuideDelegate, SidebarDelegate,
UINavigationControllerDelegate, ExperimentItemDelegate {
/// The user flow view controller delegate.
weak var delegate: UserFlowViewControllerDelegate?
/// The experiment coordinator view controller. Exposed for testing.
weak var experimentCoordinatorVC: ExperimentCoordinatorViewController?
/// The experiments list view controller.
weak var experimentsListVC: ExperimentsListViewController?
/// The settings view controller.
weak var settingsVC: SettingsViewController?
private let accountsManager: AccountsManager
private lazy var _actionAreaController = ActionArea.Controller()
override var actionAreaController: ActionArea.Controller? { return _actionAreaController }
private let analyticsReporter: AnalyticsReporter
private let commonUIComponents: CommonUIComponents
private let documentManager: DocumentManager
private let drawerConfig: DrawerConfig
private var existingDataMigrationManager: ExistingDataMigrationManager?
private let experimentDataDeleter: ExperimentDataDeleter
private let feedbackReporter: FeedbackReporter
private let metadataManager: MetadataManager
private lazy var _navController = UINavigationController()
private var navController: UINavigationController {
return FeatureFlags.isActionAreaEnabled ? _actionAreaController.navController : _navController
}
private let networkAvailability: NetworkAvailability
private let devicePreferenceManager: DevicePreferenceManager
private let preferenceManager: PreferenceManager
private let queue = GSJOperationQueue()
private let sensorController: SensorController
private let sensorDataManager: SensorDataManager
private let sidebar: SidebarViewController
private let userManager: UserManager
private weak var trialDetailVC: TrialDetailViewController?
private weak var noteDetailController: NoteDetailController?
private var importSpinnerVC: SpinnerViewController?
private var importBeganOperation: GSJBlockOperation?
private let userAssetManager: UserAssetManager
private let operationQueue = GSJOperationQueue()
private var shouldShowPreferenceMigrationMessage: Bool
private let exportCoordinator: ExportCoordinator
// Whether to show the experiment list pull to refresh animation. It should show once for a fresh
// launch per user.
private var shouldShowExperimentListPullToRefreshAnimation = true
// The experiment update manager for the displayed experiment. This is populated when an
// experiment is shown. Callbacks received from detail view controllers will route updates to
// this manager.
private var openExperimentUpdateManager: ExperimentUpdateManager?
// Handles state updates to any experiment.
private lazy var experimentStateManager: ExperimentStateManager = {
let stateManager = ExperimentStateManager(experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
stateManager.addListener(self)
return stateManager
}()
// Drawer view controller is created lazily to avoid loading drawer contents until needed.
private lazy var drawerVC: DrawerViewController? = {
if FeatureFlags.isActionAreaEnabled {
return nil
} else {
return DrawerViewController(analyticsReporter: analyticsReporter,
drawerConfig: drawerConfig,
preferenceManager: preferenceManager,
sensorController: sensorController,
sensorDataManager: sensorDataManager)
}
}()
/// Designated initializer.
///
/// - Parameters:
/// - accountsManager: The accounts manager.
/// - analyticsReporter: The analytics reporter.
/// - commonUIComponents: Common UI components.
/// - devicePreferenceManager: The device preference manager.
/// - drawerConfig: The drawer config.
/// - existingDataMigrationManager: The existing data migration manager.
/// - feedbackReporter: The feedback reporter.
/// - networkAvailability: Network availability.
/// - sensorController: The sensor controller.
/// - shouldShowPreferenceMigrationMessage: Whether to show the preference migration message.
/// - userManager: The user manager.
init(accountsManager: AccountsManager,
analyticsReporter: AnalyticsReporter,
commonUIComponents: CommonUIComponents,
devicePreferenceManager: DevicePreferenceManager,
drawerConfig: DrawerConfig,
existingDataMigrationManager: ExistingDataMigrationManager?,
feedbackReporter: FeedbackReporter,
networkAvailability: NetworkAvailability,
sensorController: SensorController,
shouldShowPreferenceMigrationMessage: Bool,
userManager: UserManager) {
self.accountsManager = accountsManager
self.analyticsReporter = analyticsReporter
self.commonUIComponents = commonUIComponents
self.devicePreferenceManager = devicePreferenceManager
self.drawerConfig = drawerConfig
self.existingDataMigrationManager = existingDataMigrationManager
self.feedbackReporter = feedbackReporter
self.networkAvailability = networkAvailability
self.sensorController = sensorController
self.shouldShowPreferenceMigrationMessage = shouldShowPreferenceMigrationMessage
self.userManager = userManager
self.documentManager = userManager.documentManager
self.metadataManager = userManager.metadataManager
self.preferenceManager = userManager.preferenceManager
self.sensorDataManager = userManager.sensorDataManager
self.userAssetManager = userManager.assetManager
self.experimentDataDeleter = userManager.experimentDataDeleter
sidebar = SidebarViewController(accountsManager: accountsManager,
analyticsReporter: analyticsReporter)
exportCoordinator = ExportCoordinator(exportType: userManager.exportType)
super.init(nibName: nil, bundle: nil)
// Set user tracking opt-out.
analyticsReporter.setOptOut(preferenceManager.hasUserOptedOutOfUsageTracking)
// Register user-specific sensors.
metadataManager.registerBluetoothSensors()
// Get updates for changes based on Drive sync.
userManager.driveSyncManager?.delegate = self
exportCoordinator.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override open func viewDidLoad() {
super.viewDidLoad()
if FeatureFlags.isActionAreaEnabled {
addChild(_actionAreaController)
view.addSubview(_actionAreaController.view)
_actionAreaController.didMove(toParent: self)
} else {
addChild(navController)
view.addSubview(navController.view)
navController.didMove(toParent: self)
navController.isNavigationBarHidden = true
navController.delegate = self
}
sidebar.delegate = self
if !devicePreferenceManager.hasAUserCompletedPermissionsGuide {
let permissionsVC =
PermissionsGuideViewController(delegate: self,
analyticsReporter: analyticsReporter,
devicePreferenceManager: devicePreferenceManager,
showWelcomeView: !accountsManager.supportsAccounts)
navController.setViewControllers([permissionsVC], animated: false)
} else {
// Don't need the permissions guide, just show the experiments list.
showExperimentsList(animated: false)
}
// Listen to application notifications.
NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillTerminate),
name: UIApplication.willTerminateNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidEnterBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
// Listen to notifications of newly imported experiments.
NotificationCenter.default.addObserver(self,
selector: #selector(experimentImportBegan),
name: .documentManagerDidBeginImportExperiment,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(experimentImported),
name: .documentManagerDidImportExperiment,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(experimentImportFailed),
name: .documentManagerImportExperimentFailed,
object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Generate the default experiment if necessary.
createDefaultExperimentIfNecessary()
}
override var prefersStatusBarHidden: Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return navController.topViewController?.preferredStatusBarStyle ?? .lightContent
}
/// Handles a file import URL if possible.
///
/// - Parameter url: A file URL.
/// - Returns: True if the URL can be handled, otherwise false.
func handleImportURL(_ url: URL) -> Bool {
return documentManager.handleImportURL(url)
}
// MARK: - Notifications
@objc private func applicationWillTerminate() {
sensorDataManager.saveAllContexts()
}
@objc private func applicationWillResignActive() {
sensorDataManager.saveAllContexts()
}
@objc private func applicationDidEnterBackground() {
sensorDataManager.saveAllContexts()
}
@objc private func experimentImportBegan() {
// Wrap the UI work of beginning an import in an operation so we can ensure it finishes before
// handling success or failure.
let operation = GSJBlockOperation(mainQueueBlock: { (continuation) in
let showSpinnerBlock = {
if let experimentsListVC = self.experimentsListVC {
// Dismiss the feature highlight if necessary first.
experimentsListVC.dismissFeatureHighlightIfNecessary()
self.navController.popToViewController(experimentsListVC, animated: false)
}
guard let topViewController = self.navController.topViewController else {
self.importBeganOperation = nil
continuation()
return
}
self.importSpinnerVC = SpinnerViewController()
self.importSpinnerVC?.present(fromViewController: topViewController)
self.importBeganOperation = nil
continuation()
}
// Dismiss any VCs presented on the top view controller.
if self.navController.topViewController?.presentedViewController != nil {
self.navController.topViewController?.dismiss(animated: true, completion: showSpinnerBlock)
} else {
showSpinnerBlock()
}
})
importBeganOperation = operation
queue.addOperation(operation)
}
@objc private func experimentImported(_ notification: Notification) {
let finishedOperation = GSJBlockOperation(mainQueueBlock: { (continuation) in
self.dismissExperimentImportSpinner {
if let experimentID =
notification.userInfo?[DocumentManager.importedExperimentIDKey] as? String {
self.experimentsListShowExperiment(withID: experimentID)
}
continuation()
}
})
// Add began operation as a dependency so we don't show the experiment while the UI is still
// preparing to begin.
if let importBeganOperation = importBeganOperation {
finishedOperation.addDependency(importBeganOperation)
}
queue.addOperation(finishedOperation)
}
@objc private func experimentImportFailed(_ notification: Notification) {
let errorOperation = GSJBlockOperation(mainQueueBlock: { (continuation) in
// Check for an importing while recording error, otherwise the default generic error will
// be used.
var errorMessage = String.importFailedFile
if let errors = notification.userInfo?[DocumentManager.importFailedErrorsKey] as? [Error] {
forLoop: for error in errors {
switch error {
case DocumentManagerError.importingDocumentWhileRecording:
errorMessage = String.importFailedRecording
break forLoop
default: break
}
}
}
self.dismissExperimentImportSpinner {
MDCAlertColorThemer.apply(ViewConstants.alertColorScheme)
let alert = MDCAlertController(title: nil, message: errorMessage)
let cancelAction = MDCAlertAction(title: String.actionOk)
alert.addAction(cancelAction)
guard var topViewController = self.navController.topViewController else { return }
if let presentedViewController = topViewController.presentedViewController {
// On iPad, the welcome flow is in a presented view controller, so the alert must be
// presented on that.
topViewController = presentedViewController
}
topViewController.present(alert, animated: true)
continuation()
}
})
// Add began operation as a dependency so we don't show the error while the UI is still
// preparing to begin.
if let importBeganOperation = importBeganOperation {
errorOperation.addDependency(importBeganOperation)
}
queue.addOperation(errorOperation)
}
// MARK: - PermissionsGuideDelegate
func permissionsGuideDidComplete(_ viewController: PermissionsGuideViewController) {
showExperimentsList(animated: true)
}
// MARK: - SidebarDelegate
func sidebarShouldShow(_ item: SidebarRow) {
switch item {
case .about:
let aboutVC = AboutViewController(analyticsReporter: analyticsReporter)
guard UIDevice.current.userInterfaceIdiom == .pad else {
navController.pushViewController(aboutVC, animated: true)
return
}
// iPad should present modally in a navigation controller of its own since About has
// sub-navigation items.
let aboutNavController = UINavigationController()
aboutNavController.viewControllers = [ aboutVC ]
aboutNavController.isNavigationBarHidden = true
aboutNavController.modalPresentationStyle = .formSheet
present(aboutNavController, animated: true)
case .settings:
let settingsVC = SettingsViewController(analyticsReporter: analyticsReporter,
driveSyncManager: userManager.driveSyncManager,
preferenceManager: preferenceManager)
if UIDevice.current.userInterfaceIdiom == .pad {
// iPad should present modally.
settingsVC.modalPresentationStyle = .formSheet
present(settingsVC, animated: true)
} else {
navController.pushViewController(settingsVC, animated: true)
}
self.settingsVC = settingsVC
case .feedback:
guard let feedbackViewController = feedbackReporter.feedbackViewController(
withStyleMatching: navController.topViewController) else { return }
navController.pushViewController(feedbackViewController, animated: true)
default:
break
}
}
func sidebarShouldShowSignIn() {
delegate?.presentAccountSelector()
}
func sidebarDidOpen() {
analyticsReporter.track(.sidebarOpened)
}
func sidebarDidClose() {
analyticsReporter.track(.sidebarClosed)
}
// MARK: - ExperimentsListViewControllerDelegate
func experimentsListShowSidebar() {
showSidebar()
}
func experimentsListManualSync() {
userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: true)
}
func experimentsListShowExperiment(withID experimentID: String) {
guard let experiment = metadataManager.experiment(withID: experimentID) else {
experimentsListVC?.handleExperimentLoadingFailure()
return
}
showExperiment(experiment)
}
func experimentsListShowNewExperiment() {
let (experiment, overview) = metadataManager.createExperiment()
experimentsListVC?.insertOverview(overview, atBeginning: true)
showExperiment(experiment)
}
func experimentsListToggleArchiveStateForExperiment(withID experimentID: String) {
experimentStateManager.toggleArchiveStateForExperiment(withID: experimentID)
}
func experimentsListDeleteExperiment(withID experimentID: String) {
experimentStateManager.deleteExperiment(withID: experimentID)
}
func experimentsListDeleteExperimentCompleted(_ deletedExperiment: DeletedExperiment) {
experimentStateManager.confirmDeletion(for: deletedExperiment)
userManager.driveSyncManager?.deleteExperiment(withID: deletedExperiment.experimentID)
}
func experimentsListDidAppear() {
userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false)
showPreferenceMigrationMessageIfNeeded()
}
func experimentsListDidSetTitle(_ title: String?, forExperimentID experimentID: String) {
if openExperimentUpdateManager?.experiment.ID == experimentID {
openExperimentUpdateManager?.setTitle(title)
} else {
metadataManager.setExperimentTitle(title, forID: experimentID)
userManager.driveSyncManager?.syncExperiment(withID: experimentID, condition: .onlyIfDirty)
}
}
func experimentsListDidSetCoverImageData(_ imageData: Data?,
metadata: NSDictionary?,
forExperimentID experimentID: String) {
if openExperimentUpdateManager?.experiment.ID == experimentID {
openExperimentUpdateManager?.setCoverImageData(imageData, metadata: metadata)
} else {
let experimentUpdateManager =
ExperimentUpdateManager(experimentID: experimentID,
experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
experimentUpdateManager?.setCoverImageData(imageData, metadata: metadata)
}
}
func experimentsListExportExperimentPDF(
_ experiment: Experiment,
completionHandler: @escaping PDFExportController.CompletionHandler
) {
presentPDFExportFlow(experiment, completionHandler: completionHandler)
}
func experimentsListExportFlowAction(for experiment: Experiment,
from presentingViewController: UIViewController,
sourceView: UIView) -> PopUpMenuAction {
return PopUpMenuAction.exportFlow(for: experiment,
from: self,
documentManager: documentManager,
sourceView: sourceView,
exportCoordinator: exportCoordinator)
}
// MARK: - ExperimentCoordinatorViewControllerDelegate
func experimentViewControllerToggleArchiveStateForExperiment(withID experimentID: String) {
experimentStateManager.toggleArchiveStateForExperiment(withID: experimentID)
}
func experimentViewControllerDidRequestDeleteExperiment(_ experiment: Experiment) {
experimentStateManager.deleteExperiment(withID: experiment.ID)
if let experimentsListVC = experimentsListVC {
navController.popToViewController(experimentsListVC, animated: true)
}
}
func experimentViewControllerToggleArchiveStateForTrial(withID trialID: String) {
openExperimentUpdateManager?.toggleArchivedState(forTrialID: trialID)
}
func experimentViewControllerDeleteExperimentNote(withID noteID: String) {
openExperimentUpdateManager?.deleteExperimentNote(withID: noteID)
}
func experimentViewControllerShowTrial(withID trialID: String, jumpToCaption: Bool) {
guard let experiment = openExperimentUpdateManager?.experiment,
let trialIndex = experiment.trials.firstIndex(where: { $0.ID == trialID }) else {
return
}
let trial = experiment.trials[trialIndex]
let experimentInteractionOptions = interactionOptions(forExperiment: experiment)
let experimentDataParser = ExperimentDataParser(experimentID: experiment.ID,
metadataManager: metadataManager,
sensorController: sensorController)
let trialDetailVC =
TrialDetailViewController(trial: trial,
experiment: experiment,
experimentInteractionOptions: experimentInteractionOptions,
exportType: userManager.exportType,
delegate: self,
itemDelegate: self,
analyticsReporter: analyticsReporter,
experimentDataParser: experimentDataParser,
metadataManager: metadataManager,
preferenceManager: preferenceManager,
sensorDataManager: sensorDataManager)
self.trialDetailVC = trialDetailVC
openExperimentUpdateManager?.addListener(trialDetailVC)
if FeatureFlags.isActionAreaEnabled {
if let experimentCoordinator = experimentCoordinatorVC {
let content = configure(trialDetailViewController: trialDetailVC,
experimentCoordinator: experimentCoordinator)
actionAreaController?.show(content, sender: self)
} else {
fatalError("Experiment coordinator not available.")
}
} else {
navController.pushViewController(trialDetailVC, animated: true)
}
}
func experimentViewControllerShowNote(_ displayNote: DisplayNote, jumpToCaption: Bool) {
showNote(displayNote, jumpToCaption: jumpToCaption)
}
func experimentViewControllerAddTrial(_ trial: Trial, recording isRecording: Bool) {
openExperimentUpdateManager?.addTrial(trial, recording: isRecording)
}
func experimentViewControllerDeleteTrialCompleted(_ trial: Trial,
fromExperiment experiment: Experiment) {
// Delete trial data locally.
openExperimentUpdateManager?.confirmTrialDeletion(for: trial)
userAssetManager.deleteSensorData(forTrialID: trial.ID, experimentID: experiment.ID)
// Delete trial data from Drive.
let recordingURL =
metadataManager.recordingURL(forTrialID: trial.ID, experimentID: experiment.ID)
userManager.driveSyncManager?.deleteSensorDataAsset(atURL: recordingURL,
experimentID: experiment.ID)
// Delete trial image assets from Drive.
let imageURLs = trial.allImagePaths.map { return URL(fileURLWithPath: $0) }
userManager.driveSyncManager?.deleteImageAssets(atURLs: imageURLs, experimentID: experiment.ID)
}
func experimentViewControllerShouldPermanentlyDeleteTrial(_ trial: Trial,
fromExperiment experiment: Experiment) {
guard experiment.ID == openExperimentUpdateManager?.experiment.ID else {
return
}
openExperimentUpdateManager?.permanentlyDeleteTrial(withID: trial.ID)
}
func experimentsListShowClaimExperiments() {
guard let existingDataMigrationManager = existingDataMigrationManager,
let authAccount = accountsManager.currentAccount else { return }
let claimExperimentsVC =
ClaimExperimentsFlowController(authAccount: authAccount,
analyticsReporter: analyticsReporter,
existingDataMigrationManager: existingDataMigrationManager,
sensorController: sensorController)
present(claimExperimentsVC, animated: true)
}
func experimentViewControllerDidFinishRecordingTrial(_ trial: Trial,
forExperiment experiment: Experiment) {
userAssetManager.storeSensorData(forTrial: trial, experiment: experiment)
}
// No-op in non-claim flow.
func experimentViewControllerRemoveCoverImageForExperiment(_ experiment: Experiment) -> Bool {
return false
}
func experimentViewControllerDidSetTitle(_ title: String?, forExperiment experiment: Experiment) {
guard openExperimentUpdateManager?.experiment.ID == experiment.ID else {
return
}
openExperimentUpdateManager?.setTitle(title)
}
func experimentViewControllerDidSetCoverImageData(_ imageData: Data?,
metadata: NSDictionary?,
forExperiment experiment: Experiment) {
guard openExperimentUpdateManager?.experiment.ID == experiment.ID else {
return
}
openExperimentUpdateManager?.setCoverImageData(imageData, metadata: metadata)
}
func experimentViewControllerDidChangeRecordingTrial(_ recordingTrial: Trial,
experiment: Experiment) {
guard openExperimentUpdateManager?.experiment.ID == experiment.ID else {
return
}
openExperimentUpdateManager?.recordingTrialChangedExternally(recordingTrial)
}
func experimentViewControllerExportExperimentPDF(
_ experiment: Experiment,
completionHandler: @escaping PDFExportController.CompletionHandler) {
presentPDFExportFlow(experiment, completionHandler: completionHandler)
}
func experimentViewControllerExportFlowAction(for experiment: Experiment,
from presentingViewController: UIViewController,
sourceView: UIView) -> PopUpMenuAction? {
return PopUpMenuAction.exportFlow(for: experiment,
from: self,
documentManager: documentManager,
sourceView: sourceView,
exportCoordinator: exportCoordinator)
}
// MARK: - ExperimentItemDelegate
func detailViewControllerDidAddNote(_ note: Note, forTrialID trialID: String?) {
if let trialID = trialID {
openExperimentUpdateManager?.addTrialNote(note, trialID: trialID)
} else {
openExperimentUpdateManager?.addExperimentNote(note)
}
guard FeatureFlags.isActionAreaEnabled, actionAreaController?.isMasterVisible == false else {
return
}
showSnackbar(
withMessage: String.actionAreaRecordingNoteSavedMessage,
category: nil,
actionTitle: String.actionAreaRecordingNoteSavedViewButton,
actionHandler: {
self.actionAreaController?.revealMaster()
})
}
func detailViewControllerDidDeleteNote(_ deletedDisplayNote: DisplayNote) {
if let trialID = deletedDisplayNote.trialID {
// Trial note.
openExperimentUpdateManager?.deleteTrialNote(withID: deletedDisplayNote.ID, trialID: trialID)
} else {
// Experiment note.
openExperimentUpdateManager?.deleteExperimentNote(withID: deletedDisplayNote.ID)
}
}
func detailViewControllerDidUpdateCaptionForNote(_ updatedDisplayNote: CaptionableNote) {
openExperimentUpdateManager?.updateNoteCaption(updatedDisplayNote.caption,
forNoteWithID: updatedDisplayNote.ID,
trialID: updatedDisplayNote.trialID)
}
func detailViewControllerDidUpdateTextForNote(_ updatedDisplayTextNote: DisplayTextNote) {
openExperimentUpdateManager?.updateText(updatedDisplayTextNote.text,
forNoteWithID: updatedDisplayTextNote.ID,
trialID: updatedDisplayTextNote.trialID)
}
func trialDetailViewControllerDidUpdateTrial(cropRange: ChartAxis<Int64>?,
name trialName: String?,
caption: String?,
withID trialID: String) {
openExperimentUpdateManager?.updateTrial(cropRange: cropRange,
name: trialName,
captionString: caption,
forTrialID: trialID)
}
func trialDetailViewControllerDidRequestDeleteTrial(withID trialID: String) {
openExperimentUpdateManager?.deleteTrial(withID: trialID)
}
func trialDetailViewController(_ trialDetailViewController: TrialDetailViewController,
trialArchiveStateChanged trial: Trial) {
openExperimentUpdateManager?.toggleArchivedState(forTrialID: trial.ID)
}
func trialDetailViewController(_ trialDetailViewController: TrialDetailViewController,
trialArchiveStateToggledForTrialID trialID: String) {
openExperimentUpdateManager?.toggleArchivedState(forTrialID: trialID)
}
func experimentViewControllerDeletePictureNoteCompleted(_ pictureNote: PictureNote,
forExperiment experiment: Experiment) {
guard let pictureNoteFilePath = pictureNote.filePath else {
return
}
userManager.driveSyncManager?.deleteImageAssets(
atURLs: [URL(fileURLWithPath: pictureNoteFilePath)], experimentID: experiment.ID)
}
// MARK: - Private
/// Shows the sidebar.
private func showSidebar() {
present(sidebar, animated: false) {
self.sidebar.show()
}
}
/// Shows the experiments list view controller.
///
/// - Parameter animated: Whether to animate the showing of the view controller.
func showExperimentsList(animated: Bool) {
// Force the drawer to be created here, to avoid it being created when the first experiment is
// shown as it is a performance issue.
// TODO: Avoid lazy loading drawer by making drawer contents load on demand. http://b/72745126
_ = drawerVC
let experimentsListVC =
ExperimentsListViewController(accountsManager: accountsManager,
analyticsReporter: analyticsReporter,
commonUIComponents: commonUIComponents,
existingDataMigrationManager: existingDataMigrationManager,
metadataManager: metadataManager,
networkAvailability: networkAvailability,
preferenceManager: preferenceManager,
sensorDataManager: sensorDataManager,
documentManager: documentManager,
exportType: userManager.exportType,
shouldAllowManualSync: userManager.isDriveSyncEnabled)
experimentsListVC.delegate = self
// Add as listeners for experiment state changes.
experimentStateManager.addListener(experimentsListVC)
self.experimentsListVC = experimentsListVC
navController.setViewControllers([experimentsListVC], animated: animated)
}
/// Presents the PDF export flow.
///
/// - Parameter experiment: An experiment.
func presentPDFExportFlow(_ experiment: Experiment,
completionHandler: @escaping PDFExportController.CompletionHandler) {
let experimentCoordinatorVC = ExperimentCoordinatorViewController(
experiment: experiment,
experimentInteractionOptions: .readOnly,
exportType: userManager.exportType,
drawerViewController: nil,
analyticsReporter: analyticsReporter,
metadataManager: metadataManager,
preferenceManager: preferenceManager,
sensorController: sensorController,
sensorDataManager: sensorDataManager,
documentManager: documentManager)
experimentCoordinatorVC.experimentDisplay = .pdfExport
let container = PDFExportController(contentViewController: experimentCoordinatorVC,
analyticsReporter: analyticsReporter)
container.completionHandler = completionHandler
let readyForPDFExport = {
let headerInfo = PDFExportController.HeaderInfo(
title: experiment.titleOrDefault,
subtitle: experiment.notesAndTrialsString,
image: self.metadataManager.imageForExperiment(experiment)
)
let documentFilename = experiment.titleOrDefault.validFilename(withExtension: "pdf")
let pdfURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(documentFilename)
container.exportPDF(with: headerInfo, to: pdfURL)
}
experimentCoordinatorVC.readyForPDFExport = readyForPDFExport
let navController = UINavigationController(rootViewController: container)
present(navController, animated: true)
}
/// Shows an experiment. Exposed for testing.
///
/// - Parameter experiment: An experiment.
func showExperiment(_ experiment: Experiment) {
openExperimentUpdateManager =
ExperimentUpdateManager(experiment: experiment,
experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
openExperimentUpdateManager?.delegate = self
let experimentInteractionOptions = interactionOptions(forExperiment: experiment)
let experimentCoordinatorVC = ExperimentCoordinatorViewController(
experiment: experiment,
experimentInteractionOptions: experimentInteractionOptions,
exportType: userManager.exportType,
drawerViewController: drawerVC,
analyticsReporter: analyticsReporter,
metadataManager: metadataManager,
preferenceManager: preferenceManager,
sensorController: sensorController,
sensorDataManager: sensorDataManager,
documentManager: documentManager)
experimentCoordinatorVC.delegate = self
experimentCoordinatorVC.itemDelegate = self
self.experimentCoordinatorVC = experimentCoordinatorVC
// Add as listeners for all experiment changes.
openExperimentUpdateManager?.addListener(experimentCoordinatorVC)
experimentStateManager.addListener(experimentCoordinatorVC)
if FeatureFlags.isActionAreaEnabled {
let content = configure(experimentCoordinator: experimentCoordinatorVC)
actionAreaController?.show(content, sender: self)
} else {
navController.pushViewController(experimentCoordinatorVC, animated: true)
}
if isExperimentTooNewToEdit(experiment) {
let alertController = MDCAlertController(title: nil,
message: String.experimentVersionTooNewToEdit)
alertController.addAction(MDCAlertAction(title: String.actionOk))
alertController.accessibilityViewIsModal = true
experimentCoordinatorVC.present(alertController, animated: true)
}
// Mark opened in experiment library.
metadataManager.markExperimentOpened(withID: experiment.ID)
// Tell drive manager to sync the experiment.
userManager.driveSyncManager?.syncExperiment(withID: experiment.ID, condition: .always)
// This is a good time to generate any missing recording protos.
userAssetManager.writeMissingSensorDataProtos(forExperiment: experiment)
}
private func configure(trialDetailViewController: TrialDetailViewController,
experimentCoordinator: ExperimentCoordinatorViewController) ->
ActionArea.MasterContent {
let recordingDetailEmptyState = RecordingDetailEmptyStateViewController()
trialDetailViewController.subscribeToTimestampUpdate { (timestamp) in
recordingDetailEmptyState.timestampString = timestamp
}
let textItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonText,
accessibilityHint: String.actionAreaButtonTextContentDescription,
image: UIImage(named: "ic_action_area_text")
) {
let notesVC = trialDetailViewController.notesViewController
trialDetailViewController.prepareToAddNote()
self.actionAreaController?.showDetailViewController(notesVC, sender: self)
}
let galleryItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonGallery,
accessibilityHint: String.actionAreaButtonGalleryContentDescription,
image: UIImage(named: "ic_action_area_gallery")
) {
let photoLibraryVC = trialDetailViewController.photoLibraryViewController
self.actionAreaController?.showDetailViewController(photoLibraryVC, sender: self)
}
let cameraItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonCamera,
accessibilityHint: String.actionAreaButtonCameraContentDescription,
image: UIImage(named: "ic_action_area_camera")
) {
trialDetailViewController.cameraButtonPressed()
}
let content = ActionArea.MasterContentContainerViewController(
content: trialDetailViewController,
emptyState: recordingDetailEmptyState,
actionEnablingKeyPath: \.isEditable,
outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea,
mode: .stateless(actionItem: ActionArea.ActionItem(
items: [textItem, cameraItem, galleryItem]
))
)
return content
}
private func configure(
experimentCoordinator: ExperimentCoordinatorViewController
) -> ActionArea.MasterContent {
let textItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonText,
accessibilityHint: String.actionAreaButtonTextContentDescription,
image: UIImage(named: "ic_action_area_text")
) {
let textTitle = experimentCoordinator.observeViewController.isRecording ?
String.actionAreaRecordingTitleAddTextNote : String.actionAreaTitleAddTextNote
experimentCoordinator.notesViewController.title = textTitle
self.actionAreaController?.showDetailViewController(
experimentCoordinator.notesViewController,
sender: self)
}
let cameraItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonCamera,
accessibilityHint: String.actionAreaButtonCameraContentDescription,
image: UIImage(named: "ic_action_area_camera")
) {
experimentCoordinator.cameraButtonPressed()
}
let galleryItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonGallery,
accessibilityHint: String.actionAreaButtonGalleryContentDescription,
image: UIImage(named: "ic_action_area_gallery")
) {
self.actionAreaController?.showDetailViewController(
experimentCoordinator.photoLibraryViewController,
sender: self)
}
let detail = ActionArea.DetailContentContainerViewController(
content: experimentCoordinator.observeViewController,
outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea
) {
let addSensorItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonAddSensor,
accessibilityHint: String.actionAreaButtonAddSensorContentDescription,
image: UIImage(named: "ic_action_area_add_sensor")
) {
experimentCoordinator.observeViewController.observeFooterAddButtonPressed()
}
let snapshotItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonSnapshot,
accessibilityHint: String.actionAreaButtonSnapshotContentDescription,
image: UIImage(named: "ic_action_area_snapshot")
) {
experimentCoordinator.observeViewController.snapshotButtonPressed()
}
let recordItem = ActionArea.BarButtonItem(
title: String.actionAreaFabRecord,
accessibilityHint: String.actionAreaFabRecordContentDescription,
image: UIImage(named: "record_button")
) {
experimentCoordinator.observeViewController.recordButtonPressed()
}
let stopItem = ActionArea.BarButtonItem(
title: String.actionAreaFabStop,
accessibilityHint: String.actionAreaFabStopContentDescription,
image: UIImage(named: "stop_button")
) {
experimentCoordinator.observeViewController.recordButtonPressed()
}
return .stateful(
nonModal: ActionArea.ActionItem(primary: recordItem, items: [addSensorItem, snapshotItem]),
modal: ActionArea.ActionItem(
primary: stopItem,
items: [textItem, snapshotItem, cameraItem, galleryItem]
)
)
}
let sensorsItem = ActionArea.BarButtonItem(
title: String.actionAreaButtonSensors,
accessibilityHint: String.actionAreaButtonSensorsContentDescription,
image: UIImage(named: "ic_action_area_sensors")
) {
self.actionAreaController?.showDetailViewController(detail, sender: self)
}
let emptyState = ExperimentDetailEmptyStateViewController()
let content = ActionArea.MasterContentContainerViewController(
content: experimentCoordinator,
emptyState: emptyState,
actionEnablingKeyPath: \.shouldAllowAdditions,
outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea,
mode: .stateless(actionItem: ActionArea.ActionItem(
items: [textItem, sensorsItem, cameraItem, galleryItem]
))
)
return content
}
/// Shows a note.
///
/// - Parameters:
/// - displayNote: A display note.
/// - jumpToCaption: Whether to jump to the caption input when showing the note.
private func showNote(_ displayNote: DisplayNote, jumpToCaption: Bool) {
guard let experiment = openExperimentUpdateManager?.experiment else {
return
}
let experimentInteractionOptions = interactionOptions(forExperiment: experiment)
var viewController: UIViewController?
switch displayNote {
case let displayTextNote as DisplayTextNote:
viewController =
TextNoteDetailViewController(displayTextNote: displayTextNote,
delegate: self,
experimentInteractionOptions: experimentInteractionOptions,
analyticsReporter: analyticsReporter)
case let displayPicture as DisplayPictureNote:
viewController =
PictureDetailViewController(displayPicture: displayPicture,
experimentInteractionOptions: experimentInteractionOptions,
exportType: userManager.exportType,
delegate: self,
jumpToCaption: jumpToCaption,
analyticsReporter: analyticsReporter,
metadataManager: metadataManager,
preferenceManager: preferenceManager)
case let displaySnapshot as DisplaySnapshotNote:
viewController =
SnapshotDetailViewController(displaySnapshot: displaySnapshot,
experimentInteractionOptions: experimentInteractionOptions,
delegate: self,
jumpToCaption: jumpToCaption,
analyticsReporter: analyticsReporter)
case let displayTrigger as DisplayTriggerNote:
viewController =
TriggerDetailViewController(displayTrigger: displayTrigger,
experimentInteractionOptions: experimentInteractionOptions,
delegate: self,
jumpToCaption: jumpToCaption,
analyticsReporter: analyticsReporter)
default:
return
}
noteDetailController = viewController as? NoteDetailController
if let viewController = viewController {
navController.pushViewController(viewController, animated: true)
}
}
private func dismissExperimentImportSpinner(completion: (() -> Void)? = nil) {
if importSpinnerVC != nil {
importSpinnerVC?.dismissSpinner(completion: completion)
importSpinnerVC = nil
} else {
completion?()
}
}
/// Whether an experiment is too new to allow editing.
///
/// - Parameter experiment: An experiment.
/// - Returns: True if the experiment is too new to allow editing, otherwise false.
private func isExperimentTooNewToEdit(_ experiment: Experiment) -> Bool {
let isMajorVersionNewer = experiment.fileVersion.version > Experiment.Version.major
let isMinorVersionNewer = experiment.fileVersion.version == Experiment.Version.major &&
experiment.fileVersion.minorVersion > Experiment.Version.minor
return isMajorVersionNewer || isMinorVersionNewer
}
/// The experiment interaction options to use for an experiment.
///
/// - Parameter experiment: An experiment.
/// - Returns: The experiment interaction options to use.
private func interactionOptions(forExperiment experiment: Experiment) ->
ExperimentInteractionOptions {
let experimentInteractionOptions: ExperimentInteractionOptions
if isExperimentTooNewToEdit(experiment) {
experimentInteractionOptions = .readOnly
} else {
let isExperimentArchived = metadataManager.isExperimentArchived(withID: experiment.ID)
experimentInteractionOptions = isExperimentArchived ? .archived : .normal
}
return experimentInteractionOptions
}
private func createDefaultExperimentIfNecessary() {
guard !self.preferenceManager.defaultExperimentWasCreated else {
return
}
guard let driveSyncManager = userManager.driveSyncManager else {
// If there is no Drive sync manager, create the default experiment if it has not been
// created yet.
metadataManager.createDefaultExperimentIfNecessary()
experimentsListVC?.reloadExperiments()
return
}
let createDefaultOp = GSJBlockOperation(mainQueueBlock: { finished in
guard !self.preferenceManager.defaultExperimentWasCreated else {
finished()
return
}
// A spinner will be shown if the experiments list is visible.
var spinnerVC: SpinnerViewController?
let createDefaultExperiment = {
driveSyncManager.experimentLibraryExists { (libraryExists) in
// If existence is unknown, perhaps due to a fetch error or lack of network, don't create
// the default experiment.
if libraryExists == false {
self.metadataManager.createDefaultExperimentIfNecessary()
self.userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: false,
userInitiated: false)
DispatchQueue.main.async {
if let spinnerVC = spinnerVC {
spinnerVC.dismissSpinner {
self.experimentsListVC?.reloadExperiments()
finished()
}
} else {
finished()
}
}
} else {
// If library exists or the state is unknown, mark the default experiment as created
// to avoid attempting to create it again in the future.
self.preferenceManager.defaultExperimentWasCreated = true
DispatchQueue.main.async {
if let spinnerVC = spinnerVC {
spinnerVC.dismissSpinner {
finished()
}
} else {
finished()
}
}
if libraryExists == true {
self.analyticsReporter.track(.signInSyncExistingAccount)
}
}
}
}
if let experimentsListVC = self.experimentsListVC,
experimentsListVC.presentedViewController == nil {
spinnerVC = SpinnerViewController()
spinnerVC?.present(fromViewController: experimentsListVC) {
createDefaultExperiment()
}
} else {
createDefaultExperiment()
}
})
createDefaultOp.addCondition(MutuallyExclusive(primaryCategory: "CreateDefaultExperiment"))
createDefaultOp.addCondition(MutuallyExclusive.modalUI)
operationQueue.addOperation(createDefaultOp)
}
private func showPreferenceMigrationMessageIfNeeded() {
guard shouldShowPreferenceMigrationMessage else { return }
let showPreferenceMigrationMessageOp = GSJBlockOperation(mainQueueBlock: { finished in
// If signing in and immediately showing experiments list, the sign in view controller needs a
// brief delay to finish dismissing before showing a snackbar.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showSnackbar(withMessage: String.preferenceMigrationMessage)
self.shouldShowPreferenceMigrationMessage = false
finished()
}
})
showPreferenceMigrationMessageOp.addCondition(MutuallyExclusive.modalUI)
operationQueue.addOperation(showPreferenceMigrationMessageOp)
}
// MARK: - UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool) {
setNeedsStatusBarAppearanceUpdate()
if viewController is ExperimentsListViewController {
// Reset open experiment update manager and observe state in the drawer when the list appears.
openExperimentUpdateManager = nil
experimentCoordinatorVC?.observeViewController.prepareForReuse()
}
}
}
// MARK: - TrialDetailViewControllerDelegate
extension UserFlowViewController: TrialDetailViewControllerDelegate {
func trialDetailViewControllerShowNote(_ displayNote: DisplayNote, jumpToCaption: Bool) {
showNote(displayNote, jumpToCaption: jumpToCaption)
}
func trialDetailViewControllerDeletePictureNoteCompleted(_ pictureNote: PictureNote,
forExperiment experiment: Experiment) {
guard let pictureNoteFilePath = pictureNote.filePath else {
return
}
userManager.driveSyncManager?.deleteImageAssets(
atURLs: [URL(fileURLWithPath: pictureNoteFilePath)], experimentID: experiment.ID)
}
}
// MARK: - DriveSyncManagerDelegate
extension UserFlowViewController: DriveSyncManagerDelegate {
func driveSyncWillUpdateExperimentLibrary() {
if shouldShowExperimentListPullToRefreshAnimation {
experimentsListVC?.startPullToRefreshAnimation()
shouldShowExperimentListPullToRefreshAnimation = false
}
}
func driveSyncDidUpdateExperimentLibrary() {
experimentsListVC?.reloadExperiments()
experimentsListVC?.endPullToRefreshAnimation()
}
func driveSyncDidDeleteTrial(withID trialID: String, experimentID: String) {
openExperimentUpdateManager?.experimentTrialDeletedExternally(trialID: trialID,
experimentID: experimentID)
}
func driveSyncDidUpdateExperiment(_ experiment: Experiment) {
// Reload experiments list in case cover image, title, or sort changed.
experimentsListVC?.reloadExperiments()
// If the experiment ID matches the open experiment, refresh views as needed.
if let experimentCoordinatorVC = experimentCoordinatorVC,
experimentCoordinatorVC.experiment.ID == experiment.ID {
// Replace instance handled by the update manager as well as experiment view.
openExperimentUpdateManager?.experiment = experiment
experimentCoordinatorVC.reloadWithNewExperiment(experiment)
// Check if trial detail exists and reload or pop as needed.
if let trialDetailVC = trialDetailVC {
let trialID = trialDetailVC.trialDetailDataSource.trial.ID
if let trial = experiment.trial(withID: trialID) {
trialDetailVC.reloadTrial(trial)
} else {
trialDetailVC.dismissPresentedVCIfNeeded(animated: true) {
self.navController.popToViewController(experimentCoordinatorVC, animated: true)
}
// If we pop back to the experiment view there is no need to continue.
return
}
}
// Check if a detail view exists and reload or pop as needed.
if let detailNoteID = noteDetailController?.displayNote.ID {
// Make a parser for this experiment.
let parser = ExperimentDataParser(experimentID: experiment.ID,
metadataManager: metadataManager,
sensorController: sensorController)
// Find the note in the experiment.
let (note, trial) = experiment.findNote(withID: detailNoteID)
if let note = note, let displayNote = parser.parseNote(note) {
// The note being displayed still exists, reload the view with a new display model in
// case there are changes.
noteDetailController?.displayNote = displayNote
} else if trial != nil, let trialDetailVC = trialDetailVC {
// It's a trial note, has been deleted and the trial view exists, pop back to that.
navController.popToViewController(trialDetailVC, animated: true)
} else {
// The note has been deleted and there is no trial view, pop back to the experiment view.
navController.popToViewController(experimentCoordinatorVC, animated: true)
}
}
}
}
func driveSyncDidDeleteExperiment(withID experimentID: String) {
experimentsListVC?.reloadExperiments()
// If an experiment was deleted and is currently being displayed, cancel its recording if needed
// and pop back to the experiments list.
guard let experimentsListVC = experimentsListVC,
experimentCoordinatorVC?.experiment.ID == experimentID else {
return
}
experimentCoordinatorVC?.cancelRecordingIfNeeded()
navController.popToViewController(experimentsListVC, animated: true)
}
}
// MARK: - ExperimentUpdateManagerDelegate
extension UserFlowViewController: ExperimentUpdateManagerDelegate {
func experimentUpdateManagerDidSaveExperiment(withID experimentID: String) {
userManager.driveSyncManager?.syncExperiment(withID: experimentID, condition: .onlyIfDirty)
}
func experimentUpdateManagerDidDeleteCoverImageAsset(withPath assetPath: String,
experimentID: String) {
userManager.driveSyncManager?.deleteImageAssets(atURLs: [URL(fileURLWithPath: assetPath)],
experimentID: experimentID)
}
}
// MARK: - ExperimentStateListener
extension UserFlowViewController: ExperimentStateListener {
func experimentStateArchiveStateChanged(forExperiment experiment: Experiment,
overview: ExperimentOverview,
undoBlock: @escaping () -> Void) {
userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false)
}
func experimentStateDeleted(_ deletedExperiment: DeletedExperiment, undoBlock: (() -> Void)?) {
userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false)
}
func experimentStateRestored(_ experiment: Experiment, overview: ExperimentOverview) {
userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false)
}
}
extension UserFlowViewController: ExportCoordinatorDelegate {
func showPDFExportFlow(for experiment: Experiment,
completionHandler: @escaping PDFExportController.CompletionHandler) {
presentPDFExportFlow(experiment, completionHandler: completionHandler)
}
}
// swiftlint:enable file_length, type_body_length
| 168cf6dd2af59047c5999197396ee800 | 41.509489 | 100 | 0.689327 | false | false | false | false |
xBrux/Pensieve | refs/heads/master | Source/Core/Connection.swift | mit | 1 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 Dispatch
/// A connection to SQLite.
/*public*/ final class Connection {
/// The location of a SQLite database.
/*public*/ enum Location {
/// An in-memory database (equivalent to `.URI(":memory:")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb>
case InMemory
/// A temporary, file-backed database (equivalent to `.URI("")`).
///
/// See: <https://www.sqlite.org/inmemorydb.html#temp_db>
case Temporary
/// A database located at the given URI filename (or path).
///
/// See: <https://www.sqlite.org/uri.html>
///
/// - Parameter filename: A URI filename
case URI(String)
}
/*public*/ var handle: COpaquePointer { return _handle }
private var _handle: COpaquePointer = nil
/// Initializes a new SQLite connection.
///
/// - Parameters:
///
/// - location: The location of the database. Creates a new database if it
/// doesn’t already exist (unless in read-only mode).
///
/// Default: `.InMemory`.
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Returns: A new database connection.
/*public*/ init(_ location: Location = .InMemory, readonly: Bool = false) throws {
let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE
try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil))
dispatch_queue_set_specific(queue, Connection.queueKey, queueContext, nil)
}
/// Initializes a new connection to a database.
///
/// - Parameters:
///
/// - filename: The location of the database. Creates a new database if
/// it doesn’t already exist (unless in read-only mode).
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Throws: `Result.Error` iff a connection cannot be established.
///
/// - Returns: A new database connection.
/*public*/ convenience init(_ filename: String, readonly: Bool = false) throws {
try self.init(.URI(filename), readonly: readonly)
}
deinit {
sqlite3_close(handle)
}
// MARK: -
/// Whether or not the database was opened in a read-only state.
/*public*/ var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 }
/// The last rowid inserted into the database via this connection.
/*public*/ var lastInsertRowid: Int64? {
let rowid = sqlite3_last_insert_rowid(handle)
return rowid > 0 ? rowid : nil
}
/// The last number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
/*public*/ var changes: Int {
return Int(sqlite3_changes(handle))
}
/// The total number of changes (inserts, updates, or deletes) made to the
/// database via this connection.
/*public*/ var totalChanges: Int {
return Int(sqlite3_total_changes(handle))
}
// MARK: - Execute
/// Executes a batch of SQL statements.
///
/// - Parameter SQL: A batch of zero or more semicolon-separated SQL
/// statements.
///
/// - Throws: `Result.Error` if query execution fails.
/*public*/ func execute(SQL: String) throws {
try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) }
}
// MARK: - Prepare
/// Prepares a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: Binding?...) throws -> Statement {
if !bindings.isEmpty {
return try prepare(sqlString, bindings)
} else {
return try Statement(self, sqlString)
}
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: [Binding?]) throws -> Statement {
return try prepare(sqlString).bind(bindings)
}
/// Prepares a single SQL statement and binds parameters to it.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: A prepared statement.
@warn_unused_result /*public*/ func prepare(sqlString: String, _ bindings: [String: Binding?]) throws -> Statement {
return try prepare(sqlString).bind(bindings)
}
// MARK: - Run
/// Runs a single SQL statement (with optional parameter bindings).
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
/*public*/ func run(sqlString: String, _ bindings: Binding?...) throws -> Statement {
return try run(sqlString, bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
/*public*/ func run(sqlString: String, _ bindings: [Binding?]) throws -> Statement {
return try prepare(sqlString).run(bindings)
}
/// Prepares, binds, and runs a single SQL statement.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement.
/*public*/ func run(sqlString: String, _ bindings: [String: Binding?]) throws -> Statement {
return try prepare(sqlString).run(bindings)
}
// MARK: - Scalar
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: Binding?...) throws -> Binding? {
return try scalar(sqlString, bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: [Binding?]) throws -> Binding? {
return try prepare(sqlString).scalar(bindings)
}
/// Runs a single SQL statement (with optional parameter bindings),
/// returning the first value of the first row.
///
/// - Parameters:
///
/// - statement: A single SQL statement.
///
/// - bindings: A dictionary of named parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
@warn_unused_result /*public*/ func scalar(sqlString: String, _ bindings: [String: Binding?]) throws -> Binding? {
return try prepare(sqlString).scalar(bindings)
}
// MARK: - Transactions
/// The mode in which a transaction acquires a lock.
/*public*/ enum TransactionMode : String {
/// Defers locking the database till the first read/write executes.
case Deferred = "DEFERRED"
/// Immediately acquires a reserved lock on the database.
case Immediate = "IMMEDIATE"
/// Immediately acquires an exclusive lock on all databases.
case Exclusive = "EXCLUSIVE"
}
// TODO: Consider not requiring a throw to roll back?
/// Runs a transaction with the given mode.
///
/// - Note: Transactions cannot be nested. To nest transactions, see
/// `savepoint()`, instead.
///
/// - Parameters:
///
/// - mode: The mode in which a transaction acquires a lock.
///
/// Default: `.Deferred`
///
/// - block: A closure to run SQL statements within the transaction.
/// The transaction will be committed when the block returns. The block
/// must throw to roll the transaction back.
///
/// - Throws: `Result.Error`, and rethrows.
/*public*/ func transaction(mode: TransactionMode = .Deferred, block: () throws -> Void) throws {
try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION")
}
// TODO: Consider not requiring a throw to roll back?
// TODO: Consider removing ability to set a name?
/// Runs a transaction with the given savepoint name (if omitted, it will
/// generate a UUID).
///
/// - SeeAlso: `transaction()`.
///
/// - Parameters:
///
/// - savepointName: A unique identifier for the savepoint (optional).
///
/// - block: A closure to run SQL statements within the transaction.
/// The savepoint will be released (committed) when the block returns.
/// The block must throw to roll the savepoint back.
///
/// - Throws: `SQLite.Result.Error`, and rethrows.
/*public*/ func savepoint(name: String = NSUUID().UUIDString, block: () throws -> Void) throws {
let name = name.quote("'")
let savepoint = "SAVEPOINT \(name)"
try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)")
}
private func transaction(begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws {
return try sync {
try self.run(begin)
do {
try block()
} catch {
try self.run(rollback)
throw error
}
try self.run(commit)
}
}
/// Interrupts any long-running queries.
/*public*/ func interrupt() {
sqlite3_interrupt(handle)
}
// MARK: - Handlers
/// The number of seconds a connection will attempt to retry a statement
/// after encountering a busy signal (lock).
/*public*/ var busyTimeout: Double = 0 {
didSet {
sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000))
}
}
/// Sets a handler to call after encountering a busy signal (lock).
///
/// - Parameter callback: This block is executed during a lock in which a
/// busy error would otherwise be returned. It’s passed the number of
/// times it’s been called for this lock. If it returns `true`, it will
/// try again. If it returns `false`, no further attempts will be made.
/*public*/ func busyHandler(callback: ((tries: Int) -> Bool)?) {
guard let callback = callback else {
sqlite3_busy_handler(handle, nil, nil)
busyHandler = nil
return
}
let box: BusyHandler = { callback(tries: Int($0)) ? 1 : 0 }
sqlite3_busy_handler(handle, { callback, tries in
unsafeBitCast(callback, BusyHandler.self)(tries)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
busyHandler = box
}
private typealias BusyHandler = @convention(block) Int32 -> Int32
private var busyHandler: BusyHandler?
/// Sets a handler to call when a statement is executed with the compiled
/// SQL.
///
/// - Parameter callback: This block is invoked when a statement is executed
/// with the compiled SQL as its argument.
///
/// db.trace { SQL in print(SQL) }
/*public*/ func trace(callback: (String -> Void)?) {
guard let callback = callback else {
sqlite3_trace(handle, nil, nil)
trace = nil
return
}
let box: Trace = { callback(String.fromCString($0)!) }
sqlite3_trace(handle, { callback, SQL in
unsafeBitCast(callback, Trace.self)(SQL)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
trace = box
}
private typealias Trace = @convention(block) UnsafePointer<Int8> -> Void
private var trace: Trace?
/// Registers a callback to be invoked whenever a row is inserted, updated,
/// or deleted in a rowid table.
///
/// - Parameter callback: A callback invoked with the `Operation` (one of
/// `.Insert`, `.Update`, or `.Delete`), database name, table name, and
/// rowid.
/*public*/ func updateHook(callback: ((operation: Operation, db: String, table: String, rowid: Int64) -> Void)?) {
guard let callback = callback else {
sqlite3_update_hook(handle, nil, nil)
updateHook = nil
return
}
let box: UpdateHook = {
callback(
operation: Operation(rawValue: $0),
db: String.fromCString($1)!,
table: String.fromCString($2)!,
rowid: $3
)
}
sqlite3_update_hook(handle, { callback, operation, db, table, rowid in
unsafeBitCast(callback, UpdateHook.self)(operation, db, table, rowid)
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
updateHook = box
}
private typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void
private var updateHook: UpdateHook?
/// Registers a callback to be invoked whenever a transaction is committed.
///
/// - Parameter callback: A callback invoked whenever a transaction is
/// committed. If this callback throws, the transaction will be rolled
/// back.
/*public*/ func commitHook(callback: (() throws -> Void)?) {
guard let callback = callback else {
sqlite3_commit_hook(handle, nil, nil)
commitHook = nil
return
}
let box: CommitHook = {
do {
try callback()
} catch {
return 1
}
return 0
}
sqlite3_commit_hook(handle, { callback in
unsafeBitCast(callback, CommitHook.self)()
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
commitHook = box
}
private typealias CommitHook = @convention(block) () -> Int32
private var commitHook: CommitHook?
/// Registers a callback to be invoked whenever a transaction rolls back.
///
/// - Parameter callback: A callback invoked when a transaction is rolled
/// back.
/*public*/ func rollbackHook(callback: (() -> Void)?) {
guard let callback = callback else {
sqlite3_rollback_hook(handle, nil, nil)
rollbackHook = nil
return
}
let box: RollbackHook = { callback() }
sqlite3_rollback_hook(handle, { callback in
unsafeBitCast(callback, RollbackHook.self)()
}, unsafeBitCast(box, UnsafeMutablePointer<Void>.self))
rollbackHook = box
}
private typealias RollbackHook = @convention(block) () -> Void
private var rollbackHook: RollbackHook?
/// Creates or redefines a custom SQL function.
///
/// - Parameters:
///
/// - function: The name of the function to create or redefine.
///
/// - argumentCount: The number of arguments that the function takes. If
/// `nil`, the function may take any number of arguments.
///
/// Default: `nil`
///
/// - deterministic: Whether or not the function is deterministic (_i.e._
/// the function always returns the same result for a given input).
///
/// Default: `false`
///
/// - block: A block of code to run when the function is called. The block
/// is called with an array of raw SQL values mapped to the function’s
/// parameters and should return a raw SQL value (or nil).
/*public*/ func createFunction(function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: (args: [Binding?]) -> Binding?) {
let argc = argumentCount.map { Int($0) } ?? -1
let box: Function = { context, argc, argv in
let arguments: [Binding?] = (0..<Int(argc)).map { idx in
let value = argv[idx]
switch sqlite3_value_type(value) {
case SQLITE_BLOB:
return Blob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value)))
case SQLITE_FLOAT:
return sqlite3_value_double(value)
case SQLITE_INTEGER:
return sqlite3_value_int64(value)
case SQLITE_NULL:
return nil
case SQLITE_TEXT:
return String.fromCString(UnsafePointer(sqlite3_value_text(value)))!
case let type:
fatalError("unsupported value type: \(type)")
}
}
let result = block(args: arguments)
if let result = result as? Blob {
sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil)
} else if let result = result as? Double {
sqlite3_result_double(context, result)
} else if let result = result as? Int64 {
sqlite3_result_int64(context, result)
} else if let result = result as? String {
sqlite3_result_text(context, result, Int32(result.characters.count), SQLITE_TRANSIENT)
} else if result == nil {
sqlite3_result_null(context)
} else {
fatalError("unsupported result type: \(result)")
}
}
var flags = SQLITE_UTF8
if deterministic {
flags |= SQLITE_DETERMINISTIC
}
sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { context, argc, value in
unsafeBitCast(sqlite3_user_data(context), Function.self)(context, argc, value)
}, nil, nil, nil)
if functions[function] == nil { self.functions[function] = [:] }
functions[function]?[argc] = box
}
private typealias Function = @convention(block) (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) -> Void
private var functions = [String: [Int: Function]]()
/// The return type of a collation comparison function.
/*public*/ typealias ComparisonResult = NSComparisonResult
/// Defines a new collating sequence.
///
/// - Parameters:
///
/// - collation: The name of the collation added.
///
/// - block: A collation function that takes two strings and returns the
/// comparison result.
/*public*/ func createCollation(collation: String, _ block: (lhs: String, rhs: String) -> ComparisonResult) {
let box: Collation = { lhs, rhs in
Int32(block(lhs: String.fromCString(UnsafePointer<Int8>(lhs))!, rhs: String.fromCString(UnsafePointer<Int8>(rhs))!).rawValue)
}
try! check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, UnsafeMutablePointer<Void>.self), { callback, _, lhs, _, rhs in
unsafeBitCast(callback, Collation.self)(lhs, rhs)
}, nil))
collations[collation] = box
}
private typealias Collation = @convention(block) (UnsafePointer<Void>, UnsafePointer<Void>) -> Int32
private var collations = [String: Collation]()
// MARK: - Error Handling
func sync<T>(block: () throws -> T) rethrows -> T {
var success: T?
var failure: ErrorType?
let box: () -> Void = {
do {
success = try block()
} catch {
failure = error
}
}
if dispatch_get_specific(Connection.queueKey) == queueContext {
box()
} else {
dispatch_sync(queue, box) // FIXME: rdar://problem/21389236
}
if let failure = failure {
try { () -> Void in throw failure }()
}
return success!
}
func check(resultCode: Int32, statement: Statement? = nil) throws -> Int32 {
guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else {
return resultCode
}
throw PensieveDBError(sqliteError: error)
}
private var queue = dispatch_queue_create("SQLite.Database", DISPATCH_QUEUE_SERIAL)
private static let queueKey = unsafeBitCast(Connection.self, UnsafePointer<Void>.self)
private lazy var queueContext: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
}
extension Connection : CustomStringConvertible {
/*public*/ var description: String {
return String.fromCString(sqlite3_db_filename(handle, nil))!
}
}
extension Connection.Location : CustomStringConvertible {
/*public*/ var description: String {
switch self {
case .InMemory:
return ":memory:"
case .Temporary:
return ""
case .URI(let URI):
return URI
}
}
}
/// An SQL operation passed to update callbacks.
/*public*/ enum Operation {
/// An INSERT operation.
case Insert
/// An UPDATE operation.
case Update
/// A DELETE operation.
case Delete
private init(rawValue: Int32) {
switch rawValue {
case SQLITE_INSERT:
self = .Insert
case SQLITE_UPDATE:
self = .Update
case SQLITE_DELETE:
self = .Delete
default:
fatalError("unhandled operation code: \(rawValue)")
}
}
}
/*public*/ enum Result : ErrorType {
private static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE]
case Error(message: String, code: Int32, statement: Statement?)
init?(errorCode: Int32, connection: Connection, statement: Statement? = nil) {
guard !Result.successCodes.contains(errorCode) else { return nil }
let message = String.fromCString(sqlite3_errmsg(connection.handle))!
self = Error(message: message, code: errorCode, statement: statement)
}
}
extension Result : CustomStringConvertible {
/*public*/ var description: String {
switch self {
case let .Error(message, _, statement):
guard let statement = statement else { return message }
return "\(message) (\(statement))"
}
}
}
| 8ab4f2e6174594ac6f67fc60049a569e | 34.829942 | 161 | 0.601477 | false | false | false | false |
alblue/swift | refs/heads/master | test/decl/func/dynamic_self.swift | apache-2.0 | 7 | // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-objc-interop
// ----------------------------------------------------------------------------
// DynamicSelf is only allowed on the return type of class and
// protocol methods.
func global() -> Self { } // expected-error{{global function cannot return 'Self'}}
func inFunction() {
func local() -> Self { } // expected-error{{local function cannot return 'Self'}}
}
struct S0 {
func f() -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{15-19=S0}}
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{16-20=S0}}
}
enum E0 {
func f() -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{15-19=E0}}
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{16-20=E0}}
}
class C0 {
func f() -> Self { } // okay
func g(_ ds: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}}
func h(_ ds: Self) -> Self { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{16-20=C0}}
}
protocol P0 {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P0 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
protocol P1: class {
func f() -> Self // okay
func g(_ ds: Self) // okay
}
extension P1 {
func h() -> Self { // okay
func g(_ t : Self) -> Self { // okay
return t
}
return g(self)
}
}
// ----------------------------------------------------------------------------
// The 'self' type of a Self method is based on Self
class C1 {
required init(int i: Int) {}
// Instance methods have a self of type Self.
func f(_ b: Bool) -> Self {
// FIXME: below diagnostic should complain about C1 -> Self conversion
if b { return C1(int: 5) } // expected-error{{cannot convert return expression of type 'C1' to return type 'Self'}}
// One can use `type(of:)` to attempt to construct an object of type Self.
if !b { return type(of: self).init(int: 5) }
// Can't utter Self within the body of a method.
var _: Self = self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{12-16=C1}}
// Okay to return 'self', because it has the appropriate type.
return self // okay
}
// Type methods have a self of type Self.Type.
class func factory(_ b: Bool) -> Self {
// Check directly.
var x: Int = self // expected-error{{cannot convert value of type 'Self.Type' to specified type 'Int'}}
// Can't utter Self within the body of a method.
var c1 = C1(int: 5) as Self // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C1'?}} {{28-32=C1}}
if b { return self.init(int: 5) }
return Self() // expected-error{{use of unresolved identifier 'Self'; did you mean 'self'?}}
}
// This used to crash because metatype construction went down a
// different code path that didn't handle DynamicSelfType.
class func badFactory() -> Self {
return self(int: 0)
// expected-error@-1 {{initializing from a metatype value must reference 'init' explicitly}}
}
}
// ----------------------------------------------------------------------------
// Using a method with a Self result carries the receiver type.
class X {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceX() -> X { }
}
class Y : X {
func produceY() -> Y { }
}
func testInvokeInstanceMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = x.instance()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = y.instance();
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testInvokeTypeMethodSelf() {
// Trivial case: invoking on the declaring class.
var x = X()
var x2 = X.factory()
x = x2 // at least an X
x2 = x // no more than an X
// Invoking on a subclass.
var y = Y()
var y2 = Y.factory()
y = y2 // at least a Y
y2 = y // no more than a Y
}
func testCurryInstanceMethodSelf() {
// Trivial case: currying on the declaring class.
var produceX = X.produceX
var produceX2 = X.instance
produceX = produceX2
produceX2 = produceX
// Currying on a subclass.
var produceY = Y.produceY
var produceY2 = Y.instance
produceY = produceY2
produceY2 = produceY
}
class GX<T> {
func instance() -> Self {
}
class func factory() -> Self {
}
func produceGX() -> GX { }
}
class GY<T> : GX<[T]> {
func produceGY() -> GY { }
}
func testInvokeInstanceMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = x.instance()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = y.instance();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testInvokeTypeMethodSelfGeneric() {
// Trivial case: invoking on the declaring class.
var x = GX<Int>()
var x2 = GX<Int>.factory()
x = x2 // at least an GX<Int>
x2 = x // no more than an GX<Int>
// Invoking on a subclass.
var y = GY<Int>()
var y2 = GY<Int>.factory();
y = y2 // at least a GY<Int>
y2 = y // no more than a GY<Int>
}
func testCurryInstanceMethodSelfGeneric() {
// Trivial case: currying on the declaring class.
var produceGX = GX<Int>.produceGX
var produceGX2 = GX<Int>.instance
produceGX = produceGX2
produceGX2 = produceGX
// Currying on a subclass.
var produceGY = GY<Int>.produceGY
var produceGY2 = GY<Int>.instance
produceGY = produceGY2
produceGY2 = produceGY
}
// ----------------------------------------------------------------------------
// Overriding a method with a Self
class Z : Y {
override func instance() -> Self {
}
override class func factory() -> Self {
}
}
func testOverriddenMethodSelfGeneric() {
var z = Z()
var z2 = z.instance();
z = z2
z2 = z
var z3 = Z.factory()
z = z3
z3 = z
}
// ----------------------------------------------------------------------------
// Generic uses of Self methods.
protocol P {
func f() -> Self
}
func testGenericCall<T: P>(_ t: T) {
var t = t
var t2 = t.f()
t2 = t
t = t2
}
// ----------------------------------------------------------------------------
// Existential uses of Self methods.
func testExistentialCall(_ p: P) {
_ = p.f()
}
// ----------------------------------------------------------------------------
// Dynamic lookup of Self methods.
@objc class SomeClass {
@objc func method() -> Self { return self }
}
func testAnyObject(_ ao: AnyObject) {
var ao = ao
var result : AnyObject = ao.method!()
result = ao
ao = result
}
// ----------------------------------------------------------------------------
// Name lookup on Self values
extension Y {
func testInstance() -> Self {
if false { return self.instance() }
return instance()
}
class func testFactory() -> Self {
if false { return self.factory() }
return factory()
}
}
// ----------------------------------------------------------------------------
// Optional Self returns
extension X {
func tryToClone() -> Self? { return nil }
func tryHarderToClone() -> Self! { return nil }
func cloneOrFail() -> Self { return self }
func cloneAsObjectSlice() -> X? { return self }
}
extension Y {
func operationThatOnlyExistsOnY() {}
}
func testOptionalSelf(_ y : Y) {
if let clone = y.tryToClone() {
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneOrFail() { // expected-error {{initializer for conditional binding must have Optional type, not 'Y'}}
clone.operationThatOnlyExistsOnY()
}
// Sanity-checking to make sure that the above succeeding
// isn't coincidental.
if let clone = y.cloneAsObjectSlice() {
clone.operationThatOnlyExistsOnY() // expected-error {{value of type 'X' has no member 'operationThatOnlyExistsOnY'}}
}
if let clone = y.tryHarderToClone().tryToClone() {
clone.operationThatOnlyExistsOnY();
}
}
// ----------------------------------------------------------------------------
// Conformance lookup on Self
protocol Runcible {
}
extension Runcible {
func runce() {}
}
func wantsRuncible<T : Runcible>(_: T) {}
class Runce : Runcible {
func getRunced() -> Self {
runce()
wantsRuncible(self)
return self
}
}
// ----------------------------------------------------------------------------
// Forming a type with 'Self' in invariant position
struct Generic<T> { init(_: T) {} }
class InvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<InvariantSelf> = a
// expected-error@-1 {{cannot convert value of type 'Generic<Self>' to specified type 'Generic<InvariantSelf>'}}
return self
}
}
// FIXME: This should be allowed
final class FinalInvariantSelf {
func me() -> Self {
let a = Generic(self)
let _: Generic<FinalInvariantSelf> = a
// expected-error@-1 {{cannot convert value of type 'Generic<Self>' to specified type 'Generic<FinalInvariantSelf>'}}
return self
}
}
// ----------------------------------------------------------------------------
// Semi-bogus factory init pattern
protocol FactoryPattern {
init(factory: @autoclosure () -> Self)
}
extension FactoryPattern {
init(factory: @autoclosure () -> Self) { self = factory() }
}
class Factory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: Factory(_string: string))
// expected-error@-1 {{incorrect argument label in call (have 'factory:', expected '_string:')}}
// FIXME: Bogus diagnostic
}
}
// Final classes are OK
final class FinalFactory : FactoryPattern {
init(_string: String) {}
convenience init(string: String) {
self.init(factory: FinalFactory(_string: string))
}
}
| 52bb52c2debe204b7ab854b765fd37bc | 25.43038 | 164 | 0.580556 | false | false | false | false |
ACChe/eidolon | refs/heads/master | KioskTests/Bid Fulfillment/LoadingViewControllerTests.swift | mit | 1 | import Quick
import Nimble
@testable
import Kiosk
import Moya
import ReactiveCocoa
import Nimble_Snapshots
import Forgeries
class LoadingViewControllerTests: QuickSpec {
override func spec() {
var subject: LoadingViewController!
beforeEach {
subject = testLoadingViewController()
subject.animate = false
}
describe("default") {
it("placing a bid") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.completes = false
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("registering a user") {
subject.placingBid = false
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.completes = false
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
}
describe("errors") {
it("correctly placing a bid") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.errors = true
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("correctly registering a user") {
subject.placingBid = false
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.errors = true
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
}
describe("ending") {
it("placing bid success highest") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.bidIsResolved = true
stubViewModel.isHighestBidder = true
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("dismisses by tapping green checkmark when bidding was a success") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.bidIsResolved = true
stubViewModel.isHighestBidder = true
subject.viewModel = stubViewModel
var closed = false
subject.closeSelf = {
closed = true
}
let testingRecognizer = ForgeryTapGestureRecognizer()
subject.recognizer = testingRecognizer
subject.loadViewProgrammatically()
testingRecognizer.invoke()
expect(closed).to( beTrue() )
}
it("placing bid success not highest") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.bidIsResolved = true
stubViewModel.isHighestBidder = false
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("placing bid error due to outbid") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
subject.viewModel = stubViewModel
subject.loadViewProgrammatically()
let error = NSError(domain: OutbidDomain, code: 0, userInfo: nil)
subject.bidderError(error)
expect(subject).to(haveValidSnapshot())
}
it("placing bid succeeded but not resolved") {
subject.placingBid = true
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.bidIsResolved = false
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("registering user success") {
subject.placingBid = false
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.createdNewBidder = true
stubViewModel.bidIsResolved = true
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
it("registering user not resolved") {
subject.placingBid = false
let fulfillmentController = StubFulfillmentController()
let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid)
stubViewModel.bidIsResolved = true
subject.viewModel = stubViewModel
expect(subject).to(haveValidSnapshot())
}
}
}
}
let loadingViewControllerTestImage = UIImage.testImage(named: "artwork", ofType: "jpg")
func testLoadingViewController() -> LoadingViewController {
let controller = UIStoryboard.fulfillment().viewControllerWithID(.LoadingBidsorRegistering).wrapInFulfillmentNav() as! LoadingViewController
return controller
}
class StubLoadingViewModel: LoadingViewModel {
var errors = false
var completes = true
init(bidNetworkModel: BidderNetworkModel, placingBid: Bool) {
super.init(bidNetworkModel: bidNetworkModel, placingBid: placingBid, actionsCompleteSignal: RACSignal.never())
}
override func performActions() -> RACSignal {
if completes {
if errors {
return RACSignal.error(NSError(domain: "", code: 0, userInfo: nil))
} else {
return RACSignal.empty()
}
} else {
return RACSignal.never()
}
}
}
| ff093fd26507d09368e3c4cc5d6a0e71 | 40.370968 | 171 | 0.632878 | false | false | false | false |
criticalmaps/criticalmaps-ios | refs/heads/main | CriticalMapsKit/Sources/MapFeature/MapOverlayView.swift | mit | 1 | import ComposableArchitecture
import Foundation
import Styleguide
import SwiftUI
/// A view to overlay the map and indicate the next ride
public struct MapOverlayView<Content>: View where Content: View {
public struct ViewState: Equatable {
let isVisible: Bool
let isExpanded: Bool
public init(isVisible: Bool, isExpanded: Bool) {
self.isVisible = isVisible
self.isExpanded = isExpanded
}
}
@Environment(\.accessibilityReduceTransparency) var reduceTransparency
@Environment(\.accessibilityReduceMotion) var reduceMotion
let store: Store<ViewState, Never>
@ObservedObject var viewStore: ViewStore<ViewState, Never>
@State var isExpanded = false
@State var isVisible = false
let action: () -> Void
let content: () -> Content
public init(
store: Store<ViewState, Never>,
action: @escaping () -> Void,
@ViewBuilder content: @escaping () -> Content
) {
self.store = store
viewStore = ViewStore(store)
self.action = action
self.content = content
}
public var body: some View {
Button(
action: action,
label: {
HStack {
Image(uiImage: Asset.cm.image)
if isExpanded {
content()
.padding(.grid(2))
.transition(
.asymmetric(
insertion: .opacity.animation(reduceMotion ? nil : .easeInOut(duration: 0.1).delay(0.2)),
removal: .opacity.animation(reduceMotion ? nil : .easeOut(duration: 0.15))
)
)
}
}
.padding(.horizontal, isExpanded ? .grid(2) : 0)
}
)
.frame(minWidth: 50, minHeight: 50)
.foregroundColor(reduceTransparency ? .white : Color(.textPrimary))
.background(
Group {
if reduceTransparency {
RoundedRectangle(
cornerRadius: 12,
style: .circular
)
.fill(Color(.backgroundPrimary))
} else {
Blur()
.cornerRadius(12)
}
}
)
.transition(.scale.animation(reduceMotion ? nil : .easeOut(duration: 0.2)))
.onChange(of: viewStore.isExpanded, perform: { newValue in
let updateAction: () -> Void = { self.isExpanded = newValue }
reduceMotion ? updateAction() : withAnimation { updateAction() }
})
.onChange(of: viewStore.isVisible, perform: { newValue in
let updateAction: () -> Void = { self.isVisible = newValue }
reduceMotion ? updateAction() : withAnimation { updateAction() }
})
}
}
// MARK: Preview
struct MapOverlayView_Previews: PreviewProvider {
static var previews: some View {
Group {
MapOverlayView(
store: Store<MapFeature.State, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ()
)
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: true)
}
),
action: {},
content: {
VStack {
Text("Next Ride")
Text("FRIDAY")
}
}
)
MapOverlayView(
store: Store<MapFeature.State, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ()
)
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: true)
}
),
action: {},
content: {
VStack {
Text("Next Ride")
Text("FRIDAY")
}
}
)
MapOverlayView(
store: Store<MapFeature.State, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ()
)
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: false)
}
),
action: {},
content: {}
)
}
}
}
| 8ff331278a8948ea1b4ff01d03daca82 | 26.66 | 107 | 0.563027 | false | false | false | false |
gtrabanco/JSQDataSourcesKit | refs/heads/develop | Example/Example/FetchedTableViewController.swift | mit | 2 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import CoreData
import JSQDataSourcesKit
class FetchedTableViewController: UIViewController {
// MARK: outlets
@IBOutlet weak var tableView: UITableView!
// MARK: properties
let stack = CoreDataStack()
typealias CellFactory = TableViewCellFactory<TableViewCell, Thing>
var dataSourceProvider: TableViewFetchedResultsDataSourceProvider<Thing, CellFactory>?
var delegateProvider: TableViewFetchedResultsDelegateProvider<Thing, CellFactory>?
// MARK: view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// register cells
tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: tableCellId)
// create factory
let factory = TableViewCellFactory(reuseIdentifier: tableCellId) { (cell: TableViewCell, model: Thing, tableView: UITableView, indexPath: NSIndexPath) -> TableViewCell in
cell.textLabel?.text = model.displayName
cell.textLabel?.textColor = model.displayColor
cell.detailTextLabel?.text = "\(indexPath.section), \(indexPath.row)"
return cell
}
// create fetched results controller
let frc: NSFetchedResultsController = NSFetchedResultsController(fetchRequest: Thing.fetchRequest(), managedObjectContext: stack.context, sectionNameKeyPath: "category", cacheName: nil)
// create delegate provider
// by passing `frc` the provider automatically sets `frc.delegate = self.delegateProvider.delegate`
self.delegateProvider = TableViewFetchedResultsDelegateProvider(tableView: tableView, cellFactory: factory, controller: frc)
// create data source provider
// by passing `self.tableView`, the provider automatically sets `self.tableView.dataSource = self.dataSourceProvider.dataSource`
self.dataSourceProvider = TableViewFetchedResultsDataSourceProvider(fetchedResultsController: frc, cellFactory: factory, tableView: tableView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.dataSourceProvider?.performFetch()
}
// MARK: actions
@IBAction func didTapAddButton(sender: UIBarButtonItem) {
tableView.deselectAllRows()
let newThing = Thing.newThing(stack.context)
stack.saveAndWait()
dataSourceProvider?.performFetch()
if let indexPath = dataSourceProvider?.fetchedResultsController.indexPathForObject(newThing) {
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle)
}
println("Added new thing: \(newThing)")
}
@IBAction func didTapDeleteButton(sender: UIBarButtonItem) {
if let indexPaths = tableView.indexPathsForSelectedRows() as? [NSIndexPath] {
println("Deleting things at indexPaths: \(indexPaths)")
for i in indexPaths {
let thingToDelete = dataSourceProvider?.fetchedResultsController.objectAtIndexPath(i) as! Thing
stack.context.deleteObject(thingToDelete)
}
stack.saveAndWait()
dataSourceProvider?.performFetch()
}
}
@IBAction func didTapHelpButton(sender: UIBarButtonItem) {
UIAlertController.showHelpAlert(self)
}
}
// MARK: extensions
extension UITableView {
func deselectAllRows() {
if let indexPaths = indexPathsForSelectedRows() as? [NSIndexPath] {
for i in indexPaths {
deselectRowAtIndexPath(i, animated: true)
}
}
}
}
| 9737ff3e87a9f1fa0ecc07f00f103b08 | 29.4 | 193 | 0.689777 | false | false | false | false |
simonkim/AVCapture | refs/heads/master | AVCapture/AVEncoderVideoToolbox/NALUtil.swift | apache-2.0 | 1 | //
// NALUtil.swift
// AVCapture
//
// Created by Simon Kim on 2016. 9. 11..
// Copyright © 2016 DZPub.com. All rights reserved.
//
import Foundation
import CoreMedia
enum NALUnitType: Int8 {
case IDR = 5
case SPS = 7
case PPS = 8
}
class NALUtil {
static func readNALUnitLength(at pointer: UnsafePointer<UInt8>, headerLength: Int) -> Int
{
var result: Int = 0
for i in 0...(headerLength - 1) {
result |= Int(pointer[i]) << (((headerLength - 1) - i) * 8)
}
return result
}
}
extension CMBlockBuffer {
/*
* List of NAL Units without NALUnitHeader
*/
public func NALUnits(headerLength: Int) -> [Data] {
var totalLength: Int = 0
var pointer:UnsafeMutablePointer<Int8>? = nil
var dataArray: [Data] = []
if noErr == CMBlockBufferGetDataPointer(self, 0, &totalLength, nil, &pointer) {
while totalLength > Int(headerLength) {
let unitLength = pointer!.withMemoryRebound(to: UInt8.self, capacity: totalLength) {
NALUtil.readNALUnitLength(at: $0, headerLength: Int(headerLength))
}
dataArray.append(Data(bytesNoCopy: pointer!.advanced(by: Int(headerLength)),
count: unitLength,
deallocator: .none))
let nextOffset = headerLength + unitLength
pointer = pointer!.advanced(by: nextOffset)
totalLength -= Int(nextOffset)
}
}
return dataArray
}
}
| 115544c742e1edf4af601ee5a24d8354 | 27.237288 | 100 | 0.537815 | false | false | false | false |
jeevanRao7/Swift_Playgrounds | refs/heads/master | Swift Playgrounds/Challenges/Famous Color.playground/Contents.swift | mit | 1 | /************************
Problem Statement:
Print Most repeated Colors in a given colors array.
************************/
import Foundation
//Input Array of colors
let inputArray = ["green", "red" , "green", "blue", "green", "black", "red", "blue", "blue", "gray", "purple", "white", "green", "red", "yellow", "red", "blue", "green"]
func getTopItemsArray(_ array:[String]) -> [String] {
var topArray = [String]()
var colorDictionary = [String:Int]()
//Step 1 : Form dictionary of items with its count
for color in array {
if let count = colorDictionary[color] {
colorDictionary[color] = count + 1
}
else{
//First time encoured a color, initialize value to '1'
colorDictionary[color] = 1
}
}
//Step 2 : Find the max value in the colors count dictionary
let highest = colorDictionary.values.max()
//Step 3 : Get the 'color' key having 'height' value
for (color, count) in colorDictionary {
if count == highest {
topArray.append(color)
}
}
return topArray
}
//Print array of colors most repeated.
print(getTopItemsArray(inputArray))
| 008d7b60bfa7d5ac14b6d266ac750cca | 23.509804 | 169 | 0.5552 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.