repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gosick/calculator | calculator/calculator/ViewController.swift | 1 | 2036 | //
// ViewController.swift
// calculator
//
// Created by gosick on 2015/10/8.
// Copyright © 2015年 gosick. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsTypingNow = false
@IBAction func digitAppend(sender: UIButton) {
let digit = sender.currentTitle!
if userIsTypingNow {
display.text = display.text! + digit
}
else{
display.text = digit
userIsTypingNow = true
}
}
var operandStack = Array<Double>()
@IBAction func enterKey() {
userIsTypingNow = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsTypingNow = false
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsTypingNow {
enterKey()
}
switch operation {
case "+": performOperation{ $0 + $1 }
case "−": performOperation{ $1 - $0 }
case "×": performOperation{ $0 * $1 }
case "÷": performOperation{ $1 / $0 }
case "√": performOperation{ sqrt($0) }
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enterKey()
}
}
@nonobjc
func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enterKey()
}
}
}
| mit | 78790f556290f9338e9ba098cf22841a | 22.034091 | 90 | 0.529354 | 5.092965 | false | false | false | false |
DaRkD0G/EasyHelper | EasyHelper/SequenceTypeExtensions.swift | 1 | 2355 | //
// SequenceTypeExtensions.swift
// EasyHelper
//
// Created by DaRk-_-D0G on 02/10/2015.
// Copyright © 2015 DaRk-_-D0G. All rights reserved.
//
import Foundation
public extension AnySequence {
/**
Returns each element of the sequence in an array
:returns: Each element of the sequence in an array
*/
public func toArray () -> [Element] {
var result: [Element] = []
for item in self {
result.append(item)
}
return result
}
}
public extension SequenceType {
}
// MARK: - String
public extension SequenceType where Generator.Element == String {
/**
Count characters each cell of the array
- returns: [Int] Array of count characters by cell in the array
*/
public func countByCharactersInArray() -> [Int] {
return self.map{$0.characters.count}
}
/**
Apprend all string after by after
- returns: String
*/
public func appendAll() -> String {
return String( self.map{$0.characters}.reduce(String.CharacterView(), combine: {$0 + $1}))
}
/**
Array of String, find in array if has prefix String
:param: ignoreCase True find lowercaseString
:param: target String find
:returns: Array of String find
*/
public func containsPrefix(ignoreCase:Bool,var target: String) -> [String] {
let values = self.filter({
var val = $0
if ignoreCase {
val = val.lowercaseString
target = target.lowercaseString
}
return val.hasPrefix(target) ? true : false
})
return values
}
/**
Array of String, find in array if has suffix String
:param: ignoreCase True find lowercaseString
:param: target String find
:returns: Array of String find
*/
public func containsSuffix(ignoreCase:Bool,var target: String) -> [String] {
let values = self.filter({
var val = $0
if ignoreCase {
val = val.lowercaseString
target = target.lowercaseString
}
return val.hasSuffix(target) ? true : false
})
return values
}
} | mit | 2b97933dfe0bead525e9b45c307652ae | 24.053191 | 98 | 0.551827 | 4.708 | false | false | false | false |
Reflejo/ClosureKit | Sources/LambdaKit/UIImagePickerController+LambdaKit.swift | 2 | 3840 | //
// UIImagePickerController+LamdaKit.swift
// Created by Martin Conte Mac Donell on 3/31/15.
//
// Copyright (c) 2015 Lyft (http://lyft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public typealias LKFinishPickingMediaClosure = (UIImagePickerController, [UIImagePickerController.InfoKey: Any]) -> Void
public typealias LKCancelClosure = (UIImagePickerController) -> Void
// A global var to produce a unique address for the assoc object handle
private var associatedEventHandle: UInt8 = 0
/// UIImagePickerController with closure callback(s).
///
/// Example:
///
/// ```swift
/// let picker = UIImagePickerController()
/// picker.didCancel = { picker in
/// print("DID CANCEL! \(picker)")
/// }
/// picker.didFinishPickingMedia = { picker, media in
/// print("Media: \(media[UIImagePickerControllerEditedImage])")
/// }
/// self.presentViewController(picker, animated: true, completion: nil)
/// ```
extension UIImagePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private var closuresWrapper: ClosuresWrapper {
get {
if let wrapper = objc_getAssociatedObject(self, &associatedEventHandle) as? ClosuresWrapper {
return wrapper
}
let closuresWrapper = ClosuresWrapper()
self.closuresWrapper = closuresWrapper
return closuresWrapper
}
set {
self.delegate = self
objc_setAssociatedObject(self, &associatedEventHandle, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// The closure that fires after the receiver finished picking up an image.
public var didFinishPickingMedia: LKFinishPickingMediaClosure? {
set { self.closuresWrapper.didFinishPickingMedia = newValue }
get { return self.closuresWrapper.didFinishPickingMedia }
}
/// The closure that fires after the user cancels out of picker.
public var didCancel: LKCancelClosure? {
set { self.closuresWrapper.didCancel = newValue }
get { return self.closuresWrapper.didCancel }
}
// MARK: UIImagePickerControllerDelegate implementation
open func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
{
self.closuresWrapper.didFinishPickingMedia?(picker, info)
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.closuresWrapper.didCancel?(picker)
}
}
// MARK: - Private classes
fileprivate final class ClosuresWrapper {
fileprivate var didFinishPickingMedia: LKFinishPickingMediaClosure?
fileprivate var didCancel: LKCancelClosure?
}
| mit | 64de48f222e3ea29c436d1fbc19ab949 | 38.183673 | 120 | 0.722135 | 4.910486 | false | false | false | false |
TableBooking/ios-client | TableBooking/SearchViewController.swift | 1 | 12991 | //
// SearchViewController.swift
// TableBooking
//
// Created by Nikita Kirichek on 11/19/16.
// Copyright © 2016 Nikita Kirichek. All rights reserved.
//
import UIKit
import GooglePlaces
class SearchViewController: UIViewController {
// MARK: - Constants
let rowHeight:CGFloat = 130
let maxPeople = 10
let stringFormatForPeopleQtyButton = "Table for %i people"
let dateFormatTimeButton = "MMM dd, yyyy hh:mm a"
// MARK: - IBOutlets
@IBOutlet weak var restaurantSearchBar: UISearchBar!
@IBOutlet weak var timeButton: UIButton!
@IBOutlet weak var peopleQtyButton: UIButton!
@IBOutlet weak var restaurantsTabelView: UITableView!
// MARK: - Views
var peopleQtyPicker: PeopleQtyPickerView!
var timePicker: DatePickerView!
//Google Places
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var resultView: UITextView?
// MARK: - Local Helpers
var chosenTime: Date?
var chosenQty: UInt?
var restaurants:[Restaurant] = []
var selectedRestaurant: Restaurant?
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//Colors
view.backgroundColor = Color.TBBackground
timeButton.backgroundColor = Color.TBGreen
timeButton.setTitleColor(Color.TBBackground, for: .normal)
restaurantsTabelView.backgroundColor = Color.TBBackground
peopleQtyButton.backgroundColor = Color.TBGreen
peopleQtyButton.setTitleColor(Color.TBBackground, for: .normal)
navigationController?.navigationBar.barTintColor = Color.TBGreen
navigationController?.navigationBar.barStyle = .black;
setDefaultTitleForDateButton()
setDefaultTitleForTimeButton()
setUpDatePicker()
setUpQtyPicker()
setUpGooglePlaces()
let rest1 = Restaurant()
let rest2 = Restaurant()
let rest3 = Restaurant()
let rest4 = Restaurant()
let rest5 = Restaurant()
rest1.name = "Le bernardin"
rest2.name = "Bouley"
rest3.name = "Jean-Georges"
rest4.name = "Daiel"
rest5.name = "Gotham Bar and Grill"
rest1.location = Location(address: "155 West 51st Street New York, New York 10019", longitude: 100, latitude: 100)
rest2.location = Location(address: "163 Duane Street New York, New York 10013", longitude: 100, latitude: 100)
rest3.location = Location(address: "1 Central Park West New York, New York 10023", longitude: 100, latitude: 100)
rest4.location = Location(address: "60 East 65th StreetNew York, New York 10065", longitude: 100, latitude: 100)
rest5.location = Location(address: "12 E 12th St New York, New York 10003", longitude:-73.993805, latitude: 40.734244)
rest1.imagePath = "bernandin.jpg"
rest2.imagePath = "bouley.jpg"
rest3.imagePath = "jean.jpg"
rest4.imagePath = "daniel.jpg"
rest5.imagePath = "got.jpg"
// rest3.location.address = "1 Central Park West New York, New York 10023"
// rest4.location.address = "60 East 65th StreetNew York, New York 10065"
// rest5.location.address = "12 E 12th St New York, New York 10003"
restaurants.append(rest1)
restaurants.append(rest2)
restaurants.append(rest3)
restaurants.append(rest4)
restaurants.append(rest5)
}
override func viewWillAppear(_ animated: Bool) {
let leftBarButtonItem = UIBarButtonItem(title: "Map",
style: .plain,
target: self,
action:#selector(openMaps(sender:)));
let rightBarButtonItem = UIBarButtonItem(title: "Filter",
style: .plain,
target: self,
action: #selector(filter(sender:)))
leftBarButtonItem.tintColor = Color.TBBackground
rightBarButtonItem.tintColor = Color.TBBackground
navigationItem.leftBarButtonItem = leftBarButtonItem
navigationItem.rightBarButtonItem = rightBarButtonItem
DataAPI.sharedInstance.getAllRestaurants {result in
switch result {
case .success(let restaurants):
self.restaurants = (restaurants as? [Restaurant])!
self.reloadTableView()
default:break
}
}
}
override func viewWillDisappear(_ animated: Bool) {
//clear up
tabBarController?.navigationItem.leftBarButtonItem = nil;
tabBarController?.navigationItem.rightBarButtonItem = nil;
}
// MARK: - User Interaction
@IBAction func setTime(_ sender: UIButton) {
timePicker.presentOverFromBottom()
}
@IBAction func setPeopleQty(_ sender: UIButton) {
peopleQtyPicker.presentOverFromBottom()
}
func openMaps(sender: UIBarButtonItem){
print("Hello")
reloadTableView()
}
func filter(sender: UIBarButtonItem){
self.performSegue(withIdentifier: "filterSearchSegue", sender: self);
DataAPI.sharedInstance.bookTable(restaurantId: 2, time: Date(), qty: 2, completion: {result in print("")})
}
// MARK: - Additional Helpers
func setDefaultTitleForTimeButton() {
chosenQty = Config.defaultPeopleQtyForTable
peopleQtyButton.setTitle(String.init(format: stringFormatForPeopleQtyButton, chosenQty!), for: .normal)
}
func setDefaultTitleForDateButton() {
chosenTime = Date()
let formatter = DateFormatter()
formatter.dateFormat = dateFormatTimeButton
timeButton.setTitle(formatter.string(from: chosenTime!), for: .normal)
}
func setUpGooglePlaces() {
resultsViewController = GMSAutocompleteResultsViewController()
resultsViewController?.delegate = self
searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
searchController?.searchBar.searchBarStyle = .minimal
let subView = UIView(frame: CGRect(x: 0,
y: restaurantSearchBar.frame.origin.y - restaurantSearchBar.frame.height,
width: view.frame.width,
height: restaurantSearchBar.frame.height))
subView.addSubview((searchController?.searchBar)!)
view.addSubview(subView)
searchController?.searchBar.sizeToFit()
searchController?.hidesNavigationBarDuringPresentation = false
// When UISearchController presents the results view, present it in
// this view controller, not one further up the chain.
self.definesPresentationContext = true
}
func setUpDatePicker() {
timePicker = DatePickerView.instanceFromNib()
let y = view.frame.height - (timePicker.frame.size.height +
(tabBarController?.tabBar.frame.height)!)
timePicker.frameForPeresenting = CGRect(x: 0,
y: y,
width: view.frame.width,
height: timePicker.frame.size.height)
timePicker.delegate = self
view.addSubview(timePicker)
}
func setUpQtyPicker() {
peopleQtyPicker = PeopleQtyPickerView.instanceFromNib()
let y = view.frame.height - (peopleQtyPicker.frame.size.height +
(tabBarController?.tabBar.frame.height)!)
peopleQtyPicker.frameForPeresenting = CGRect(x: 0,
y: y,
width: view.frame.width,
height: peopleQtyPicker.frame.size.height)
peopleQtyPicker.maxPeopleQty = 10
peopleQtyPicker.delegate = self
view.addSubview(peopleQtyPicker)
}
func reloadTableView() {
restaurantsTabelView.reloadData();
//fitting talble view to content
var frame = restaurantsTabelView.frame
frame.size.height = restaurantsTabelView.contentSize.height
restaurantsTabelView.frame = frame
}
//MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier! {
case "restaurantSearchSegue":
if let restaurantViewController = segue.destination as? RestaurantPageViewController {
restaurantViewController.restaurant = selectedRestaurant!
}
default: break
}
}
}
// MARK: - DatePickerViewDelegate
extension SearchViewController: DatePickerViewDelegate {
func cancelClicked(dateView: DatePickerView) {
setTimeForButton(time: chosenTime!)
}
func doneClicked(dateView: DatePickerView, date: Date) {
chosenTime = date
setTimeForButton(time: chosenTime!)
}
func valueChanged(dateView: DatePickerView, date: Date) {
setTimeForButton(time: date)
}
func setTimeForButton(time: Date) {
let formatter = DateFormatter()
formatter.dateFormat = dateFormatTimeButton
timeButton.setTitle(formatter.string(from: time), for: .normal)
}
}
// MARK: - DatePickerViewDelegate
extension SearchViewController: PeopleQtyPickerViewDelegate {
func doneClicked(pickerView: PeopleQtyPickerView, qty: UInt) {
chosenQty = qty
let title = String.init(format: stringFormatForPeopleQtyButton, qty)
peopleQtyButton.setTitle(title, for: .normal)
}
func cancelClicked(pickerView: PeopleQtyPickerView) {
let title = String.init(format: stringFormatForPeopleQtyButton, chosenQty!)
peopleQtyButton.setTitle(title, for: .normal)
}
func valueChanged(pickerView: PeopleQtyPickerView, qty: UInt) {
let title = String.init(format: stringFormatForPeopleQtyButton, qty)
peopleQtyButton.setTitle(title, for: .normal)
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension SearchViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return rowHeight;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurants.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "restaurantTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell;
cell.nameLabel.text = restaurants[indexPath.item].name
cell.adressLabel.text = restaurants[indexPath.item].location.address
cell.restImage.image = UIImage(named: restaurants[indexPath.item].imagePath!)
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedRestaurant = restaurants[indexPath.item]
performSegue(withIdentifier: "restaurantSearchSegue", sender: self)
}
}
// MARK: - GMSAutocompleteResultsViewControllerDelegate
extension SearchViewController: GMSAutocompleteResultsViewControllerDelegate {
func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didAutocompleteWith place: GMSPlace) {
searchController?.isActive = false
// Do something with the selected place.
print("Place name: ", place.name )
print("Place address: ", place.formattedAddress ?? "ss")
print("Place attributions: ", place.attributions ?? "aatt")
}
func resultsController(_ resultsController: GMSAutocompleteResultsViewController, didFailAutocompleteWithError error: Swift.Error) {
print("Error: ", error.localizedDescription)
}
func didRequestAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
| mit | de57ca275cb4de39f4a99a58af2fdf75 | 33.64 | 136 | 0.634103 | 5.256981 | false | false | false | false |
Tangdixi/DCCornerTag | Source/DCCornerTag.swift | 1 | 6474 | //
// DCCornerTag.swift
// Example-DCDate
//
// Created by Tangdixi on 19/12/2015.
// Copyright © 2015 Tangdixi. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import Darwin
@IBDesignable
class DCCornerTag: UIView {
private lazy var tagShapePath:UIBezierPath = {
let type:CornerType = CornerType(rawValue: self.cornerType)!
return type.shapePathInRect(self.bounds)
}()
private lazy var tagShape:CAShapeLayer = {
var shape = CAShapeLayer()
shape.frame = self.bounds
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5)
shape.path = self.tagShapePath.CGPath
return shape
}()
private lazy var tagLabel:UILabel = {
var label = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: 30))
let type:TagDirection = TagDirection(rawValue: self.tagDirection)!
label.center = type.labelCenterPoint(self.bounds)
label.transform = CGAffineTransformMakeRotation(type.labelRotationAngel())
label.textAlignment = NSTextAlignment.Center
return label
}()
@IBInspectable var tagTextColor:UIColor = UIColor.redColor() {
willSet (newColor) {
self.tagLabel.textColor = newColor
}
}
@IBInspectable var tagLabelText:String = "tag" {
willSet (newText) {
self.tagLabel.text = newText
}
}
@IBInspectable var borderWidth:CGFloat = 1.0 {
willSet (newValue) {
self.tagShape.lineWidth = newValue
}
}
@IBInspectable var tagBackgroundColor:UIColor = UIColor.redColor() {
willSet (newColor) {
self.tagShape.fillColor = newColor.CGColor
}
}
@IBInspectable var borderColor:UIColor = UIColor.redColor() {
willSet (newColor) {
self.tagShape.strokeColor = newColor.CGColor
}
}
@IBInspectable var tagDirection:Int = 0 {
willSet {
let type = TagDirection(rawValue: newValue)!
let transform = CATransform3DMakeRotation(type.shapeRotationAngel(), 0, 0, 1.0)
self.tagShape.transform = transform
}
}
@IBInspectable var cornerType:Int = 0 {
willSet {
let type:CornerType = CornerType(rawValue: newValue)!
self.tagShapePath = type.shapePathInRect(self.bounds)
}
}
override func drawRect(rect: CGRect) {
self.backgroundColor = UIColor.clearColor()
self.layer.addSublayer(self.tagShape)
self .addSubview(self.tagLabel)
}
#if !TARGET_INTERFACE_BUILDER
init(frame:CGRect, tagDirection:TagDirection, cornerType:CornerType) {
self.tagDirection = tagDirection.rawValue
self.cornerType = cornerType.rawValue
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
#endif
}
enum CornerType:Int {
case Triangle = 0
case Trapezium = 1
func shapePathInRect(bounds:CGRect) -> UIBezierPath {
let shapePath = UIBezierPath()
switch self {
case .Triangle:
shapePath.moveToPoint(CGPoint(x: 0, y: 0))
shapePath.addLineToPoint(CGPoint(x:0, y:bounds.size.height))
shapePath.addLineToPoint(CGPoint(x: bounds.size.width, y: 0))
shapePath.addLineToPoint(CGPoint(x: 0, y: 0))
return shapePath
case .Trapezium:
shapePath.moveToPoint(CGPoint(x: 0, y: bounds.size.height * (1 - goldRatio)))
shapePath.addLineToPoint(CGPoint(x: 0, y: bounds.size.height))
shapePath.addLineToPoint(CGPoint(x: bounds.size.width, y: 0))
shapePath.addLineToPoint(CGPoint(x: bounds.size.width * (1 - goldRatio), y: 0))
shapePath.addLineToPoint(CGPoint(x: 0, y: bounds.size.height * (1 - goldRatio)))
return shapePath
}
}
}
enum TagDirection:Int {
case TopLeft = 0
case TopRight = 1
case BottomLeft = 2
case BottomRight = 3
func shapeRotationAngel() -> CGFloat {
switch self {
case .TopLeft:
return 0.0
case .TopRight:
return CGFloat(M_PI_2)
case .BottomLeft:
return -CGFloat(M_PI_2)
case .BottomRight:
return CGFloat(M_PI)
}
}
func labelCenterPoint(bounds:CGRect) -> CGPoint {
switch self {
case .TopLeft:
let x = (bounds.size.width * (1 - goldRatio/2))/2
let y = x
return CGPoint(x: x, y: y)
case .TopRight:
let x = bounds.size.width - (bounds.size.width * (1 - goldRatio/2))/2
let y = (bounds.size.width * (1 - goldRatio/2))/2
return CGPoint(x: x, y: y)
case .BottomLeft:
let x = (bounds.size.width * (1 - goldRatio/2))/2
let y = bounds.size.height - (bounds.size.height * (1 - goldRatio/2))/2
return CGPoint(x: x, y: y)
case .BottomRight:
let x = bounds.size.width - (bounds.size.width * (1 - goldRatio/2))/2
let y = x
return CGPoint(x: x, y: y)
}
}
func labelRotationAngel() -> CGFloat {
switch self {
case .TopLeft:
return -CGFloat(M_PI_4)
case .TopRight:
return CGFloat(M_PI_4)
case .BottomLeft:
return CGFloat(M_PI_4)
case .BottomRight:
return -CGFloat(M_PI_4)
}
}
}
private var goldRatio:CGFloat = 0.618
| mit | 2230099a7e26443a84b640d9a6a36b65 | 23.152985 | 97 | 0.507802 | 4.711063 | false | false | false | false |
onmyway133/Github.swift | GithubSwiftTests/Classes/Client+RequestSpec.swift | 1 | 6099 | //
// Client+RequestSpec.swift
// GithubSwift
//
// Created by Khoa Pham on 02/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import GithubSwift
import Quick
import Nimble
import Mockingjay
import RxSwift
import Construction
class ClientRequestSpec: QuickSpec {
override func spec() {
describe("without a user") {
var client: Client!
// A random ETag for testing.
let etag = "644b5b0155e6404a9cc4bd9d8b1ae730"
beforeEach {
client = Client(server: Server.dotComServer)
}
it("should create a GET request with default parameters") {
let requestDescriptor: RequestDescriptor = construct {
$0.path = "rate_limit"
}
let request = client.makeRequest(requestDescriptor)
expect(request).notTo(beNil())
expect(request.request?.URL).to(equal(NSURL(string: "https://api.github.com/rate_limit?per_page=100")!))
}
it("should create a POST request with default parameters") {
let requestDescriptor: RequestDescriptor = construct {
$0.method = .POST
$0.path = "diver/dave"
}
let request = client.makeRequest(requestDescriptor)
expect(request).notTo(beNil())
expect(request.request?.URL).to(equal(NSURL(string: "https://api.github.com/diver/dave")!))
}
it("should create a request using etags") {
let etag = "\"deadbeef\""
let requestDescriptor: RequestDescriptor = construct {
$0.path = "diver/dan"
$0.etag = etag
}
let request = client.makeRequest(requestDescriptor)
expect(request).notTo(beNil())
expect(request.request!.URL).to(equal(NSURL(string: "https://api.github.com/diver/dan?per_page=100")!))
expect(request.request?.allHTTPHeaderFields?["If-None-Match"] ?? "").to(equal(etag))
}
it("should GET a JSON dictionary") {
self.stub(uri("/rate_limit"), builder: jsonData(Helper.read("rate_limit")))
let requestDescriptor: RequestDescriptor = construct {
$0.path = "rate_limit"
}
let observable = client.enqueue(requestDescriptor)
self.async { expectation in
let _ = observable.subscribe { event in
switch(event) {
case .Error(_):
fail()
case let .Next(response):
let expected = [
"rate": [
"remaining": 4999,
"limit": 5000
]
]
expect(NSDictionary(dictionary: response.jsonArray[0])).to(equal(NSDictionary(dictionary: expected)))
expectation.fulfill()
default:
break;
}
}
}
}
it("should conditionally GET a modified JSON dictionary") {
self.stub(uri("/rate_limit"), builder: jsonData(Helper.read("rate_limit"), status: 200, headers: ["Etag": etag]))
let requestDescriptor: RequestDescriptor = construct {
$0.path = "rate_limit"
}
let observable = client.enqueue(requestDescriptor)
self.async { expectation in
let _ = observable.subscribe { event in
switch(event) {
case .Error:
fail()
case let .Next(response):
let expected = [
"rate": [
"remaining": 4999,
"limit": 5000
]
]
expect(response.etag).to(equal(etag))
expect(NSDictionary(dictionary: response.jsonArray[0])).to(equal(NSDictionary(dictionary: expected)))
expectation.fulfill()
default:
break
}
}
}
}
it("should conditionally GET an unmodified endpoint") {
self.stub(uri("/rate_limit"), builder: jsonData(Helper.read("rate_limit"), status: 304))
let requestDescriptor: RequestDescriptor = construct {
$0.path = "rate_limit"
$0.etag = etag
}
let observable = client.enqueue(requestDescriptor)
self.async { expectation in
let _ = observable.subscribe { event in
switch(event) {
case .Error:
fail()
case .Next:
fail()
case .Completed:
expectation.fulfill()
}
}
}
}
it("should GET a paginated endpoint") {
let link1 = "<https://api.github.com/items2>; rel=\"next\", <https://api.github.com/items3>; rel=\"last\""
let link2 = "<https://api.github.com/items3>; rel=\"next\", <https://api.github.com/items3>; rel=\"last\""
self.stub(uri("/items1"), builder: jsonData(Helper.read("page1"), status: 200, headers: ["Link": link1]))
self.stub(uri("/items2"), builder: jsonData(Helper.read("page2"), status: 200, headers: ["Link": link2]))
self.stub(uri("/items3"), builder: jsonData(Helper.read("page3")))
let requestDescriptor: RequestDescriptor = construct {
$0.path = "items1"
}
let expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.async { expectation in
var items: [Int] = []
let _ = client.enqueue(requestDescriptor)
.subscribeNext { response in
expect(response.jsonArray[0].array("items")).toNot(beNil())
if let array = response.jsonArray[0].array("items") {
items.appendContentsOf(array.map({$0["item"] as! Int}))
}
if items.count == expected.count {
expect(items).to(equal(expected))
expectation.fulfill()
}
}
}
}
}
}
}
| mit | 9824a658b2205f773b6e13f27e107c71 | 30.926702 | 121 | 0.522466 | 4.644326 | false | false | false | false |
ccdeccdecc/ccemoticon | 表情键盘/表情键盘/Emoticon/CCEmoticon.swift | 1 | 3558 | //
// CCEmoticon.swift
// 表情键盘
//
// Created by apple on 15/11/9.
// Copyright © 2015年 eason. All rights reserved.
//
import UIKit
//MARK: - 表情包模型
///表情包模型
class CCEmoticonPackage: NSObject {
//MARK: - 属性
///获取Emoticon.boundle的路径
private static let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
///表示文件夹名称
var id: String?
///表情包名称
var group_name_cn: String?
///所有表情
var emoticons: [CCEmoticon]?
///构造方法,通过表情包路径
init(id: String) {
self.id = id
super.init()
}
override var description: String {
return "\n\t表情包模型:id:\(id), group_name_cn:\(group_name_cn), emoticons: \(emoticons)"
}
///加载表情包
class func packages() -> [CCEmoticonPackage] {
//拼接 emoticon.plist的路径
let plistPath = bundlePath + "/emoticons.plist"
//加载plist
let plistDict = NSDictionary(contentsOfFile: plistPath)!
print("plistDict: \(plistDict)")
///表情包数组
var packages = [CCEmoticonPackage]()
//获取packages数组里面每个字典的key为id的值
if let packageArray = plistDict["packages"] as? [[String : AnyObject]] {
//遍历数组
for dict in packageArray {
//获取字典里面的key为id的值
let id = dict["id"] as! String //对应表情包得路径
//创建表情包,表情包里面只有id,其它的数据需要知道表情包的文件名称才能进行
let package = CCEmoticonPackage(id: id)
//让表情包去进一步加载数据(表情模型,表情包名称)
package.loadEmoticon()
packages.append(package)
}
}
return packages
}
///加载表情包里面的表情和其它数据
func loadEmoticon() {
//获取表情包文件里面的info.plist
//info.plist = bundle + 表情包文件夹名称 + info.plist
let infoPath = CCEmoticonPackage.bundlePath + "/" + id! + "/info.plist"
//加载info.plist
let infoDict = NSDictionary(contentsOfFile: infoPath)!
print("infoDict:\(infoDict)")
//获取表情包名称
group_name_cn = infoDict["group_name_cn"] as? String
//创建表情模型数组
emoticons = [CCEmoticon]()
//获取表情包模型
if let array = infoDict["emoticons"] as? [[String: String]] {
//遍历数组
for dict in array {
//字典转模型
emoticons?.append(CCEmoticon(dict: dict))
}
}
}
}
//MARK: - 表情模型
///表情模型
class CCEmoticon: NSObject {
///表情名称,用于网络传输
var chs: String?
///表情图片对应的名称
var png: String?
//emoji表情对应的16进制字符串
var code: String?
///字典转模型
init(dict: [String: String]) {
super.init()
//KVC赋值
setValuesForKeysWithDictionary(dict)
}
///字典的key在模型里面没有对应的属性
override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
override var description: String {
return "\n\t\t表情模型:chs:\(chs), png:\(png), code:\(code)"
}
}
| apache-2.0 | be839b74ea44cff78934db4374efb0f4 | 23.401639 | 105 | 0.544844 | 4.078082 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Fitting/Actions/DamagePatternsPredefined.swift | 2 | 3457 | //
// DamagePatternsPredefined.swift
// Neocom
//
// Created by Artem Shimanski on 3/19/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Dgmpp
import CoreData
struct DamagePatternsPredefined: View {
var onSelect: (DGMDamageVector) -> Void
struct Row: Identifiable {
var name: String
var damage: DGMDamageVector
var id: String {return name}
}
static let patterns: [Row] = {
return NSArray(contentsOf: Bundle.main.url(forResource: "damagePatterns", withExtension: "plist")!)?.compactMap { item -> Row? in
guard let item = item as? [String: Any] else {return nil}
guard let name = item["name"] as? String else {return nil}
guard let em = item["em"] as? Double else {return nil}
guard let thermal = item["thermal"] as? Double else {return nil}
guard let kinetic = item["kinetic"] as? Double else {return nil}
guard let explosive = item["explosive"] as? Double else {return nil}
let vector = DGMDamageVector(em: em, thermal: thermal, kinetic: kinetic, explosive: explosive)
return Row(name: name, damage: vector)
} ?? []
}()
var body: some View {
Section(header: Text("PREDEFINED")) {
ForEach(DamagePatternsPredefined.patterns) { row in
PredefinedDamagePatternCell(row: row, onSelect: self.onSelect)
}
}
}
}
struct PredefinedDamagePatternCell: View {
var row: DamagePatternsPredefined.Row
var onSelect: (DGMDamageVector) -> Void
@Environment(\.editMode) private var editMode
@Environment(\.self) private var environment
@Environment(\.managedObjectContext) private var managedObjectContext
@State private var selectedDamagePattern: DamagePattern?
@EnvironmentObject private var sharedState: SharedState
private func action() {
if editMode?.wrappedValue == .active {
self.selectedDamagePattern = DamagePattern(entity: NSEntityDescription.entity(forEntityName: "DamagePattern", in: self.managedObjectContext)!, insertInto: nil)
self.selectedDamagePattern?.damageVector = self.row.damage
self.selectedDamagePattern?.name = self.row.name
}
else {
self.onSelect(row.damage)
}
}
var body: some View {
Button(action: action) {
VStack(alignment: .leading, spacing: 4) {
Text(row.name)
DamageVectorView(damage: row.damage)
}.contentShape(Rectangle())
}.buttonStyle(PlainButtonStyle())
.sheet(item: $selectedDamagePattern) { pattern in
NavigationView {
DamagePatternEditor(damagePattern: pattern) {
self.selectedDamagePattern = nil
}
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
#if DEBUG
struct DamagePatternsPredefined_Previews: PreviewProvider {
static var previews: some View {
return NavigationView {
List {
DamagePatternsPredefined { _ in}
}.listStyle(GroupedListStyle())
.navigationBarItems(trailing: EditButton())
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | 3a3fa20c1cb28972661ba8239f4e0c53 | 35.378947 | 171 | 0.62963 | 4.88826 | false | false | false | false |
frtlupsvn/Flappy-Dragon | FlappyBird/ZCCLoginViewController.swift | 1 | 7477 | //
// ZCCLoginViewController.swift
// FlappyBird
//
// Created by Zoom Nguyen on 11/1/15.
// Copyright © 2015 ZoomCanCode.com. All rights reserved.
//
import UIKit
import Parse
import ParseFacebookUtilsV4
class ZCCLoginViewController: UIViewController {
@IBOutlet weak var btnFacebook: UIButton!
@IBOutlet weak var lblFacebookName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if ((PFUser.currentUser()) == nil){
// Show Message
// User must login facebook to continue playing game
showPopUp()
}else {
updateFacebookStatus()
}
}
override func viewWillAppear(animated: Bool) {
//Check User login facebook
if ((PFUser.currentUser()) == nil){
btnFacebook .setImage(UIImage(named: "facebookBtn.png"), forState: .Normal)
self.lblFacebookName.text = "Login Facebook"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnFacebookTapped(sender: AnyObject) {
if ((PFUser.currentUser()) != nil){
}else{
let permissions = ["public_profile","email","user_friends"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"name,email,picture"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil){
} else {
let userFullName = result.valueForKey("name") as? String
let userEmail = result.valueForKey("email") as? String
let facebookId = result.valueForKey("id") as? String
let imageFile = PFFile(name: "profileImage.png", data: self.getProfPic(facebookId!)!)
// Here I try to add the retrieved Facebook data to the PFUser object
user["fullname"] = userFullName
user.email = userEmail
user["facebookProfilePicture"] = imageFile
user.saveInBackgroundWithBlock({ (boolValue, error) -> Void in
self.updateFacebookStatus()
})
}
})
} else {
print("User logged in through Facebook!")
self.updateFacebookStatus()
}
} else {
print("Uh oh. The user cancelled the Facebook login.")
}
}
}
}
func getProfPic(fid: String) -> NSData? {
if (fid != "") {
let imgURLString = "http://graph.facebook.com/" + fid + "/picture?type=large" //type=normal
let imgURL = NSURL(string: imgURLString)
let imageData = NSData(contentsOfURL: imgURL!)
return imageData
}
return nil
}
func updateFacebookStatus(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let currentUser = PFUser.currentUser()
let imageFile = currentUser?.objectForKey("facebookProfilePicture")
let imageURL = NSURL(string: (imageFile?.url)!)
let imageData = NSData(contentsOfURL: imageURL!)
dispatch_async(dispatch_get_main_queue()) {
self.btnFacebook.layer.cornerRadius = 0.5 * self.btnFacebook.bounds.size.width
self.btnFacebook.clipsToBounds = true
self.btnFacebook.setImage(UIImage(data: imageData!), forState: .Normal)
self.lblFacebookName.text = currentUser?.objectForKey("fullname") as? String
self.getUserRecord()
}
}
}
func startGame(){
self.performSegueWithIdentifier("LoginSuccess", sender: self)
}
func showPopUp(){
let alertView = SCLAlertView()
alertView.showInfo("Flappy Bat", subTitle: "You have to login with Facebook for play")
}
func showLoginFBSuccess(name:String){
let alertView = SCLAlertView()
alertView.showCloseButton = false
alertView.addButton("Start Game") {
self.startGame()
}
let highestScore = NSUserDefaults.standardUserDefaults().objectForKey("highestScore") as! NSInteger
alertView.showSuccess("Flappy Bat", subTitle: "Hello " + name + "\n Your record:" + String(highestScore) + "\n You can start a game now !")
}
func getUserRecord(){
var scoreUser = 0
// get device information
let currentUser = PFUser.currentUser()
//Check this device has data exist on Parse?
let query = PFQuery(className:"GameScore")
query.whereKey("facebookUser", equalTo:currentUser!)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
if (objects!.count == 0){
}else{
for object in objects! {
let query = PFQuery(className:"GameScore")
query.getObjectInBackgroundWithId(object.objectId!) {
(gameScore: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let gameScore = gameScore {
scoreUser = (gameScore["score"] as? NSInteger)!
// Save score to local database
NSUserDefaults.standardUserDefaults().setObject(scoreUser, forKey: "highestScore")
NSUserDefaults.standardUserDefaults().synchronize()
self.showLoginFBSuccess((currentUser?.objectForKey("fullname") as? String)!)
}
}
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
/*
// 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.
}
*/
}
| mit | 9f0efbdadf790fe89adfca26f0c4d2cf | 38.555556 | 147 | 0.520198 | 5.781903 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Other/Defaults.swift | 2 | 2321 | //
// Defaults.swift
// WikiRaces
//
// Created by Andrew Finke on 6/24/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import Foundation
struct Defaults {
private static let defaults = UserDefaults.standard
private static let promptedGlobalRacesPopularityKey = "PromptedGlobalRacesPopularity"
static var promptedGlobalRacesPopularity: Bool {
get {
return defaults.bool(forKey: promptedGlobalRacesPopularityKey)
}
set {
defaults.set(newValue, forKey: promptedGlobalRacesPopularityKey)
}
}
private static let fastlaneKey = "FASTLANE_SNAPSHOT"
static var isFastlaneSnapshotInstance: Bool {
get {
return defaults.bool(forKey: fastlaneKey)
}
}
private static let isAutoInviteOnKey = "isAutoInviteOnKey"
static var isAutoInviteOn: Bool {
get {
return defaults.bool(forKey: isAutoInviteOnKey)
}
set {
defaults.set(newValue, forKey: isAutoInviteOnKey)
}
}
private static let promptedAutoInviteKey = "PromptedAutoInviteKey"
static var promptedAutoInvite: Bool {
get {
return defaults.bool(forKey: promptedAutoInviteKey)
}
set {
defaults.set(newValue, forKey: promptedAutoInviteKey)
}
}
private static let shouldPromptForRatingKey = "ShouldPromptForRating"
static var shouldPromptForRating: Bool {
get {
return defaults.bool(forKey: shouldPromptForRatingKey)
}
set {
defaults.setValue(newValue, forKey: shouldPromptForRatingKey)
}
}
private static let shouldAutoSaveResultImageKey = "force_save_result_image"
static var shouldAutoSaveResultImage: Bool {
get {
return defaults.bool(forKey: shouldAutoSaveResultImageKey)
}
set {
defaults.setValue(newValue, forKey: shouldAutoSaveResultImageKey)
}
}
private static let promptedSoloRacesStatsKey = "PromptedSoloRacesStatsKey"
static var promptedSoloRacesStats: Bool {
get {
return defaults.bool(forKey: promptedSoloRacesStatsKey)
}
set {
defaults.set(newValue, forKey: promptedSoloRacesStatsKey)
}
}
}
| mit | 55684f5c5c70cc48a18be752f7c471ff | 27.292683 | 89 | 0.646983 | 4.53125 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/App/AppStyle.swift | 1 | 1885 | //
// AppStyle.swift
// zhuishushenqi
//
// Created by yung on 2017/8/8.
// Copyright © 2017年 QS. All rights reserved.
//
import Foundation
let nightKey = "light.key"
let fontSizeKey = "fontSize.key"
let animationStyleKey = "animationStyle.key"
struct AppStyle {
static var shared = AppStyle()
var readFontSize:Int {
set {
UserDefaults.standard.set(newValue, forKey: fontSizeKey)
}
get {
let size = UserDefaults.standard.integer(forKey: fontSizeKey)
if size == 0 {
return 20;
}
return size
}
}
var reader:Reader = AppStyle.getReader() {
didSet{
AppStyle.setReader(reader)
}
}
var theme:AppTheme = UserDefaults.standard.bool(forKey: nightKey) ? .night : .day {
didSet{
UserDefaults.standard.set(theme == .night, forKey: nightKey)
}
}
var animationStyle:ZSReaderAnimationStyle = ZSReaderAnimationStyle(rawValue: UserDefaults.standard.integer(forKey: animationStyleKey)) ?? .none {
didSet {
UserDefaults.standard.set(animationStyle.rawValue, forKey: animationStyleKey)
UserDefaults.standard.synchronize()
}
}
private init(){}
static func getReader()->Reader{
let value = UserDefaults.standard.integer(forKey: readerKey)
switch value {
case 1:
return .yellow
case 2:
return .green
default:
return .white
}
}
static func setReader(_ reader:Reader){
var value = 0
switch reader {
case .yellow:
value = 1
case .green:
value = 2
default:
value = 0
}
UserDefaults.standard.set(value, forKey: readerKey)
}
}
| mit | 8fde36b611eb196ded1d261dd0754673 | 23.128205 | 149 | 0.559511 | 4.601467 | false | false | false | false |
allengaller/actor-platform | actor-apps/app-ios/Actor/Controllers/Settings/SettingsViewController.swift | 13 | 12783 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
class SettingsViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let UserInfoCellIdentifier = "UserInfoCellIdentifier"
private let TitledCellIdentifier = "TitledCellIdentifier"
private var tableData: UATableData!
private let uid: Int
private var user: AMUserVM?
private var binder = Binder()
private var phones: JavaUtilArrayList?
// MARK: -
// MARK: Constructors
init() {
uid = Int(MSG.myUid())
super.init(style: UITableViewStyle.Plain)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabSettings", comment: "Settings Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("ic_settings_outline"),
selectedImage: MainAppTheme.tab.createSelectedIcon("ic_settings_filled"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
edgesForExtendedLayout = UIRectEdge.Top
automaticallyAdjustsScrollViewInsets = false
user = MSG.getUserWithUid(jint(uid))
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.clipsToBounds = false
tableView.tableFooterView = UIView()
tableData = UATableData(tableView: tableView)
tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier)
tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier)
tableData.tableScrollClosure = { (tableView: UITableView) -> () in
self.applyScrollUi(tableView)
}
// Avatar
tableData.addSection().addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell
cell.contentView.superview?.clipsToBounds = false
if self.user != nil {
cell.setUsername(self.user!.getNameModel().get())
}
cell.setLeftInset(15.0)
self.applyScrollUi(tableView, cell: cell)
return cell
}.setHeight(Double(avatarHeight))
// Phones
tableData.addSection()
.setFooterHeight(15)
.addCustomCells(55, countClosure: { () -> Int in
if (self.phones != nil) {
return Int(self.phones!.size())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
var cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
cell.setLeftInset(15.0)
if let phone = self.phones!.getWithInt(jint(index)) as? AMUserPhone {
cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())")
}
cell.hideTopSeparator()
cell.showBottomSeparator()
var phonesCount = Int(self.phones!.size());
if index == phonesCount - 1 {
cell.setBottomSeparatorLeftInset(0.0)
} else {
cell.setBottomSeparatorLeftInset(15.0)
}
return cell
}.setAction { (index) -> () in
var phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())!
var hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!)
if (!hasPhone) {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
} else {
self.showActionSheet(["CallNumber", "CopyNumber"],
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == 0) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!)
} else if index == 1 {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
}
})
}
}
// Profile
var topSection = tableData.addSection()
topSection.setHeaderHeight(15)
topSection.setFooterHeight(15)
// Profile: Set Photo
topSection.addActionCell("SettingsSetPhoto", actionClosure: { () -> () in
var hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user!.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
MSG.removeMyAvatar()
})
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
MSG.changeOwnAvatar(image)
})
}
})
}).hideTopSeparator().hideBottomSeparator()
// Profile: Set Name
topSection.addActionCell("SettingsChangeName", actionClosure: { () -> () in
var alertView = UIAlertView(title: nil,
message: NSLocalizedString("SettingsEditHeader", comment: "Title"),
delegate: nil,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString("AlertSave", comment: "Save Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = self.user!.getNameModel().get()
alertView.textFieldAtIndex(0)?.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alertView, buttonIndex) -> () in
if (buttonIndex == 1) {
let textField = alertView.textFieldAtIndex(0)!
if count(textField.text) > 0 {
self.execute(MSG.editMyNameCommandWithName(textField.text))
}
}
}
alertView.show()
}).showTopSeparator(15)
// Settings
var actionsSection = tableData.addSection()
.setHeaderHeight(15)
.setFooterHeight(15)
// Settings: Notifications
actionsSection.addNavigationCell("SettingsNotifications", actionClosure: { () -> () in
self.navigateNext(SettingsNotificationsViewController(), removeCurrent: false)
}).showBottomSeparator(15)
// Settings: Privacy
actionsSection.addNavigationCell("SettingsSecurity", actionClosure: { () -> () in
self.navigateNext(SettingsPrivacyViewController(), removeCurrent: false)
}).hideTopSeparator()
// Support
var supportSection = tableData.addSection()
.setHeaderHeight(15)
.setFooterHeight(15)
// Support: Ask Question
supportSection.addNavigationCell("SettingsAskQuestion", actionClosure: { () -> () in
self.execute(MSG.findUsersCommandWithQuery("75551234567"), successBlock: { (val) -> Void in
var user:AMUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? AMUserVM {
user = tempUser
}
}
}
self.navigateDetail(ConversationViewController(peer: AMPeer.userWithInt(user.getId())))
}, failureBlock: { (val) -> Void in
// TODO: Implement
})
}).showBottomSeparator(15)
// Support: Ask Question
supportSection.addNavigationCell("SettingsAbout", actionClosure: { () -> () in
UIApplication.sharedApplication().openURL(NSURL(string: "https://actor.im")!)
}).showBottomSeparator(15).hideTopSeparator()
// Support: App version
var version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
supportSection.addCommonCell()
.setContent("App Version: \(version)")
.setStyle(.Hint)
.hideTopSeparator()
// Bind
tableView.reloadData()
binder.bind(user!.getNameModel()!, closure: { (value: String?) -> () in
if value == nil {
return
}
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setUsername(value!)
}
})
binder.bind(MSG.getOwnAvatarVM().getUploadState(), valueModel2: user!.getAvatarModel()) { (upload: AMAvatarUploadState?, avatar: AMAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
if (upload != nil && upload!.isUploading().boolValue) {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), fileName: upload?.getDescriptor())
cell.setProgress(true)
} else {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: avatar, clearPrev: false)
cell.setProgress(false)
}
}
}
binder.bind(user!.getPresenceModel(), closure: { (presence: AMUserPresence?) -> () in
var presenceText = MSG.getFormatter().formatPresence(presence, withSex: self.user!.getSex())
if presenceText != nil {
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setPresence(presenceText)
}
}
})
binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in
if phones != nil {
self.phones = phones
self.tableView.reloadData()
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MSG.onProfileOpenWithUid(jint(uid))
MainAppTheme.navigation.applyStatusBar()
navigationController?.navigationBar.shadowImage = UIImage()
applyScrollUi(tableView)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MSG.onProfileClosedWithUid(jint(uid))
navigationController?.navigationBar.lt_reset()
}
}
| mit | 3f2d36ba99d60152cfdb058b1b9e278c | 40.77451 | 157 | 0.550653 | 5.577225 | false | false | false | false |
sebastiancrossa/smack | Smack/Services/AuthService.swift | 1 | 5998 | //
// AuthService.swift
// Smack
//
// Created by Sebastian Crossa on 7/30/17.
// Copyright © 2017 Sebastian Crossa. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
// Handle user registration
class AuthService {
static let instance = AuthService()
// Easiest way of saving persistent data on the device
let defaults = UserDefaults.standard
var isLoggedIn: Bool {
// Get = When we try to access it
// Set = When we try to set it
get {
return defaults.bool(forKey: LOGGED_IN_KEY)
} set {
defaults.set(newValue, forKey: LOGGED_IN_KEY) // newValue = Whatever value we write down when setting it
}
}
var authToken: String {
get {
return defaults.value(forKey: TOKEN_KEY) as! String
} set {
defaults.set(newValue, forKey: TOKEN_KEY)
}
}
var userEmail: String {
get {
return defaults.value(forKey: USER_EMAIL) as! String
} set {
defaults.set(newValue, forKey: USER_EMAIL)
}
}
// Function in charge of registering a user with a web request
func registerUser(email: String, password: String, completion: @escaping CompletionHandler) {
let lowerCaseEmail = email.lowercased()
let body: [String: Any] = [
"email": lowerCaseEmail,
"password": password
]
// Creating the actual web request
Alamofire.request(URL_REGISTER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: HEADER).responseString { (response) in
if response.result.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.result.error as Any)
}
}
}
// Function in charge of logging in the user, with an AUTH token as a response
func loginUser(email: String, password: String, completion: @escaping CompletionHandler) {
let lowerCaseEmail = email.lowercased()
let body: [String: Any] = [
"email": lowerCaseEmail,
"password": password
]
// Request that will recieve the auth token of the email logged in
Alamofire.request(URL_LOGIN, method: .post, parameters: body, encoding: JSONEncoding.default, headers: HEADER).responseJSON { (response) in
// JSON parsing
if response.result.error == nil {
// if let json = response.result.value as? Dictionary<String, Any> {
// if let email = json["user"] as? String {
// self.userEmail = email
// }
//
// if let token = json["token"] as? String {
// self.authToken = token
// }
// }
// Using SwiftyJSON
guard let data = response.data else { return } // Making sure data exists
let json = JSON(data: data) // Creating a data object
self.userEmail = json["user"].stringValue // Safely unwraps it as a String for us with .stringValue
self.authToken = json["token"].stringValue
// Succesfully logged in a user
self.isLoggedIn = true
completion(true)
} else {
completion(false)
debugPrint(response.result.error as Any)
}
}
}
// Function in charge of creating the user
func createUser(name: String, email: String, avatarName: String, avatarColor: String, completion: @escaping CompletionHandler) {
let lowerCaseEmail = email.lowercased()
let body: [String: Any] = [
"name": name,
"email": lowerCaseEmail,
"avatarName": avatarName,
"avatarColor": avatarColor
]
Alamofire.request(URL_USER_ADD, method: .post, parameters: body, encoding: JSONEncoding.default, headers: BEARER_HEADER).responseJSON { (response) in
if response.result.error == nil {
// JSON parsing
guard let data = response.data else { return }
// Will set the users data
self.setUserInfo(data: data)
completion(true)
} else {
completion(false)
debugPrint("-- Smack : Error in createUser function", response.result.error as Any)
}
}
}
func findUserByEmail(completion: @escaping CompletionHandler) {
Alamofire.request("\(URL_USER_BY_EMAIL)\(userEmail)", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: BEARER_HEADER).responseJSON { (response) in
if response.result.error == nil {
// JSON parsing
guard let data = response.data else { return }
// Will set the users data
self.setUserInfo(data: data)
completion(true)
} else {
completion(false)
debugPrint("-- Smack : Error in createUser function", response.result.error as Any)
}
}
}
func setUserInfo(data: Data) {
let json = JSON(data: data)
// Variables that will be passed to the UserDataService function created
let id = json["_id"].stringValue
let color = json["avatarColor"].stringValue
let avatarName = json["avatarName"].stringValue
let email = json["email"].stringValue
let name = json["name"].stringValue
UserDataService.instance.setUserData(id: id, color: color, avatarName: avatarName, email: email, name: name)
}
}
| apache-2.0 | cc56b6642d07d349bdf5f86e9892ad3b | 34.91018 | 177 | 0.547774 | 4.968517 | false | false | false | false |
adib/Core-ML-Playgrounds | Photo-Explorations/EnlargeImages.playground/Sources/CGImage+Expand.swift | 1 | 6138 | //
// UIImage+MultiArray.swift
// waifu2x-ios
//
// Created by xieyi on 2017/9/14.
// Copyright © 2017年 xieyi. All rights reserved.
//
import AppKit
import CoreML
extension CGImage {
/// Expand the original image by shrink_size and store rgb in float array.
/// The model will shrink the input image by 7 px.
///
/// - Returns: Float array of rgb values
public func expand() -> [Float] {
let startTime = Date.timeIntervalSinceReferenceDate
let width = Int(self.width)
let height = Int(self.height)
let exwidth = width + 2 * shrink_size
let exheight = height + 2 * shrink_size
let pixels = self.dataProvider?.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixels!)
var arr = [Float](repeating: 0, count: 3 * exwidth * exheight)
var xx, yy, pixel: Int
var r, g, b: UInt8
var fr, fg, fb: Float
// http://www.jianshu.com/p/516f01fed6e4
for y in 0..<height {
for x in 0..<width {
xx = x + shrink_size
yy = y + shrink_size
pixel = (width * y + x) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
// !!! rgb values are from 0 to 1
// https://github.com/chungexcy/waifu2x-new/blob/master/image_test.py
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
arr[yy * exwidth + xx] = fr
arr[yy * exwidth + xx + exwidth * exheight] = fg
arr[yy * exwidth + xx + exwidth * exheight * 2] = fb
}
}
// Top-left corner
pixel = 0
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in 0..<shrink_size {
for x in 0..<shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Top-right corner
pixel = (width - 1) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in 0..<shrink_size {
for x in width+shrink_size..<width+2*shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Bottom-left corner
pixel = (width * (height - 1)) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in height+shrink_size..<height+2*shrink_size {
for x in 0..<shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Bottom-right corner
pixel = (width * (height - 1) + (width - 1)) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
for y in height+shrink_size..<height+2*shrink_size {
for x in width+shrink_size..<width+2*shrink_size {
arr[y * exwidth + x] = fr
arr[y * exwidth + x + exwidth * exheight] = fg
arr[y * exwidth + x + exwidth * exheight * 2] = fb
}
}
// Top & bottom bar
for x in 0..<width {
pixel = x * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
xx = x + shrink_size
for y in 0..<shrink_size {
arr[y * exwidth + xx] = fr
arr[y * exwidth + xx + exwidth * exheight] = fg
arr[y * exwidth + xx + exwidth * exheight * 2] = fb
}
pixel = (width * (height - 1) + x) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
xx = x + shrink_size
for y in height+shrink_size..<height+2*shrink_size {
arr[y * exwidth + xx] = fr
arr[y * exwidth + xx + exwidth * exheight] = fg
arr[y * exwidth + xx + exwidth * exheight * 2] = fb
}
}
// Left & right bar
for y in 0..<height {
pixel = (width * y) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
yy = y + shrink_size
for x in 0..<shrink_size {
arr[yy * exwidth + x] = fr
arr[yy * exwidth + x + exwidth * exheight] = fg
arr[yy * exwidth + x + exwidth * exheight * 2] = fb
}
pixel = (width * y + (width - 1)) * 4
r = data[pixel]
g = data[pixel + 1]
b = data[pixel + 2]
fr = Float(r) / 255
fg = Float(g) / 255
fb = Float(b) / 255
yy = y + shrink_size
for x in width+shrink_size..<width+2*shrink_size {
arr[yy * exwidth + x] = fr
arr[yy * exwidth + x + exwidth * exheight] = fg
arr[yy * exwidth + x + exwidth * exheight * 2] = fb
}
}
let endTime = Date.timeIntervalSinceReferenceDate
print("cgimage-expand: ",endTime - startTime)
return arr
}
}
| bsd-3-clause | fd15726280a8ce27592e6736d7dc32b3 | 33.273743 | 85 | 0.439283 | 3.689116 | false | false | false | false |
edx/edx-app-ios | Source/CourseUpgradeCompletion.swift | 1 | 2204 | //
// CourseUpgradeCompletion.swift
// edX
//
// Created by Muhammad Umer on 16/12/2021.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
let CourseUpgradeCompletionNotification = "CourseUpgradeCompletionNotification"
class CourseUpgradeCompletion {
static let courseID = "CourseID"
static let blockID = "BlockID"
static let shared = CourseUpgradeCompletion()
enum CompletionState {
case success(_ courseID: String, _ componentID: String?)
case error
}
private init() { }
func handleCompletion(state: CompletionState) {
switch state {
case .success(let courseID, let blockID):
let dictionary = [
CourseUpgradeCompletion.courseID: courseID,
CourseUpgradeCompletion.blockID: blockID
]
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: CourseUpgradeCompletionNotification), object: dictionary))
showSuccess()
case .error:
showError()
}
}
private func showSuccess() {
guard let topController = UIApplication.shared.topMostController() else { return }
let alertController = UIAlertController().showAlert(withTitle: Strings.CourseUpgrade.successAlertTitle, message: Strings.CourseUpgrade.successAlertMessage, cancelButtonTitle: nil, onViewController: topController) { _, _, _ in }
alertController.addButton(withTitle: Strings.CourseUpgrade.successAlertContinue, style: .cancel) { action in
}
}
private func showError() {
guard let topController = UIApplication.shared.topMostController() else { return }
let alertController = UIAlertController().showAlert(withTitle: Strings.CourseUpgrade.failureAlertTitle, message: Strings.CourseUpgrade.failureAlertMessage, cancelButtonTitle: nil, onViewController: topController) { _, _, _ in }
alertController.addButton(withTitle: Strings.CourseUpgrade.failureAlertGetHelp) { action in
}
alertController.addButton(withTitle: Strings.close, style: .default) { action in
}
}
}
| apache-2.0 | a6f27f56fe87b9a2f9a1b0e86cf488da | 36.338983 | 235 | 0.674989 | 5.347087 | false | false | false | false |
kildevaeld/restler | Pod/Classes/BaseResource.swift | 1 | 6344 | //
// BBaseResource.swift
// Pods
//
// Created by Rasmus Kildevæld on 30/09/15.
//
//
import Foundation
import Alamofire
import Promissum
public protocol IResource {
var name: String { get }
var timeout: Double { get set }
func request(parameters:Parameters?, completion:(result:[AnyObject]?, error:ErrorType?) -> Void)
}
public typealias Parameters = Dictionary<String, AnyObject>
func +(var lhs:Parameters, rhs:Parameters) -> Parameters {
for (key, value) in rhs {
lhs.updateValue(value, forKey: key)
}
return lhs
}
func +=(inout lhs:Parameters, rhs:Parameters) {
lhs = lhs + rhs
}
public class BaseResource<T:ResponseDescriptor where T.ReturnType:AnyObject> : IResource {
// MARK: - Properties
private let restler: Restler
private let _lock = NSObject();
private var _lastUpdate: NSDate?
public var lastUpdate: NSDate? {
get {
return synchronized(_lock) { () -> NSDate? in
return self._lastUpdate
}
}
set (value) {
synchronized(_lock) {
self._lastUpdate = value
}
}
}
private var _baseURL: NSURL?
public var baseURL: NSURL {
get {
if _baseURL == nil {
_baseURL = self.restler.baseURL
}
return _baseURL!
}
set (url) {
_baseURL = url
}
}
public var onRequestBlock: ((request: NSMutableURLRequest, parameters: Parameters) -> Parameters?)?
public func setOnRequest (fn: (request: NSMutableURLRequest, parameters: Parameters) -> Parameters?) -> Self {
self.onRequestBlock = fn
return self
}
// Name of the resouce
public let name: String
// The path of the resource, relative to baseURL
public let path: String
// Minimum duration since last update
public var timeout: Double = 0
// Reponse descriptor
public var descriptor: T
// Parameters for all request on the resource
public var parameters: Parameters = Parameters()
init(restler: Restler, name: String, path: String, descriptor:T) {
self.restler = restler
self.name = name
self.path = path
self.descriptor = descriptor
}
func request(request: NSURLRequest, progress: ProgressBlock?, completion:(data:[T.ReturnType]?, error:ErrorType?) -> Void) {
//self.lastUpdate = NSDate()
self.restler.request(request, progress: progress) { [unowned self] (req, res, data, error) -> Void in
if error != nil {
completion(data: nil,error: error)
return
}
do {
let item: [T.ReturnType]?
if let array = data as? [AnyObject] {
item = try self.descriptor.respondArray(array)
} else {
let i = try self.descriptor.respond(data)
if i != nil {
item = [i!]
} else {
item = nil
}
}
completion(data: item, error: nil)
} catch let e as NSError {
completion(data: nil, error: e)
}
}
}
func request (path: String, parameters: Parameters?, method: Alamofire.Method = .GET, progress: ProgressBlock? = nil) -> Promise<[T.ReturnType]?, ErrorType> {
let promiseSource = PromiseSource<[T.ReturnType]?, ErrorType>()
let request: NSURLRequest
do {
(request,_) = try self.getRequest(method, path: path, parameters: parameters)
} catch let e {
promiseSource.reject(e)
return promiseSource.promise
}
self.request(request, progress: progress) { (data, error) -> Void in
if error != nil {
promiseSource.reject(error!)
} else {
promiseSource.resolve(data)
}
}
return promiseSource.promise
}
// IResource
public func request(parameters:Parameters?, completion:(result:[AnyObject]?, error:ErrorType?) -> Void) {
self.request(self.path, parameters: parameters)
.then { (result: [T.ReturnType]?) -> Void in
var res: [AnyObject]? = nil
if result != nil {
res = result! as [AnyObject]
}
completion(result: res, error: nil)
}.trap { (error) -> Void in
completion(result: nil, error: error)
}
}
// MARK: - Internals
private func getRequest (method: Alamofire.Method = .GET, path: String, parameters: Parameters?) throws -> (request: NSURLRequest, parameters: Parameters) {
let url = self.baseURL.URLByAppendingPathComponent(path)
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method.rawValue
var params = self.parameters
if parameters != nil {
params += parameters!
}
if self.onRequestBlock != nil {
let p = self.onRequestBlock!(request: request, parameters: params)
if p != nil {
params = p!
}
}
if !params.isEmpty {
request = try self.encodeRequest(request, parameters: params)
}
return (request, params)
}
func encodeRequest (request: NSURLRequest, parameters: Parameters) throws -> NSMutableURLRequest {
let encoding = Alamofire.ParameterEncoding.URL
let encoded = encoding.encode(request, parameters: parameters)
if encoded.1 != nil {
throw encoded.1!
}
return (encoded.0 as NSURLRequest).mutableCopy() as! NSMutableURLRequest
}
func should_update () -> Bool {
let diff = self.get_diff()
return diff >= self.timeout
}
func get_diff () -> Double {
let now = NSDate()
let diff = self.lastUpdate != nil ? now.timeIntervalSinceNow - self.lastUpdate!.timeIntervalSinceNow : self.timeout
return diff
}
}
| mit | fedccc999fd8fbdd4399e4feb327b094 | 28.640187 | 162 | 0.54501 | 4.853099 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Views/UpdatingLabel.swift | 1 | 2599 | //
// UpdatingLabel.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-04-15.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class UpdatingLabel: UILabel {
var formatter: NumberFormatter {
didSet {
setFormattedText(forValue: value)
}
}
init(formatter: NumberFormatter) {
self.formatter = formatter
super.init(frame: .zero)
text = self.formatter.string(from: 0 as NSNumber)
}
var completion: (() -> Void)?
private var value: Decimal = 0.0
func setValue(_ value: Decimal) {
self.value = value
setFormattedText(forValue: value)
}
func setValueAnimated(_ endingValue: Decimal, completion: @escaping () -> Void) {
self.completion = completion
guard let currentText = text else { return }
guard let startingValue = formatter.number(from: currentText)?.decimalValue else { return }
self.startingValue = startingValue
self.endingValue = endingValue
timer?.invalidate()
lastUpdate = CACurrentMediaTime()
progress = 0.0
startTimer()
}
private let duration = 0.6
private var easingRate: Double = 3.0
private var timer: CADisplayLink?
private var startingValue: Decimal = 0.0
private var endingValue: Decimal = 0.0
private var progress: Double = 0.0
private var lastUpdate: CFTimeInterval = 0.0
private func startTimer() {
timer = CADisplayLink(target: self, selector: #selector(UpdatingLabel.update))
timer?.preferredFramesPerSecond = 30
timer?.add(to: .main, forMode: RunLoop.Mode.default)
timer?.add(to: .main, forMode: RunLoop.Mode.tracking)
}
@objc private func update() {
let now = CACurrentMediaTime()
progress += (now - lastUpdate)
lastUpdate = now
if progress >= duration {
timer?.invalidate()
timer = nil
setFormattedText(forValue: endingValue)
completion?()
} else {
let percentProgress = progress/duration
let easedVal = 1.0-pow((1.0-percentProgress), easingRate)
setFormattedText(forValue: startingValue + (Decimal(easedVal) * (endingValue - startingValue)))
}
}
private func setFormattedText(forValue: Decimal) {
value = forValue
text = formatter.string(from: value as NSDecimalNumber)
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 153435c67930739789074dfd05673334 | 28.862069 | 107 | 0.627021 | 4.557895 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/repos/GsRepoSourceFileViewController.swift | 1 | 4290 | //
// GsRepoSourceFileViewController.swift
// GitHubStar
//
// Created by midoks on 16/3/15.
// Copyright © 2016年 midoks. All rights reserved.
//
//#url:https://developer.github.com/v3/git/trees/#get-a-tree
import UIKit
import SwiftyJSON
class GsRepoSourceFileViewController: GsListViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override func refreshUrl(){
super.refreshUrl()
self.startPull()
GitHubApi.instance.webGet(absoluteUrl: _fixedUrl, callback: { (data, response, error) -> Void in
self.pullingEnd()
self._tableData = Array<JSON>()
if data != nil {
let _dataJson = self.gitJsonParse(data: data!)
for i in _dataJson["tree"] {
self._tableData.append(i.1)
}
let rep = response as! HTTPURLResponse
if rep.allHeaderFields["Link"] != nil {
let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String)
self.pageInfo = r
}
self.asynTask(callback: { () -> Void in
self._tableView?.reloadData()
})
}
})
}
func setUrlData(url:String){
_fixedUrl = url
}
func setPathUrlData(url:String){
_fixedUrl = url
}
}
extension GsRepoSourceFileViewController:GsListViewDelegate {
func listTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let indexData = self.getSelectTableData(indexPath: indexPath)
let cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
if indexData["type"].stringValue == "tree" {
cell.imageView?.image = UIImage(named: "repo_file")
cell.textLabel?.text = indexData["path"].stringValue
} else if indexData["type"].stringValue == "blob" {
cell.imageView?.image = UIImage(named: "repo_gists")
cell.textLabel?.text = indexData["path"].stringValue
} else if indexData["type"] == "commit" {
cell.imageView?.image = UIImage(named: "repo_gists")
cell.textLabel?.text = indexData["path"].stringValue
}
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell.accessoryType = .disclosureIndicator
return cell
}
func listTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexData = self.getSelectTableData(indexPath: indexPath)
if indexData["type"].stringValue == "tree" {
let path = GsRepoSourceFileViewController()
path.setPathUrlData(url: indexData["url"].stringValue)
self.push(v: path)
} else if indexData["type"].stringValue == "blob" {
//TODO
let code = GsRepoSourceCodeViewController()
code.setUrlData(url: indexData["url"].stringValue)
self.push(v: code)
} else if indexData["type"].stringValue == "commit" {
print("commit")
}
}
func applyFilter(searchKey:String, data:JSON) -> Bool {
let name = data["path"].stringValue.lowercased()
if name.contains(searchKey.lowercased()) {
return true
}
return false
}
func pullUrlLoad(url: String){
GitHubApi.instance.webGet(absoluteUrl: url) { (data, response, error) -> Void in
self.pullingEnd()
if data != nil {
let _dataJson = self.gitJsonParse(data: data!)
for i in _dataJson {
self._tableData.append(i.1)
}
let rep = response as! HTTPURLResponse
if rep.allHeaderFields["Link"] != nil {
let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String)
self.pageInfo = r
}
self._tableView?.reloadData()
}
}
}
}
| apache-2.0 | a356c12096abdd9589b7bff2efa83374 | 32.492188 | 113 | 0.547469 | 4.827703 | false | false | false | false |
Witcast/witcast-ios | WiTcast/ViewController/Menu/MenuViewController.swift | 1 | 3282 | //
// MenuViewController.swift
// WiTcast
//
// Created by Tanakorn Phoochaliaw on 2/23/16.
// Copyright © 2016 Tanakorn Phoochaliaw. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var lblVersion: UILabel!
@IBOutlet var imgLogo: UIImageView!
@IBOutlet var lblTitle: UILabel!
@IBOutlet var mainTable: UITableView!
var indexMenu = 0;
let menu = ["New Feed", "WiTcast", "WiTcast Special", "WiTThai", "Other", "Favorites", "Download", "Support WiTcast", "About"];
let img = ["newfeed.png", "witcast.png", "special.png", "witthai.png", "other.png", "favorite.png", "download.png", "donate.png", "about.png"];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
self.mainTable.register(UINib(nibName: "MenuTableViewCell", bundle: nil), forCellReuseIdentifier: "MenuTableViewCell");
self.mainTable.separatorStyle = UITableViewCellSeparatorStyle.none;
let colorView = UIView();
colorView.backgroundColor = UIColor.clear;
UITableViewCell.appearance().selectedBackgroundView = colorView;
if UIScreen.main.bounds.width == 414 {
self.mainTable.rowHeight = 60.0
}
else if UIScreen.main.bounds.width == 375 {
self.mainTable.rowHeight = 55.0
}
self.initUI();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initUI(){
lblVersion.font = UIFont(name: font_header_regular, size: lblVersion.font.pointSize);
lblTitle.font = UIFont(name: font_header_regular, size: lblTitle.font.pointSize);
imgLogo.layer.cornerRadius = imgLogo.frame.size.width / 2;
imgLogo.clipsToBounds = true;
imgLogo.layer.borderWidth = 2.0;
imgLogo.layer.borderColor = UIColor.black.cgColor;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.menu.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell", for: indexPath as IndexPath) as! MenuTableViewCell
cell.lblTitle.font = UIFont(name: font_header_regular, size: cell.lblTitle.font.pointSize)!;
cell.lblTitle.text = "\(self.menu[indexPath.row])";
cell.imgDot.image = UIImage(named: img[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true);
self.closeSideMenu();
UserDefaults.standard.set(indexPath.row, forKey: "index")
UserDefaults.standard.synchronize()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
}
}
| apache-2.0 | 518394dc0d7f012414256d8eeedf5943 | 37.6 | 147 | 0.655898 | 4.470027 | false | false | false | false |
wolffan/chatExample | chatExample/simpleChat/keyboardExtension.swift | 1 | 2041 | //
// keyboardExtension.swift
// chatExample
//
// Created by Raimon Lapuente on 23/10/2016.
// Copyright © 2016 Raimon Lapuente. All rights reserved.
//
import Foundation
import UIKit
protocol keyboardAnimations {
func animateKeyboardChange(height: Float)
}
protocol keyboardRegistration {
func registerForKeyboard()
func deregisterKeyboard()
}
extension UIViewController : keyboardRegistration {
func registerForKeyboard() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func deregisterKeyboard() {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let controller = self as? keyboardAnimations {
if let info = notification.userInfo {
let keyboardFrame : CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let newBottomDistance = Float(keyboardFrame.size.height)
controller.animateKeyboardChange(height: newBottomDistance)
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let controller = self as? keyboardAnimations {
if let info = notification.userInfo {
let keyboardFrame : CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let newBottomDistance = 0 - Float(keyboardFrame.size.height)
controller.animateKeyboardChange(height: newBottomDistance)
}
}
}
}
| mit | 6fb8973461997d48c69e8853f8b550e1 | 37.490566 | 142 | 0.703431 | 5.382586 | false | false | false | false |
apple/swift-syntax | Sources/SwiftSyntax/Utils.swift | 1 | 4292 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public struct ByteSourceRange: Equatable {
public var offset: Int
public var length: Int
public init(offset: Int, length: Int) {
self.offset = offset
self.length = length
}
public var endOffset: Int {
return offset+length
}
public var isEmpty: Bool {
return length == 0
}
public func intersectsOrTouches(_ other: ByteSourceRange) -> Bool {
return self.endOffset >= other.offset &&
self.offset <= other.endOffset
}
public func intersects(_ other: ByteSourceRange) -> Bool {
return self.endOffset > other.offset &&
self.offset < other.endOffset
}
/// Returns the byte range for the overlapping region between two ranges.
public func intersected(_ other: ByteSourceRange) -> ByteSourceRange {
let start = max(self.offset, other.offset)
let end = min(self.endOffset, other.endOffset)
if start > end {
return ByteSourceRange(offset: 0, length: 0)
} else {
return ByteSourceRange(offset: start, length: end-start)
}
}
}
public struct SourceEdit: Equatable {
/// The byte range of the original source buffer that the edit applies to.
public let range: ByteSourceRange
/// The length of the edit replacement in UTF8 bytes.
public let replacementLength: Int
public var offset: Int { return range.offset }
public var length: Int { return range.length }
public var endOffset: Int { return range.endOffset }
/// After the edit has been applied the range of the replacement text.
public var replacementRange: ByteSourceRange {
return ByteSourceRange(offset: offset, length: replacementLength)
}
public init(range: ByteSourceRange, replacementLength: Int) {
self.range = range
self.replacementLength = replacementLength
}
public init(offset: Int, length: Int, replacementLength: Int) {
self.range = ByteSourceRange(offset: offset, length: length)
self.replacementLength = replacementLength
}
public func intersectsOrTouchesRange(_ other: ByteSourceRange) -> Bool {
return self.range.intersectsOrTouches(other)
}
public func intersectsRange(_ other: ByteSourceRange) -> Bool {
return self.range.intersects(other)
}
}
extension String {
static func fromBuffer(_ textBuffer: UnsafeBufferPointer<UInt8>) -> String {
return String(decoding: textBuffer, as: UTF8.self)
}
}
extension UnsafeBufferPointer where Element == UInt8 {
func hasPrefix(_ char: UInt8) -> Bool {
guard self.count >= 1 else { return false }
return self[0] == char
}
func hasPrefix(_ char1: UInt8, _ char2: UInt8) -> Bool {
guard self.count >= 2 else { return false }
return self[0] == char1 && self[1] == char2
}
func hasSuffix(_ char: UInt8) -> Bool {
guard self.count >= 1 else { return false }
return self[self.count-1] == char
}
func hasSuffix(_ char1: UInt8, _ char2: UInt8) -> Bool {
guard self.count >= 2 else { return false }
return self[self.count-2] == char1 && self[self.count-1] == char2
}
}
extension UInt8 {
static var asciiDoubleQuote: UInt8 { return 34 /* " */ }
static var asciiLeftAngleBracket: UInt8 { return 60 /* < */ }
static var asciiRightAngleBracket: UInt8 { return 62 /* > */ }
static var asciiPound: UInt8 { return 35 /* # */ }
}
extension RawUnexpectedNodesSyntax {
public init(elements: [RawSyntax], isMaximumNestingLevelOverflow: Bool, arena: __shared SyntaxArena) {
let raw = RawSyntax.makeLayout(
kind: .unexpectedNodes, uninitializedCount: elements.count, isMaximumNestingLevelOverflow: isMaximumNestingLevelOverflow, arena: arena) { layout in
guard var ptr = layout.baseAddress else { return }
for elem in elements {
ptr.initialize(to: elem.raw)
ptr += 1
}
}
self.init(raw: raw)
}
}
| apache-2.0 | 923f049d5ece55165f842cd92fecfaf0 | 30.792593 | 153 | 0.66589 | 4.279163 | false | false | false | false |
Ricky-Choi/AppcidCocoaUtil | ACUSample/MasterViewController.swift | 1 | 2402 | //
// MasterViewController.swift
// ACUSample
//
// Created by Jae Young Choi on 2017. 2. 2..
// Copyright © 2017년 Appcid. All rights reserved.
//
import UIKit
enum Sample: Int, CustomStringConvertible {
case autolayout
case presentOverlay
case count
var description: String {
switch self {
case .autolayout:
return "Auto Layout"
case .presentOverlay:
return "Present Overlay"
case .count:
return ""
}
}
}
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = Sample(rawValue: indexPath.row)!
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Sample.count.rawValue
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let object = Sample(rawValue: indexPath.row)!
cell.textLabel!.text = object.description
return cell
}
}
| mit | c509792262b24685222794f9c80e39b3 | 30.155844 | 144 | 0.661109 | 5.566125 | false | false | false | false |
czechboy0/Buildasaur | BuildaKit/BlueprintFileParser.swift | 3 | 2435 | //
// BlueprintFileParser.swift
// Buildasaur
//
// Created by Honza Dvorsky on 10/21/15.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
class BlueprintFileParser: SourceControlFileParser {
func supportedFileExtensions() -> [String] {
return ["xcscmblueprint"]
}
func parseFileAtUrl(url: NSURL) throws -> WorkspaceMetadata {
//JSON -> NSDictionary
let data = try NSData(contentsOfURL: url, options: NSDataReadingOptions())
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
guard let dictionary = jsonObject as? NSDictionary else { throw Error.withInfo("Failed to parse \(url)") }
//parse our required keys
let projectName = dictionary.optionalStringForKey("DVTSourceControlWorkspaceBlueprintNameKey")
let projectPath = dictionary.optionalStringForKey("DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey")
let projectWCCIdentifier = dictionary.optionalStringForKey("DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey")
var primaryRemoteRepositoryDictionary: NSDictionary?
if let wccId = projectWCCIdentifier {
if let wcConfigs = dictionary["DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey"] as? [NSDictionary] {
primaryRemoteRepositoryDictionary = wcConfigs.filter({
if let loopWccId = $0.optionalStringForKey("DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey") {
return loopWccId == wccId
}
return false
}).first
}
}
let projectURLString = primaryRemoteRepositoryDictionary?.optionalStringForKey("DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey")
var projectWCCName: String?
if
let copyPaths = dictionary["DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey"] as? [String: String],
let primaryRemoteRepoId = projectWCCIdentifier
{
projectWCCName = copyPaths[primaryRemoteRepoId]
}
return try WorkspaceMetadata(projectName: projectName, projectPath: projectPath, projectWCCIdentifier: projectWCCIdentifier, projectWCCName: projectWCCName, projectURLString: projectURLString)
}
}
| mit | 3e005f9918bb29f684a90bdff71e4b0f | 44.074074 | 200 | 0.696385 | 5.326039 | false | false | false | false |
strawberrycode/SCSectionBackground | SCSectionBackground/SectionBackgroundFlowLayout.swift | 1 | 3850 | //
// SectionBackgroundFlowLayout.swift
// SCSectionBackground
//
// Created by Catherine Schwartz on 12/02/2016.
// Copyright © 2016 StrawberryCode. All rights reserved.
//
import UIKit
class SectionBackgroundFlowLayout: UICollectionViewFlowLayout {
// MARK: prepareLayout
override func prepareLayout() {
super.prepareLayout()
minimumLineSpacing = 8.0
minimumInteritemSpacing = 8.0
sectionInset = UIEdgeInsetsMake(8, 8, 8, 8)
let width = (UIScreen.mainScreen().bounds.width / 3) - 2 * 8.0
itemSize = CGSizeMake(width, 100)
registerClass(SCSBCollectionReusableView.self, forDecorationViewOfKind: "sectionBackground")
}
// MARK: layoutAttributesForElementsInRect
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElementsInRect(rect)
var allAttributes = [UICollectionViewLayoutAttributes]()
if let attributes = attributes {
for attr in attributes {
// Look for the first item in a row
// You can also calculate it by item (remove the second check in the if below and change the tmpWidth and frame origin
if (attr.representedElementCategory == UICollectionElementCategory.Cell && attr.frame.origin.x == self.sectionInset.left) {
// Create decoration attributes
let decorationAttributes = SCSBCollectionViewLayoutAttributes(forDecorationViewOfKind: "sectionBackground", withIndexPath: attr.indexPath)
// Set the color(s)
if (attr.indexPath.section % 2 == 0) {
decorationAttributes.color = UIColor.greenColor().colorWithAlphaComponent(0.5)
} else {
decorationAttributes.color = UIColor.blueColor().colorWithAlphaComponent(0.5)
}
// Make the decoration view span the entire row
let tmpWidth = self.collectionView!.contentSize.width
let tmpHeight = self.itemSize.height + self.minimumLineSpacing + self.sectionInset.top / 2 + self.sectionInset.bottom / 2 // or attributes.frame.size.height instead of itemSize.height if dynamic or recalculated
decorationAttributes.frame = CGRectMake(0, attr.frame.origin.y - self.sectionInset.top, tmpWidth, tmpHeight)
// Set the zIndex to be behind the item
decorationAttributes.zIndex = attr.zIndex - 1
// Add the attribute to the list
allAttributes.append(decorationAttributes)
}
}
// Combine the items and decorations arrays
allAttributes.appendContentsOf(attributes)
}
return allAttributes
}
}
class SCSBCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes {
var color: UIColor = UIColor.whiteColor()
override func copyWithZone(zone: NSZone) -> AnyObject {
let newAttributes: SCSBCollectionViewLayoutAttributes = super.copyWithZone(zone) as! SCSBCollectionViewLayoutAttributes
newAttributes.color = self.color.copyWithZone(zone) as! UIColor
return newAttributes
}
}
class SCSBCollectionReusableView : UICollectionReusableView {
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
super.applyLayoutAttributes(layoutAttributes)
let scLayoutAttributes = layoutAttributes as! SCSBCollectionViewLayoutAttributes
self.backgroundColor = scLayoutAttributes.color
}
}
| mit | 4f110644aed7dc6b1b0f0eb8f3b31ce6 | 42.247191 | 231 | 0.642764 | 6.023474 | false | false | false | false |
caicai0/ios_demo | load/thirdpart/SwiftSoup/Whitelist.swift | 3 | 23975 | //
// Whitelist.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 14/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
/*
Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired
this whitelist configuration, and the initial defaults.
*/
/**
Whitelists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed.
<p>
Start with one of the defaults:
</p>
<ul>
<li>{@link #none}
<li>{@link #simpleText}
<li>{@link #basic}
<li>{@link #basicWithImages}
<li>{@link #relaxed}
</ul>
<p>
If you need to allow more through (please be careful!), tweak a base whitelist with:
</p>
<ul>
<li>{@link #addTags}
<li>{@link #addAttributes}
<li>{@link #addEnforcedAttribute}
<li>{@link #addProtocols}
</ul>
<p>
You can remove any setting from an existing whitelist with:
</p>
<ul>
<li>{@link #removeTags}
<li>{@link #removeAttributes}
<li>{@link #removeEnforcedAttribute}
<li>{@link #removeProtocols}
</ul>
<p>
The cleaner and these whitelists assume that you want to clean a <code>body</code> fragment of HTML (to add user
supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the
document HTML around the cleaned body HTML, or create a whitelist that allows <code>html</code> and <code>head</code>
elements as appropriate.
</p>
<p>
If you are going to extend a whitelist, please be very careful. Make sure you understand what attributes may lead to
XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See
http://ha.ckers.org/xss.html for some XSS attack examples.
</p>
*/
import Foundation
public class Whitelist {
private var tagNames: Set<TagName> // tags allowed, lower case. e.g. [p, br, span]
private var attributes: Dictionary<TagName, Set<AttributeKey>> // tag -> attribute[]. allowed attributes [href] for a tag.
private var enforcedAttributes: Dictionary<TagName, Dictionary<AttributeKey, AttributeValue>> // always set these attribute values
private var protocols: Dictionary<TagName, Dictionary<AttributeKey, Set<Protocol>>> // allowed URL protocols for attributes
private var preserveRelativeLinks: Bool // option to preserve relative links
/**
This whitelist allows only text nodes: all HTML will be stripped.
@return whitelist
*/
public static func none() -> Whitelist {
return Whitelist()
}
/**
This whitelist allows only simple text formatting: <code>b, em, i, strong, u</code>. All other HTML (tags and
attributes) will be removed.
@return whitelist
*/
public static func simpleText()throws ->Whitelist {
return try Whitelist().addTags("b", "em", "i", "strong", "u")
}
/**
<p>
This whitelist allows a fuller range of text nodes: <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,
ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul</code>, and appropriate attributes.
</p>
<p>
Links (<code>a</code> elements) can point to <code>http, https, ftp, mailto</code>, and have an enforced
<code>rel=nofollow</code> attribute.
</p>
<p>
Does not allow images.
</p>
@return whitelist
*/
public static func basic()throws->Whitelist {
return try Whitelist()
.addTags(
"a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em",
"i", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", "sub",
"sup", "u", "ul")
.addAttributes("a", "href")
.addAttributes("blockquote", "cite")
.addAttributes("q", "cite")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addEnforcedAttribute("a", "rel", "nofollow")
}
/**
This whitelist allows the same text tags as {@link #basic}, and also allows <code>img</code> tags, with appropriate
attributes, with <code>src</code> pointing to <code>http</code> or <code>https</code>.
@return whitelist
*/
public static func basicWithImages()throws->Whitelist {
return try basic()
.addTags("img")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addProtocols("img", "src", "http", "https")
}
/**
This whitelist allows a full range of text and structural body HTML: <code>a, b, blockquote, br, caption, cite,
code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub,
sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>
<p>
Links do not have an enforced <code>rel=nofollow</code> attribute, but you can add that if desired.
</p>
@return whitelist
*/
public static func relaxed()throws->Whitelist {
return try Whitelist()
.addTags(
"a", "b", "blockquote", "br", "caption", "cite", "code", "col",
"colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
"i", "img", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong",
"sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
"ul")
.addAttributes("a", "href", "title")
.addAttributes("blockquote", "cite")
.addAttributes("col", "span", "width")
.addAttributes("colgroup", "span", "width")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addAttributes("ol", "start", "type")
.addAttributes("q", "cite")
.addAttributes("table", "summary", "width")
.addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width")
.addAttributes(
"th", "abbr", "axis", "colspan", "rowspan", "scope",
"width")
.addAttributes("ul", "type")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addProtocols("img", "src", "http", "https")
.addProtocols("q", "cite", "http", "https")
}
/**
Create a new, empty whitelist. Generally it will be better to start with a default prepared whitelist instead.
@see #basic()
@see #basicWithImages()
@see #simpleText()
@see #relaxed()
*/
init() {
tagNames = Set<TagName>()
attributes = Dictionary<TagName, Set<AttributeKey>>()
enforcedAttributes = Dictionary<TagName, Dictionary<AttributeKey, AttributeValue>>()
protocols = Dictionary<TagName, Dictionary<AttributeKey, Set<Protocol>>>()
preserveRelativeLinks = false
}
/**
Add a list of allowed elements to a whitelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to allow
@return this (for chaining)
*/
@discardableResult
open func addTags(_ tags: String...)throws ->Whitelist {
for tagName in tags {
try Validate.notEmpty(string: tagName)
tagNames.insert(TagName.valueOf(tagName))
}
return self
}
/**
Remove a list of allowed elements from a whitelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to disallow
@return this (for chaining)
*/
@discardableResult
open func removeTags(_ tags: String...)throws ->Whitelist {
try Validate.notNull(obj:tags)
for tag in tags {
try Validate.notEmpty(string: tag)
let tagName: TagName = TagName.valueOf(tag)
if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed
tagNames.remove(tagName)
attributes.removeValue(forKey: tagName)
enforcedAttributes.removeValue(forKey: tagName)
protocols.removeValue(forKey: tagName)
}
}
return self
}
/**
Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>addAttributes("a", "href", "class")</code> allows <code>href</code> and <code>class</code> attributes
on <code>a</code> tags.
</p>
<p>
To make an attribute valid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>addAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary.
@param keys List of valid attributes for the tag
@return this (for chaining)
*/
@discardableResult
open func addAttributes(_ tag: String, _ keys: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.")
let tagName = TagName.valueOf(tag)
if (!tagNames.contains(tagName)) {
tagNames.insert(tagName)
}
var attributeSet = Set<AttributeKey>()
for key in keys {
try Validate.notEmpty(string: key)
attributeSet.insert(AttributeKey.valueOf(key))
}
if var currentSet = attributes[tagName] {
for at in attributeSet {
currentSet.insert(at)
}
attributes[tagName] = currentSet
} else {
attributes[tagName] = attributeSet
}
return self
}
/**
Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>removeAttributes("a", "href", "class")</code> disallows <code>href</code> and <code>class</code>
attributes on <code>a</code> tags.
</p>
<p>
To make an attribute invalid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>removeAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for.
@param keys List of invalid attributes for the tag
@return this (for chaining)
*/
@discardableResult
open func removeAttributes(_ tag: String, _ keys: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.")
let tagName: TagName = TagName.valueOf(tag)
var attributeSet = Set<AttributeKey>()
for key in keys {
try Validate.notEmpty(string: key)
attributeSet.insert(AttributeKey.valueOf(key))
}
if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed
if var currentSet = attributes[tagName] {
for l in attributeSet {
currentSet.remove(l)
}
attributes[tagName] = currentSet
if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag
attributes.removeValue(forKey: tagName)
}
}
}
if(tag == ":all") { // Attribute needs to be removed from all individually set tags
for name in attributes.keys {
var currentSet: Set<AttributeKey> = attributes[name]!
for l in attributeSet {
currentSet.remove(l)
}
attributes[name] = currentSet
if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag
attributes.removeValue(forKey: name)
}
}
}
return self
}
/**
Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element
already has the attribute set, it will be overridden.
<p>
E.g.: <code>addEnforcedAttribute("a", "rel", "nofollow")</code> will make all <code>a</code> tags output as
<code><a href="..." rel="nofollow"></code>
</p>
@param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary.
@param key The attribute key
@param value The enforced attribute value
@return this (for chaining)
*/
@discardableResult
open func addEnforcedAttribute(_ tag: String, _ key: String, _ value: String)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
try Validate.notEmpty(string: value)
let tagName: TagName = TagName.valueOf(tag)
if (!tagNames.contains(tagName)) {
tagNames.insert(tagName)
}
let attrKey: AttributeKey = AttributeKey.valueOf(key)
let attrVal: AttributeValue = AttributeValue.valueOf(value)
if (enforcedAttributes[tagName] != nil) {
enforcedAttributes[tagName]?[attrKey] = attrVal
} else {
var attrMap: Dictionary<AttributeKey, AttributeValue> = Dictionary<AttributeKey, AttributeValue>()
attrMap[attrKey] = attrVal
enforcedAttributes[tagName] = attrMap
}
return self
}
/**
Remove a previously configured enforced attribute from a tag.
@param tag The tag the enforced attribute is for.
@param key The attribute key
@return this (for chaining)
*/
@discardableResult
open func removeEnforcedAttribute(_ tag: String, _ key: String)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
if(tagNames.contains(tagName) && (enforcedAttributes[tagName] != nil)) {
let attrKey: AttributeKey = AttributeKey.valueOf(key)
var attrMap: Dictionary<AttributeKey, AttributeValue> = enforcedAttributes[tagName]!
attrMap.removeValue(forKey: attrKey)
enforcedAttributes[tagName] = attrMap
if(attrMap.isEmpty) { // Remove tag from enforced attribute map if no enforced attributes are present
enforcedAttributes.removeValue(forKey: tagName)
}
}
return self
}
/**
* Configure this Whitelist to preserve relative links in an element's URL attribute, or convert them to absolute
* links. By default, this is <b>false</b>: URLs will be made absolute (e.g. start with an allowed protocol, like
* e.g. {@code http://}.
* <p>
* Note that when handling relative links, the input document must have an appropriate {@code base URI} set when
* parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative
* links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute
* will be removed.
* </p>
*
* @param preserve {@code true} to allow relative links, {@code false} (default) to deny
* @return this Whitelist, for chaining.
* @see #addProtocols
*/
@discardableResult
open func preserveRelativeLinks(_ preserve: Bool) -> Whitelist {
preserveRelativeLinks = preserve
return self
}
/**
Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to
URLs with the defined protocol.
<p>
E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
</p>
<p>
To allow a link to an in-page URL anchor (i.e. <code><a href="#anchor"></code>, add a <code>#</code>:<br>
E.g.: <code>addProtocols("a", "href", "#")</code>
</p>
@param tag Tag the URL protocol is for
@param key Attribute key
@param protocols List of valid protocols
@return this, for chaining
*/
@discardableResult
open func addProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
let attrKey: AttributeKey = AttributeKey.valueOf(key)
var attrMap: Dictionary<AttributeKey, Set<Protocol>>
var protSet: Set<Protocol>
if (self.protocols[tagName] != nil) {
attrMap = self.protocols[tagName]!
} else {
attrMap = Dictionary<AttributeKey, Set<Protocol>>()
self.protocols[tagName] = attrMap
}
if (attrMap[attrKey] != nil) {
protSet = attrMap[attrKey]!
} else {
protSet = Set<Protocol>()
attrMap[attrKey] = protSet
self.protocols[tagName] = attrMap
}
for ptl in protocols {
try Validate.notEmpty(string: ptl)
let prot: Protocol = Protocol.valueOf(ptl)
protSet.insert(prot)
}
attrMap[attrKey] = protSet
self.protocols[tagName] = attrMap
return self
}
/**
Remove allowed URL protocols for an element's URL attribute.
<p>
E.g.: <code>removeProtocols("a", "href", "ftp")</code>
</p>
@param tag Tag the URL protocol is for
@param key Attribute key
@param protocols List of invalid protocols
@return this, for chaining
*/
@discardableResult
open func removeProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
let attrKey: AttributeKey = AttributeKey.valueOf(key)
if(self.protocols[tagName] != nil) {
var attrMap: Dictionary<AttributeKey, Set<Protocol>> = self.protocols[tagName]!
if(attrMap[attrKey] != nil) {
var protSet: Set<Protocol> = attrMap[attrKey]!
for ptl in protocols {
try Validate.notEmpty(string: ptl)
let prot: Protocol = Protocol.valueOf(ptl)
protSet.remove(prot)
}
attrMap[attrKey] = protSet
if(protSet.isEmpty) { // Remove protocol set if empty
attrMap.removeValue(forKey: attrKey)
if(attrMap.isEmpty) { // Remove entry for tag if empty
self.protocols.removeValue(forKey: tagName)
}
}
}
self.protocols[tagName] = attrMap
}
return self
}
/**
* Test if the supplied tag is allowed by this whitelist
* @param tag test tag
* @return true if allowed
*/
public func isSafeTag(_ tag: String) -> Bool {
return tagNames.contains(TagName.valueOf(tag))
}
/**
* Test if the supplied attribute is allowed by this whitelist for this tag
* @param tagName tag to consider allowing the attribute in
* @param el element under test, to confirm protocol
* @param attr attribute under test
* @return true if allowed
*/
public func isSafeAttribute(_ tagName: String, _ el: Element, _ attr: Attribute)throws -> Bool {
let tag: TagName = TagName.valueOf(tagName)
let key: AttributeKey = AttributeKey.valueOf(attr.getKey())
if (attributes[tag] != nil) {
if (attributes[tag]?.contains(key))! {
if (protocols[tag] != nil) {
let attrProts: Dictionary<AttributeKey, Set<Protocol>> = protocols[tag]!
// ok if not defined protocol; otherwise test
return try (attrProts[key] == nil) || testValidProtocol(el, attr, attrProts[key]!)
} else { // attribute found, no protocols defined, so OK
return true
}
}
}
// no attributes defined for tag, try :all tag
return try !(tagName == ":all") && isSafeAttribute(":all", el, attr)
}
private func testValidProtocol(_ el: Element, _ attr: Attribute, _ protocols: Set<Protocol>)throws->Bool {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
var value: String = try el.absUrl(attr.getKey())
if (value.characters.count == 0) {
value = attr.getValue()
}// if it could not be made abs, run as-is to allow custom unknown protocols
if (!preserveRelativeLinks) {
attr.setValue(value: value)
}
for ptl in protocols {
var prot: String = ptl.toString()
if (prot=="#") { // allows anchor links
if (isValidAnchor(value)) {
return true
} else {
continue
}
}
prot += ":"
if (value.lowercased().hasPrefix(prot)) {
return true
}
}
return false
}
private func isValidAnchor(_ value: String) -> Bool {
return value.startsWith("#") && !(Pattern(".*\\s.*").matcher(in: value).count > 0)
}
public func getEnforcedAttributes(_ tagName: String)throws->Attributes {
let attrs: Attributes = Attributes()
let tag: TagName = TagName.valueOf(tagName)
if let keyVals: Dictionary<AttributeKey, AttributeValue> = enforcedAttributes[tag] {
for entry in keyVals {
try attrs.put(entry.key.toString(), entry.value.toString())
}
}
return attrs
}
}
// named types for config. All just hold strings, but here for my sanity.
open class TagName: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> TagName {
return TagName(value)
}
}
open class AttributeKey: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> AttributeKey {
return AttributeKey(value)
}
}
open class AttributeValue: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> AttributeValue {
return AttributeValue(value)
}
}
open class Protocol: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> Protocol {
return Protocol(value)
}
}
open class TypedValue {
fileprivate let value: String
init(_ value: String) {
self.value = value
}
public func toString() -> String {
return value
}
}
extension TypedValue: Hashable {
public var hashValue: Int {
let prime = 31
var result = 1
result = Int.addWithOverflow(Int.multiplyWithOverflow(prime, result).0, value.hash).0
return result
}
}
public func == (lhs: TypedValue, rhs: TypedValue) -> Bool {
if(lhs === rhs) {return true}
return lhs.value == rhs.value
}
| mit | 7845b87c4ca9e752342100749cd1624d | 35.713629 | 134 | 0.581547 | 4.270395 | false | false | false | false |
krevis/MIDIApps | Applications/MIDIMonitor/AppController.swift | 1 | 19928 | /*
Copyright (c) 2001-2021, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Cocoa
import SnoizeMIDI
import Sparkle.SPUStandardUpdaterController
class AppController: NSObject {
enum AutoConnectOption: Int {
case disabled
case addInCurrentWindow
case openNewWindow
}
var midiContext: MIDIContext?
var midiSpyClient: MIDISpyClientRef?
@IBOutlet var updaterController: SPUStandardUpdaterController?
private var shouldOpenUntitledDocument = false
private var newlyAppearedInputStreamSources: Set<InputStreamSource>?
override init() {
super.init()
}
override func awakeFromNib() {
// Migrate autoconnect preference, before we show any windows.
// Old: PreferenceKeys.openWindowsForNewSources = BOOL (default: false)
// New: PreferenceKeys.autoConnectNewSources = int (default: 1 = AutoConnectOption.addInCurrentWindow)
let defaults = UserDefaults.standard
if defaults.object(forKey: PreferenceKeys.openWindowsForNewSources) != nil {
let option: AutoConnectOption = defaults.bool(forKey: PreferenceKeys.openWindowsForNewSources) ? .openNewWindow : .disabled
defaults.set(option.rawValue, forKey: PreferenceKeys.autoConnectNewSources)
defaults.removeObject(forKey: PreferenceKeys.openWindowsForNewSources)
}
}
func disconnectMIDI() {
midiContext?.disconnect()
if let spyClient = midiSpyClient {
MIDISpyClientDispose(spyClient)
MIDISpyClientDisposeSharedMIDIClient()
}
}
}
extension AppController: NSApplicationDelegate {
// MARK: NSApplicationDelegate
func applicationWillFinishLaunching(_ notification: Notification) {
// Before CoreMIDI is initialized, make sure the spying driver is installed
let installError = MIDISpyInstallDriverIfNecessary()
// Initialize CoreMIDI while the app's icon is still bouncing, so we don't have a large pause after it stops bouncing
// but before the app's window opens. (CoreMIDI needs to find and possibly start its server process, which can take a while.)
midiContext = MIDIContext()
guard let context = midiContext, context.connectedToCoreMIDI else {
midiContext = nil
failedToInitCoreMIDI()
return
}
// After this point, we are OK to open documents (untitled or otherwise)
shouldOpenUntitledDocument = true
if let err = installError {
failedToInstallSpyDriver(err)
}
else {
// Create our client for spying on MIDI output.
let status = MIDISpyClientCreate(&midiSpyClient)
if status != noErr {
failedToConnectToSpyClient()
}
}
}
func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool {
return shouldOpenUntitledDocument
}
func applicationDidFinishLaunching(_ notification: Notification) {
// Listen for new source endpoints. Don't do this earlier--we only are interested in ones
// that appear after we've been launched.
NotificationCenter.default.addObserver(self, selector: #selector(self.midiObjectsAppeared(_:)), name: .midiObjectsAppeared, object: midiContext)
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
true
}
}
extension AppController {
// MARK: Menus and actions
@IBAction func showPreferences(_ sender: Any?) {
PreferencesWindowController.shared.showWindow(nil)
}
@IBAction func showAboutBox(_ sender: Any?) {
var options: [NSApplication.AboutPanelOptionKey: Any] = [:]
options[NSApplication.AboutPanelOptionKey.version] = ""
// The RTF file Credits.rtf has foreground text color = black, but that's wrong for 10.14 dark mode.
// Similarly the font is not necessarily the systme font. Override both.
if let creditsURL = Bundle.main.url(forResource: "Credits", withExtension: "rtf"),
let credits = try? NSMutableAttributedString(url: creditsURL, options: [:], documentAttributes: nil) {
let range = NSRange(location: 0, length: credits.length)
credits.addAttribute(.font, value: NSFont.labelFont(ofSize: NSFont.labelFontSize), range: range)
if #available(macOS 10.14, *) {
credits.addAttribute(.foregroundColor, value: NSColor.labelColor, range: range)
}
options[NSApplication.AboutPanelOptionKey.credits] = credits
}
NSApp.orderFrontStandardAboutPanel(options: options)
}
@IBAction func showHelp(_ sender: Any?) {
var message: String?
if var url = Bundle.main.url(forResource: "docs", withExtension: "htmld") {
url.appendPathComponent("index.html")
if !NSWorkspace.shared.open(url) {
message = NSLocalizedString("The help file could not be opened.", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "error message if opening the help file fails")
}
}
else {
message = NSLocalizedString("The help file could not be found.", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "error message if help file can't be found")
}
if let message = message {
let title = NSLocalizedString("Error", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "title of error alert")
let alert = NSAlert()
alert.messageText = title
alert.informativeText = message
_ = alert.runModal()
}
}
@IBAction func sendFeedback(_ sender: Any?) {
var success = false
let feedbackEmailAddress = "[email protected]" // Don't localize this
let feedbackEmailSubject = NSLocalizedString("MIDI Monitor Feedback", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "subject of feedback email")
let mailToURLString = "mailto:\(feedbackEmailAddress)?Subject=\(feedbackEmailSubject)"
// Escape the whitespace characters in the URL before opening
let allowedCharacterSet = CharacterSet.whitespaces.inverted
if let escapedMailToURLString = mailToURLString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet),
let mailToURL = URL(string: escapedMailToURLString) {
success = NSWorkspace.shared.open(mailToURL)
}
if !success {
let message = NSLocalizedString("MIDI Monitor could not ask your email application to create a new message.\nPlease send email to:\n%@", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "message of alert when can't send feedback email")
let title = NSLocalizedString("Error", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "title of error alert")
let alert = NSAlert()
alert.messageText = title
alert.informativeText = String.localizedStringWithFormat(message, feedbackEmailAddress)
_ = alert.runModal()
}
}
@IBAction func restartMIDI(_ sender: Any?) {
let status = MIDIRestart()
if status != noErr {
let message = NSLocalizedString("Rescanning the MIDI system resulted in an unexpected error (%d).", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "error message if MIDIRestart() fails")
let title = NSLocalizedString("MIDI Error", tableName: "MIDIMonitor", bundle: Bundle.main, comment: "title of MIDI error panel")
let alert = NSAlert()
alert.messageText = title
alert.informativeText = String.localizedStringWithFormat(message, status)
_ = alert.runModal()
}
}
}
extension AppController {
// MARK: Startup failure handling
private func failedToInitCoreMIDI() {
let bundle = Bundle.main
let alert = NSAlert()
alert.alertStyle = .critical
alert.messageText = NSLocalizedString("The MIDI system could not be started.", tableName: "MIDIMonitor", bundle: bundle, comment: "error message if MIDI initialization fails")
alert.informativeText = NSLocalizedString("This probably affects all apps that use MIDI, not just MIDI Monitor.\n\nMost likely, the cause is a bad MIDI driver. Remove any MIDI drivers that you don't recognize, then try again.", tableName: "MIDIMonitor", bundle: bundle, comment: "informative text if MIDI initialization fails")
alert.addButton(withTitle: NSLocalizedString("Quit", tableName: "MIDIMonitor", bundle: bundle, comment: "title of quit button"))
alert.addButton(withTitle: NSLocalizedString("Show MIDI Drivers", tableName: "MIDIMonitor", bundle: bundle, comment: "Show MIDI Drivers button after MIDI spy client creation fails"))
if alert.runModal() == .alertSecondButtonReturn {
NSWorkspace.shared.open(URL(fileURLWithPath: "/Library/Audio/MIDI Drivers"))
}
NSApp.terminate(nil)
}
private func failedToInstallSpyDriver(_ error: Error) {
// Failure to install. Customize the error before presenting it.
let bundle = Bundle.main
let installError = error as NSError
var presentedErrorUserInfo: [String: Any] = installError.userInfo
presentedErrorUserInfo[NSLocalizedDescriptionKey] = NSLocalizedString("MIDI Monitor could not install its driver.", tableName: "MIDIMonitor", bundle: bundle, comment: "error message if spy driver install fails")
if installError.domain == MIDISpyDriverInstallationErrorDomain {
// Errors with this domain should be very rare and indicate a problem with the app itself.
if let reason = installError.localizedFailureReason, reason != "" {
presentedErrorUserInfo[NSLocalizedRecoverySuggestionErrorKey] =
reason
+ "\n\n"
+ NSLocalizedString("This shouldn't happen. Try downloading MIDI Monitor again.", tableName: "MIDIMonitor", bundle: bundle, comment: "suggestion if spy driver install fails due to our own error")
+ "\n\n"
+ NSLocalizedString("MIDI Monitor will not be able to see the output of other MIDI applications, but all other features will still work.", tableName: "MIDIMonitor", bundle: bundle, comment: "more suggestion if spy driver install fails")
}
}
else {
var fullSuggestion = ""
if let reason = installError.localizedFailureReason, reason != "" {
fullSuggestion += reason
}
if let suggestion = installError.localizedRecoverySuggestion, suggestion != "" {
if fullSuggestion != "" {
fullSuggestion += "\n\n"
}
fullSuggestion += suggestion
}
if fullSuggestion != "" {
presentedErrorUserInfo[NSLocalizedRecoverySuggestionErrorKey] =
fullSuggestion
+ "\n\n"
+ NSLocalizedString("MIDI Monitor will not be able to see the output of other MIDI applications, but all other features will still work.", tableName: "MIDIMonitor", bundle: bundle, comment: "more suggestion if spy driver install fails")
}
// To find the path involved, look for NSDestinationFilePath first (it's set for failures to copy, and is better than the source path),
// then fall back to the documented keys.
var filePath = installError.userInfo["NSDestinationFilePath"] as? String
if filePath == nil {
filePath = installError.userInfo[NSFilePathErrorKey] as? String
}
if filePath == nil {
if let url = installError.userInfo[NSURLErrorKey] as? URL,
url.isFileURL {
filePath = url.path
}
}
if let realFilePath = filePath, realFilePath != "" {
presentedErrorUserInfo[NSFilePathErrorKey] = realFilePath
presentedErrorUserInfo[NSLocalizedRecoveryOptionsErrorKey] = [
NSLocalizedString("Continue", tableName: "MIDIMonitor", bundle: bundle, comment: "Continue button if spy driver install fails"),
NSLocalizedString("Show in Finder", tableName: "MIDIMonitor", bundle: bundle, comment: "Show in Finder button if spy driver install fails")
]
presentedErrorUserInfo[NSRecoveryAttempterErrorKey] = self
}
}
let presentedError = NSError(domain: installError.domain, code: installError.code, userInfo: presentedErrorUserInfo)
NSApp.presentError(presentedError)
}
// NSErrorRecoveryAttempting informal protocol
@objc override func attemptRecovery(fromError error: Error, optionIndex recoveryOptionIndex: Int) -> Bool {
if recoveryOptionIndex == 0 {
// Continue: do nothing
}
else if recoveryOptionIndex == 1 {
// Show in Finder
let nsError = error as NSError
if let filePath = nsError.userInfo[NSFilePathErrorKey] as? String {
NSWorkspace.shared.selectFile(filePath, inFileViewerRootedAtPath: "")
}
}
return true // recovery was successful
}
private func failedToConnectToSpyClient() {
let bundle = Bundle.main
let alert = NSAlert()
alert.messageText = NSLocalizedString("MIDI Monitor could not connect to its MIDI driver", tableName: "MIDIMonitor", bundle: bundle, comment: "error message if MIDI spy client creation fails")
alert.informativeText = NSLocalizedString("MIDI Monitor will not be able to spy on the output of other MIDI applications. It can still receive incoming MIDI events.\n\n1. Check your MIDI drivers in /Library/Audio/MIDI Drivers. There might be old drivers that are interfering with new ones. Remove drivers for hardware that you no longer use.\n2. Restart your computer, whether or not you did anything in step 1.", tableName: "MIDIMonitor", bundle: bundle, comment: "second line of warning when MIDI spy is unavailable")
alert.addButton(withTitle: NSLocalizedString("Continue", tableName: "MIDIMonitor", bundle: bundle, comment: "Continue button after MIDI spy client creation fails"))
alert.addButton(withTitle: NSLocalizedString("Show MIDI Drivers", tableName: "MIDIMonitor", bundle: bundle, comment: "Show MIDI Drivers button after MIDI spy client creation fails"))
alert.addButton(withTitle: NSLocalizedString("Restart", tableName: "MIDIMonitor", bundle: bundle, comment: "Restart button after MIDI spy client creation fails"))
let response = alert.runModal()
if response == .alertSecondButtonReturn {
// Show MIDI Drivers
NSWorkspace.shared.open(URL(fileURLWithPath: "/Library/Audio/MIDI Drivers"))
}
else if response == .alertThirdButtonReturn {
// Restart
let ynAlert = NSAlert()
ynAlert.messageText = NSLocalizedString("Are you sure you want to restart now?", tableName: "MIDIMonitor", bundle: bundle, comment: "Restart y/n?")
ynAlert.addButton(withTitle: NSLocalizedString("Restart", tableName: "MIDIMonitor", bundle: bundle, comment: "Restart button title"))
ynAlert.addButton(withTitle: NSLocalizedString("Cancel", tableName: "MIDIMonitor", bundle: bundle, comment: "Cancel button title"))
if ynAlert.runModal() == .alertFirstButtonReturn {
let appleScript = NSAppleScript(source: "tell application \"Finder\" to restart")
appleScript?.executeAndReturnError(nil)
}
}
}
}
extension AppController {
// MARK: When sources and/or destinations appear
@objc func midiObjectsAppeared(_ notification: Notification) {
guard let objects = notification.userInfo?[MIDIContext.objectsThatAppeared] as? [MIDIObject] else { return }
// For each endpoint (Source or Destination) that appeared, which is not a virtual endpoint owned by this process,
// get its InputStreamSource. Select them all in the active document or a new document.
let endpoints = objects.compactMap({ $0 as? Endpoint }).filter({ !$0.isOwnedByThisProcess })
let inputStreamSources = endpoints.map(\.asInputStreamSource)
guard inputStreamSources.count > 0 else { return }
if newlyAppearedInputStreamSources == nil {
if let autoConnectOption = AutoConnectOption(rawValue: UserDefaults.standard.integer(forKey: PreferenceKeys.autoConnectNewSources)) {
switch autoConnectOption {
case .addInCurrentWindow:
newlyAppearedInputStreamSources = Set<InputStreamSource>()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.autoConnectToNewlyAppearedSources()
}
case .openNewWindow:
newlyAppearedInputStreamSources = Set<InputStreamSource>()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.openWindowForNewlyAppearedSources()
}
case .disabled:
break // do nothing
}
}
}
newlyAppearedInputStreamSources?.formUnion(inputStreamSources)
}
private func autoConnectToNewlyAppearedSources() {
if let inputStreamSources = newlyAppearedInputStreamSources,
inputStreamSources.count > 0,
let document = (NSDocumentController.shared.currentDocument ?? NSApp.orderedDocuments.first) as? Document {
document.selectedInputSources = document.selectedInputSources.union(inputStreamSources)
if let windowController = document.windowControllers.first as? MonitorWindowController {
windowController.revealInputSources(inputStreamSources)
document.updateChangeCount(.changeCleared)
}
}
newlyAppearedInputStreamSources = nil
}
private func openWindowForNewlyAppearedSources() {
if let inputStreamSources = newlyAppearedInputStreamSources,
inputStreamSources.count > 0,
let document = try? NSDocumentController.shared.openUntitledDocumentAndDisplay(false) as? Document {
document.makeWindowControllers()
document.selectedInputSources = inputStreamSources
document.showWindows()
if let windowController = document.windowControllers.first as? MonitorWindowController {
windowController.revealInputSources(inputStreamSources)
document.updateChangeCount(.changeCleared)
}
}
newlyAppearedInputStreamSources = nil
}
}
extension AppController: SPUUpdaterDelegate {
func updater(_ updater: SPUUpdater, shouldPostponeRelaunchForUpdate item: SUAppcastItem, untilInvokingBlock installHandler: @escaping () -> Void) -> Bool {
// The update might contain a MIDI driver that needs to get
// installed. In order for it to work immediately,
// we want the MIDIServer to shut down now, so we can install
// the driver and then trigger the MIDIServer to run again.
// Remove our connections to the MIDIServer first:
disconnectMIDI()
// Wait a few seconds for the MIDIServer to hopefully shut down,
// then relaunch for the update:
DispatchQueue.main.asyncAfter(deadline: .now() + 6.0) {
installHandler()
}
return true
}
}
| bsd-3-clause | feb03ed43506b22cf8ecf982591b27e7 | 46.334917 | 527 | 0.662334 | 5.099284 | false | false | false | false |
radioboo/ListKitDemo | ListKitDemo/Models/Feed.swift | 1 | 773 | //
// Feed.swift
// ListKitDemo
//
// Created by 酒井篤 on 2016/12/10.
// Copyright © 2016年 Atsushi Sakai. All rights reserved.
//
import UIKit
import IGListKit
class Feed {
let id: String
let user: User
let comment: String
let image: UIImage
init(id: String, user: User, comment: String, image: UIImage) {
self.id = id
self.user = user
self.comment = comment
self.image = image
}
}
extension Feed: IGListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return id as NSObjectProtocol
}
func isEqual(toDiffableObject object: IGListDiffable?) -> Bool {
if let feed = object as? Feed {
return id == feed.id
}
return false
}
}
| mit | 4ba9be6469c075a82bf3659d214bf0f0 | 19.105263 | 68 | 0.594241 | 4.042328 | false | false | false | false |
matsune/YMCalendar | YMCalendar/Month/EventKit/EventKitManager.swift | 1 | 1344 | //
// EventKitManager.swift
// YMCalendarDemo
//
// Created by Yuma Matsune on 2017/03/17.
// Copyright © 2017年 Yuma Matsune. All rights reserved.
//
import Foundation
import UIKit
import EventKit
final public class EventKitManager {
public typealias EventSaveCompletionBlockType = (_ accessGranted: Bool) -> Void
public var eventStore: EKEventStore
public init(eventStore: EKEventStore?=nil) {
if let eventStore = eventStore {
self.eventStore = eventStore
} else {
self.eventStore = EKEventStore()
}
}
public var isGranted: Bool = false
public func checkEventStoreAccessForCalendar(completion: EventSaveCompletionBlockType?) {
let status = EKEventStore.authorizationStatus(for: .event)
switch status {
case .authorized:
isGranted = true
completion?(isGranted)
case .notDetermined:
requestCalendarAccess(completion: completion)
case .denied, .restricted:
isGranted = false
completion?(isGranted)
}
}
private func requestCalendarAccess(completion: EventSaveCompletionBlockType?) {
eventStore.requestAccess(to: .event) { [weak self] granted, _ in
self?.isGranted = granted
completion?(granted)
}
}
}
| mit | 62f1516db803f628a8ec328db635c1e4 | 26.9375 | 93 | 0.645041 | 4.894161 | false | false | false | false |
epv44/TwitchAPIWrapper | Sources/TwitchAPIWrapper/Requests/ModifyUserFollowRequest.swift | 1 | 1292 | //
// CreateUserFollowRequest.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/23/21.
//
import Foundation
/// Create or delete user follow request, see https://dev.twitch.tv/docs/api/reference/#create-user-follows
/// and https://dev.twitch.tv/docs/api/reference/#delete-user-follows
public struct ModifyUserFollowRequest: JSONConstructableRequest {
public let url: URL?
public let method: HTTPMethod
public let data: Data
public init(httpMethod: HTTPMethod, fromID: String, toID: String, allowNotifications: Bool? = nil) throws {
if ![.post, .delete].contains(httpMethod) {
throw RequestValidationError.invalidInput("Ony post and delete are valid http methods")
}
var body = ["from_id": fromID, "to_id": toID]
if let a = allowNotifications {
body["allow_notifications"] = a ? "true" : "false"
}
if httpMethod == .delete {
self.url = TwitchEndpoints.userFollows.construct()?.appending(queryItems: body.buildQueryItems())
self.data = Data()
} else {
self.url = TwitchEndpoints.userFollows.construct()
self.data = try JSONSerialization.data(withJSONObject: body, options: [])
}
self.method = httpMethod
}
}
| mit | 258be22921e0d98309fa626273b7d439 | 37 | 111 | 0.650929 | 4.141026 | false | false | false | false |
esttorhe/Watch_BotLauncher | Carthage/Checkouts/XcodeServerSDK/XcodeServerSDK/XcodeServerEntity.swift | 1 | 1472 | //
// XcodeServerEntity.swift
// Buildasaur
//
// Created by Honza Dvorsky on 14/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
public protocol XcodeRead {
init(json: NSDictionary)
}
public class XcodeServerEntity : XcodeRead {
public let id: String!
public let rev: String!
public let tinyID: String!
//initializer which takes a dictionary and fills in values for recognized keys
public required init(json: NSDictionary) {
self.id = json.optionalStringForKey("_id")
self.rev = json.optionalStringForKey("_rev")
self.tinyID = json.optionalStringForKey("tinyID")
}
public init() {
self.id = nil
self.rev = nil
self.tinyID = nil
}
public func dictionarify() -> NSDictionary {
assertionFailure("Must be overriden by subclasses that wish to dictionarify their data")
return NSDictionary()
}
public class func optional<T: XcodeRead>(json: NSDictionary?) -> T? {
if let json = json {
return T(json: json)
}
return nil
}
}
//parse an array of dictionaries into an array of parsed entities
public func XcodeServerArray<T where T:XcodeRead>(jsonArray: NSArray!) -> [T] {
let array = jsonArray as! [NSDictionary]!
let parsed = array.map {
(json: NSDictionary) -> (T) in
return T(json: json)
}
return parsed
}
| mit | d8f7abfbbab95ca890134e56f847acea | 24.37931 | 96 | 0.627717 | 4.304094 | false | false | false | false |
kumabook/MusicFav | MusicFav/OnpuIndicatorView.swift | 1 | 6798 | //
// OnpuActivityIndicatorView.swift
// MusicFav
//
// Created by KumamotoHiroki on 10/10/15.
// Copyright © 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
class OnpuIndicatorView: UIView, CAAnimationDelegate {
let rotationKey = "rotationAnimation"
let crossfadeKey = "crossfadeAnimation"
let duration = 1.2 as Double
static let animationImages = [UIImage(named: Color.normal.imageName)!,
UIImage(named: Color.blue.imageName)!,
UIImage(named: Color.green.imageName)!,
UIImage(named: Color.cyan.imageName)!]
enum State {
case pause
case animating
}
enum Color: Int {
case normal = 0
case red = 1
case blue = 2
case green = 3
case cyan = 4
static let count: UInt32 = 5
var imageName: String {
switch self {
case .normal: return "loading_icon"
case .red: return "loading_icon_0"
case .blue: return "loading_icon_1"
case .green: return "loading_icon_2"
case .cyan: return "loading_icon_3"
}
}
}
enum Animation: Int {
case rotate = 0
case colorSwitch = 1
func random() -> Animation {
return Animation(rawValue: Int(arc4random_uniform(2)))!
}
}
var state: State
var color: Color
var animation: Animation
var imageView: UIImageView
var subImageView: UIImageView
var currentImageView: UIImageView
var isFadeIn: Bool = false
override convenience init(frame: CGRect) {
self.init(frame: frame, animation: .rotate)
}
init(frame: CGRect, animation anim: Animation) {
state = .pause
color = .normal
animation = anim
imageView = UIImageView(image: UIImage(named: Color.blue.imageName))
subImageView = UIImageView(image: UIImage(named: Color.green.imageName))
currentImageView = imageView
super.init(frame: frame)
isUserInteractionEnabled = false
imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
subImageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
addSubview(imageView)
addSubview(subImageView)
}
required init?(coder aDecoder: NSCoder) {
state = .pause
color = .normal
animation = .colorSwitch
imageView = UIImageView()
subImageView = UIImageView()
currentImageView = imageView
super.init(coder: aDecoder)
addSubview(imageView)
addSubview(subImageView)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, with:event)
if self == hitView {
return nil
}
return super.hitTest(point, with: event)
}
func isAnimating() -> Bool {
return state == .animating
}
func startAnimating() {
startAnimating(animation)
}
func startAnimating(_ anim: Animation) {
animation = anim
state = .animating
switch animation {
case .rotate:
if let _ = currentImageView.layer.animation(forKey: rotationKey) {
return
}
rotate()
stopAnimatingCrossFade()
case .colorSwitch:
if let _ = currentImageView.layer.animation(forKey: crossfadeKey) {
return
}
stopAnimatingRotate()
fadeIn()
}
}
func stopAnimating() {
state = .pause
stopAnimatingRotate()
stopAnimatingCrossFade()
}
func stopAnimatingRotate() {
layer.removeAllAnimations()
}
func stopAnimatingCrossFade() {
imageView.layer.removeAllAnimations()
subImageView.layer.removeAllAnimations()
imageView.layer.opacity = 1.0
subImageView.layer.opacity = 1.0
}
func setColor(_ c: Color) {
color = c
currentImageView.image = UIImage(named: color.imageName)
}
func changeColorAtRandom() {
if let color = Color(rawValue: Int(arc4random_uniform(Color.count))) {
setColor(color)
}
}
func replaceImageView() {
currentImageView = currentImageView == imageView ? subImageView : imageView
}
fileprivate func rotate() {
imageView.image = UIImage(named: color.imageName)
subImageView.image = UIImage(named: color.imageName)
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: Float(2.0 * Double.pi) as Float)
rotationAnimation.duration = duration
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = Float.infinity
layer.add(rotationAnimation, forKey: rotationKey)
}
fileprivate func fadeIn() {
if !isAnimating() { return }
changeColorAtRandom()
imageView.layer.opacity = 0.0
subImageView.layer.opacity = 0.0
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = duration
animation.fromValue = 0.0
animation.toValue = 1.0
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeBoth
animation.delegate = self
isFadeIn = true
currentImageView.layer.add(animation, forKey: crossfadeKey)
}
fileprivate func fadeOut() {
if !isAnimating() { return }
currentImageView.layer.opacity = 1.0
let animation = CABasicAnimation(keyPath: "opacity")
animation.duration = duration
animation.fromValue = 1.0
animation.toValue = 0.0
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeBoth
animation.delegate = self
isFadeIn = false
currentImageView.layer.add(animation, forKey: crossfadeKey)
}
func animationDidStart(_ anim: CAAnimation) {
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if !flag || animation != .colorSwitch || !isAnimating() {
return
}
if isFadeIn {
fadeOut()
} else {
fadeIn()
}
}
}
| mit | 4b6c5c11a6b80b271ab7d47a3cfcd819 | 31.061321 | 89 | 0.562601 | 4.986794 | false | false | false | false |
wjk930726/Nexus | Nexus/Application/Tools/TXTEditor.swift | 1 | 5680 | //
// TXTEditor.swift
// Nexus
//
// Created by 王靖凯 on 2017/3/19.
// Copyright © 2017年 王靖凯. All rights reserved.
//
import Cocoa
class TXTEditor: NSObject {
var importIsFinished: (() -> Void)?
fileprivate var txtName = ""
fileprivate var xmlPath = ""
fileprivate var TXT: Data?
fileprivate var txtArray: [String] = []
class func writeToOutput(txt: String, fileName: String) {
guard let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/Output/" + fileName + ".txt").addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed) else {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "请截图并联系开发者\n未知错误2", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
return
}
let url = URL(fileURLWithPath: path)
do {
try txt.write(to: url, atomically: true, encoding: .utf8)
} catch {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "写\(fileName).txt入/Users/你/Documents/Output/发生错误\n请截图并联系开发者\n\(error)", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
}
}
class func writeToOutput(xml: String, fileName: String) {
guard let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/Output/" + fileName).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed) else {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "请截图并联系开发者\n未知错误3", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
return
}
let url = URL(fileURLWithPath: path)
do {
try xml.write(to: url, atomically: true, encoding: .utf8)
} catch {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "写\(fileName).xml入/Users/你/Documents/Output/发生错误\n请截图并联系开发者\n\(error)", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
}
}
}
extension TXTEditor {
func importTXT(filePath: String, xmlPath: String) {
txtName = (filePath as NSString).lastPathComponent
self.xmlPath = xmlPath
getTXT(filePath: filePath)
parseTXT()
}
fileprivate func getTXT(filePath: String) {
let fileURL = URL(fileURLWithPath: filePath)
do {
try TXT = Data(contentsOf: fileURL)
} catch {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "读取\((filePath as NSString).lastPathComponent)错误,请截图并联系开发者", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
}
}
fileprivate func parseTXT() {
if TXT != nil {
if var txt: String = String(data: TXT!, encoding: .utf8) {
txt = txt.trimmingCharacters(in: .whitespacesAndNewlines)
var i = 0
while true {
let start = txt.range(of: String(format: "@ROW%04d@", i))
i += 1
let end = txt.range(of: String(format: "@ROW%04d@", i))
if let sb = start?.upperBound, let eb = end?.lowerBound {
var el = txt.substring(with: sb ..< eb)
if el.hasSuffix("\r\n") {
el = (el as NSString).substring(to: el.count )
}
if el.hasSuffix("\n") {
el = (el as NSString).substring(to: el.count )
}
el = el.replacingOccurrences(of: "\n", with: " ")
el = el.replacingOccurrences(of: "\r\n", with: " ")
el = el.replacingOccurrences(of: "<", with: "<")
el = el.replacingOccurrences(of: ">", with: ">")
txtArray.append(el)
} else if start?.upperBound != nil {
let el = txt.substring(from: start!.upperBound)
txtArray.append(el)
break
} else {
DispatchQueue.main.async {
NSAlert.alertModal(messageText: "警告⚠️", informativeText: "解析\(self.txtName)错误,请截图并联系开发者", firstButtonTitle: "确定", secondButtonTitle: nil, thirdButtonTitle: nil, firstButtonReturn: nil, secondButtonReturn: nil, thirdButtonReturn: nil)
}
break
}
}
if txtArray.count > 0 {
let tool: XMLParserTool = XMLParserTool()
tool.replace(filePath: xmlPath, txtArray: txtArray)
}
}
}
}
}
| mit | 649f54d54651aa84a7a582a94eabd700 | 47.401786 | 288 | 0.57019 | 4.559294 | false | false | false | false |
sessuru/AlamofireImage | Example/ImageViewController.swift | 2 | 2289 | //
// ImageViewController.swift
//
// Copyright (c) 2015-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import AlamofireImage
import Foundation
import UIKit
class ImageViewController : UIViewController {
var gravatar: Gravatar!
var imageView: UIImageView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setUpInstanceProperties()
setUpImageView()
}
// MARK: - Private - Setup Methods
private func setUpInstanceProperties() {
title = gravatar.email
edgesForExtendedLayout = UIRectEdge()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
}
private func setUpImageView() {
imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
let URL = gravatar.url(size: view.bounds.size.width)
imageView.af_setImage(
withURL: URL,
placeholderImage: nil,
filter: CircleFilter(),
imageTransition: .flipFromBottom(0.5)
)
view.addSubview(imageView)
imageView.frame = view.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
| mit | 323eef3cb2375f2036a295df7fdd2129 | 32.661765 | 81 | 0.696811 | 4.719588 | false | false | false | false |
Tsukishita/CaveCommentViewer | CaveCommentViewer/CreateRoomDetailView.swift | 1 | 4271 | //
// CreateRoomDetailView.swift
// CaveCommentViewer
//
// Created by 月下 on 2015/12/28.
// Copyright © 2015年 月下. All rights reserved.
//
import Foundation
import UIKit
protocol CreateRoomDetailViewDelegate{
func selectRowAtIndex(Tag Tag:Int,Row:Int)
}
class CreateRoomDetailView:UIViewController,UITableViewDataSource,UITableViewDelegate {
var delegate: CreateRoomDetailViewDelegate! = nil
var tableTag:Int!
var thumb_select:[Int]!
var ThumbImage:Dictionary<Int,UIImage> = Dictionary()
var Presets = CaveAPI().presets
let Api = CaveAPI()
let genre:[String]=["配信ジャンルを選択 (含まれるタグ)","FPS (FPS ゲーム)",
"MMO (MMO ゲーム)","MOBA (MOBA ゲーム)",
"TPS (TPS ゲーム)","サンドボックス (サンドボックス ゲーム)",
"FINAL FANTASY XIV (FF14 ゲーム)","PSO2 (PSO2 ゲーム)",
"フットボールゲーム (サッカー ゲーム)","音ゲー (音ゲー ゲーム)",
"イラスト (イラスト)","マンガ (マンガ)",
"ゲーム (ゲーム)","手芸 工作 (手芸工作)","演奏 (演奏)",
"開発 (開発)","雑談 (雑談)"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch tableTag{
case 0:
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel!.text = genre[indexPath.row]
cell.textLabel?.font = UIFont.systemFontOfSize(14)
return cell
case 1:
let cell:ThumbnailCell = tableView.dequeueReusableCellWithIdentifier("ThumbnailCell") as! ThumbnailCell
cell.thumbLabel.text = "サムネイル\(thumb_select[indexPath.row]+1)"
cell.thumbnail!.image = ThumbImage[thumb_select[indexPath.row]]
return cell
case 2:
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel!.text = Presets[indexPath.row].PresetName
cell.detailTextLabel!.text = "タイトル : \(Presets[indexPath.row].Title)"
return cell
default :
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch tableTag{
case 0:
return 16
case 1:
return thumb_select.count
case 2:
return Presets.count
default :return 0
}
}
func tableView(tableView: UITableView,canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{
if tableTag == 2{
return true
}
return false
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
if Api.deletePreset(preset: Presets[indexPath.row]) == true{
Presets = Api.presets
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
if Presets.count == 0{
self.delegate.selectRowAtIndex(Tag: 2, Row: -1)
}
}
}
// Cell が選択された場合
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:(NSIndexPath)) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.delegate.selectRowAtIndex(Tag: tableTag, Row: indexPath.row)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch tableTag{
case 0:
return 44
case 1:
return 88
case 2:
return 44
default :return 44
}
}
} | mit | 3d12c280fd78c2a6a53bb7a01336ae87 | 34.345455 | 148 | 0.608108 | 4.484848 | false | false | false | false |
jverdi/Gramophone | Source/Resources/MediaAPI.swift | 1 | 3023 | //
// Media.swift
// Gramophone
//
// Copyright (c) 2017 Jared Verdi. All Rights Reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Result
extension Client.API {
enum Media: Resource {
case withID(String)
case byShortcode(String)
case search
func uri() -> String {
switch self {
case .withID(let mediaID): return "/v1/media/\(mediaID)"
case .byShortcode(let shortcode): return "/v1/media/shortcode/\(shortcode)"
case .search: return "/v1/media/search"
}
}
}
}
extension Client {
@discardableResult
public func media(withID ID: String, completion: @escaping (APIResult<Media>) -> Void) -> URLSessionDataTask? {
if let error = validateScopes([Scope.publicContent]) { completion(Result.failure(error)); return nil }
return get(API.Media.withID(ID), completion: completion)
}
@discardableResult
public func media(withShortcode shortcode: String, completion: @escaping (APIResult<Media>) -> Void) -> URLSessionDataTask? {
if let error = validateScopes([Scope.publicContent]) { completion(Result.failure(error)); return nil }
return get(API.Media.byShortcode(shortcode), completion: completion)
}
@discardableResult
public func media(latitude: Double, longitude: Double, distanceInMeters: Double?, completion: @escaping (APIResult<Array<Media>>) -> Void) -> URLSessionDataTask? {
if let error = validateScopes([Scope.publicContent]) { completion(Result.failure(error)); return nil }
var params = [
Param.latitude: latitude,
Param.longitude: longitude
]
if let distanceInMeters = distanceInMeters {
params[Param.distance] = distanceInMeters
}
return get(API.Media.search, params: params, completion: completion)
}
}
| mit | 5bea0ee58f2083d5f67f2eeb6bfa4501 | 40.986111 | 167 | 0.673834 | 4.505216 | false | false | false | false |
lemberg/connfa-ios | Connfa/Classes/EventTableView/BaseEventTableViewController.swift | 1 | 5589 | //
// BaseEventTableController.swift
// Connfa
//
// Created by Marian Fedyk on 9/19/18.
// Copyright © 2018 Lemberg Solution. All rights reserved.
//
import UIKit
protocol BaseEventTableControllerDelegate: class {
func didSelect(eventId: String)
func tableView(willRemoveEvent: String) -> Bool
}
extension BaseEventTableControllerDelegate {
func tableView(willRemoveEvent: String) -> Bool {
return false
}
}
class BaseEventTableController: NSObject {
private let defaultBackgroundImage = UIImage(named: "ic-event-bg")
private let highlightedBackground = UIImage(named: "ic-event-bg-active")
var dayList: DayList = [:] {
didSet {
sortedSlots = Array(dayList.keys).sorted{ $0.end < $1.end }.sorted{ $0.start < $1.start }
tableView.delegate = self
tableView.dataSource = self
reload()
}
}
weak var delegate: BaseEventTableControllerDelegate?
var tableView: EventsTableView
var sortedSlots: [ProgramListSlotViewData] = []
init(tableView: EventsTableView) {
self.tableView = tableView
super.init()
tableView.delegate = self
tableView.dataSource = self
setupObserving()
}
func reload() {
tableView.reloadData()
}
func scrollToActualEvent() {
if let section = sortedSlots.firstIndex(where: { ($0.marker == ProgramListSlotViewData.Marker.going || $0.marker == ProgramListSlotViewData.Marker.upcoming ) }) {
let indexPath = IndexPath(row: 0, section: section)
tableView.scrollToRow(at: indexPath, at: .middle, animated: false)
}
}
func addContentInset(_ inset: UIEdgeInsets) {
tableView.contentInset = inset
}
func card(for indexPath: IndexPath) -> ProgramListViewData {
let slot = sortedSlots[indexPath.section]
return dayList[slot]![indexPath.row]
}
func indexPathForVisibleCell(with eventId: String) -> IndexPath? {
guard let visibleIndexPaths = tableView.indexPathsForVisibleRows else { return nil }
var path: IndexPath? = nil
for (section, slot) in sortedSlots.enumerated() {
if dayList[slot]!.contains(where: { (event) -> Bool in
event.eventId == eventId
}) {
let row = dayList[slot]!.sorted{ $0.name < $1.name }.index { (event) -> Bool in
event.eventId == eventId
}
path = IndexPath(row: row!, section: section)
guard visibleIndexPaths.contains(where: { $0 == path! }) else { return nil }
return path
}
}
return path
}
//MARK: - Actions
@objc func unlikeEvent(_ notification: Notification) {
if let id = notification.userInfo?[Keys.Event.eventId] as? String, let indexPath = indexPathForVisibleCell(with: id) {
let cell = tableView.cellForRow(at: indexPath) as! ProgramListCell
cell.unlike()
}
}
@objc func likeEvent(_ notification: Notification) {
if let id = notification.userInfo?[Keys.Event.eventId] as? String, let indexPath = indexPathForVisibleCell(with: id) {
let cell = tableView.cellForRow(at: indexPath) as! ProgramListCell
cell.like()
}
}
//MARK: - Private
private func setupObserving() {
NotificationCenter.default.addObserver(self, selector: #selector(likeEvent(_:)), name: .interestedAdded , object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(unlikeEvent(_:)), name: .interestedRemoved , object: nil)
}
}
extension BaseEventTableController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let slot = sortedSlots[section]
let slotList = dayList[slot] ?? []
return slotList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: EventsTableView.programListCellIdentifier, for: indexPath) as! ProgramListCell
cell.fill(with: card(for: indexPath))
let totalInSection = self.tableView(tableView, numberOfRowsInSection: indexPath.section)
let zPos = CGFloat(indexPath.item) / CGFloat(totalInSection)
cell.layer.zPosition = zPos
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return dayList.keys.count
}
}
extension BaseEventTableController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: ProgramListHeader.identifier) as! ProgramListHeader
header.layer.zPosition = CGFloat(section) + 1
header.fill(with: sortedSlots[section])
return header
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ProgramListCell
if let highlightedBackground = highlightedBackground {
cell.changeBackground(image: highlightedBackground)
}
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! ProgramListCell
if let defaultBackgroundImage = defaultBackgroundImage {
cell.changeBackground(image: defaultBackgroundImage)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = card(for: indexPath)
delegate?.didSelect(eventId: item.eventId)
}
}
| apache-2.0 | eb43607b2f62637af260de88bf6fd931 | 33.708075 | 166 | 0.705798 | 4.477564 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/ForecastIO/Source/DataPoint.swift | 1 | 10470 | //
// DataPoint.swift
// ForecastIO
//
// Created by Satyam Ghodasara on 7/10/15.
// Copyright (c) 2015 Satyam. All rights reserved.
//
import Foundation
/// Weather data for a specific location and time.
public struct DataPoint {
/// The time at which this `DataPoint` occurs.
public let time: Date
/// A human-readable text summary of the weather.
public let summary: String?
/// A machine-readable summary of the weather suitable for selecting an icon for display.
public let icon: Icon?
/// The time of the last sunrise before the solar noon closest to local noon on the given day. Only defined on `Forecast`'s `daily` `DataPoint`s. Note: near the poles, this may occur on a different day entirely!
public let sunriseTime: Date?
/// The time of the first sunset after the solar noon closest to local noon on the given day. Only defined on `Forecast`'s `daily` `DataPoint`s. Note: near the poles, this may occur on a different day entirely!
public let sunsetTime: Date?
/// The fractional part of the lunation number of the given day. This can be thought of as the "percentage complete" of the current lunar month. A value of `0` represents a new moon, a value of `0.25` represents a first quarter moon, a value of `0.5` represents a full moon, and a value of `0.75` represents a last quarter moon. The ranges between these values represent waxing crescent, waxing gibbous, waning gibbous, and waning crescent moons, respectively. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let moonPhase: Float?
/// The distance to the nearest storm in miles. This value is *very approximate* and should not be used in scenarios requiring accurate results. A storm distance of `0` doesn't necessarily refer to a storm at the requested location, but rather a storm in the vicinity of the requested location. Only defined on `Forecast`'s `currently` `DataPoint`s.
public let nearestStormDistance: Float?
/// The direction of the nearest storm in degrees, with true north at 0º and progressing clockwise. If `nearestStormDistance` is `0`, then this value will be `nil`. The caveats that apply to `nearestStormDistance` apply to this too. Only defined on `Forecast`'s `currently` `DataPoint`s.
public let nearestStormBearing: Float?
/// The average expected intensity in inches of liquid water per hour of precipitation occurring at the given time *conditional on probability* (assuming any precipitation occurs at all). A *very* rough guide is that a value of `0` corresponds to no precipitation, `0.002` corresponds to very light precipitation, `0.017` corresponds to light precipitation, `0.1` corresponds to moderate precipitation, and `0.4` corresponds to heavy precipitation.
public let precipIntensity: Float?
/// Maximum expected intensity of precipitation on the given day in inches of liquid water per hour. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let precipIntensityMax: Float?
/// Time at which the maximum expected intensity of precipitation will occur. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let precipIntensityMaxTime: Date?
/// Value between `0` and `1` (inclusive) representing the probability of precipitation occurring at the given time.
public let precipProbability: Float?
/// Type of precipitation occurring at the given time. If `precipIntensity` is `0`, then this will be `nil`.
public let precipType: Precipitation?
/// The amount of snowfall accumulation expected to occur on the given day, in inches. This will be `nil` if no accumulation is expected. Only defined on `Forecast`'s `hourly` and `daily` `DataPoint`s.
public let precipAccumulation: Float?
/// The temperature at the given time in degrees Fahrenheit. Not defined on `Forecast`'s `daily` `DataPoint`s.
public let temperature: Float?
/// The minimum temperature on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let temperatureMin: Float?
/// The time at which the minimum temperature will occur on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let temperatureMinTime: Date?
/// The maximum temperature on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let temperatureMax: Float?
/// The time at which the maximum temperature will occur on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let temperatureMaxTime: Date?
/// The apparent or "feels like" temperature at the given time in degrees Fahrenheit. Not defined on `Forecast`'s `daily` `DataPoint`s.
public let apparentTemperature: Float?
/// The minimum apparent or "feels like" temperature on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let apparentTemperatureMin: Float?
/// The time at which the minimum apparent or "feels like" temperature will occur on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let apparentTemperatureMinTime: Date?
/// The maximum apparent or "feels like" temperature on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let apparentTemperatureMax: Float?
/// The time at which the maximum apparent or "feels like" temperature will occur on the given day in degrees Fahrenheit. Only defined on `Forecast`'s `daily` `DataPoint`s.
public let apparentTemperatureMaxTime: Date?
/// The dew point at the given time in degrees Fahrenheit.
public let dewPoint: Float?
/// The wind speed at the given time in miles per hour.
public let windSpeed: Float?
/// The direction that the wind is coming from in degrees, with true north at 0º and progressing clockwise. If `windSpeed` is `0`, then this will be `nil`.
public let windBearing: Float?
/// Value between `0` and `1` (inclusive) representing the percentage of sky occluded by clouds. A value of `0` corresponds to a clear sky, `0.4` corresponds to scattered clouds, `0.75` correspond to broken cloud cover, and `1` corresponds to completely overcast skies.
public let cloudCover: Float?
/// Value between `0` and `1` (inclusive) representing the relative humidity.
public let humidity: Float?
/// The sea-level air pressure in millibars.
public let pressure: Float?
/// The average visibility in miles, capped at `10`.
public let visibility: Float?
/// The columnar density of total atomspheric ozone at the given time in Dobson units.
public let ozone: Float?
/**
Creates a new `DataPoint` from a JSON object.
- parameter fromJSON: A JSON object with keys corresponding to the `DataPoint`'s properties.
- returns: A new `DataPoint` filled with data from the given JSON object.
*/
public init(fromJSON json: NSDictionary) {
time = Date(timeIntervalSince1970: json["time"] as! Double)
summary = json["summary"] as? String
if let jsonIcon = json["icon"] as? String {
icon = Icon(rawValue: jsonIcon)
} else {
icon = nil
}
if let jsonSunriseTime = json["sunriseTime"] as? Double {
sunriseTime = Date(timeIntervalSince1970: jsonSunriseTime)
} else {
sunriseTime = nil
}
if let jsonSunsetTime = json["sunsetTime"] as? Double {
sunsetTime = Date(timeIntervalSince1970: jsonSunsetTime)
} else {
sunsetTime = nil
}
moonPhase = json["moonPhase"] as? Float
nearestStormDistance = json["nearestStormDistance"] as? Float
nearestStormBearing = json["nearestStormBearing"] as? Float
precipIntensity = json["precipIntensity"] as? Float
precipIntensityMax = json["precipIntensityMax"] as? Float
if let jsonPrecipIntensityMaxTime = json["precipIntensityMaxTime"] as? Double {
precipIntensityMaxTime = Date(timeIntervalSince1970: jsonPrecipIntensityMaxTime)
} else {
precipIntensityMaxTime = nil
}
precipProbability = json["precipProbability"] as? Float
if let jsonPrecipType = json["precipType"] as? String {
precipType = Precipitation(rawValue: jsonPrecipType)
} else {
precipType = nil
}
precipAccumulation = json["precipAccumulation"] as? Float
temperature = json["temperature"] as? Float
temperatureMin = json["temperatureMin"] as? Float
if let jsonTemperatureMinTime = json["temperatureMinTime"] as? Double {
temperatureMinTime = Date(timeIntervalSince1970: jsonTemperatureMinTime)
} else {
temperatureMinTime = nil
}
temperatureMax = json["temperatureMax"] as? Float
if let jsonTemperatureMaxTime = json["temperatureMaxTime"] as? Double {
temperatureMaxTime = Date(timeIntervalSince1970: jsonTemperatureMaxTime)
} else {
temperatureMaxTime = nil
}
apparentTemperature = json["apparentTemperature"] as? Float
apparentTemperatureMin = json["apparentTemperatureMin"] as? Float
if let jsonApparentTemperatureMinTime = json["apparentTemperatureMinTime"] as? Double {
apparentTemperatureMinTime = Date(timeIntervalSince1970: jsonApparentTemperatureMinTime)
} else {
apparentTemperatureMinTime = nil
}
apparentTemperatureMax = json["apparentTemperatureMax"] as? Float
if let jsonApparentTemperatureMaxTime = json["apparentTemperatureMaxTime"] as? Double {
apparentTemperatureMaxTime = Date(timeIntervalSince1970: jsonApparentTemperatureMaxTime)
} else {
apparentTemperatureMaxTime = nil
}
dewPoint = json["dewPoint"] as? Float
windSpeed = json["windSpeed"] as? Float
windBearing = json["windBearing"] as? Float
cloudCover = json["cloudCover"] as? Float
humidity = json["humidity"] as? Float
pressure = json["pressure"] as? Float
visibility = json["visibility"] as? Float
ozone = json["ozone"] as? Float
}
}
| mit | 73c5fa99dab0a16b8819f6d2a2bc4395 | 54.97861 | 515 | 0.694115 | 4.638015 | false | false | false | false |
hoangdang1449/Spendy | Spendy/Category.swift | 1 | 2807 | //
// Category.swift
// Spendy
//
// Created by Harley Trung on 9/18/15.
// Copyright (c) 2015 Cheetah. All rights reserved.
//
import Foundation
import Parse
var _allCategories: [Category]?
class Category: HTObject {
dynamic var name: String?
dynamic var icon: String?
init(name: String?, icon: String?) {
super.init(parseClassName: "Category")
self["name"] = name
self["icon"] = icon
}
override init(object: PFObject) {
super.init(object: object)
self["name"] = object.objectForKey("name")
self["icon"] = object.objectForKey("icon")
}
class func loadAll() {
// load from local first
let localQuery = PFQuery(className: "Category")
localQuery.fromLocalDatastore().findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if let error = error {
print("Error loading categories from Local: \(error)", terminator: "\n")
return
}
_allCategories = objects?.map({ Category(object: $0 ) })
print("\n[local] categories: \(objects)", terminator: "\n")
if _allCategories == nil || _allCategories!.isEmpty {
print("No categories found locally. Loading from server", terminator: "\n")
// load from remote
let remoteQuery = PFQuery(className: "Category")
remoteQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let error = error {
print("Error loading categories from Server: \(error)")
} else {
print("[server] categories: \(objects)")
_allCategories = objects?.map({ Category(object: $0 ) })
// already in background
PFObject.pinAllInBackground(objects!, withName: "MyCategories", block: { (success, error: NSError?) -> Void in
print("bool: \(success); error: \(error)")
})
// no need to save because we are not adding data
}
}
}
}
}
class func defaultCategory() -> Category? {
return _allCategories?.first
}
class func all() -> [Category]? {
return _allCategories;
}
class func findById(objectId: String) -> Category? {
let record = _allCategories?.filter({ (el) -> Bool in
el.objectId == objectId
}).first
return record
}
}
//extension Category: CustomStringConvertible {
// override var description: String {
// let base = super.description
// return "name: \(name), icon: \(icon), base: \(base)"
// }
//} | mit | 4e1e9e026203f6296072d2258ff8cb61 | 30.2 | 134 | 0.536872 | 4.848014 | false | false | false | false |
lanjing99/RxSwiftDemo | 13-intermediate-rxcocoa/starter/Wundercast/ViewController.swift | 1 | 3380 | /*
* Copyright (c) 2014-2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import RxSwift
import RxCocoa
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var mapButton: UIButton!
@IBOutlet weak var geoLocationButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var searchCityName: UITextField!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var iconLabel: UILabel!
@IBOutlet weak var cityNameLabel: UILabel!
let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
style()
let search = searchCityName.rx.controlEvent(.editingDidEndOnExit).asObservable()
.map { self.searchCityName.text }
.filter { ($0 ?? "").characters.count > 0 }
.flatMap { text in
return ApiController.shared.currentWeather(city: text ?? "Error")
.catchErrorJustReturn(ApiController.Weather.dummy)
}
.asDriver(onErrorJustReturn: ApiController.Weather.dummy)
search.map { "\($0.temperature)° C" }
.drive(tempLabel.rx.text)
.addDisposableTo(bag)
search.map { $0.icon }
.drive(iconLabel.rx.text)
.addDisposableTo(bag)
search.map { "\($0.humidity)%" }
.drive(humidityLabel.rx.text)
.addDisposableTo(bag)
search.map { $0.cityName }
.drive(cityNameLabel.rx.text)
.addDisposableTo(bag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
Appearance.applyBottomLine(to: searchCityName)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Style
private func style() {
view.backgroundColor = UIColor.aztec
searchCityName.textColor = UIColor.ufoGreen
tempLabel.textColor = UIColor.cream
humidityLabel.textColor = UIColor.cream
iconLabel.textColor = UIColor.cream
cityNameLabel.textColor = UIColor.cream
}
}
| mit | dd18cc090f6d6b48193915ffb70e608a | 31.180952 | 84 | 0.724475 | 4.572395 | false | false | false | false |
stephencelis/SQLite.swift | Sources/SQLite/Typed/CoreFunctions.swift | 1 | 28340 | //
// 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 Foundation
private enum Function: String {
case abs
case round
case random
case randomblob
case zeroblob
case length
case lower
case upper
case ltrim
case rtrim
case trim
case replace
case substr
case like = "LIKE"
case `in` = "IN"
case glob = "GLOB"
case match = "MATCH"
case regexp = "REGEXP"
case collate = "COLLATE"
case ifnull
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> {
self.rawValue.infix(lhs, rhs, wrap: wrap)
}
func wrap<T>(_ expression: Expressible) -> Expression<T> {
self.rawValue.wrap(expression)
}
func wrap<T>(_ expressions: [Expressible]) -> Expression<T> {
self.rawValue.wrap(", ".join(expressions))
}
}
extension ExpressionType where UnderlyingType: Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue: Expression<UnderlyingType> {
Function.abs.wrap(self)
}
}
extension ExpressionType where UnderlyingType: _OptionalType, UnderlyingType.WrappedType: Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int?>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue: Expression<UnderlyingType> {
Function.abs.wrap(self)
}
}
extension ExpressionType where UnderlyingType == Double {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return Function.round.wrap([self])
}
return Function.round.wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType == Double? {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return Function.round.wrap(self)
}
return Function.round.wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType: Value, UnderlyingType.Datatype == Int64 {
/// Builds an expression representing the `random` function.
///
/// Expression<Int>.random()
/// // random()
///
/// - Returns: An expression calling the `random` function.
public static func random() -> Expression<UnderlyingType> {
Function.random.wrap([])
}
}
extension ExpressionType where UnderlyingType == Data {
/// Builds an expression representing the `randomblob` function.
///
/// Expression<Int>.random(16)
/// // randomblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `randomblob` function.
public static func random(_ length: Int) -> Expression<UnderlyingType> {
Function.randomblob.wrap([])
}
/// Builds an expression representing the `zeroblob` function.
///
/// Expression<Int>.allZeros(16)
/// // zeroblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `zeroblob` function.
public static func allZeros(_ length: Int) -> Expression<UnderlyingType> {
Function.zeroblob.wrap([])
}
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
Function.length.wrap(self)
}
}
extension ExpressionType where UnderlyingType == Data? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData?>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
Function.length.wrap(self)
}
}
extension ExpressionType where UnderlyingType == String {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
Function.length.wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
Function.lower.wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
Function.upper.wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool> {
Function.glob.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
Function.match.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool> {
Function.regexp.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
Function.collate.infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.ltrim.wrap(self)
}
return Function.ltrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.rtrim.wrap(self)
}
return Function.rtrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.trim.wrap([self])
}
return Function.trim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
Function.replace.wrap([self, pattern, replacement])
}
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return Function.substr.wrap([self, location])
}
return Function.substr.wrap([self, location, length])
}
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension ExpressionType where UnderlyingType == String? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String?>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
Function.length.wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String?>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
Function.lower.wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String?>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
Function.upper.wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String?>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String?>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool?> {
Function.glob.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String?>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
Function.match.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool?> {
Function.regexp.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String?>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
Function.collate.infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String?>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.ltrim.wrap(self)
}
return Function.ltrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String?>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.rtrim.wrap(self)
}
return Function.rtrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String?>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.trim.wrap(self)
}
return Function.trim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String?>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
Function.replace.wrap([self, pattern, replacement])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title.substr(-100)
/// // substr("title", -100)
/// title.substr(0, length: 100)
/// // substr("title", 0, 100)
///
/// - Parameters:
///
/// - location: The substring’s start index.
///
/// - length: An optional substring length.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return Function.substr.wrap([self, location])
}
return Function.substr.wrap([self, location, length])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title[0..<100]
/// // substr("title", 0, 100)
///
/// - Parameter range: The character index range of the substring.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension Collection where Iterator.Element: Value {
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return Function.in.infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String?>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return Function.in.infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
}
extension String {
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = "[email protected]"
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // '[email protected]' LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let name = Expression<String?>("name")
/// name ?? "An Anonymous Coward"
/// // ifnull("name", 'An Anonymous Coward')
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback value for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V: Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> {
Function.ifnull.wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V: Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> {
Function.ifnull.wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String?>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V: Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> {
Function.ifnull.wrap([optional, defaultValue])
}
| mit | a076ea20de6ef688346d89ed670a7180 | 34.644025 | 110 | 0.595935 | 4.275992 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/Central/PeripheralAdvertisementsViewController.swift | 1 | 2569 | //
// PeripheralAdvertisements.swift
// BlueCap
//
// Created by Troy Stribling on 6/19/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
import BlueCapKit
class PeripheralAdvertisementsViewController : UITableViewController {
weak var peripheral : Peripheral?
var names : Array<String> = []
var values : Array<String> = []
struct MainStoryboard {
static let peripheralAdvertisementCell = "PeripheralAdvertisementCell"
}
required init(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let peripheral = self.peripheral {
self.names = peripheral.advertisements.keys.array
self.values = peripheral.advertisements.values.array
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didResignActive() {
self.navigationController?.popToRootViewControllerAnimated(false)
Logger.debug("PeripheralServiceCharacteristicEditDiscreteValuesViewController#didResignActive")
}
func didBecomeActive() {
Logger.debug("PeripheralServiceCharacteristicEditDiscreteValuesViewController#didBecomeActive")
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int {
println("Count:\(self.names.count)")
return self.names.count
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralAdvertisementCell, forIndexPath: indexPath) as PeripheralAdvertisementCell
cell.nameLabel.text = self.names[indexPath.row]
cell.valueLabel.text = self.values[indexPath.row]
return cell
}
// UITableViewDelegate
// PRIVATE INTERFACE
}
| mit | 6d1924818eedf880d52928d1fe257be9 | 32.802632 | 162 | 0.703776 | 5.548596 | false | false | false | false |
danstorre/CookIt | CookIt/CookIt/Recipe.swift | 1 | 4699 | //
// Recipe.swift
// CookIt
//
// Created by Daniel Torres on 3/23/17.
// Copyright © 2017 Danieltorres. All rights reserved.
//
import Foundation
import UIKit
struct Recipe {
// list properties
var id : Int?
var title : String?
var readyInMinutes : Int?
var image : UIImage?
var imageString : String?
var baseUri : String?
// recipe information properties
var vegetarian : Bool?
var glutenFree : Bool?
var cheap : Bool?
var sustainable : Bool?
var servings : Int?
var instructions : String?
// complex recipe information
var calories : Int?
var protein : String?
var fat : String?
var carbs : String?
var ingredients: [Ingredient]?
//var extendedIngredients : Bool?
init(id : Int, title : String, readyInMinutes : Int? = nil, image : UIImage? = nil, baseUri : String? = nil,
ingredients: [Ingredient]? = nil){
self.id = id
self.title = title
self.readyInMinutes = readyInMinutes
self.image = image
self.baseUri = baseUri
}
init(){
self.id = 0
self.title = ""
self.readyInMinutes = 0
}
init(dictionary: [String:AnyObject]){
if let id = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.id] as? Int {
self.id = id
}
if let title = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.title] as? String {
self.title = title
}
if let readyInMinutes = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.readyInMinutes] as? Int {
self.readyInMinutes = readyInMinutes
}
if let baseUri = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.baseUri] as? String {
self.baseUri = baseUri
}
if let vegetarian = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.vegetarian] as? Bool {
self.vegetarian = vegetarian
}
if let glutenFree = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.glutenFree] as? Bool {
self.glutenFree = glutenFree
}
if let cheap = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.cheap] as? Bool {
self.cheap = cheap
}
if let sustainable = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.sustainable] as? Bool {
self.sustainable = sustainable
}
if let servings = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.servings] as? Int {
self.servings = servings
}
if let calories = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.calories] as? Int {
self.calories = calories
}
if let protein = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.protein] as? String {
self.protein = protein
}
if let fat = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.fat] as? String {
self.fat = fat
}
if let carbs = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.carbs] as? String {
self.carbs = carbs
}
if let instructions = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.instructions] as? String {
self.instructions = instructions
}
if let imageString = dictionary[APIConstants.JSONBodyResponseKeys.Recipe.image] as? String {
self.imageString = imageString
}
}
static func arrayOfRecipes(from dictionary: [[String:AnyObject]]) -> [Recipe]{
var recipesToReturn = [Recipe]()
for recipe in dictionary{
recipesToReturn.append(Recipe(dictionary: recipe))
}
return recipesToReturn
}
static func toRecipe(from dbRecipe: DBRecipe) -> Recipe{
var recipe = Recipe()
recipe.id = Int(dbRecipe.id)
recipe.title = dbRecipe.title
recipe.readyInMinutes = Int(dbRecipe.readyInMinutes)
recipe.baseUri = dbRecipe.baseUri
recipe.vegetarian = dbRecipe.vegetarian
recipe.glutenFree = dbRecipe.glutenFree
recipe.cheap = dbRecipe.cheap
recipe.sustainable = dbRecipe.sustainable
recipe.servings = Int(dbRecipe.servings)
recipe.calories = Int(dbRecipe.calories)
recipe.protein = dbRecipe.protein
recipe.fat = dbRecipe.fat
recipe.carbs = dbRecipe.carbs
recipe.instructions = dbRecipe.instructions
recipe.imageString = dbRecipe.imageString
return recipe
}
}
| mit | 4cd7b478660ee60e7a48eb3306826815 | 29.705882 | 112 | 0.607918 | 4.66998 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemAnyRoot.swift | 1 | 1002 | import UIKit
class MCalculatorFunctionsItemAnyRoot:MCalculatorFunctionsItem
{
init()
{
let icon:UIImage = #imageLiteral(resourceName: "assetFunctionAnyRoot")
let title:String = NSLocalizedString("MCalculatorFunctionsItemAnyRoot_title", comment:"")
super.init(
icon:icon,
title:title)
}
override func selected(controller:CCalculator)
{
guard
let textView:UITextView = controller.viewCalculator.viewText,
let keyboard:VKeyboard = textView.inputView as? VKeyboard
else
{
return
}
let model:MKeyboard = keyboard.model
model.commitIfNeeded(view:textView)
let previousValue:Double = model.lastNumber()
let stateRoot:MKeyboardStateRoot = MKeyboardStateRoot(
previousValue:previousValue,
editing:model.kInitial)
model.states.append(stateRoot)
}
}
| mit | bfb082560bb0ec72a69d767a1dab60de | 26.833333 | 97 | 0.607784 | 5.035176 | false | false | false | false |
allen-zeng/PromiseKit | Categories/MessageUI/MFMessageComposeViewController+Promise.swift | 2 | 2649 | import Foundation
import MessageUI.MFMessageComposeViewController
import UIKit.UIViewController
#if !COCOAPODS
import PromiseKit
#endif
/**
To import this `UIViewController` category:
use_frameworks!
pod "PromiseKit/MessageUI"
And then in your sources:
import PromiseKit
*/
extension UIViewController {
public func promiseViewController(vc: MFMessageComposeViewController, animated: Bool = true, completion:(() -> Void)? = nil) -> Promise<Void> {
let proxy = PMKMessageComposeViewControllerDelegate()
proxy.retainCycle = proxy
vc.messageComposeDelegate = proxy
presentViewController(vc, animated: animated, completion: completion)
proxy.promise.always {
vc.dismissViewControllerAnimated(animated, completion: nil)
}
return proxy.promise
}
}
extension MFMessageComposeViewController {
public enum Error: ErrorType {
case Cancelled
}
}
private class PMKMessageComposeViewControllerDelegate: NSObject, MFMessageComposeViewControllerDelegate, UINavigationControllerDelegate {
let (promise, fulfill, reject) = Promise<Void>.pendingPromise()
var retainCycle: NSObject?
@objc func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
defer { retainCycle = nil }
#if swift(>=2.3)
switch result {
case .Sent:
fulfill()
case .Failed:
var info = [NSObject: AnyObject]()
info[NSLocalizedDescriptionKey] = "The attempt to save or send the message was unsuccessful."
info[NSUnderlyingErrorKey] = NSNumber(integer: result.rawValue)
reject(NSError(domain: PMKErrorDomain, code: PMKOperationFailed, userInfo: info))
case .Cancelled:
reject(MFMessageComposeViewController.Error.Cancelled)
}
#else
switch result.rawValue {
case MessageComposeResultSent.rawValue:
fulfill()
case MessageComposeResultFailed.rawValue:
var info = [NSObject: AnyObject]()
info[NSLocalizedDescriptionKey] = "The attempt to save or send the message was unsuccessful."
info[NSUnderlyingErrorKey] = NSNumber(unsignedInt: result.rawValue)
reject(NSError(domain: PMKErrorDomain, code: PMKOperationFailed, userInfo: info))
case MessageComposeResultCancelled.rawValue:
reject(MFMessageComposeViewController.Error.Cancelled)
default:
fatalError("Swift Sucks")
}
#endif
}
}
public enum MessageUIError: ErrorType {
case Failed
}
| mit | a1f1542faa26204d58bf59ac5402979c | 33.402597 | 147 | 0.694602 | 5.600423 | false | false | false | false |
orcudy/archive | ios/apps/UCLALibrary/Code/UCLALibrary/UIView+Utilities.swift | 1 | 594 | //
// Utilities.swift
// UCLALibrary
//
// Created by Chris Orcutt on 8/2/15.
// Copyright (c) 2015 Chris Orcutt. All rights reserved.
//
import UIKit
extension UIView {
static func screenSize() -> CGSize {
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
return CGSize(width: width, height: height)
}
static func screenCenter() -> CGPoint {
let screenSize = UIView.screenSize()
let centerX = screenSize.width / 2
let centerY = screenSize.height / 2
return CGPoint(x: centerX, y: centerY)
}
} | gpl-3.0 | 393ac5059e1101449872c9aa0bc9b31f | 23.791667 | 57 | 0.678451 | 3.832258 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/SectionEditorViewController.swift | 1 | 35096 | import CocoaLumberjackSwift
protocol SectionEditorViewControllerDelegate: AnyObject {
func sectionEditorDidCancelEditing(_ sectionEditor: SectionEditorViewController)
func sectionEditorDidFinishEditing(_ sectionEditor: SectionEditorViewController, result: Result<SectionEditorChanges, Error>)
func sectionEditorDidFinishLoadingWikitext(_ sectionEditor: SectionEditorViewController)
}
@objc(WMFSectionEditorViewController)
class SectionEditorViewController: ViewController {
@objc public static let editWasPublished = NSNotification.Name(rawValue: "EditWasPublished")
weak var delegate: SectionEditorViewControllerDelegate?
private let sectionID: Int
private let articleURL: URL
private let languageCode: String
private var selectedTextEditInfo: SelectedTextEditInfo?
private var dataStore: MWKDataStore
private var webView: SectionEditorWebView!
private let sectionFetcher: SectionFetcher
private var inputViewsController: SectionEditorInputViewsController!
private var messagingController: SectionEditorWebViewMessagingController!
private var menuItemsController: SectionEditorMenuItemsController!
private var navigationItemController: SectionEditorNavigationItemController!
lazy var readingThemesControlsViewController: ReadingThemesControlsViewController = {
return ReadingThemesControlsViewController.init(nibName: ReadingThemesControlsViewController.nibName, bundle: nil)
}()
private lazy var focusNavigationView: FocusNavigationView = {
return FocusNavigationView.wmf_viewFromClassNib()
}()
private var webViewTopConstraint: NSLayoutConstraint!
private var didFocusWebViewCompletion: (() -> Void)?
private var needsSelectLastSelection: Bool = false
@objc var editFunnel = EditFunnel.shared
private var isInFindReplaceActionSheetMode = false
private var wikitext: String? {
didSet {
setWikitextToWebViewIfReady()
}
}
private var isCodemirrorReady: Bool = false {
didSet {
setWikitextToWebViewIfReady()
}
}
struct ScriptMessageHandler {
let handler: WKScriptMessageHandler
let name: String
}
private var scriptMessageHandlers: [ScriptMessageHandler] = []
private let findAndReplaceHeaderTitle = WMFLocalizedString("find-replace-header", value: "Find and replace", comment: "Find and replace header title.")
private var editConfirmationSavedData: EditSaveViewController.SaveData? = nil
init(articleURL: URL, sectionID: Int, messagingController: SectionEditorWebViewMessagingController? = nil, dataStore: MWKDataStore, selectedTextEditInfo: SelectedTextEditInfo? = nil, theme: Theme = Theme.standard) {
self.articleURL = articleURL
self.sectionID = sectionID
self.dataStore = dataStore
self.selectedTextEditInfo = selectedTextEditInfo
self.messagingController = messagingController ?? SectionEditorWebViewMessagingController()
languageCode = articleURL.wmf_languageCode ?? NSLocale.current.languageCode ?? "en"
self.sectionFetcher = SectionFetcher(session: dataStore.session, configuration: dataStore.configuration)
super.init(theme: theme)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
loadWikitext()
navigationItemController = SectionEditorNavigationItemController(navigationItem: navigationItem)
navigationItemController.delegate = self
configureWebView()
dataStore.authenticationManager.loginWithSavedCredentials { (_) in }
webView.scrollView.delegate = self
scrollView = webView.scrollView
setupFocusNavigationView()
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectLastSelectionIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
UIMenuController.shared.menuItems = menuItemsController.originalMenuItems
super.viewWillDisappear(animated)
}
deinit {
removeScriptMessageHandlers()
}
@objc func keyboardDidHide() {
inputViewsController.resetFormattingAndStyleSubmenus()
}
private func setupFocusNavigationView() {
let closeAccessibilityText = WMFLocalizedString("find-replace-header-close-accessibility", value: "Close find and replace", comment: "Accessibility label for closing the find and replace view.")
focusNavigationView.configure(titleText: findAndReplaceHeaderTitle, closeButtonAccessibilityText: closeAccessibilityText, traitCollection: traitCollection)
focusNavigationView.isHidden = true
focusNavigationView.delegate = self
focusNavigationView.apply(theme: theme)
focusNavigationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(focusNavigationView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: focusNavigationView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: focusNavigationView.trailingAnchor)
let topConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: focusNavigationView.topAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint])
}
private func showFocusNavigationView() {
navigationController?.setNavigationBarHidden(true, animated: false)
webViewTopConstraint.constant = -focusNavigationView.frame.height
focusNavigationView.isHidden = false
}
private func hideFocusNavigationView() {
webViewTopConstraint.constant = 0
focusNavigationView.isHidden = true
navigationController?.setNavigationBarHidden(false, animated: false)
}
private func removeScriptMessageHandlers() {
guard let userContentController = webView?.configuration.userContentController else {
return
}
for handler in scriptMessageHandlers {
userContentController.removeScriptMessageHandler(forName: handler.name)
}
scriptMessageHandlers.removeAll()
}
private func addScriptMessageHandlers(to contentController: WKUserContentController) {
for handler in scriptMessageHandlers {
contentController.add(handler.handler, name: handler.name)
}
}
private func configureWebView() {
let configuration = WKWebViewConfiguration()
configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
let textSizeAdjustment = UserDefaults.standard.wmf_articleFontSizeMultiplier().intValue
let contentController = WKUserContentController()
messagingController.textSelectionDelegate = self
messagingController.buttonSelectionDelegate = self
messagingController.alertDelegate = self
messagingController.scrollDelegate = self
let contentLanguageCode: String = articleURL.wmf_contentLanguageCode ?? dataStore.languageLinkController.preferredLanguageVariantCode(forLanguageCode: languageCode) ?? languageCode
let layoutDirection = MWKLanguageLinkController.layoutDirection(forContentLanguageCode: contentLanguageCode)
let isSyntaxHighlighted = UserDefaults.standard.wmf_IsSyntaxHighlightingEnabled
let setupUserScript = CodemirrorSetupUserScript(languageCode: languageCode, direction: CodemirrorSetupUserScript.CodemirrorDirection(rawValue: layoutDirection) ?? .ltr, theme: theme, textSizeAdjustment: textSizeAdjustment, isSyntaxHighlighted: isSyntaxHighlighted) { [weak self] in
self?.isCodemirrorReady = true
}
contentController.addUserScript(setupUserScript)
scriptMessageHandlers.append(ScriptMessageHandler(handler: setupUserScript, name: setupUserScript.messageHandlerName))
scriptMessageHandlers.append(ScriptMessageHandler(handler: messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorMessage))
scriptMessageHandlers.append(ScriptMessageHandler(handler: messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorSearchMessage))
scriptMessageHandlers.append(ScriptMessageHandler(handler: messagingController, name: SectionEditorWebViewMessagingController.Message.Name.smoothScrollToYOffsetMessage))
scriptMessageHandlers.append(ScriptMessageHandler(handler: messagingController, name: SectionEditorWebViewMessagingController.Message.Name.replaceAllCountMessage))
scriptMessageHandlers.append(ScriptMessageHandler(handler: messagingController, name: SectionEditorWebViewMessagingController.Message.Name.didSetWikitextMessage))
addScriptMessageHandlers(to: contentController)
configuration.userContentController = contentController
webView = SectionEditorWebView(frame: .zero, configuration: configuration)
webView.navigationDelegate = self
webView.isHidden = true // hidden until wikitext is set
webView.scrollView.keyboardDismissMode = .interactive
inputViewsController = SectionEditorInputViewsController(webView: webView, messagingController: messagingController, findAndReplaceDisplayDelegate: self)
inputViewsController.delegate = self
webView.inputViewsSource = inputViewsController
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: webView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: webView.trailingAnchor)
webViewTopConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: webView.topAnchor)
let bottomConstraint = view.bottomAnchor.constraint(equalTo: webView.bottomAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, webViewTopConstraint, bottomConstraint])
let folderURL = Bundle.wmf.assetsFolderURL
let fileURL = folderURL.appendingPathComponent("codemirror/codemirror-index.html")
webView.loadFileURL(fileURL, allowingReadAccessTo: folderURL)
messagingController.webView = webView
menuItemsController = SectionEditorMenuItemsController(messagingController: messagingController)
menuItemsController.delegate = self
webView.menuItemsDataSource = menuItemsController
webView.menuItemsDelegate = menuItemsController
}
@objc var shouldFocusWebView = true {
didSet {
guard shouldFocusWebView else {
return
}
logSectionReadyToEdit()
focusWebViewIfReady()
}
}
private var didSetWikitextToWebView: Bool = false {
didSet {
guard shouldFocusWebView else {
return
}
focusWebViewIfReady()
}
}
private func selectLastSelectionIfNeeded() {
guard isCodemirrorReady,
shouldFocusWebView,
didSetWikitextToWebView,
needsSelectLastSelection,
wikitext != nil else {
return
}
messagingController.selectLastSelection()
messagingController.focusWithoutScroll()
needsSelectLastSelection = false
}
private func showCouldNotFindSelectionInWikitextAlert() {
editFunnel.logSectionHighlightToEditError(language: languageCode)
let alertTitle = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-title", value:"The text that you selected could not be located", comment:"Title for alert informing user their text selection could not be located in the article wikitext.")
let alertMessage = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-message", value:"This might be because the text you selected is not editable (eg. article title or infobox titles) or the because of the length of the text that was highlighted", comment:"Description of possible reasons the user text selection could not be located in the article wikitext.")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: CommonStrings.okTitle, style:.default, handler: nil))
present(alert, animated: true, completion: nil)
}
private func setWikitextToWebViewIfReady() {
assert(Thread.isMainThread)
guard isCodemirrorReady, let wikitext = wikitext else {
return
}
setWikitextToWebView(wikitext) { [weak self] (error) in
if let error = error {
assertionFailure(error.localizedDescription)
} else {
DispatchQueue.main.async {
self?.didSetWikitextToWebView = true
if let selectedTextEditInfo = self?.selectedTextEditInfo {
self?.messagingController.highlightAndScrollToText(for: selectedTextEditInfo) { [weak self] (error) in
if error != nil {
self?.showCouldNotFindSelectionInWikitextAlert()
}
}
}
}
}
}
}
private func focusWebViewIfReady() {
guard didSetWikitextToWebView else {
return
}
webView.isHidden = false
webView.becomeFirstResponder()
messagingController.focus {
assert(Thread.isMainThread)
self.delegate?.sectionEditorDidFinishLoadingWikitext(self)
guard let didFocusWebViewCompletion = self.didFocusWebViewCompletion else {
return
}
didFocusWebViewCompletion()
self.didFocusWebViewCompletion = nil
}
}
func setWikitextToWebView(_ wikitext: String, completionHandler: ((Error?) -> Void)? = nil) {
messagingController.setWikitext(wikitext, completionHandler: completionHandler)
}
private func loadWikitext() {
let isShowingStatusMessage = shouldFocusWebView
if isShowingStatusMessage {
let message = WMFLocalizedString("wikitext-downloading", value: "Loading content...", comment: "Alert text shown when obtaining latest revision of the section being edited")
WMFAlertManager.sharedInstance.showAlert(message, sticky: true, dismissPreviousAlerts: true)
}
sectionFetcher.fetchSection(with: sectionID, articleURL: articleURL) { (result) in
DispatchQueue.main.async {
if isShowingStatusMessage {
WMFAlertManager.sharedInstance.dismissAlert()
}
switch result {
case .failure(let error):
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true)
}
case .success(let response):
self.wikitext = response.wikitext
self.handle(protection: response.protection)
}
}
}
}
private func handle(protection: [SectionFetcher.Protection]) {
let allowedGroups = protection.map { $0.level }
guard !allowedGroups.isEmpty else {
return
}
let message: String
if allowedGroups.contains("autoconfirmed") {
message = WMFLocalizedString("page-protected-autoconfirmed", value: "This page has been semi-protected.", comment: "Brief description of Wikipedia 'autoconfirmed' protection level, shown when editing a page that is protected.")
} else if allowedGroups.contains("sysop") {
message = WMFLocalizedString("page-protected-sysop", value: "This page has been fully protected.", comment: "Brief description of Wikipedia 'sysop' protection level, shown when editing a page that is protected.")
} else {
message = WMFLocalizedString("page-protected-other", value: "This page has been protected to the following levels: %1$@", comment: "Brief description of Wikipedia unknown protection level, shown when editing a page that is protected. %1$@ will refer to a list of protection levels.")
}
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
delegate?.sectionEditorDidCancelEditing(self)
return true
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: nil) { (_) in
self.inputViewsController.didTransitionToNewCollection()
self.focusNavigationView.updateLayout(for: newCollection)
}
}
// MARK: Event logging
private var loggedEditActions: NSMutableSet = []
private func logSectionReadyToEdit() {
guard !loggedEditActions.contains(EditFunnel.Action.ready) else {
return
}
editFunnel.logSectionReadyToEdit(from: editFunnelSource, language: languageCode)
loggedEditActions.add(EditFunnel.Action.ready)
}
private var editFunnelSource: EditFunnelSource {
return selectedTextEditInfo == nil ? .pencil : .highlight
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
webView.scrollView.backgroundColor = theme.colors.paperBackground
webView.backgroundColor = theme.colors.paperBackground
messagingController.applyTheme(theme: theme)
inputViewsController.apply(theme: theme)
navigationItemController.apply(theme: theme)
apply(presentationTheme: theme)
focusNavigationView.apply(theme: theme)
}
private var previousContentInset = UIEdgeInsets.zero
override func scrollViewInsetsDidChange() {
super.scrollViewInsetsDidChange()
guard
let newContentInset = scrollView?.contentInset,
newContentInset != previousContentInset
else {
return
}
previousContentInset = newContentInset
messagingController.setAdjustedContentInset(newInset: newContentInset)
}
}
extension SectionEditorViewController: SectionEditorNavigationItemControllerDelegate {
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapProgressButton progressButton: UIBarButtonItem) {
messagingController.getWikitext { [weak self] (result, error) in
guard let self = self else { return }
self.webView.resignFirstResponder()
if let error = error {
assertionFailure(error.localizedDescription)
return
} else if let wikitext = result {
if wikitext != self.wikitext {
let vc = EditPreviewViewController(articleURL: self.articleURL)
self.inputViewsController.resetFormattingAndStyleSubmenus()
self.needsSelectLastSelection = true
vc.theme = self.theme
vc.sectionID = self.sectionID
vc.languageCode = self.languageCode
vc.wikitext = wikitext
vc.delegate = self
vc.editFunnel = self.editFunnel
vc.loggedEditActions = self.loggedEditActions
vc.editFunnelSource = self.editFunnelSource
self.navigationController?.pushViewController(vc, animated: true)
} else {
let message = WMFLocalizedString("wikitext-preview-changes-none", value: "No changes were made to be previewed.", comment: "Alert text shown if no changes were made to be previewed.")
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
}
}
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapCloseButton closeButton: UIBarButtonItem) {
delegate?.sectionEditorDidCancelEditing(self)
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapUndoButton undoButton: UIBarButtonItem) {
messagingController.undo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapRedoButton redoButton: UIBarButtonItem) {
messagingController.redo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapReadingThemesControlsButton readingThemesControlsButton: UIBarButtonItem) {
webView.resignFirstResponder()
inputViewsController.suppressMenus = true
showReadingThemesControlsPopup(on: self, responder: self, theme: theme)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerTextSelectionDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveTextSelectionChangeMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, isRangeSelected: Bool) {
if isRangeSelected {
menuItemsController.setEditMenuItems()
}
navigationItemController.textSelectionDidChange(isRangeSelected: isRangeSelected)
inputViewsController.textSelectionDidChange(isRangeSelected: isRangeSelected)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerButtonMessageDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveSelectButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
inputViewsController.buttonSelectionDidChange(button: button)
}
func sectionEditorWebViewMessagingControllerDidReceiveDisableButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
navigationItemController.disableButton(button: button)
inputViewsController.disableButton(button: button)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerAlertDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveReplaceAllMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, replacedCount: Int) {
let format = WMFLocalizedString("replace-replace-all-results-count", value: "{{PLURAL:%1$d|%1$d item replaced|%1$d items replaced}}", comment: "Alert view label that tells the user how many instances they just replaced via \"Replace all\". %1$d is replaced with the number of instances that were replaced.")
let alertText = String.localizedStringWithFormat(format, replacedCount)
wmf_showAlertWithMessage(alertText)
}
}
extension SectionEditorViewController: FindAndReplaceKeyboardBarDisplayDelegate {
func keyboardBarDidHide(_ keyboardBar: FindAndReplaceKeyboardBar) {
hideFocusNavigationView()
}
func keyboardBarDidShow(_ keyboardBar: FindAndReplaceKeyboardBar) {
showFocusNavigationView()
}
func keyboardBarDidTapReplaceSwitch(_ keyboardBar: FindAndReplaceKeyboardBar) {
let alertController = UIAlertController(title: findAndReplaceHeaderTitle, message: nil, preferredStyle: .actionSheet)
let replaceAllActionTitle = WMFLocalizedString("action-replace-all", value: "Replace all", comment: "Title of the replace all action.")
let replaceActionTitle = WMFLocalizedString("action-replace", value: "Replace", comment: "Title of the replace all action.")
let replaceAction = UIAlertAction(title: replaceActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceSingle)
}
let replaceAllAction = UIAlertAction(title: replaceAllActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceAll)
}
let cancelAction = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel, handler: nil)
alertController.addAction(replaceAction)
alertController.addAction(replaceAllAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = keyboardBar.replaceSwitchButton
alertController.popoverPresentationController?.sourceRect = keyboardBar.replaceSwitchButton.bounds
isInFindReplaceActionSheetMode = true
present(alertController, animated: true, completion: nil)
}
}
// MARK: - WKNavigationDelegate
extension SectionEditorViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
DDLogError("Section editor did fail navigation with error: \(error)")
}
}
// MARK: - EditSaveViewControllerDelegate
extension SectionEditorViewController: EditSaveViewControllerDelegate {
func editSaveViewControllerDidSave(_ editSaveViewController: EditSaveViewController, result: Result<SectionEditorChanges, Error>) {
delegate?.sectionEditorDidFinishEditing(self, result: result)
}
func editSaveViewControllerWillCancel(_ saveData: EditSaveViewController.SaveData) {
editConfirmationSavedData = saveData
}
}
// MARK: - EditPreviewViewControllerDelegate
extension SectionEditorViewController: EditPreviewViewControllerDelegate {
func editPreviewViewControllerDidTapNext(_ editPreviewViewController: EditPreviewViewController) {
guard let vc = EditSaveViewController.wmf_initialViewControllerFromClassStoryboard() else {
return
}
vc.savedData = editConfirmationSavedData
vc.dataStore = dataStore
vc.articleURL = self.articleURL
vc.sectionID = self.sectionID
vc.languageCode = self.languageCode
vc.wikitext = editPreviewViewController.wikitext
vc.delegate = self
vc.theme = self.theme
vc.editFunnel = self.editFunnel
vc.editFunnelSource = editFunnelSource
vc.loggedEditActions = loggedEditActions
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension SectionEditorViewController: ReadingThemesControlsPresenting {
var shouldPassthroughNavBar: Bool {
return false
}
var showsSyntaxHighlighting: Bool {
return true
}
var readingThemesControlsToolbarItem: UIBarButtonItem {
return self.navigationItemController.readingThemesControlsToolbarItem
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
inputViewsController.suppressMenus = false
}
}
extension SectionEditorViewController: ReadingThemesControlsResponding {
func updateWebViewTextSize(textSize: Int) {
messagingController.scaleBodyText(newSize: String(textSize))
}
func toggleSyntaxHighlighting(_ controller: ReadingThemesControlsViewController) {
messagingController.toggleSyntaxColors()
}
}
extension SectionEditorViewController: FocusNavigationViewDelegate {
func focusNavigationViewDidTapClose(_ focusNavigationView: FocusNavigationView) {
hideFocusNavigationView()
inputViewsController.closeFindAndReplace()
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerScrollDelegate {
func sectionEditorWebViewMessagingController(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, didReceiveScrollMessageWithNewContentOffset newContentOffset: CGPoint) {
guard
presentedViewController == nil,
newContentOffset.x.isFinite,
newContentOffset.y.isFinite
else {
return
}
self.webView.scrollView.setContentOffset(newContentOffset, animated: true)
}
}
extension SectionEditorViewController: SectionEditorInputViewsControllerDelegate {
func sectionEditorInputViewsControllerDidTapMediaInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
let insertMediaViewController = InsertMediaViewController(articleTitle: articleURL.wmf_title, siteURL: articleURL.wmf_site)
insertMediaViewController.delegate = self
insertMediaViewController.apply(theme: theme)
let navigationController = WMFThemeableNavigationController(rootViewController: insertMediaViewController, theme: theme)
navigationController.isNavigationBarHidden = true
present(navigationController, animated: true)
}
func showLinkWizard() {
messagingController.getLink { link in
guard let link = link else {
assertionFailure("Link button should be disabled")
return
}
let siteURL = self.articleURL.wmf_site
if link.exists {
guard let editLinkViewController = EditLinkViewController(link: link, siteURL: siteURL, dataStore: self.dataStore) else {
return
}
editLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: editLinkViewController, theme: self.theme)
navigationController.isNavigationBarHidden = true
self.present(navigationController, animated: true)
} else {
let insertLinkViewController = InsertLinkViewController(link: link, siteURL: siteURL, dataStore: self.dataStore)
insertLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: insertLinkViewController, theme: self.theme)
self.present(navigationController, animated: true)
}
}
}
func sectionEditorInputViewsControllerDidTapLinkInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: SectionEditorMenuItemsControllerDelegate {
func sectionEditorMenuItemsControllerDidTapLink(_ sectionEditorMenuItemsController: SectionEditorMenuItemsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: EditLinkViewControllerDelegate {
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFinishEditingLink displayText: String?, linkTarget: String) {
messagingController.insertOrEditLink(page: linkTarget, label: displayText)
dismiss(animated: true)
}
func editLinkViewControllerDidRemoveLink(_ editLinkViewController: EditLinkViewController) {
messagingController.removeLink()
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFailToExtractArticleTitleFromArticleURL articleURL: URL) {
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertLinkViewControllerDelegate {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?) {
messagingController.insertOrEditLink(page: page, label: label)
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertMediaViewControllerDelegate {
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didPrepareWikitextToInsert wikitext: String) {
dismiss(animated: true)
messagingController.getLineInfo { lineInfo in
guard let lineInfo = lineInfo else {
self.messagingController.replaceSelection(text: wikitext)
return
}
if !lineInfo.hasLineTokens && lineInfo.isAtLineEnd {
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.isAtLineEnd {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.hasLineTokens {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
self.messagingController.newlineAndIndent()
} else {
self.messagingController.replaceSelection(text: wikitext)
}
}
}
}
extension SectionEditorViewController: EditingFlowViewController {
}
#if (TEST)
// MARK: Helpers for testing
extension SectionEditorViewController {
func openFindAndReplaceForTesting() {
inputViewsController.textFormattingProvidingDidTapFindInPage()
}
var webViewForTesting: WKWebView {
return webView
}
var findAndReplaceViewForTesting: FindAndReplaceKeyboardBar? {
return inputViewsController.findAndReplaceViewForTesting
}
}
#endif
| mit | 3d3bb9e7bd6158759f8b8835c500958d | 44.579221 | 384 | 0.715153 | 6.462162 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support | BirdBlox/BirdBlox/HummingbirdDuoPeripheral.swift | 1 | 17162 | //
// HummingbirdDuoPeripheral.swift
// BirdBlox
//
// Created by birdbrain on 3/23/17.
// Copyright © 2017 Birdbrain Technologies LLC. All rights reserved.
//
import Foundation
import CoreBluetooth
class HummingbirdDuoPeripheral: NSObject, CBPeripheralDelegate, BBTRobotBLEPeripheral {
public let peripheral: CBPeripheral
public var id: String {
return peripheral.identifier.uuidString
}
public static let type: BBTRobotType = .HummingbirdDuo
private let BLE_Manager: BLECentralManager
public static let minimumFirmware = "2.2a"
public static let latestFirmware = "2.2b"
//BLE adapter
public static let deviceUUID = CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
//UART Service
static let SERVICE_UUID = CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
//sending
static let TX_UUID = CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
//receiving
static let RX_UUID = CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E")
static let RX_CONFIG_UUID = CBUUID(string: "00002902-0000-1000-8000-00805f9b34fb")
var rx_line, tx_line: CBCharacteristic?
static let sensorByteCount = 4
private var lastSensorUpdate: [UInt8] = Array<UInt8>(repeating: 0, count: sensorByteCount)
var sensorValues: [UInt8] {
return lastSensorUpdate
}
private let initializationCompletion: ((BBTRobotBLEPeripheral) -> Void)?
private var _initialized = false
public var initialized: Bool {
return self._initialized
}
//MARK: Variables to coordinate set all
private var useSetall = true
private var writtenCondition: NSCondition = NSCondition()
//MARK: Variables write protected by writtenCondition
private var currentOutputState: BBTHummingbirdOutputState
public var nextOutputState: BBTHummingbirdOutputState
var lastWriteWritten: Bool = false
var lastWriteStart: DispatchTime = DispatchTime.now()
//End variables write protected by writtenCondition
private var syncTimer: Timer = Timer()
let syncInterval = 0.03125 //(32Hz)
let cacheTimeoutDuration: UInt64 = 1 * 1_000_000_000 //nanoseconds
let waitRefreshTime = 0.5 //seconds
let creationTime = DispatchTime.now()
private var initializingCondition = NSCondition()
private var lineIn: [UInt8] = [0, 0, 0, 0, 0, 0, 0, 0]
private var hardwareString = ""
private var firmwareVersionString = ""
//MARK: Variables for HB renaming
// static let ADALE_COMMAND_MODE_TOGGLE = "+++\n"
// static let ADALE_GET_MAC = "AT+BLEGETADDR\n"
// static let ADALE_SET_NAME = "AT+GAPDEVNAME="
// static let ADALE_RESET = "ATZ\n"
// static let NAME_PREFIX = "HB"
// var macStr: String? = nil
// let macReplyLen = 17e
// let macLen = 12
// var oneOffTimer: Timer = Timer()
// var resettingName = false
// var gettingMAC = false
// var commandMode = false
override public var description: String {
let gapName = self.peripheral.name ?? "Unknown"
let name = BBTgetDeviceNameForGAPName(gapName)
var updateDesc = ""
if !self.useSetall {
updateDesc = "\n\nThis Hummingbird needs to be updated. " +
"See the link below: \n" +
"http://www.hummingbirdkit.com/learning/installing-birdblox#BurnFirmware "
}
return
"Hummingbird Peripheral\n" +
"Name: \(name)\n" +
"Bluetooth Name: \(gapName)\n" +
"Hardware Version: \(self.hardwareString)\n" +
"Firmware Version: \(self.firmwareVersionString)" +
updateDesc
}
required init(peripheral: CBPeripheral, completion: ((BBTRobotBLEPeripheral) -> Void)? = nil){
self.peripheral = peripheral
self.BLE_Manager = BLECentralManager.shared
self.currentOutputState = BBTHummingbirdOutputState()
self.nextOutputState = BBTHummingbirdOutputState()
self.initializationCompletion = completion
super.init()
self.peripheral.delegate = self
self.peripheral.discoverServices([HummingbirdDuoPeripheral.SERVICE_UUID])
}
/**
* This is called when a service is discovered for a peripheral
* We specifically want the GATT service and start discovering characteristics
* for that GATT service
*/
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if (peripheral != self.peripheral || error != nil) {
//not the right device
return
}
if let services = peripheral.services{
for service in services {
if(service.uuid == HummingbirdDuoPeripheral.SERVICE_UUID){
peripheral.discoverCharacteristics([HummingbirdDuoPeripheral.RX_UUID,
HummingbirdDuoPeripheral.TX_UUID],
for: service)
return
}
}
}
}
/**
* Once we find a characteristic, we check if it is the RX or TX line that was
* found. Once we have found both, we send a notification saying the device
* is now conencted
*/
func peripheral(_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if (peripheral != self.peripheral || error != nil) {
//not the right device
return
}
var wasTXSet = false
var wasRXSet = false
if let characteristics = service.characteristics{
for characteristic in characteristics {
if(characteristic.uuid == HummingbirdDuoPeripheral.TX_UUID){
tx_line = characteristic
peripheral.setNotifyValue(true, for: characteristic )
wasTXSet = true
}
else if(characteristic.uuid == HummingbirdDuoPeripheral.RX_UUID){
rx_line = characteristic
peripheral.setNotifyValue(true, for: characteristic )
wasRXSet = true
}
if(wasTXSet && wasRXSet){
DispatchQueue.main.async {
self.initialize()
}
return
}
}
}
}
private func initialize() {
print("start init")
//Get ourselves a fresh slate
self.sendData(data: BBTHummingbirdUtility.getPollStopCommand())
// Thread.sleep(forTimeInterval: 4) //make sure that the HB is booted up
//Worked 4 of 5 times when at 3 seconds.
let timeoutTime = Date(timeIntervalSinceNow: TimeInterval(7)) //seconds
self.initializingCondition.lock()
let oldLineIn = self.lineIn
self.sendData(data: "G4".data(using: .utf8)!)
//Wait until we get a response or until we timeout.
//If we time out the verion will be 0.0, which is invalid.
while (self.lineIn == oldLineIn && (Date().timeIntervalSince(timeoutTime) < 0)) {
self.initializingCondition.wait(until: Date(timeIntervalSinceNow: 1))
}
let versionArray = self.lineIn
self.hardwareString = String(versionArray[0]) + "." + String(versionArray[1])
self.firmwareVersionString = String(versionArray[2]) + "." + String(versionArray[3]) +
(String(bytes: [versionArray[4]], encoding: .ascii) ?? "")
print(versionArray)
print("end hi")
self.initializingCondition.unlock()
guard self.connected else {
BLE_Manager.disconnect(byID: self.id)
NSLog("Initialization failed because HB got disconnected.")
return
}
//If the firmware version is too low, then disconnect and inform the user.
//Must be higher than 2.2b OR be 2.1i
guard versionArray[2] >= 2 &&
((versionArray[3] >= 2) || (versionArray[3] == 1 && versionArray[4] >= 105)) else {
let _ = FrontendCallbackCenter.shared
.robotFirmwareIncompatible(id: self.id, firmware: self.firmwareVersionString)
BLE_Manager.disconnect(byID: self.id)
NSLog("Initialization failed due to incompatible firmware.")
return
}
//Old firmware, but still compatible
if versionArray[3] == 1 && versionArray[4] >= 105 {
let _ = FrontendCallbackCenter.shared.robotFirmwareStatus(id: self.id, status: "old")
self.useSetall = false
}
Thread.sleep(forTimeInterval: 0.1)
self.sendData(data: BBTHummingbirdUtility.getPollStartCommand())
// DispatchQueue.main.async{
if self.useSetall {
self.syncTimer =
Timer.scheduledTimer(timeInterval: self.syncInterval, target: self,
selector: #selector(HummingbirdDuoPeripheral.syncronizeOutputs),
userInfo: nil, repeats: true)
self.syncTimer.fire()
}
// }
self._initialized = true
print("Hummingbird initialized")
if let completion = self.initializationCompletion {
completion(self)
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic,
error: Error?) {
//If we are trying to reset the hummingbird's name, this should be the device's MAC
// print("Did update characteristic \(characteristic)")
if characteristic.uuid != HummingbirdDuoPeripheral.RX_UUID {
return
}
guard let inData = characteristic.value else {
return
}
guard self.initialized else {
self.initializingCondition.lock()
print("hi")
print(inData.debugDescription)
inData.copyBytes(to: &self.lineIn, count: self.lineIn.count)
self.initializingCondition.signal()
self.initializingCondition.unlock()
return
}
if characteristic.value!.count % 5 != 0 {
return
}
//Assume it's sensor in data
inData.copyBytes(to: &self.lastSensorUpdate, count: HummingbirdDuoPeripheral.sensorByteCount)
}
/**
* Called when we update a characteristic (when we write to the HB)
*/
func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
NSLog("Unable to write to hummingbird due to error \(error)")
}
// print("did write")
//We successfully sent a command
self.writtenCondition.lock()
self.lastWriteWritten = true
self.writtenCondition.signal()
// self.currentOutputState = self.nextOutputState.immutableCopy
self.writtenCondition.unlock()
// print(self.lastWriteStart)
}
public func endOfLifeCleanup() -> Bool{
// self.sendData(data: BBTHummingbirdUtility.getPollStopCommand())
self.syncTimer.invalidate()
return true
}
public var connected: Bool {
return peripheral.state == CBPeripheralState.connected
}
private func sendData(data: Data) {
if self.connected {
peripheral.writeValue(data, for: tx_line!, type: .withResponse)
// if self.commandMode {
// print("Sent command: " +
// (NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String))
// }
// else {
//// print("Sent non-command mode message")
// }
}
else{
print("Not connected")
}
}
private func conditionHelper(condition: NSCondition, holdLock: Bool = true,
predicate: (() -> Bool), work: (() -> ())) {
if holdLock {
condition.lock()
}
while !predicate() {
condition.wait(until: Date(timeIntervalSinceNow: self.waitRefreshTime))
}
work()
condition.signal()
if holdLock {
condition.unlock()
}
}
//MAKR: Robot outputs
func setLED(port: Int, intensity: UInt8) -> Bool {
guard self.peripheral.state == .connected else {
return false
}
guard self.useSetall else {
self.sendData(data: BBTHummingbirdUtility.getLEDCommand(UInt8(port),
intensity: intensity))
Thread.sleep(forTimeInterval: 0.1)
return true
}
let i = port - 1
self.writtenCondition.lock()
self.conditionHelper(condition: self.writtenCondition, holdLock: false,
predicate: {
self.nextOutputState.leds[i] == self.currentOutputState.leds[i]
}, work: {
self.nextOutputState.leds[i] = intensity
})
self.writtenCondition.unlock()
print("exit")
return true
}
func setTriLED(port: UInt, intensities: BBTTriLED) -> Bool {
guard self.peripheral.state == .connected else {
return false
}
guard self.useSetall else {
let command = BBTHummingbirdUtility.getTriLEDCommand(UInt8(port),
red_val: intensities.red,
green_val: intensities.green,
blue_val: intensities.blue)
self.sendData(data: command)
Thread.sleep(forTimeInterval: 0.1)
return true
}
let i = Int(port - 1)
let (r, g, b) = (intensities.red, intensities.green, intensities.blue)
self.writtenCondition.lock()
self.conditionHelper(condition: self.writtenCondition, holdLock: false,
predicate: {
self.nextOutputState.trileds[i] == self.currentOutputState.trileds[i]
}, work: {
self.nextOutputState.trileds[i] = BBTTriLED(red: r, green: g, blue: b)
})
self.writtenCondition.unlock()
print("exit")
return true
}
func setVibration(port: Int, intensity: UInt8) -> Bool {
guard self.peripheral.state == .connected else {
return false
}
guard self.useSetall else {
let command = BBTHummingbirdUtility.getVibrationCommand(UInt8(port),
intensity: intensity)
self.sendData(data: command)
Thread.sleep(forTimeInterval: 0.1)
return true
}
let i = port - 1
self.writtenCondition.lock()
self.conditionHelper(condition: self.writtenCondition, holdLock: false,
predicate: {
self.nextOutputState.vibrators[i] == self.currentOutputState.vibrators[i]
}, work: {
self.nextOutputState.vibrators[i] = intensity
})
self.writtenCondition.unlock()
return true
}
func setMotor(port: Int, speed: Int8) -> Bool {
guard self.peripheral.state == .connected else {
return false
}
guard self.useSetall else {
let command = BBTHummingbirdUtility.getMotorCommand(UInt8(port),
speed: Int(speed))
self.sendData(data: command)
Thread.sleep(forTimeInterval: 0.1)
return true
}
let i = port - 1
self.writtenCondition.lock()
self.conditionHelper(condition: self.writtenCondition, holdLock: false,
predicate: {
self.nextOutputState.motors[i] == self.currentOutputState.motors[i]
}, work: {
self.nextOutputState.motors[i] = speed
})
self.writtenCondition.unlock()
return true
}
func setServo(port: UInt, angle: UInt8) -> Bool {
guard self.peripheral.state == .connected else {
return false
}
guard self.useSetall else {
let command = BBTHummingbirdUtility.getServoCommand(UInt8(port),
angle: angle)
self.sendData(data: command)
Thread.sleep(forTimeInterval: 0.1)
return true
}
let i = Int(port - 1)
self.writtenCondition.lock()
self.conditionHelper(condition: self.writtenCondition, holdLock: false,
predicate: {
self.nextOutputState.servos[i] == self.currentOutputState.servos[i]
}, work: {
self.nextOutputState.servos[i] = angle
})
self.writtenCondition.unlock()
return true
}
func syncronizeOutputs() {
self.writtenCondition.lock()
// print("s ", separator: "", terminator: "")
let nextCopy = self.nextOutputState
let changeOccurred = !(nextCopy == self.currentOutputState)
let currentCPUTime = DispatchTime.now().uptimeNanoseconds
let timeout = ((currentCPUTime - self.lastWriteStart.uptimeNanoseconds) >
self.cacheTimeoutDuration)
let shouldSync = changeOccurred || timeout
if self.initialized && (self.lastWriteWritten || timeout) && shouldSync {
let cmdMkr = BBTHummingbirdUtility.getSetAllCommand
let tris = nextCopy.trileds
let leds = nextCopy.leds
let servos = nextCopy.servos
let motors = nextCopy.motors
let vibrators = nextCopy.vibrators
let command = cmdMkr((tris[0].tuple, tris[1].tuple),
(leds[0], leds[1], leds[2], leds[3]),
(servos[0], servos[1], servos[2], servos[3]),
(motors[0], motors[1]),
(vibrators[0], vibrators[1]))
self.sendData(data: command)
self.lastWriteStart = DispatchTime.now()
self.lastWriteWritten = false
self.currentOutputState = nextCopy
//For debugging
#if DEBUG
let bytes = UnsafeMutableBufferPointer<UInt8>(
start: UnsafeMutablePointer<UInt8>.allocate(capacity: 20), count: 19)
let _ = command.copyBytes(to: bytes)
print("\(self.creationTime)")
print("Setting All: \(bytes.map({return $0}))")
#endif
}
else {
if !self.lastWriteWritten {
// print("miss")
}
}
self.writtenCondition.unlock()
}
func setAllOutputsToOff() -> Bool {
//Sending an ASCII capital X should do the same thing.
//Useful for legacy firmware
self.writtenCondition.lock()
self.nextOutputState = BBTHummingbirdOutputState()
self.writtenCondition.unlock()
return true
}
}
| mit | fff83ab2aa5e34cc40ec2edca0437d54 | 29.427305 | 101 | 0.649554 | 3.697694 | false | false | false | false |
matsprea/omim | iphone/Maps/Classes/CarPlay/CarPlayService.swift | 2 | 28725 | import CarPlay
import Contacts
@available(iOS 12.0, *)
@objc(MWMCarPlayService)
final class CarPlayService: NSObject {
@objc static let shared = CarPlayService()
@objc var isCarplayActivated: Bool = false
private var searchService: CarPlaySearchService?
private var router: CarPlayRouter?
private var window: CPWindow?
private var interfaceController: CPInterfaceController?
private var sessionConfiguration: CPSessionConfiguration?
var currentPositionMode: MWMMyPositionMode = .pendingPosition
var isSpeedCamActivated: Bool {
set {
router?.updateSpeedCameraMode(newValue ? .always: .never)
}
get {
let mode: SpeedCameraManagerMode = router?.speedCameraMode ?? .never
return mode == .always ? true : false
}
}
var isKeyboardLimited: Bool {
return sessionConfiguration?.limitedUserInterfaces.contains(.keyboard) ?? false
}
private var carplayVC: CarPlayMapViewController? {
return window?.rootViewController as? CarPlayMapViewController
}
private var rootMapTemplate: CPMapTemplate? {
return interfaceController?.rootTemplate as? CPMapTemplate
}
var preparedToPreviewTrips: [CPTrip] = []
var isUserPanMap: Bool = false
@objc func setup(window: CPWindow, interfaceController: CPInterfaceController) {
isCarplayActivated = true
self.window = window
self.interfaceController = interfaceController
self.interfaceController?.delegate = self
sessionConfiguration = CPSessionConfiguration(delegate: self)
searchService = CarPlaySearchService()
let router = CarPlayRouter()
router.addListener(self)
router.subscribeToEvents()
router.setupCarPlaySpeedCameraMode()
self.router = router
MWMRouter.unsubscribeFromEvents()
applyRootViewController()
if let sessionData = router.restoredNavigationSession() {
applyNavigationRootTemplate(trip: sessionData.0, routeInfo: sessionData.1)
} else {
applyBaseRootTemplate()
router.restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: true)
}
ThemeManager.invalidate()
FrameworkHelper.updatePositionArrowOffset(false, offset: 5)
}
@objc func destroy() {
if let carplayVC = carplayVC {
carplayVC.removeMapView()
}
MapViewController.shared()?.disableCarPlayRepresentation()
MapViewController.shared()?.remove(self)
router?.removeListener(self)
router?.unsubscribeFromEvents()
router?.setupInitialSpeedCameraMode()
MWMRouter.subscribeToEvents()
isCarplayActivated = false
if router?.currentTrip != nil {
MWMRouter.showNavigationMapControls()
} else if router?.previewTrip != nil {
MWMRouter.rebuild(withBestRouter: true)
}
searchService = nil
router = nil
sessionConfiguration = nil
interfaceController = nil
ThemeManager.invalidate()
FrameworkHelper.updatePositionArrowOffset(true, offset: 0)
}
@objc func interfaceStyle() -> UIUserInterfaceStyle {
if let window = window,
window.traitCollection.userInterfaceIdiom == .carPlay {
return window.traitCollection.userInterfaceStyle
}
return .unspecified
}
private func applyRootViewController() {
guard let window = window else { return }
let carplaySotyboard = UIStoryboard.instance(.carPlay)
let carplayVC = carplaySotyboard.instantiateInitialViewController() as! CarPlayMapViewController
window.rootViewController = carplayVC
if let mapVC = MapViewController.shared() {
currentPositionMode = mapVC.currentPositionMode
mapVC.enableCarPlayRepresentation()
carplayVC.addMapView(mapVC.mapView, mapButtonSafeAreaLayoutGuide: window.mapButtonSafeAreaLayoutGuide)
mapVC.add(self)
}
}
private func applyBaseRootTemplate() {
let mapTemplate = MapTemplateBuilder.buildBaseTemplate(positionMode: currentPositionMode)
mapTemplate.mapDelegate = self
interfaceController?.setRootTemplate(mapTemplate, animated: true)
FrameworkHelper.rotateMap(0.0, animated: false)
}
private func applyNavigationRootTemplate(trip: CPTrip, routeInfo: RouteInfo) {
let mapTemplate = MapTemplateBuilder.buildNavigationTemplate()
mapTemplate.mapDelegate = self
interfaceController?.setRootTemplate(mapTemplate, animated: true)
router?.startNavigationSession(forTrip: trip, template: mapTemplate)
if let estimates = createEstimates(routeInfo: routeInfo) {
mapTemplate.updateEstimates(estimates, for: trip)
}
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(routeInfo.speed)
carplayVC.showSpeedControl()
}
}
func pushTemplate(_ templateToPush: CPTemplate, animated: Bool) {
if let interfaceController = interfaceController {
switch templateToPush {
case let list as CPListTemplate:
list.delegate = self
case let search as CPSearchTemplate:
search.delegate = self
case let map as CPMapTemplate:
map.mapDelegate = self
default:
break
}
interfaceController.pushTemplate(templateToPush, animated: animated)
}
}
func popTemplate(animated: Bool) {
interfaceController?.popTemplate(animated: animated)
}
func presentAlert(_ template: CPAlertTemplate, animated: Bool) {
interfaceController?.dismissTemplate(animated: false)
interfaceController?.presentTemplate(template, animated: animated)
}
func cancelCurrentTrip() {
router?.cancelTrip()
if let carplayVC = carplayVC {
carplayVC.hideSpeedControl()
}
updateMapTemplateUIToBase()
}
func updateCameraUI(isCameraOnRoute: Bool, speedLimit limit: String?) {
if let carplayVC = carplayVC {
let speedLimit = limit == nil ? nil : Int(limit!)
carplayVC.updateCameraInfo(isCameraOnRoute: isCameraOnRoute, speedLimit: speedLimit)
}
}
func updateMapTemplateUIToBase() {
guard let mapTemplate = rootMapTemplate else {
return
}
MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate)
if currentPositionMode == .pendingPosition {
mapTemplate.leadingNavigationBarButtons = []
} else if currentPositionMode == .follow || currentPositionMode == .followAndRotate {
MapTemplateBuilder.setupDestinationButton(mapTemplate: mapTemplate)
} else {
MapTemplateBuilder.setupRecenterButton(mapTemplate: mapTemplate)
}
updateVisibleViewPortState(.default)
FrameworkHelper.rotateMap(0.0, animated: true)
}
func updateMapTemplateUIToTripFinished(_ trip: CPTrip) {
guard let mapTemplate = rootMapTemplate else {
return
}
mapTemplate.leadingNavigationBarButtons = []
mapTemplate.trailingNavigationBarButtons = []
mapTemplate.mapButtons = []
let doneAction = CPAlertAction(title: L("done"), style: .cancel) { [unowned self] _ in
self.updateMapTemplateUIToBase()
}
var subtitle = ""
if let locationName = trip.destination.name {
subtitle = locationName
}
if let address = trip.destination.placemark.addressDictionary?[CNPostalAddressStreetKey] as? String {
subtitle = subtitle + "\n" + address
}
let alert = CPNavigationAlert(titleVariants: [L("trip_finished")],
subtitleVariants: [subtitle],
imageSet: nil,
primaryAction: doneAction,
secondaryAction: nil,
duration: 0)
mapTemplate.present(navigationAlert: alert, animated: true)
}
func updateVisibleViewPortState(_ state: CPViewPortState) {
guard let carplayVC = carplayVC else {
return
}
carplayVC.updateVisibleViewPortState(state)
}
func updateRouteAfterChangingSettings() {
router?.rebuildRoute()
}
@objc func showNoMapAlert() {
guard let mapTemplate = interfaceController?.topTemplate as? CPMapTemplate,
let info = mapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.main else {
return
}
let alert = CPAlertTemplate(titleVariants: [L("download_map_carplay")], actions: [])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.downloadMap]
presentAlert(alert, animated: true)
}
@objc func hideNoMapAlert() {
if let presentedTemplate = interfaceController?.presentedTemplate,
let info = presentedTemplate.userInfo as? [String: String],
let alertType = info[CPConstants.TemplateKey.alert],
alertType == CPConstants.TemplateType.downloadMap {
interfaceController?.dismissTemplate(animated: true)
}
}
}
// MARK: - CPInterfaceControllerDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPInterfaceControllerDelegate {
func templateWillAppear(_ aTemplate: CPTemplate, animated: Bool) {
guard let info = aTemplate.userInfo as? MapInfo else {
return
}
switch info.type {
case CPConstants.TemplateType.main:
updateVisibleViewPortState(.default)
case CPConstants.TemplateType.preview:
updateVisibleViewPortState(.preview)
case CPConstants.TemplateType.navigation:
updateVisibleViewPortState(.navigation)
case CPConstants.TemplateType.previewSettings:
aTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.preview)
default:
break
}
}
func templateDidAppear(_ aTemplate: CPTemplate, animated: Bool) {
guard let mapTemplate = aTemplate as? CPMapTemplate,
let info = aTemplate.userInfo as? MapInfo else {
return
}
if !preparedToPreviewTrips.isEmpty && info.type == CPConstants.TemplateType.main {
preparePreview(trips: preparedToPreviewTrips)
preparedToPreviewTrips = []
return
}
if info.type == CPConstants.TemplateType.preview, let trips = info.trips {
showPreview(mapTemplate: mapTemplate, trips: trips)
}
}
func templateWillDisappear(_ aTemplate: CPTemplate, animated: Bool) {
guard let info = aTemplate.userInfo as? MapInfo else {
return
}
if info.type == CPConstants.TemplateType.preview {
router?.completeRouteAndRemovePoints()
}
}
func templateDidDisappear(_ aTemplate: CPTemplate, animated: Bool) {
guard !preparedToPreviewTrips.isEmpty,
let info = aTemplate.userInfo as? [String: String],
let alertType = info[CPConstants.TemplateKey.alert],
alertType == CPConstants.TemplateType.redirectRoute ||
alertType == CPConstants.TemplateType.restoreRoute else {
return
}
preparePreview(trips: preparedToPreviewTrips)
preparedToPreviewTrips = []
}
}
// MARK: - CPSessionConfigurationDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPSessionConfigurationDelegate {
func sessionConfiguration(_ sessionConfiguration: CPSessionConfiguration,
limitedUserInterfacesChanged limitedUserInterfaces: CPLimitableUserInterface) {
}
}
// MARK: - CPMapTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPMapTemplateDelegate {
public func mapTemplateDidShowPanningInterface(_ mapTemplate: CPMapTemplate) {
isUserPanMap = false
MapTemplateBuilder.configurePanUI(mapTemplate: mapTemplate)
FrameworkHelper.stopLocationFollow()
}
public func mapTemplateDidDismissPanningInterface(_ mapTemplate: CPMapTemplate) {
if let info = mapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.navigation {
MapTemplateBuilder.configureNavigationUI(mapTemplate: mapTemplate)
} else {
MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate)
}
FrameworkHelper.switchMyPositionMode()
}
func mapTemplate(_ mapTemplate: CPMapTemplate, panEndedWith direction: CPMapTemplate.PanDirection) {
var offset = UIOffset(horizontal: 0.0, vertical: 0.0)
let offsetStep: CGFloat = 0.25
if direction.contains(.up) { offset.vertical -= offsetStep }
if direction.contains(.down) { offset.vertical += offsetStep }
if direction.contains(.left) { offset.horizontal += offsetStep }
if direction.contains(.right) { offset.horizontal -= offsetStep }
FrameworkHelper.moveMap(offset)
isUserPanMap = true
}
func mapTemplate(_ mapTemplate: CPMapTemplate, panWith direction: CPMapTemplate.PanDirection) {
var offset = UIOffset(horizontal: 0.0, vertical: 0.0)
let offsetStep: CGFloat = 0.1
if direction.contains(.up) { offset.vertical -= offsetStep }
if direction.contains(.down) { offset.vertical += offsetStep }
if direction.contains(.left) { offset.horizontal += offsetStep }
if direction.contains(.right) { offset.horizontal -= offsetStep }
FrameworkHelper.moveMap(offset)
isUserPanMap = true
}
func mapTemplate(_ mapTemplate: CPMapTemplate, startedTrip trip: CPTrip, using routeChoice: CPRouteChoice) {
guard let info = routeChoice.userInfo as? RouteInfo else {
if let info = routeChoice.userInfo as? [String: Any],
let code = info[CPConstants.Trip.errorCode] as? RouterResultCode,
let countries = info[CPConstants.Trip.missedCountries] as? [String] {
showErrorAlert(code: code, countries: countries)
}
return
}
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.previewAccepted)
mapTemplate.hideTripPreviews()
guard let router = router,
let interfaceController = interfaceController,
let rootMapTemplate = rootMapTemplate else {
return
}
MapTemplateBuilder.configureNavigationUI(mapTemplate: rootMapTemplate)
interfaceController.popToRootTemplate(animated: false)
router.startNavigationSession(forTrip: trip, template: rootMapTemplate)
router.startRoute()
if let estimates = createEstimates(routeInfo: info) {
rootMapTemplate.updateEstimates(estimates, for: trip)
}
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(info.speed)
carplayVC.showSpeedControl()
}
updateVisibleViewPortState(.navigation)
}
func mapTemplate(_ mapTemplate: CPMapTemplate, displayStyleFor maneuver: CPManeuver) -> CPManeuverDisplayStyle {
if let type = maneuver.userInfo as? String,
type == CPConstants.Maneuvers.secondary {
return .trailingSymbol
}
return .leadingSymbol
}
func mapTemplate(_ mapTemplate: CPMapTemplate,
selectedPreviewFor trip: CPTrip,
using routeChoice: CPRouteChoice) {
guard let previewTrip = router?.previewTrip, previewTrip == trip else {
applyUndefinedEstimates(template: mapTemplate, trip: trip)
router?.buildRoute(trip: trip)
return
}
guard let info = routeChoice.userInfo as? RouteInfo,
let estimates = createEstimates(routeInfo: info) else {
applyUndefinedEstimates(template: mapTemplate, trip: trip)
router?.rebuildRoute()
return
}
mapTemplate.updateEstimates(estimates, for: trip)
routeChoice.userInfo = nil
router?.rebuildRoute()
}
}
// MARK: - CPListTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPListTemplateDelegate {
func listTemplate(_ listTemplate: CPListTemplate, didSelect item: CPListItem, completionHandler: @escaping () -> Void) {
if let userInfo = item.userInfo as? ListItemInfo {
let fromStat: String
var categoryName = ""
switch userInfo.type {
case CPConstants.ListItemType.history:
fromStat = kStatRecent
let locale = window?.textInputMode?.primaryLanguage ?? "en"
guard let searchService = searchService else {
completionHandler()
return
}
searchService.searchText(item.text ?? "", forInputLocale: locale, completionHandler: { [weak self] results in
guard let self = self else { return }
let template = ListTemplateBuilder.buildListTemplate(for: .searchResults(results: results))
completionHandler()
self.pushTemplate(template, animated: true)
})
case CPConstants.ListItemType.bookmarkLists where userInfo.metadata is CategoryInfo:
fromStat = kStatCategory
let metadata = userInfo.metadata as! CategoryInfo
categoryName = metadata.category.title
let template = ListTemplateBuilder.buildListTemplate(for: .bookmarks(category: metadata.category))
completionHandler()
pushTemplate(template, animated: true)
case CPConstants.ListItemType.bookmarks where userInfo.metadata is BookmarkInfo:
fromStat = kStatBookmarks
let metadata = userInfo.metadata as! BookmarkInfo
let bookmark = MWMCarPlayBookmarkObject(bookmarkId: metadata.bookmarkId)
preparePreview(forBookmark: bookmark)
completionHandler()
case CPConstants.ListItemType.searchResults where userInfo.metadata is SearchResultInfo:
fromStat = kStatSearch
let metadata = userInfo.metadata as! SearchResultInfo
preparePreviewForSearchResults(selectedRow: metadata.originalRow)
completionHandler()
default:
fromStat = ""
completionHandler()
}
guard fromStat.count > 0 else { return }
Statistics.logEvent(kStatCarplayDestinationsItemSelected,
withParameters: [kStatFrom : fromStat,
kStatCategory : categoryName])
}
}
}
// MARK: - CPSearchTemplateDelegate implementation
@available(iOS 12.0, *)
extension CarPlayService: CPSearchTemplateDelegate {
func searchTemplate(_ searchTemplate: CPSearchTemplate, updatedSearchText searchText: String, completionHandler: @escaping ([CPListItem]) -> Void) {
let locale = window?.textInputMode?.primaryLanguage ?? "en"
guard let searchService = searchService else {
completionHandler([])
return
}
searchService.searchText(searchText, forInputLocale: locale, completionHandler: { results in
var items = [CPListItem]()
for object in results {
let item = CPListItem(text: object.title, detailText: object.address)
item.userInfo = ListItemInfo(type: CPConstants.ListItemType.searchResults,
metadata: SearchResultInfo(originalRow: object.originalRow))
items.append(item)
}
completionHandler(items)
})
Alohalytics.logEvent(kStatCarplayKeyboardSearch)
}
func searchTemplate(_ searchTemplate: CPSearchTemplate, selectedResult item: CPListItem, completionHandler: @escaping () -> Void) {
searchService?.saveLastQuery()
if let info = item.userInfo as? ListItemInfo,
let metadata = info.metadata as? SearchResultInfo {
preparePreviewForSearchResults(selectedRow: metadata.originalRow)
}
completionHandler()
}
}
// MARK: - CarPlayRouterListener implementation
@available(iOS 12.0, *)
extension CarPlayService: CarPlayRouterListener {
func didCreateRoute(routeInfo: RouteInfo, trip: CPTrip) {
guard let currentTemplate = interfaceController?.topTemplate as? CPMapTemplate,
let info = currentTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.preview else {
return
}
if let estimates = createEstimates(routeInfo: routeInfo) {
currentTemplate.updateEstimates(estimates, for: trip)
}
}
func didUpdateRouteInfo(_ routeInfo: RouteInfo, forTrip trip: CPTrip) {
if let carplayVC = carplayVC {
carplayVC.updateCurrentSpeed(routeInfo.speed)
}
guard let router = router,
let template = rootMapTemplate else {
return
}
router.updateUpcomingManeuvers()
if let estimates = createEstimates(routeInfo: routeInfo) {
template.updateEstimates(estimates, for: trip)
}
trip.routeChoices.first?.userInfo = routeInfo
}
func didFailureBuildRoute(forTrip trip: CPTrip, code: RouterResultCode, countries: [String]) {
guard let template = interfaceController?.topTemplate as? CPMapTemplate else { return }
trip.routeChoices.first?.userInfo = [CPConstants.Trip.errorCode: code, CPConstants.Trip.missedCountries: countries]
applyUndefinedEstimates(template: template, trip: trip)
}
func routeDidFinish(_ trip: CPTrip) {
if router?.currentTrip == nil { return }
router?.finishTrip()
if let carplayVC = carplayVC {
carplayVC.hideSpeedControl()
}
updateMapTemplateUIToTripFinished(trip)
}
}
// MARK: - LocationModeListener implementation
@available(iOS 12.0, *)
extension CarPlayService: LocationModeListener {
func processMyPositionStateModeEvent(_ mode: MWMMyPositionMode) {
currentPositionMode = mode
guard let rootMapTemplate = rootMapTemplate,
let info = rootMapTemplate.userInfo as? MapInfo,
info.type == CPConstants.TemplateType.main else {
return
}
switch mode {
case .follow, .followAndRotate:
if !rootMapTemplate.isPanningInterfaceVisible {
MapTemplateBuilder.setupDestinationButton(mapTemplate: rootMapTemplate)
}
case .notFollow:
if !rootMapTemplate.isPanningInterfaceVisible {
MapTemplateBuilder.setupRecenterButton(mapTemplate: rootMapTemplate)
}
case .pendingPosition, .notFollowNoPosition:
rootMapTemplate.leadingNavigationBarButtons = []
}
}
func processMyPositionPendingTimeout() {
}
}
// MARK: - Alerts and Trip Previews
@available(iOS 12.0, *)
extension CarPlayService {
func preparePreviewForSearchResults(selectedRow row: Int) {
var results = searchService?.lastResults ?? []
if let currentItemIndex = results.firstIndex(where: { $0.originalRow == row }) {
let item = results.remove(at: currentItemIndex)
results.insert(item, at: 0)
} else {
results.insert(MWMCarPlaySearchResultObject(forRow: row), at: 0)
}
if let router = router,
let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0) {
let endPoints = results.compactMap({ MWMRoutePoint(cgPoint: $0.mercatorPoint,
title: $0.title,
subtitle: $0.address,
type: .finish,
intermediateIndex: 0) })
let trips = endPoints.map({ router.createTrip(startPoint: startPoint, endPoint: $0) })
if router.currentTrip == nil {
preparePreview(trips: trips)
} else {
showRerouteAlert(trips: trips)
}
}
}
func preparePreview(forBookmark bookmark: MWMCarPlayBookmarkObject) {
if let router = router,
let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0),
let endPoint = MWMRoutePoint(cgPoint: bookmark.mercatorPoint,
title: bookmark.prefferedName,
subtitle: bookmark.address,
type: .finish,
intermediateIndex: 0) {
let trip = router.createTrip(startPoint: startPoint, endPoint: endPoint)
if router.currentTrip == nil {
preparePreview(trips: [trip])
} else {
showRerouteAlert(trips: [trip])
}
}
}
func preparePreview(trips: [CPTrip]) {
let mapTemplate = MapTemplateBuilder.buildTripPreviewTemplate(forTrips: trips)
if let interfaceController = interfaceController {
mapTemplate.mapDelegate = self
interfaceController.popToRootTemplate(animated: false)
interfaceController.pushTemplate(mapTemplate, animated: false)
}
}
func showPreview(mapTemplate: CPMapTemplate, trips: [CPTrip]) {
let tripTextConfig = CPTripPreviewTextConfiguration(startButtonTitle: L("trip_start"),
additionalRoutesButtonTitle: nil,
overviewButtonTitle: nil)
mapTemplate.showTripPreviews(trips, textConfiguration: tripTextConfig)
}
func createEstimates(routeInfo: RouteInfo) -> CPTravelEstimates? {
if let distance = Double(routeInfo.targetDistance) {
let measurement = Measurement(value: distance,
unit: routeInfo.targetUnits)
let estimates = CPTravelEstimates(distanceRemaining: measurement,
timeRemaining: routeInfo.timeToTarget)
return estimates
}
return nil
}
func applyUndefinedEstimates(template: CPMapTemplate, trip: CPTrip) {
let measurement = Measurement(value: -1,
unit: UnitLength.meters)
let estimates = CPTravelEstimates(distanceRemaining: measurement,
timeRemaining: -1)
template.updateEstimates(estimates, for: trip)
}
func showRerouteAlert(trips: [CPTrip]) {
let yesAction = CPAlertAction(title: L("redirect_route_yes"), style: .default, handler: { [unowned self] _ in
self.router?.cancelTrip()
self.updateMapTemplateUIToBase()
self.preparedToPreviewTrips = trips
self.interfaceController?.dismissTemplate(animated: true)
})
let noAction = CPAlertAction(title: L("redirect_route_no"), style: .cancel, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: [L("redirect_route_alert")], actions: [noAction, yesAction])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.redirectRoute]
presentAlert(alert, animated: true)
}
func showKeyboardAlert() {
let okAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: [L("keyboard_availability_alert")], actions: [okAction])
presentAlert(alert, animated: true)
}
func showErrorAlert(code: RouterResultCode, countries: [String]) {
var titleVariants = [String]()
switch code {
case .noCurrentPosition:
titleVariants = ["\(L("dialog_routing_check_gps_carplay"))"]
case .startPointNotFound:
titleVariants = ["\(L("dialog_routing_change_start_carplay"))"]
case .endPointNotFound:
titleVariants = ["\(L("dialog_routing_change_end_carplay"))"]
case .routeNotFoundRedressRouteError,
.routeNotFound,
.inconsistentMWMandRoute:
titleVariants = ["\(L("dialog_routing_unable_locate_route_carplay"))"]
case .routeFileNotExist,
.fileTooOld,
.needMoreMaps,
.pointsInDifferentMWM:
titleVariants = ["\(L("dialog_routing_download_files_carplay"))"]
case .internalError,
.intermediatePointNotFound:
titleVariants = ["\(L("dialog_routing_system_error_carplay"))"]
case .noError,
.cancelled,
.hasWarnings,
.transitRouteNotFoundNoNetwork,
.transitRouteNotFoundTooLongPedestrian:
return
}
let okAction = CPAlertAction(title: L("ok"), style: .cancel, handler: { [unowned self] _ in
self.interfaceController?.dismissTemplate(animated: true)
})
let alert = CPAlertTemplate(titleVariants: titleVariants, actions: [okAction])
presentAlert(alert, animated: true)
}
func showRecoverRouteAlert(trip: CPTrip, isTypeCorrect: Bool) {
let yesAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in
var info = trip.userInfo as? [String: MWMRoutePoint]
if let startPoint = MWMRoutePoint(lastLocationAndType: .start,
intermediateIndex: 0) {
info?[CPConstants.Trip.start] = startPoint
}
trip.userInfo = info
self.preparedToPreviewTrips = [trip]
self.router?.updateStartPointAndRebuild(trip: trip)
self.interfaceController?.dismissTemplate(animated: true)
})
let noAction = CPAlertAction(title: L("cancel"), style: .cancel, handler: { [unowned self] _ in
FrameworkHelper.rotateMap(0.0, animated: false)
self.router?.completeRouteAndRemovePoints()
self.interfaceController?.dismissTemplate(animated: true)
})
let title = isTypeCorrect ? L("dialog_routing_rebuild_from_current_location_carplay") : L("dialog_routing_rebuild_for_vehicle_carplay")
let alert = CPAlertTemplate(titleVariants: [title], actions: [noAction, yesAction])
alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.restoreRoute]
presentAlert(alert, animated: true)
}
}
| apache-2.0 | 3ab3b130ca1f0345147168a3d6055434 | 38.188267 | 150 | 0.691384 | 4.59453 | false | false | false | false |
jdhealy/Argo | ArgoTests/Tests/TypeTests.swift | 10 | 996 | import XCTest
import Argo
import Runes
class TypeTests: XCTestCase {
func testAllTheTypes() {
let model: TestModel? = JSONFromFile("types") >>- decode
XCTAssert(model != nil)
XCTAssert(model?.numerics.int == 5)
XCTAssert(model?.numerics.int64 == 9007199254740992)
XCTAssert(model?.numerics.double == 3.4)
XCTAssert(model?.numerics.float == 1.1)
XCTAssert(model?.numerics.intOpt != nil)
XCTAssert(model?.numerics.intOpt! == 4)
XCTAssert(model?.string == "Cooler User")
XCTAssert(model?.bool == false)
XCTAssert(model?.stringArray.count == 2)
XCTAssert(model?.stringArrayOpt == nil)
XCTAssert(model?.eStringArray.count == 2)
XCTAssert(model?.eStringArrayOpt != nil)
XCTAssert(model?.eStringArrayOpt?.count == 0)
XCTAssert(model?.userOpt != nil)
XCTAssert(model?.userOpt?.id == 6)
}
func testFailingEmbedded() {
let model: TestModel? = JSONFromFile("types_fail_embedded") >>- decode
XCTAssert(model == nil)
}
}
| mit | 7250b1daa11d9ffa3cb5af166c1b6d00 | 30.125 | 74 | 0.677711 | 3.772727 | false | true | false | false |
gsdios/SDAutoLayout | SDAutoLayoutSwiftDemo/ViewController.swift | 1 | 1082 | //
// ViewController.swift
// SDAutoLayoutSwiftDemo
//
// Created by 李响 on 2018/9/29.
// Copyright © 2018 gsd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var redView: UIView = {
$0.backgroundColor = .red
return $0
} ( UIView() )
private lazy var blueView: UIView = {
$0.backgroundColor = .blue
return $0
} ( UIView() )
override func viewDidLoad() {
super.viewDidLoad()
setup()
setupLayout()
}
private func setup() {
view.addSubview(redView)
view.addSubview(blueView)
}
private func setupLayout() {
_ = redView.sd_layout()
.topSpaceToView(view, 80)
.leftSpaceToView(view, 10)
.rightSpaceToView(view, 10)
.heightIs(100)
_ = blueView.sd_layout()
.topSpaceToView(redView, 10)
.leftSpaceToView(view, 10)
.rightSpaceToView(view, 10)
.heightIs(200)
}
}
| mit | 7e948db067eb83b155d2c777ba60a415 | 20.54 | 46 | 0.535747 | 4.46888 | false | false | false | false |
zhao765882596/XImagePickerController | XImagePickerController/Classes/XMImageCropManager.swift | 1 | 7256 | //
// XMImageCropManager.swift
// channel_sp
//
// Created by ming on 2017/10/18.
// Copyright © 2017年 TiandaoJiran. All rights reserved.
//
import Foundation
import UIKit
class XMImageCropManager: NSObject {
class func overlayClipping(view: UIView, cropRect: CGRect, containerView: UIView, isNeedCircleCrop: Bool = false) {
let path = UIBezierPath.init(rect: UIScreen.main.bounds)
let layer = CAShapeLayer()
if isNeedCircleCrop {
path.append(UIBezierPath.init(arcCenter: containerView.center, radius: cropRect.width * 0.5, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: false))
} else {
path.append(UIBezierPath.init(rect: cropRect))
}
layer.path = path.cgPath
layer.fillRule = kCAFillRuleEvenOdd
layer.fillColor = UIColor.black.cgColor
layer.opacity = 0.5
view.layer.addSublayer(layer)
}
class func cropImageView(imageView: UIImageView?, toRect: CGRect, zoomScale: CGFloat, containerView: UIView) -> UIImage? {
guard let iv = imageView else {
return nil
}
var transform = CGAffineTransform.identity
let imageViewRect = iv.convert(iv.bounds, to: containerView)
let point = CGPoint.init(x: imageViewRect.midX + imageViewRect.width * 0.5, y: imageViewRect.minY + imageViewRect.height * 0.5)
let xMargin: CGFloat = containerView.xm_width - toRect.maxX - toRect.midX
let zeroPoint = CGPoint.init(x: (containerView.xm_width - xMargin) * 0.5, y: containerView.xm_centerY)
let translation = CGPoint.init(x: point.x - zeroPoint.x, y: point.y - zeroPoint.y)
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: zoomScale, y: zoomScale)
let image = iv.image ?? UIImage()
let imageRef = self.newTransformedImage(transform: transform, sourceImage: image.cgImage!, sourceSize: image.size, outputWidth: toRect.size.width * UIScreen.main.scale, cropSize: toRect.size, imageViewSize: imageView!.frame.size)
var cropedImage = UIImage.init(cgImage: imageRef)
cropedImage = XMImageManager.manager.fixOrientation(image: cropedImage)!
return cropedImage;
}
class func newTransformedImage(transform:CGAffineTransform, sourceImage: CGImage, sourceSize: CGSize, outputWidth: CGFloat, cropSize: CGSize, imageViewSize: CGSize) -> CGImage {
let source = self.newScaledImage(source: sourceImage, size: sourceSize)
let aspect = cropSize.height / cropSize.width
let outputSize = CGSize.init(width: outputWidth, height: outputWidth * aspect)
var bitmapInfo = CGBitmapInfo.init(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
bitmapInfo.insert(.byteOrder32Big)
let context = CGContext.init(data: nil, width: Int(outputSize.width), height: Int(outputSize.height), bitsPerComponent: source.bitsPerComponent, bytesPerRow: source.bytesPerRow, space: source.colorSpace!, bitmapInfo: source.bitmapInfo.rawValue)
context?.setFillColor(UIColor.clear.cgColor)
context?.fill(CGRect.init(x: 0, y: 0, width: outputSize.width, height: outputSize.height))
var uiCoords = CGAffineTransform.identity
uiCoords = uiCoords.scaledBy(x: outputSize.width / cropSize.width, y: outputSize.height / cropSize.height)
uiCoords = uiCoords.translatedBy(x: cropSize.width / 2.0, y: cropSize.height / 2.0)
context?.concatenate(uiCoords)
context?.concatenate(transform)
context?.scaleBy(x: 1.0, y: -1.0)
context?.draw(source, in: CGRect.init(x: -imageViewSize.width * 0.5, y: -imageViewSize.height * 0.5, width: imageViewSize.width, height: imageViewSize.height))
let resultRef = context?.makeImage()
return resultRef!
}
class func newScaledImage(source: CGImage, size: CGSize) -> CGImage {
// let srcSize = size
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo = CGBitmapInfo.init(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
bitmapInfo.insert(.byteOrder32Big)
let context = CGContext.init(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: rgbColorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.interpolationQuality = .none
context?.translateBy(x: size.width * 0.5, y: size.height * 0.5)
context?.draw(source, in: CGRect.init(x: -size.width * 0.5, y: -size.height * 0.5, width: size.width, height: size.height))
return context!.makeImage()!
}
/// 获取圆形图片
class func circularClipImage(phtoto: UIImage?) -> UIImage? {
guard let image = phtoto else {
return nil
}
UIGraphicsBeginImageContextWithOptions(image.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()!
let rect = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)
context.addEllipse(in: rect)
context.clip()
image.draw(in: rect)
let circleImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return circleImage
}
}
extension UIImage {
class func xm_animatedGIFWithData(data: Data?) -> UIImage? {
guard let sourceData = data else {
return nil
}
guard let source = CGImageSourceCreateWithData(sourceData as CFData, nil) else {
return nil
}
let count = CGImageSourceGetCount(source)
if count <= 1 {
return UIImage.init(data: sourceData)
} else {
var images: Array<UIImage> = []
var duration: TimeInterval = 0.0;
for i in 0 ..< count {
guard let cgimage = CGImageSourceCreateImageAtIndex(source, i, nil) else {
continue
}
var subDuration = xm_frameDurationAtIndex(index: i, source: source)
if subDuration < 0.011 {
subDuration = 0.1
}
duration = duration + subDuration
images.append(UIImage.init(cgImage: cgimage, scale: UIScreen.main.scale, orientation: .up))
}
if duration == 0.0 {
duration = 1.0 / 10.0 * Double(count)
}
return UIImage.animatedImage(with: images, duration: duration)
}
}
class func xm_frameDurationAtIndex(index: Int, source: CGImageSource) -> TimeInterval {
guard let dict = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? Dictionary<AnyHashable, Any> else {
return 0.1
}
guard let gifProperties = dict[kCGImagePropertyGIFDictionary] as? Dictionary<AnyHashable, Any> else {
return 0.1
}
guard let delayTimeUnclampedProp = gifProperties[kCGImagePropertyGIFUnclampedDelayTime] as? TimeInterval else {
guard let delayTimeProp = gifProperties[kCGImagePropertyGIFDelayTime] as? TimeInterval else {
return 0.1
}
return delayTimeProp
}
return delayTimeUnclampedProp
}
}
| mit | 7f40132535032eab247ca3ea436521b0 | 43.423313 | 252 | 0.656677 | 4.461491 | false | false | false | false |
agrippa1994/iOS-PLC | PLC/ViewControllers/EditServerTableViewController.swift | 1 | 2457 | //
// EditServerTableViewController.swift
// PLC
//
// Created by Manuel Stampfl on 13.08.15.
// Copyright (c) 2015 mani1337. All rights reserved.
//
import UIKit
@objc protocol EditServerTableViewControllerDelegate {
func editServerTableViewServerChosen(server: Server)
}
class EditServerTableViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
weak var delegate: EditServerTableViewControllerDelegate?
var server: Server!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var hostTextField: UITextField!
@IBOutlet weak var slotRackPickerView: UIPickerView!
@IBAction func onConnect(sender: AnyObject) {
self.loadDataFromUI()
self.delegate?.editServerTableViewServerChosen(self.server)
}
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField.delegate = self
self.hostTextField.delegate = self
self.slotRackPickerView.dataSource = self
self.slotRackPickerView.delegate = self
self.loadDataToUI()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.loadDataFromUI()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 11
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(row)"
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func loadDataFromUI() {
self.server.name = self.nameTextField.text
self.server.host = self.hostTextField.text
self.server.slot = Int32(self.slotRackPickerView.selectedRowInComponent(0))
self.server.rack = Int32(self.slotRackPickerView.selectedRowInComponent(1))
CoreData.coreData.save()
}
func loadDataToUI() {
self.nameTextField.text = self.server.name
self.hostTextField.text = self.server.host
self.slotRackPickerView.selectRow(Int(self.server.slot), inComponent: 0, animated: false)
self.slotRackPickerView.selectRow(Int(self.server.rack), inComponent: 1, animated: false)
}
}
| mit | fd7496745ff0ca261b792a90a9e73dba | 30.909091 | 127 | 0.689459 | 4.780156 | false | false | false | false |
sambhav7890/SSChartView | SSChartView/Classes/Helpers/BundleHelper.swift | 1 | 1036 | //
// BundleHelper.swift
// Pods
//
// Created by Sambhav Shah on 17/11/16.
//
//
import UIKit
internal extension Bundle {
static func graphBundle() -> Bundle? {
let podBundle = Bundle(for: ExpandableLegendView.self)
guard let bundleURL = podBundle.url(forResource: "SSChartView", withExtension: "bundle") else { return nil }
guard let bundle = Bundle(url: bundleURL) else { return nil }
return bundle
}
}
public extension UIView {
public func addAsConstrainedSubview(forContainer view: UIView) {
let child = self
let container = view
container.addSubview(child)
// align graph from the left and right
container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": child]))
// align graph from the top and bottom
container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": child]))
}
}
| mit | 5a1ba05c11fe9441622dc008f0de12a4 | 30.393939 | 179 | 0.726834 | 3.822878 | false | false | false | false |
leo-lp/LPIM | LPIM/Classes/Contact/LPGroupedDataCollection.swift | 1 | 8058 | //
// LPGroupedDataCollection.swift
// LPIM
//
// Created by lipeng on 2017/6/27.
// Copyright © 2017年 lipeng. All rights reserved.
//
import Foundation
import NIMSDK
private class LPPair {
var first: String
var second: NSMutableArray
init(first: String, second: [LPGroupMemberProtocol]) {
self.first = first
self.second = NSMutableArray(array: second)
}
}
class LPGroupedDataCollection {
private lazy var specialGroupTitles = NSMutableOrderedSet()
private lazy var specialGroups = NSMutableOrderedSet()
private lazy var groupTitles: NSMutableOrderedSet = NSMutableOrderedSet()
private lazy var groups = NSMutableOrderedSet()
var groupTitleComparator: Comparator
var groupMemberComparator: Comparator
var sortedGroupTitles: [String] {
return groupTitles.array as? [String] ?? []
}
init() {
groupTitleComparator = { (title1, title2) -> ComparisonResult in
if let title1 = title1 as? String, let title2 = title2 as? String {
if title1 == "#" {
return .orderedDescending
}
if title2 == "#" {
return .orderedDescending
}
return title1.compare(title2)
}
return .orderedAscending
}
groupMemberComparator = { (key1, key2) -> ComparisonResult in
if let key1 = key1 as? String, let key2 = key2 as? String {
return key1.compare(key2)
}
return .orderedAscending
}
}
func setupMembers(_ members: [LPGroupMemberProtocol]) {
var tmp: [String: [LPGroupMemberProtocol]] = [:]
let me = NIMSDK.shared().loginManager.currentAccount()
for member in members {
if member.memberId == me {
continue
}
let groupTitle = member.groupTitle
var groupedMembers = tmp[groupTitle]
if groupedMembers == nil {
groupedMembers = []
}
groupedMembers?.append(member)
tmp[groupTitle] = groupedMembers
}
groupTitles.removeAllObjects()
groups.removeAllObjects()
for item in tmp where item.key.characters.count > 0 {
let character = item.key[item.key.startIndex]
if character >= "A" && character <= "Z" {
groupTitles.add(item.key)
} else {
groupTitles.add("#")
}
groups.add(LPPair(first: item.key, second: item.value))
}
sort()
}
func addGroupMember(_ member: LPGroupMemberProtocol) {
let groupTitle = member.groupTitle
let groupIndex = groupTitles.index(of: groupTitle)
var tmpPair: LPPair
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
tmpPair = pair
} else {
tmpPair = LPPair(first: groupTitle, second: [])
}
} else {
tmpPair = LPPair(first: groupTitle, second: [])
}
tmpPair.second.add(member)
groupTitles.add(groupTitle)
groups.add(tmpPair)
sort()
}
func removeGroupMember(_ member: LPGroupMemberProtocol) {
let groupTitle = member.groupTitle
let groupIndex = groupTitles.index(of: groupTitle)
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
pair.second.remove(member)
if pair.second.count == 0 {
groups.remove(pair)
}
sort()
}
}
}
func addGroupAbove(withTitle title: String, members: [LPGroupMemberProtocol]) {
let pair = LPPair(first: title, second: members)
specialGroupTitles.add(title)
specialGroups.add(pair)
}
func title(ofGroup index: Int) -> String? {
var index = index
if index >= 0 && index < specialGroupTitles.count {
return specialGroupTitles.object(at: index) as? String
}
index -= specialGroupTitles.count
if index >= 0 && index < groupTitles.count {
return groupTitles.object(at: index) as? String
}
return nil
}
func members(ofGroup index: Int) -> [LPGroupMemberProtocol]? {
var index = index
if index >= 0 && index < specialGroups.count {
if let pair = specialGroups.object(at: index) as? LPPair {
return pair.second as? [LPGroupMemberProtocol]
}
}
index -= specialGroups.count
if index >= 0 && index < groups.count {
if let pair = groups.object(at: index) as? LPPair {
return pair.second as? [LPGroupMemberProtocol]
}
}
return nil
}
func member(ofIndex indexPath: IndexPath) -> LPGroupMemberProtocol? {
var members: NSArray?
var groupIndex = indexPath.section
if groupIndex >= 0 && groupIndex < specialGroups.count {
if let pair = specialGroups.object(at: groupIndex) as? LPPair {
members = pair.second
}
}
groupIndex -= specialGroups.count
if groupIndex >= 0 && groupIndex < groups.count {
if let pair = groups.object(at: groupIndex) as? LPPair {
members = pair.second
}
}
let memberIndex = indexPath.row
if let members = members {
if memberIndex >= 0 && memberIndex < members.count {
return members.object(at: memberIndex) as? LPGroupMemberProtocol
}
}
return nil
}
func member(ofId uid: String) -> LPGroupMemberProtocol? {
for pair in groups {
if let pair = pair as? LPPair {
for member in pair.second {
if let member = member as? LPGroupMemberProtocol, member.memberId == uid {
return member
}
}
}
}
return nil
}
func groupCount() -> Int {
return specialGroupTitles.count + groupTitles.count
}
func memberCount(ofGroup index: Int) -> Int {
var index = index
var members: NSArray?
if index >= 0 && index < specialGroups.count {
if let pair = specialGroups.object(at: index) as? LPPair {
members = pair.second
}
}
index -= specialGroups.count
if index >= 0 && index < groups.count {
if let pair = groups.object(at: index) as? LPPair {
members = pair.second
}
}
return members?.count ?? 0
}
private func sort() {
sortGroupTitle()
sortGroupMember()
}
private func sortGroupTitle() {
groupTitles.sortedArray(comparator: groupTitleComparator)
groups.sortedArray(comparator: { (pair1, pair2) -> ComparisonResult in
if let pair1 = pair1 as? LPPair, let pair2 = pair2 as? LPPair {
return groupTitleComparator(pair1.first, pair2.first)
}
return .orderedAscending
})
}
private func sortGroupMember() {
groups.enumerateObjects({ (obj, idx, stop) in
if let pair = obj as? LPPair {
let groupedMembers = pair.second
groupedMembers.sortedArray(comparator: { (member1, member2) -> ComparisonResult in
if let member1 = member1 as? LPGroupMemberProtocol, let member2 = member2 as? LPGroupMemberProtocol {
return groupMemberComparator(member1.sortKey, member2.sortKey)
}
return .orderedAscending
})
}
})
}
}
| mit | 433f1e7190e2e86371acf4cfd8d1c002 | 32.423237 | 121 | 0.54612 | 4.806086 | false | false | false | false |
RevansChen/online-judge | Codewars/6kyu/rectangle-into-squares/Swift/solution1.swift | 1 | 364 | // Swift - 4
func sqInRect(_ lng: Int, _ wdth: Int) -> [Int]? {
if lng == wdth {
return nil
}
var w = wdth
var l = lng
if l > w {
(w, l) = (l, w)
}
var results = [Int]()
while (w > 0) && (l > 0) {
results.append(l)
let nl = w - l
(w, l) = (max(l, nl), min(l, nl))
}
return results
}
| mit | 9b34e34b4bd89c46ff50c722a6aa167c | 18.157895 | 50 | 0.398352 | 2.778626 | false | false | false | false |
greycats/Greycats.swift | Greycats/Layout/FormField.swift | 1 | 8593 | //
// FormField.swift
// Greycats
//
// Created by Rex Sheng on 2/5/16.
// Copyright (c) 2016 Interactive Labs. All rights reserved.
//
import GreycatsCore
import UIKit
public protocol FormFieldGroup: AnyObject {
func validate() -> Bool
func onChange(_ closure: @escaping (Bool) -> Void) -> Self
func onSubmit(_ closure: @escaping () -> Void) -> Self
}
extension FormFieldGroup {
public func bindButton(_ button: UIControl?) -> Self {
weak var button = button
return onChange { button?.isEnabled = $0 }
.onSubmit { button?.sendActions(for: .touchUpInside) }
}
}
class _FormFieldGroup: FormFieldGroup {
var _onSubmit: (() -> Void)?
var _onChange: ((Bool) -> Void)?
let valid: () -> (Bool)
fileprivate init(closure: @escaping () -> Bool) {
valid = closure
}
func validate() -> Bool {
let v = valid()
_onChange?(v)
return v
}
func onSubmit(_ closure: @escaping () -> Void) -> Self {
_onSubmit = closure
return self
}
func onChange(_ closure: @escaping (Bool) -> Void) -> Self {
_onChange = closure
_ = validate()
return self
}
}
@IBDesignable
open class FormField: NibView, UITextFieldDelegate {
@IBOutlet open weak var captionLabel: UILabel?
@IBOutlet open weak var field: UITextField!
@IBOutlet open weak var line: UIView!
open var regex: Regex = ".*"
@IBInspectable open var invalidErrorMessage: String?
@IBOutlet open weak var redLine: UIView?
@IBOutlet open weak var errorLabel: UILabel?
@IBOutlet open weak var errorHeight: NSLayoutConstraint?
@IBInspectable open var pattern: String = ".*" {
didSet {
if pattern == "EmailRegex" {
regex = Regex.Email
} else {
regex = Regex(pattern)
}
}
}
@IBInspectable open var enabled: Bool {
get { return field.isEnabled }
set(value) { field.isEnabled = value }
}
weak var group: _FormFieldGroup?
open var error: String? {
didSet {
if let error = error {
errorHeight?.constant = 16
redLine?.isHidden = false
errorLabel?.isHidden = false
errorLabel?.text = error
} else {
errorHeight?.constant = 0
redLine?.isHidden = true
errorLabel?.isHidden = true
}
}
}
var everEdited = false
var onReturn: (() -> Bool)?
fileprivate var triggers: [() -> Void] = []
@IBAction func valueUpdated(_ sender: Any) {
triggers.forEach { $0() }
_ = group?.validate()
}
open var handle: (UITextField) -> Bool = { _ in true }
@IBAction func didBeginEditing(_ sender: Any) {
everEdited = true
triggers.forEach { $0() }
_ = group?.validate()
}
open func pass(_ validateText: String = "", reportError: Bool = true) -> Bool {
let allowsError = everEdited == true && field.isFirstResponder == false
let passed = (field.text ?? "") =~ regex
if !passed {
if allowsError && reportError {
if !field.hasText {
error = "\(validateText)\(placeholder.lowercased()) is required."
} else if let invalidMessage = invalidErrorMessage, invalidMessage.count > 0 {
error = invalidMessage.replacingOccurrences(of: ":value", with: field.text!)
} else {
error = "Invalid \(validateText)\(placeholder.lowercased())."
}
} else {
error = nil
}
}
return passed
}
@IBInspectable open var secure: Bool = false {
didSet {
field.isSecureTextEntry = secure
field.clearButtonMode = secure ? .never : .whileEditing
}
}
open var text: String? {
get {
return field.text
}
set(value) {
field.text = value
}
}
@IBInspectable open var keyboardType: Int {
get { return field.keyboardType.rawValue }
set(value) {
if let keyboardType = UIKeyboardType(rawValue: value) {
field.keyboardType = keyboardType
}
}
}
@IBInspectable open var autocorrection: Int {
get { return field.autocorrectionType.rawValue }
set(value) {
if let type = UITextAutocorrectionType(rawValue: value) {
field.autocorrectionType = type
}
}
}
@IBInspectable open var autocapitalizationType: Int {
get { return field.autocapitalizationType.rawValue }
set(value) {
if let type = UITextAutocapitalizationType(rawValue: value) {
field.autocapitalizationType = type
}
}
}
@IBInspectable open var keyboardApperance: Int {
get { return field.keyboardAppearance.rawValue }
set(value) {
if let type = UIKeyboardAppearance(rawValue: value) {
field.keyboardAppearance = type
}
}
}
@IBInspectable open var placeholder: String = "Email Address" {
didSet {
if let captionLabel = captionLabel {
captionLabel.text = placeholder
} else {
field.placeholder = placeholder
}
}
}
@IBInspectable open var textColor: UIColor? {
didSet {
field.textColor = textColor
}
}
@IBInspectable open var lineColor: UIColor? {
didSet {
line.backgroundColor = lineColor
}
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return handle(textField)
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return onReturn?() ?? true
}
}
public protocol FormFieldData {
mutating func parse(_ input: String)
var text: String? { get }
init()
}
extension String: FormFieldData {
public mutating func parse(_ input: String) { self = input }
public var text: String? { return self }
}
extension FormField {
public func bind<T: FormFieldData>(_ value: UnsafeMutablePointer<T?>) {
triggers.append {[weak self] in
if let input = self?.text {
if value.pointee == nil {
value.initialize(to: T())
}
value.pointee?.parse(input)
}
}
field.text = value.pointee?.text
}
}
extension Collection {
public func every(closure: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try filter { try !closure($0) }.count == 0
}
}
private var formKey: Void?
extension Collection where Iterator.Element: FormField, Index == Int {
public func createForm(_ submitType: UIReturnKeyType = .send, validatePrefix: String = "", reportsError: Bool = true) -> FormFieldGroup {
let group = _FormFieldGroup(closure: { self.every { $0.pass(validatePrefix, reportError: reportsError) } })
let total = endIndex
enumerated().forEach { index, item in
item.group = group
if index != total {
weak var nextField = self[index + 1].field
item.field.returnKeyType = .next
item.onReturn = {
nextField?.becomeFirstResponder()
return true
}
} else {
item.field.returnKeyType = submitType
item.onReturn = {[weak item] in
guard let item = item, let group = item.group else {
return false
}
if group.valid() {
item.field.resignFirstResponder()
group._onSubmit?()
return true
} else {
return false
}
}
}
}
_ = group.validate()
return group
}
public func createForm(_ target: NSObjectProtocol, submitType: UIReturnKeyType = .send, validatePrefix: String = "", reportsError: Bool = true) -> FormFieldGroup {
let group = createForm(submitType, validatePrefix: validatePrefix, reportsError: reportsError)
objc_setAssociatedObject(target, &formKey, group, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return group
}
}
| mit | 09562c7b4c9bc670df216961a79cf541 | 29.257042 | 167 | 0.550681 | 4.882386 | false | false | false | false |
ketoo/actor-platform | actor-apps/app-ios/Actor/Controllers/Group/Cells/GroupMemberCell.swift | 31 | 1753 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupMemberCell: CommonCell {
// MARK: -
// MARK: Private vars
private var usernameLabel: UILabel!
// MARK: -
// MARK: Public vars
var userAvatarView: AvatarView!
// MARK: -
// MARK: Constructors
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
userAvatarView = AvatarView(frameSize: 40, type: .Rounded)
contentView.addSubview(userAvatarView)
usernameLabel = UILabel()
usernameLabel.textColor = MainAppTheme.list.textColor
usernameLabel.font = UIFont.systemFontOfSize(18.0)
usernameLabel.text = " "
usernameLabel.sizeToFit()
contentView.addSubview(usernameLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Setters
func setUsername(username: String) {
usernameLabel.text = username
}
// MARK: -
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
let userAvatarViewFrameSize: CGFloat = CGFloat(userAvatarView.frameSize)
userAvatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize)
usernameLabel.frame = CGRect(x: 65.0, y: (contentView.bounds.size.height - usernameLabel.bounds.size.height) / 2.0, width: contentView.bounds.size.width - 65.0 - 15.0, height: usernameLabel.bounds.size.height)
}
}
| mit | 876250752925e516122de76d23281c06 | 28.711864 | 217 | 0.638905 | 4.62533 | false | false | false | false |
apatronl/Left | Left/Other/AppDelegate.swift | 1 | 3537 | //
// AppDelegate.swift
// Left
//
// Created by Alejandrina Patron on 9/18/15.
// Copyright © 2015 Ale Patrón. All rights reserved.
//
import UIKit
import AlamofireNetworkActivityIndicator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NetworkActivityIndicatorManager.shared.isEnabled = true
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
guard let info = shortcutItem.userInfo else { return }
guard let recipeName = info["NAME"] as? String else { return }
guard let recipeURL = info["URL"] as? String else { return }
openRecipeFromQuickAction(recipeName: recipeName, recipeURL: recipeURL)
completionHandler(true)
}
private func openRecipeFromQuickAction(recipeName: String, recipeURL: String) {
let webView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipeWebView") as! RecipeWebView
webView.recipe = RecipeItem(name: recipeName, photo: nil, url: recipeURL)
let tabsController = self.window?.rootViewController as! UITabBarController
tabsController.selectedIndex = 1
let favsTab = tabsController.viewControllers?[1] as! UINavigationController
favsTab.popToRootViewController(animated: true)
favsTab.pushViewController(webView, animated: 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.
// Dismiss keyboard when user presses home button while typing an ingredient on SearchVC
self.window?.endEditing(true)
}
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:.
}
}
| mit | 3b47bc8d8c1506552e9d4a752b27ac8a | 50.231884 | 285 | 0.73041 | 5.380518 | false | false | false | false |
wwczwt/sdfad | PageControllerTests/MenuBarTests.swift | 1 | 2758 | //
// MenuBarTests.swift
// PageController
//
// Created by Hirohisa Kawasaki on 6/29/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
import XCTest
import PageController
class MenuBarTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testReload() {
var menuBar: MenuBar!
var view: MenuCell!
menuBar = MenuBar(frame: CGRectZero)
menuBar.frame = CGRect(x: 0, y: 0, width: 300, height: 44)
menuBar.items = ["1", "2", "3"]
menuBar.reloadData()
view = menuBar.scrollView.viewForCurrentPage() as! MenuCell
XCTAssertEqual(view.index, 0, "is failed")
}
func testMoveMinus() {
let expectation = expectationWithDescription("try move left to index")
let menuBar = MenuBar(frame: CGRect(x: 0, y: 0, width: 300, height: 44))
var items = [String]()
for index in 0 ..< 5 {
items.append(index.description)
}
menuBar.items = items
menuBar.reloadData()
menuBar.layoutIfNeeded()
XCTAssertEqual(menuBar.selectedIndex, 0, "is failed.")
menuBar.move(from: 0, until: 3)
let after = 0.3 * Double(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(after)), dispatch_get_main_queue()) {
menuBar.layoutIfNeeded()
XCTAssertEqual(menuBar.selectedIndex, 3, "is failed.")
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: { error in
if let error = error {
XCTAssertTrue(false, "expectations are still finished")
}
})
}
func testMovePlus() {
let expectation = expectationWithDescription("try move right to index")
let menuBar = MenuBar(frame: CGRect(x: 0, y: 0, width: 300, height: 44))
var items = [String]()
for index in 0 ..< 5 {
items.append(index.description)
}
menuBar.items = items
menuBar.reloadData()
menuBar.layoutIfNeeded()
XCTAssertEqual(menuBar.selectedIndex, 0, "is failed.")
menuBar.move(from: 0, until: 3)
let after = 0.3 * Double(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(after)), dispatch_get_main_queue()) {
menuBar.layoutIfNeeded()
XCTAssertEqual(menuBar.selectedIndex, 3, "is failed.")
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: { error in
if let error = error {
XCTAssertTrue(false, "expectations are still finished")
}
})
}
}
| mit | 0d6c1880d8faaa0f86fbb25deaf72867 | 27.43299 | 99 | 0.590283 | 4.441224 | false | true | false | false |
vimeo/VimeoUpload | Examples/VimeoUpload-iOS-OldUpload/VimeoUpload-iOS-OldUpload/ViewControllers/VideoSettingsViewController.swift | 1 | 8161 | //
// VideoSettingsViewController.swift
// VimeoUpload
//
// Created by Hanssen, Alfie on 10/16/15.
// Copyright © 2015 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import VimeoUpload
import AVFoundation
class VideoSettingsViewController: UIViewController, UITextFieldDelegate
{
static let NibName = "VideoSettingsViewController"
// MARK:
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
// MARK:
private var asset: VIMPHAsset
// MARK:
private var operation: ExportSessionExportOperation?
private var descriptor: Descriptor?
// MARK:
private var url: URL?
private var videoSettings: VideoSettings?
// MARK:
private var hasTappedUpload: Bool
{
get
{
return self.videoSettings != nil
}
}
// MARK: Lifecycle
init(asset: VIMPHAsset)
{
self.asset = asset
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad()
{
super.viewDidLoad()
self.edgesForExtendedLayout = []
self.setupNavigationBar()
self.setupAndStartOperation()
}
// MARK: Setup
private func setupNavigationBar()
{
self.title = "Video Settings"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(VideoSettingsViewController.didTapCancel(_:)))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Upload", style: .done, target: self, action: #selector(VideoSettingsViewController.didTapUpload(_:)))
}
private func setupAndStartOperation()
{
let phAsset = self.asset.phAsset
let operation = ExportSessionExportOperation(phAsset: phAsset)
operation.downloadProgressBlock = { (progress: Double) -> Void in
print(String(format: "Download progress: %.2f", progress)) // TODO: Dispatch to main thread
}
operation.exportProgressBlock = { (exportSession: AVAssetExportSession, progress: Double) -> Void in
print(String(format: "Export progress: %.2f", progress))
}
operation.completionBlock = { [weak self] () -> Void in
DispatchQueue.main.async(execute: { [weak self] () -> Void in
guard let strongSelf = self else
{
return
}
if operation.isCancelled == true
{
return
}
if operation.error == nil
{
strongSelf.url = operation.result!
}
if strongSelf.hasTappedUpload == true
{
if let error = operation.error
{
strongSelf.activityIndicatorView.stopAnimating()
strongSelf.presentOperationErrorAlert(with: error)
}
else
{
strongSelf.startUpload()
strongSelf.activityIndicatorView.stopAnimating()
strongSelf.navigationController?.dismiss(animated: true, completion: nil)
}
}
})
}
self.operation = operation
self.operation?.start()
}
private func startUpload()
{
let url = self.url!
let phAsset = self.asset.phAsset
let assetIdentifier = phAsset.localIdentifier
let descriptor = OldUploadDescriptor(url: url, videoSettings: self.videoSettings)
descriptor.identifier = assetIdentifier
OldVimeoUploader.sharedInstance?.uploadVideo(descriptor: descriptor)
}
// MARK: Actions
@objc func didTapCancel(_ sender: UIBarButtonItem)
{
self.operation?.cancel()
self.navigationController?.dismiss(animated: true, completion: nil)
}
@objc func didTapUpload(_ sender: UIBarButtonItem)
{
let title = self.titleTextField.text
let description = self.descriptionTextView.text
self.videoSettings = VideoSettings(title: title, description: description, privacy: "nobody", users: nil, password: nil)
if self.operation?.state == .executing
{
self.activityIndicatorView.startAnimating() // Listen for operation completion, dismiss
}
else if let error = self.operation?.error
{
self.presentOperationErrorAlert(with: error)
}
else
{
self.startUpload()
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
self.descriptionTextView.becomeFirstResponder()
return false
}
// MARK: UI Presentation
private func presentOperationErrorAlert(with error: NSError)
{
let alert = UIAlertController(title: "Operation Error", message: error.localizedDescription, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { [weak self] (action) -> Void in
self?.navigationController?.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { [weak self] (action) -> Void in
self?.setupAndStartOperation()
}))
self.present(alert, animated: true, completion: nil)
}
private func presentDescriptorErrorAlert(with error: NSError)
{
let alert = UIAlertController(title: "Descriptor Error", message: error.localizedDescription, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { [weak self] (action) -> Void in
self?.navigationController?.dismiss(animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { [weak self] (action) -> Void in
// We start from the beginning (with the operation instead of the descriptor),
// Because the exported file was deleted when the upload descriptor failed,
// We delete it because leaving it up to the API consumer to delete seems a little risky
self?.setupAndStartOperation()
}))
self.present(alert, animated: true, completion: nil)
}
}
| mit | 5a334445102dc014150e5e9b0dd8d2bc | 33.43038 | 174 | 0.615809 | 5.315961 | false | false | false | false |
lightsprint09/LADVSwift | LADVSwift/CompetitionWebservice.swift | 1 | 2454 | //
// CompetitionWebservice.swift
// Leichatletik
//
// Created by Lukas Schmidt on 09.02.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
import DBNetworkStack
public struct CompetitionWebService {
private let baseURL: URL
private let jsonDecoder: Foundation.JSONDecoder
public init(baseURL: URL) {
self.baseURL = baseURL
jsonDecoder = Foundation.JSONDecoder()
jsonDecoder.dateDecodingStrategy = .millisecondsSince1970
}
public func searchCompetitions(filter: CompetitionFilter) -> Resource<[Ausschreibung]> {
var parameters = filter.toDictionary()
parameters["mostCurrent"] = "\(true)"
parameters["limit"] = "\(100)"
let request = URLRequest(path: "ausList", baseURL: baseURL, parameters: parameters)
return Resource(request: request, decoder: jsonDecoder)
}
public func competitionDetails(for competitionIds: [Int]) -> Resource<[CompetitionDetails]> {
let ids = competitionIds.map( { "\($0)" } ).joined(separator: ",")
let parameters = ["id": "\(ids)", "all": "\(true)", "wettbewerbe": "\(true)"]
let request = URLRequest(path: "ausDetail", baseURL: baseURL, parameters: parameters)
return Resource(request: request, parse: { data in
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [Any]
return try Array(JSONArray: json)
})
}
public func competitionDetail(for competitionId: Int) -> Resource<CompetitionDetails> {
return competitionDetails(for: [competitionId]).map(transform: { $0.first! })
}
public func meldungen(for competitionId: Int) -> Resource<[MeldungPerAge]> {
let request = URLRequest(path: "/meldung/teilnehmer/\(competitionId)", baseURL: baseURL)
let parser = MeldungParser()
return Resource(request: request, parse: { try parser.parse(html: $0) })
}
}
extension CompetitionWebService {
public func competitionDetails(for competitions: [CompetitionDescribing]) -> Resource<[CompetitionDetails]> {
return competitionDetails(for: competitions.map { $0.id } )
}
public func competitionDetail(for competition: CompetitionDescribing) -> Resource<CompetitionDetails> {
return competitionDetails(for: [competition.id]).map { $0.first! }
}
}
| mit | 777db92a29c4b838f266f0d3999f1712 | 35.61194 | 113 | 0.654301 | 4.380357 | false | false | false | false |
rockgarden/swift_language | Playground/Design-Patterns.playground/Design-Patterns.playground/Pages/Creational.xcplaygroundpage/Contents.swift | 1 | 6124 | //: [Behavioral](Behavioral) |
//: Creational |
//: [Structural](Structural)
/*:
Creational
==========
> In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
>
>**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Creational_pattern)
*/
import Swift
import Foundation
/*:
🌰 Abstract Factory
-------------------
The abstract factory pattern is used to provide a client with a set of related or dependant objects.
The "family" of objects created by the factory are determined at run-time.
### Example
*/
/*:
Protocols
*/
protocol Decimal {
func stringValue() -> String
// factory
static func make(string : String) -> Decimal
}
typealias NumberFactory = (String) -> Decimal
// Number implementations with factory methods
struct NextStepNumber: Decimal {
private var nextStepNumber: NSNumber
func stringValue() -> String { return nextStepNumber.stringValue }
// factory
static func make(string: String) -> Decimal {
return NextStepNumber(nextStepNumber: NSNumber(value: (string as NSString).longLongValue))
}
}
struct SwiftNumber : Decimal {
private var swiftInt: Int
func stringValue() -> String { return "\(swiftInt)" }
// factory
static func make(string: String) -> Decimal {
return SwiftNumber(swiftInt:(string as NSString).integerValue)
}
}
/*:
Abstract factory
*/
enum NumberType {
case nextStep, swift
}
enum NumberHelper {
static func factory(for type: NumberType) -> NumberFactory {
switch type {
case .nextStep:
return NextStepNumber.make
case .swift:
return SwiftNumber.make
}
}
}
/*:
### Usage
*/
let factoryOne = NumberHelper.factory(for: .nextStep)
let numberOne = factoryOne("1")
numberOne.stringValue()
let factoryTwo = NumberHelper.factory(for: .swift)
let numberTwo = factoryTwo("2")
numberTwo.stringValue()
/*:
👷 Builder
----------
The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm.
An external class controls the construction algorithm.
### Example
*/
class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
/*:
### Usage
*/
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
/*:
>**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Builder)
*/
/*:
🏭 Factory Method
-----------------
The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
### Example
*/
protocol Currency {
func symbol() -> String
func code() -> String
}
class Euro : Currency {
func symbol() -> String {
return "€"
}
func code() -> String {
return "EUR"
}
}
class UnitedStatesDolar : Currency {
func symbol() -> String {
return "$"
}
func code() -> String {
return "USD"
}
}
enum Country {
case unitedStates, spain, uk, greece
}
enum CurrencyFactory {
static func currency(for country:Country) -> Currency? {
switch country {
case .spain, .greece :
return Euro()
case .unitedStates :
return UnitedStatesDolar()
default:
return nil
}
}
}
/*:
### Usage
*/
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code() ?? noCurrencyCode
/*:
🃏 Prototype
------------
The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone.
This practise is particularly useful when the construction of a new object is inefficient.
### Example
*/
class ChungasRevengeDisplay {
var name: String?
let font: String
init(font: String) {
self.font = font
}
func clone() -> ChungasRevengeDisplay {
return ChungasRevengeDisplay(font:self.font)
}
}
/*:
### Usage
*/
let Prototype = ChungasRevengeDisplay(font:"GotanProject")
let Philippe = Prototype.clone()
Philippe.name = "Philippe"
let Christoph = Prototype.clone()
Christoph.name = "Christoph"
let Eduardo = Prototype.clone()
Eduardo.name = "Eduardo"
/*:
>**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Prototype)
*/
/*:
💍 Singleton
------------
The singleton pattern ensures that only one object of a particular class is ever created.
All further references to objects of the singleton class refer to the same underlying instance.
There are very few applications, do not overuse this pattern!
### Example:
*/
class DeathStarSuperlaser {
static let sharedInstance = DeathStarSuperlaser()
private init() {
// Private initialization to ensure just one instance is created.
}
}
/*:
### Usage:
*/
let laser = DeathStarSuperlaser.sharedInstance
| mit | 66f229de3b950e420fdbd6059ce7d1c6 | 22.762646 | 372 | 0.6617 | 4.129141 | false | false | false | false |
fancymax/12306ForMac | 12306ForMac/TicketViewControllers/TicketQueryViewController.swift | 1 | 39947 | //
// TicketQueryMainViewController.swift
// 12306ForMac
//
// Created by fancymax on 16/3/13.
// Copyright © 2016年 fancy. All rights reserved.
//
import Cocoa
class TicketQueryViewController: BaseViewController {
@IBOutlet weak var stackContentView: NSStackView!
@IBOutlet var firstSearchView: NSView!
@IBOutlet var secondSearchView: NSView!
@IBOutlet var ticketTableView: NSView!
override var nibName: String? {
return "TicketQueryViewController"
}
override func viewDidLoad() {
super.viewDidLoad()
self.stackContentView.addView(firstSearchView, in:.top)
self.stackContentView.addView(secondSearchView, in: .top)
self.stackContentView.addView(ticketTableView, in: .top)
self.stackContentView.orientation = .vertical
self.stackContentView.alignment = .centerX
self.stackContentView.spacing = 0
filterBtn.isEnabled = false
filterCbx.isEnabled = false
filterBtn.isHidden = true
filterCbx.isHidden = true
addPassengerBtn.isHidden = true
autoQueryNumTxt.isHidden = true
self.fromStationNameTxt.tableViewDelegate = self
self.toStationNameTxt.tableViewDelegate = self
self.registerAllNotification()
self.initQueryParams()
self.initSortParams()
}
private func initQueryParams() {
let lastTicketJsonString = QueryDefaultManager.sharedInstance.lastTicketTaskManager
if lastTicketJsonString != nil {
ticketTaskManager.decodeJsonFrom(lastTicketJsonString!)
}
if ticketTaskManager.ticketTasks.count == 0 {
ticketTaskManager.ticketTasks.append(TicketTask())
}
else {
let todayStr = getStrFromDate(Date())
let today = getDateFromStr(todayStr)
for task in ticketTaskManager.ticketTasks {
var dates = ticketTaskManager.convertStr2Dates(task.date)
var hasChangeDates = false
for i in 0..<dates.count {
if dates[i] < today {
dates[i] = today
hasChangeDates = true
}
}
if hasChangeDates {
task.date = ticketTaskManager.convertDates2Str(dates)
}
}
}
setQueryParams()
self.queryDateIndex = 0
}
private func initSortParams(){
let descriptorStartTime = NSSortDescriptor(key: TicketOrder.StartTime.rawValue, ascending: true)
let descriptorArriveTime = NSSortDescriptor(key: TicketOrder.ArriveTime.rawValue, ascending: true)
let descriptorLishi = NSSortDescriptor(key: TicketOrder.Lishi.rawValue, ascending: true)
leftTicketTable.tableColumns[1].sortDescriptorPrototype = descriptorStartTime
leftTicketTable.tableColumns[2].sortDescriptorPrototype = descriptorArriveTime
leftTicketTable.tableColumns[3].sortDescriptorPrototype = descriptorLishi
}
// MARK: - firstSearchView
@IBOutlet weak var fromStationNameTxt: AutoCompleteTextField!
@IBOutlet weak var toStationNameTxt: AutoCompleteTextField!
@IBOutlet weak var queryDate: ClickableDatePicker!
@IBOutlet weak var queryBtn: NSButton!
@IBOutlet weak var converCityBtn: NSButton!
@IBOutlet weak var autoQueryNumTxt: NSTextField!
@IBOutlet weak var queryDataLabel: NSTextField!
@IBOutlet weak var fromStationLabel: NSTextField!
@IBOutlet weak var toStationLabel: NSTextField!
var autoQueryNum = 0
var calendarViewController:LunarCalendarView?
var repeatTimer:Timer?
var ticketType:TicketType = .Normal
var queryTaskIndex = 0
var queryDateIndex = 0
lazy var preventSystemSleepHandler:FSPreventSystemSleep = {
return FSPreventSystemSleep()
}()
var ticketTaskManager = TicketTasksManager()
private func getStrFromDate(_ date:Date) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
private func getDateFromStr(_ str:String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")!
return dateFormatter.date(from: str)!
}
private func setQueryParams() {
var dateStr = ticketTaskManager.ticketTasks[queryTaskIndex].date
var queryDates = ticketTaskManager.convertStr2Dates(dateStr)
var taskIndexHasChange = false
if self.queryDateIndex >= queryDates.count {
self.queryTaskIndex += 1
self.queryDateIndex = 0
taskIndexHasChange = true
}
if self.queryTaskIndex >= ticketTaskManager.ticketTasks.count {
self.queryTaskIndex = 0
taskIndexHasChange = true
}
if taskIndexHasChange {
dateStr = ticketTaskManager.ticketTasks[queryTaskIndex].date
queryDates = ticketTaskManager.convertStr2Dates(dateStr)
}
if ticketTaskManager.ticketTasks.count > 1 {
fromStationLabel.stringValue = "出发城市 \(queryTaskIndex + 1)/\(ticketTaskManager.ticketTasks.count)"
toStationLabel.stringValue = "到达城市 \(queryTaskIndex + 1)/\(ticketTaskManager.ticketTasks.count)"
}
else {
fromStationLabel.stringValue = "出发城市"
toStationLabel.stringValue = "到达城市"
}
self.fromStationNameTxt.stringValue = ticketTaskManager.ticketTasks[queryTaskIndex].startStation
self.toStationNameTxt.stringValue = ticketTaskManager.ticketTasks[queryTaskIndex].endStation
self.trainFilterKey = ticketTaskManager.ticketTasks[queryTaskIndex].trainFilterKey
self.seatFilterKey = ticketTaskManager.ticketTasks[queryTaskIndex].seatFilterKey
setQueryDateValue(queryDates, index: queryDateIndex)
self.queryDateIndex += 1
}
private func setQueryDateValue(_ dates:[Date], index:Int) {
var calender = Calendar.current
calender.timeZone = TimeZone(abbreviation: "UTC")!
if dates.count > 1 {
self.queryDataLabel.stringValue = "出发日期 \(index + 1)/\(dates.count)"
}
else {
self.queryDataLabel.stringValue = "出发日期"
}
if dates.count == 0 {
self.queryDate.dateValue = Date()
self.queryDateIndex = 0
}
else {
self.queryDate.dateValue = calender.startOfDay(for: dates[index])
}
}
private func stopAutoQuery(){
repeatTimer?.invalidate()
repeatTimer = nil
hasAutoQuery = false
}
func updateTicketTask(startStation:String? = nil, endStation:String? = nil) {
let ticketTask = ticketTaskManager.ticketTasks[queryTaskIndex]
var hasChangeStation = false
if let startStationValue = startStation {
ticketTask.startStation = startStationValue
hasChangeStation = true
}
if let endStationValue = endStation {
ticketTask.endStation = endStationValue
hasChangeStation = true
}
if hasChangeStation {
trainFilterKey = ""
self.queryDateIndex = 0
}
}
// MARK: - secondSearchView
@IBOutlet weak var passengersView: NSStackView!
var passengerViewControllerList = [PassengerViewController]()
let passengerSelectViewController = PassengerSelectViewController()
@IBOutlet weak var filterBtn: LoginButton!
@IBOutlet weak var filterCbx: NSButton!
@IBOutlet weak var addPassengerBtn: LoginButton!
@IBOutlet weak var ticketTipLabel: NSTextField!
var autoQuery = false {
didSet {
if autoQuery {
queryBtn.title = "开始抢票"
filterCbx.state = NSOnState
}
else {
queryBtn.title = "开始查询"
self.resetAutoQueryNumStatus()
filterCbx.state = NSOffState
}
}
}
var hasAutoQuery = false {
didSet {
if hasAutoQuery {
queryBtn.title = "停止抢票"
self.fromStationNameTxt.isEnabled = false
self.toStationNameTxt.isEnabled = false
self.converCityBtn.isEnabled = false
self.queryDate.clickable = false
filterCbx.isEnabled = false
preventSystemSleepHandler.preventSystemSleep(true)
}
else {
queryBtn.title = "开始抢票"
self.fromStationNameTxt.isEnabled = true
self.toStationNameTxt.isEnabled = true
self.queryDate.clickable = true
self.converCityBtn.isEnabled = true
filterCbx.isEnabled = true
if self.filterQueryResult.count > 0 {
canFilter = true
}
preventSystemSleepHandler.preventSystemSleep(false)
}
}
}
var canFilter = false {
didSet {
if canFilter {
filterBtn.isHidden = false
filterCbx.isHidden = false
filterBtn.isEnabled = true
filterCbx.isEnabled = true
}
else {
filterBtn.isEnabled = false
filterCbx.isEnabled = false
}
}
}
lazy var passengersPopover: NSPopover = {
let popover = NSPopover()
popover.behavior = .semitransient
popover.contentViewController = self.passengerSelectViewController
return popover
}()
func passengerSelected(_ passenger:PassengerDTO) -> Bool{
for controller in passengerViewControllerList where controller.passenger == passenger{
return true
}
return false
}
func checkPassenger(_ passenger:PassengerDTO){
for controller in passengerViewControllerList where controller.passenger == passenger{
controller.select()
}
}
// MARK: - TicketTableView
@IBOutlet weak var leftTicketTable: NSTableView!
var ticketQueryResult = [QueryLeftNewDTO]()
var filterQueryResult = [QueryLeftNewDTO]()
var date:String?
var ticketOrder:TicketOrder?
var ticketAscending:Bool?
var trainFilterKey:String {
get {
return ticketTaskManager.ticketTasks[queryTaskIndex].trainFilterKey
}
set {
ticketTaskManager.ticketTasks[queryTaskIndex].trainFilterKey = newValue
}
}
var seatFilterKey:String {
get {
return ticketTaskManager.ticketTasks[queryTaskIndex].seatFilterKey
}
set {
ticketTaskManager.ticketTasks[queryTaskIndex].seatFilterKey = newValue
}
}
var excludeTrainCode = ""
var trainFilterWindowController:TrainFilterWindowController?
var submitWindowController:SubmitWindowController?
var ticketTaskWindowController:TicketTaskManagerWindowController?
func ticketOrderedBy(_ tickets:[QueryLeftNewDTO], orderedBy:TicketOrder, ascending:Bool) -> [QueryLeftNewDTO] {
let sortedTickets:[QueryLeftNewDTO] = tickets.sorted{
var isOriginAscending = true
switch orderedBy
{
case .StartTime:
isOriginAscending = $0.start_time < $1.start_time
case .ArriveTime:
isOriginAscending = $0.arrive_time < $1.arrive_time
case .Lishi:
isOriginAscending = $0.lishi < $1.lishi
}
if ascending {
return isOriginAscending
}
else {
return !isOriginAscending
}
}
return sortedTickets
}
var lastAutoSubmitTrainCode = ""
var lastAutoSubmitTime = Date(timeIntervalSince1970: 0)
func queryTicketAndSubmit() {
let summitHandler = {
self.addAutoQueryNumStatus()
var hasFindTicket = false
for ticket in self.filterQueryResult {
if !ticket.hasTicketForSeatTypeFilterKey(self.seatFilterKey) {
continue
}
hasFindTicket = true
if ticket.TrainCode == self.excludeTrainCode {
logger.info("exclude train \(self.excludeTrainCode)")
continue
}
self.stopAutoQuery()
let seatTypeId = ticket.getSeatTypeNameByFilterKey(self.seatFilterKey)!
self.summitTicket(ticket, seatTypeId: seatTypeId,isAuto: true)
var shouldReminder = true
if NSApp.isActive {
shouldReminder = false
}
if (ticket.TrainCode! == self.lastAutoSubmitTrainCode) &&
(Date().timeIntervalSince1970 - self.lastAutoSubmitTime.timeIntervalSince1970) < 2 * 60 {
shouldReminder = false
}
if shouldReminder {
self.lastAutoSubmitTime = Date()
self.lastAutoSubmitTrainCode = ticket.TrainCode!
let informativeText = "\(self.date!) \(self.fromStationNameTxt.stringValue)->\(self.toStationNameTxt.stringValue) \(ticket.TrainCode!) \(seatTypeId)"
self.pushUserNotification("有票提醒",informativeText: informativeText)
let reminderStr = informativeText + " 有票提醒"
ReminderManager.sharedInstance.createReminder(reminderStr, startDate: Date())
}
break;
}
if !hasFindTicket {
self.excludeTrainCode = ""
}
}
queryTicket(summitHandler)
}
func addAutoQueryNumStatus() {
self.autoQueryNum += 1
self.autoQueryNumTxt.isHidden = false
self.autoQueryNumTxt.stringValue = "已查询\(self.autoQueryNum)次"
}
func resetAutoQueryNumStatus() {
self.autoQueryNum = 0
self.autoQueryNumTxt.isHidden = true
}
func queryTicket(_ summitHandler:@escaping ()->() = {}) {
setQueryParams()
let fromStation = self.fromStationNameTxt.stringValue
let toStation = self.toStationNameTxt.stringValue
let date = getStrFromDate(queryDate.dateValue)
logger.info("\(fromStation) -> \(toStation) \(date) \(self.autoQueryNum)")
let successHandler = { (tickets:[QueryLeftNewDTO])->() in
self.ticketQueryResult = tickets
self.filterTrainByAllAspect()
self.leftTicketTable.reloadData()
self.stopLoadingTip()
if ((tickets.count > 0) && (!self.hasAutoQuery)) {
self.canFilter = true
}
else {
self.canFilter = false
}
summitHandler()
}
let failureHandler = {(error:NSError)->() in
self.filterQueryResult = [QueryLeftNewDTO]()
self.leftTicketTable.reloadData()
self.stopLoadingTip()
self.showTip(translate(error))
self.canFilter = false
}
var excludeTip = ""
if excludeTrainCode != "" {
excludeTip = "已排除车次\(excludeTrainCode),重新查询可以撤销"
}
self.startLoadingTip("正在查询..." + excludeTip)
self.date = date
let fromStationCode = StationNameJs.sharedInstance.allStationMap[fromStation]?.Code
let toStationCode = StationNameJs.sharedInstance.allStationMap[toStation]?.Code
var params = LeftTicketParam()
params.from_stationCode = fromStationCode!
params.to_stationCode = toStationCode!
params.train_date = date
params.purpose_codes = ticketType.rawValue
Service.sharedInstance.queryTicketFlowWith(params, success: successHandler,failure: failureHandler)
}
private func filterTrainByAllAspect() {
self.filterQueryResult = self.ticketQueryResult.filter({item in
var isReturn = true
if self.trainFilterKey != "" {
isReturn = self.trainFilterKey.contains("|\(item.TrainCode!)|")
}
if (item.isTicketInvalid()) && (!GeneralPreferenceManager.sharedInstance.isShowInvalidTicket) {
isReturn = false
}
if (!item.hasTicket)&&(!GeneralPreferenceManager.sharedInstance.isShowNoTrainTicket){
isReturn = false
}
return isReturn
})
if let ticketOrderX = self.ticketOrder, let ticketAscendingX = self.ticketAscending {
self.filterQueryResult = self.ticketOrderedBy(self.filterQueryResult, orderedBy: ticketOrderX, ascending: ticketAscendingX)
}
self.leftTicketTable.reloadData()
}
func setSelectedPassenger(){
MainModel.selectPassengers = [PassengerDTO]()
for p in MainModel.passengers where p.isChecked {
MainModel.selectPassengers.append(p)
}
}
func saveLastSelectdPassengerIdToDefault(){
var lastSelectedPassengerId = ""
for p in MainModel.passengers where p.isChecked {
lastSelectedPassengerId += "\(p.passenger_id_no),"
}
if lastSelectedPassengerId != "" {
QueryDefaultManager.sharedInstance.lastSelectedPassenger = lastSelectedPassengerId
}
}
func setSeatCodeForSelectedPassenger(_ trainCode:String, seatCodeName:String){
for passenger in MainModel.selectPassengers{
passenger.seatCodeName = seatCodeName
passenger.seatCode = G_QuerySeatTypeNameDicBy(trainCode)[seatCodeName]!
passenger.setDefaultTicketType(date: self.queryDate.dateValue)
}
}
func pushUserNotification(_ title:String, informativeText:String){
let notification:NSUserNotification = NSUserNotification()
notification.title = title
notification.informativeText = informativeText
notification.deliveryDate = Date()
notification.soundName = NSUserNotificationDefaultSoundName
let center = NSUserNotificationCenter.default
center.scheduleNotification(notification)
center.delegate = self
}
func summitTicket(_ ticket:QueryLeftNewDTO,seatTypeId:String,isAuto:Bool){
let notificationCenter = NotificationCenter.default
if !MainModel.isGetUserInfo {
notificationCenter.post(name: Notification.Name.App.DidAutoLogin, object: nil)
return
}
setSelectedPassenger()
if MainModel.selectPassengers.count == 0 {
self.showTip("请先选择乘客")
return
}
MainModel.selectedTicket = ticket
setSeatCodeForSelectedPassenger(ticket.TrainCode ,seatCodeName: seatTypeId)
self.startLoadingTip("正在提交...")
let postSubmitWindowMessage = {
self.stopLoadingTip()
notificationCenter.post(name: Notification.Name.App.DidSubmit, object: nil)
}
let postSubmitWindowMessageAuto = {
self.stopLoadingTip()
notificationCenter.post(name: Notification.Name.App.DidAutoSubmit, object: nil)
}
let failHandler = {(error:NSError)->() in
self.stopLoadingTip()
if error.code == ServiceError.Code.checkUserFailed.rawValue {
notificationCenter.post(name: Notification.Name.App.DidLogin, object: nil)
}else{
self.showTip(translate(error))
}
}
logger.info("\(ticket.TrainCode!) \(ticket.trainDateStr) \(ticket.FromStationName!) -> \(ticket.ToStationName!) \(seatTypeId) isAuto=\(isAuto)")
if isAuto {
let submitParams = SubmitOrderParams(with: ticket,purposeCode: self.ticketType.rawValue)
Service.sharedInstance.submitFlow(submitParams, success: postSubmitWindowMessageAuto, failure: failHandler)
}
else {
let submitParams = SubmitOrderParams(with: ticket,purposeCode: self.ticketType.rawValue)
Service.sharedInstance.submitFlow(submitParams, success: postSubmitWindowMessage, failure: failHandler)
}
}
deinit{
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
}
// MARK: - open sheet
func openfilterTrainSheet(){
let windowController = TrainFilterWindowController()
windowController.trains = ticketQueryResult.filter({item in
return !item.isTicketInvalid()
})
windowController.fromStationName = self.fromStationNameTxt.stringValue
windowController.toStationName = self.toStationNameTxt.stringValue
windowController.trainDate = self.date!
windowController.seatFilterKey = self.seatFilterKey
windowController.trainFilterKey = self.trainFilterKey
if let window = self.view.window {
window.beginSheet(windowController.window!, completionHandler: {response in
if response == NSModalResponseOK{
self.trainFilterKey = self.trainFilterWindowController!.trainFilterKey
self.seatFilterKey = self.trainFilterWindowController!.seatFilterKey
logger.info("trainFilterKey:\(self.trainFilterKey)")
logger.info("seatFilterKey:\(self.seatFilterKey)")
self.filterQueryResult = self.ticketQueryResult.filter({item in return self.trainFilterKey.contains("|" + item.TrainCode! + "|")})
if let ticketOrderX = self.ticketOrder, let ticketAscendingX = self.ticketAscending {
self.filterQueryResult = self.ticketOrderedBy(self.filterQueryResult, orderedBy: ticketOrderX, ascending: ticketAscendingX)
}
self.leftTicketTable.reloadData()
if GeneralPreferenceManager.sharedInstance.isAutoQueryAfterFilter {
self.autoQuery = true
}
}
else {
self.autoQuery = false;
}
self.trainFilterWindowController = nil
})
self.trainFilterWindowController = windowController
}
}
func openSubmitTicketSheet(isAutoSubmit:Bool,ifShowCode:Bool = true) {
if let window = self.view.window {
let windowController = SubmitWindowController()
windowController.isAutoSubmit = isAutoSubmit
windowController.ifShowCode = ifShowCode
window.beginSheet(windowController.window!, completionHandler: {response in
self.submitWindowController = nil
})
self.submitWindowController = windowController
}
}
func openTicketTaskSheet() {
if let window = self.view.window {
let windowController = TicketTaskManagerWindowController()
windowController.ticketTasksManager = self.ticketTaskManager
window.beginSheet(windowController.window!, completionHandler: {response in
self.ticketTaskManager = self.ticketTaskWindowController!.ticketTasksManager
self.ticketTaskWindowController = nil
if self.queryTaskIndex >= self.ticketTaskManager.ticketTasks.count {
self.queryTaskIndex = self.ticketTaskManager.ticketTasks.count - 1
}
self.setQueryParams()
self.queryDateIndex = 0
})
self.ticketTaskWindowController = windowController
}
}
// MARK: - notification
func registerAllNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(recvCheckPassengerNotification(_:)), name: NSNotification.Name.App.DidCheckPassenger, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvLogoutNotification(_:)), name: NSNotification.Name.App.DidLogout, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvDidSubmitNotification(_:)), name: NSNotification.Name.App.DidSubmit, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvAutoSubmitNotification(_:)), name: NSNotification.Name.App.DidAutoSubmit, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvAutoSubmitWithoutRandCodeNotification(_:)), name: NSNotification.Name.App.DidAutoSubmitWithoutRandCode, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvAddDefaultPassengerNotification(_:)), name: NSNotification.Name.App.DidAddDefaultPassenger, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvStartQueryTicketNotification(_:)), name: NSNotification.Name.App.DidStartQueryTicket, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvRefilterQueryTicketNotification(_:)), name: NSNotification.Name.App.DidRefilterQueryTicket, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvFilterKeyChangeNotification(_:)), name: NSNotification.Name.App.DidTrainFilterKeyChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(recvExcludeTrainSubmitNotification(_:)), name: NSNotification.Name.App.DidExcludeTrainSubmit, object: nil)
}
func recvExcludeTrainSubmitNotification(_ notification:Notification) {
excludeTrainCode = notification.object as! String
}
func recvFilterKeyChangeNotification(_ notification:Notification) {
trainFilterWindowController = TrainFilterWindowController()
}
func recvStartQueryTicketNotification(_ notification:Notification) {
self.clickQueryTicketBtn(nil)
}
func recvRefilterQueryTicketNotification(_ notification:Notification) {
self.filterTrainByAllAspect()
}
func recvCheckPassengerNotification(_ notification: Notification) {
let passengerId = notification.object as! String
for passenger in MainModel.passengers where passenger.passenger_id_no == passengerId {
if passengerSelected(passenger){
checkPassenger(passenger)
}
else{
let passengerViewController = PassengerViewController()
passengerViewController.passenger = passenger
passengerViewControllerList.append(passengerViewController)
self.passengersView.addView(passengerViewController.view, in:.top)
}
break
}
}
func recvAddDefaultPassengerNotification(_ notification: Notification) {
self.addPassengerBtn.isHidden = false
self.ticketTipLabel.isHidden = true
if MainModel.passengers.count == 0 {
return
}
if let lastPassengers = QueryDefaultManager.sharedInstance.lastSelectedPassenger {
if lastPassengers == "" {
return
}
let passengerIds = lastPassengers.components(separatedBy: ",")
for passengerId in passengerIds {
for passenger in MainModel.passengers where passenger.passenger_id_no == passengerId {
passenger.isChecked = true
let passengerViewController = PassengerViewController()
passengerViewController.passenger = passenger
passengerViewControllerList.append(passengerViewController)
self.passengersView.addView(passengerViewController.view, in:.top)
}
}
}
}
func recvLogoutNotification(_ notification: Notification) {
passengerViewControllerList.removeAll()
for view in passengersView.views{
view.removeFromSuperview()
}
addPassengerBtn.isHidden = true
}
func recvDidSubmitNotification(_ note: Notification){
openSubmitTicketSheet(isAutoSubmit: false)
}
func recvAutoSubmitNotification(_ note: Notification){
openSubmitTicketSheet(isAutoSubmit: true)
}
func recvAutoSubmitWithoutRandCodeNotification(_ note: Notification){
openSubmitTicketSheet(isAutoSubmit: true,ifShowCode: false)
}
// MARK: - Click Action
@IBAction func clickOpenTicketTaskSheet(_ sender: NSButton) {
openTicketTaskSheet()
}
@IBAction func clickConvertCity(_ sender: NSButton) {
let temp = self.fromStationNameTxt.stringValue
self.fromStationNameTxt.stringValue = self.toStationNameTxt.stringValue
self.toStationNameTxt.stringValue = temp
updateTicketTask(startStation: self.fromStationNameTxt.stringValue, endStation: self.toStationNameTxt.stringValue)
}
@IBAction func clickQueryTicketBtn(_ sender: AnyObject?) {
if !StationNameJs.sharedInstance.allStationMap.keys.contains(self.fromStationNameTxt.stringValue) {
return
}
if !StationNameJs.sharedInstance.allStationMap.keys.contains(self.toStationNameTxt.stringValue) {
return
}
if hasAutoQuery {
self.stopAutoQuery()
excludeTrainCode = ""
return
}
QueryDefaultManager.sharedInstance.lastTicketTaskManager = ticketTaskManager.encodeToJsonString()
self.saveLastSelectdPassengerIdToDefault()
if autoQuery {
repeatTimer = Timer(timeInterval: Double(GeneralPreferenceManager.sharedInstance.autoQuerySeconds), target: self, selector: #selector(TicketQueryViewController.queryTicketAndSubmit), userInfo: nil, repeats: true)
repeatTimer?.fire()
RunLoop.current.add(repeatTimer!, forMode: RunLoopMode.defaultRunLoopMode)
hasAutoQuery = true
}
else {
queryTicket()
}
}
@IBAction func clickAutoQueryCbx(_ sender: NSButton) {
if sender.state == NSOnState {
if self.seatFilterKey == "" {
self.openfilterTrainSheet()
}
else {
autoQuery = true
}
}
else {
autoQuery = false
}
}
@IBAction func clickFilterTrain(_ sender: AnyObject) {
self.openfilterTrainSheet()
}
@IBAction func clickAddPassenger(_ sender: NSButton) {
let positioningView = sender
let positioningRect = NSZeroRect
let preferredEdge = NSRectEdge.maxY
passengersPopover.show(relativeTo: positioningRect, of: positioningView, preferredEdge: preferredEdge)
passengerSelectViewController.reloadPassenger(MainModel.passengers)
}
func clickSubmit(_ sender: NSButton){
if hasAutoQuery {
self.stopAutoQuery()
}
let selectedRow = leftTicketTable.row(for: sender)
let ticket = filterQueryResult[selectedRow]
let seatTypeId = sender.identifier!
self.summitTicket(ticket, seatTypeId: seatTypeId,isAuto: false)
}
func clickShowTrainDetail(_ sender:NSButton) {
let selectedRow = leftTicketTable.row(for: sender)
let ticket = filterQueryResult[selectedRow]
let trainCodeDetailViewController = TrainCodeDetailViewController(trainDetailParams: QueryTrainCodeParam(ticket), trainPriceParams: QueryTrainPriceParam(ticket))
let trainCodeDetailpopover = NSPopover()
trainCodeDetailpopover.behavior = .semitransient
trainCodeDetailpopover.contentViewController = trainCodeDetailViewController
trainCodeDetailpopover.show(relativeTo: NSZeroRect, of: sender, preferredEdge: NSRectEdge.maxX)
}
// MARK: - Menu Action
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem.action == #selector(clickRefresh(_:)) {
return true
}
if menuItem.action == #selector(clickFilterTrain(_:)) {
if ticketQueryResult.count <= 0 {
return false
}
else {
return true
}
}
let selectedRow = leftTicketTable.selectedRow
if selectedRow < 0 || selectedRow > filterQueryResult.count - 1 {
return false
}
return false
}
@IBAction func clickRefresh(_ sender:AnyObject?) {
self.clickQueryTicketBtn(nil)
}
@IBAction func clickShareInfo(_ sender:AnyObject?) {
let generalPasteboard = NSPasteboard.general()
generalPasteboard.clearContents()
let ticket = filterQueryResult[leftTicketTable.selectedRow]
let shareInfo = "\(ticket.TrainCode!) \(ticket.FromStationName!)->\(ticket.ToStationName!) \(ticket.trainDateStr) \(ticket.start_time!)->\(ticket.arrive_time!)"
generalPasteboard.setString(shareInfo, forType:NSStringPboardType)
showTip("车票信息已生成,可复制到其他App")
}
}
// MARK: - AutoCompleteTableViewDelegate
extension TicketQueryViewController: AutoCompleteTableViewDelegate{
func textField(_ textField: NSTextField, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: Int) -> [String] {
var matches = [String]()
//先按简拼 再按全拼 并保留上一次的match
for station in StationNameJs.sharedInstance.allStation
{
if let _ = station.FirstLetter.range(of: textField.stringValue, options: NSString.CompareOptions.anchored)
{
matches.append(station.Name)
}
}
if(matches.isEmpty)
{
for station in StationNameJs.sharedInstance.allStation
{
if let _ = station.Spell.range(of: textField.stringValue, options: NSString.CompareOptions.anchored)
{
matches.append(station.Name)
}
}
}
return matches
}
func textField(_ textField: NSTextField, didSelectItem item: String) {
if textField == fromStationNameTxt {
updateTicketTask(startStation: item)
}
else if textField == toStationNameTxt {
updateTicketTask(endStation: item)
}
}
}
// MARK: - NSPopoverDelegate
extension TicketQueryViewController:NSPopoverDelegate {
@IBAction func showCalendar(_ sender: AnyObject){
let calendarPopover = NSPopover()
let cp = LunarCalendarView(with:self.queryDate.dateValue)
let ticketTask = ticketTaskManager.ticketTasks[queryTaskIndex]
let dates = ticketTaskManager.convertStr2Dates(ticketTask.date)
cp.allSelectedDates = dates
calendarPopover.contentViewController = cp
calendarPopover.appearance = NSAppearance(named: "NSAppearanceNameAqua")
calendarPopover.animates = true
calendarPopover.behavior = NSPopoverBehavior.transient
calendarPopover.delegate = self
self.calendarViewController = cp
let cellRect = sender.bounds
calendarPopover.show(relativeTo: cellRect!, of: sender as! NSView, preferredEdge: .maxY)
}
func popoverDidClose(_ notification: Notification) {
self.queryDateIndex = 0
let ticketTask = ticketTaskManager.ticketTasks[queryTaskIndex]
ticketTask.date = ticketTaskManager.convertDates2Str(calendarViewController!.allSelectedDates)
autoQuery = false
self.clickQueryTicketBtn(nil)
}
}
// MARK: - NSTableViewDataSource
extension TicketQueryViewController: NSTableViewDataSource{
func numberOfRows(in tableView: NSTableView) -> Int {
return filterQueryResult.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return filterQueryResult[row]
}
func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
guard let sortDescriptor = tableView.sortDescriptors.first else {
return
}
if let ticketOrder = TicketOrder(rawValue: sortDescriptor.key!) {
self.filterQueryResult = self.ticketOrderedBy(self.filterQueryResult, orderedBy: ticketOrder, ascending: sortDescriptor.ascending)
self.ticketOrder = ticketOrder
self.ticketAscending = sortDescriptor.ascending
self.leftTicketTable.reloadData()
self.leftTicketTable.selectRowIndexes(IndexSet(integer:0), byExtendingSelection: false)
}
}
}
// MARK: - NSTableViewDelegate
extension TicketQueryViewController: NSTableViewDelegate{
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return tableView.make(withIdentifier: "row", owner: tableView) as? NSTableRowView
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let view = tableView.make(withIdentifier: tableColumn!.identifier, owner: nil) as! NSTableCellView
let columnIdentifier = tableColumn!.identifier
if(columnIdentifier == "余票信息"){
let cell = view as! TrainInfoTableCellView
cell.ticketInfo = filterQueryResult[row]
cell.setTarget(self, action: #selector(TicketQueryViewController.clickSubmit(_:)))
}
else if(columnIdentifier == "发站" || columnIdentifier == "到站"){
let cell = view as! TrainTableCellView
cell.ticketInfo = filterQueryResult[row]
}
else if(columnIdentifier == "车次"){
let cell = view as! TrainCodeTableCellView
cell.setTarget(self, action:#selector(TicketQueryViewController.clickShowTrainDetail(_:)))
}
return view
}
}
// MARK: - NSUserNotificationCenterDelegate
extension TicketQueryViewController:NSUserNotificationCenterDelegate {
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
self.view.window?.makeKeyAndOrderFront(nil)
// NSApp.activateIgnoringOtherApps(false)
center.removeDeliveredNotification(notification)
}
}
| mit | 87f9bcf9e170bbba09ca214dfaf27e9c | 37.070949 | 224 | 0.622771 | 5.224049 | false | false | false | false |
weihongjiang/PROJECTTOWN | Town/Town/JALeftViewController.swift | 1 | 1274 | //
// JALeftViewController.swift
// Town
//
// Created by john.wei on 15/6/8.
// Copyright (c) 2015年 whj. All rights reserved.
//
import UIKit
class JALeftViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var bgImageView = UIImageView(frame: self.view.bounds)
bgImageView.image = UIImage(named: "beijing.jpg")
self.view.addSubview(bgImageView)
var blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
var effectImageView = UIVisualEffectView(effect: blur)
effectImageView.frame = bgImageView.bounds
bgImageView.addSubview(effectImageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 6d327f4b90b2ea88d78f444df4d5a6d3 | 27.909091 | 106 | 0.672956 | 4.873563 | false | false | false | false |
ahoppen/swift | test/Generics/protocol_requirement_signatures.swift | 2 | 2685 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -warn-redundant-requirements > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
// CHECK-LABEL: .P1@
// CHECK-NEXT: Requirement signature: <Self>
protocol P1 {}
// CHECK-LABEL: .P2@
// CHECK-NEXT: Requirement signature: <Self>
protocol P2 {}
// CHECK-LABEL: .P3@
// CHECK-NEXT: Requirement signature: <Self>
protocol P3 {}
// basic protocol
// CHECK-LABEL: .Q1@
// CHECK-NEXT: Requirement signature: <Self where Self.[Q1]X : P1>
protocol Q1 {
associatedtype X: P1 // expected-note 3{{declared here}}
}
// inheritance
// CHECK-LABEL: .Q2@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1>
protocol Q2: Q1 {}
// inheritance without any new requirements
// CHECK-LABEL: .Q3@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1>
protocol Q3: Q1 {
associatedtype X
}
// inheritance adding a new conformance
// CHECK-LABEL: .Q4@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1, Self.[Q1]X : P2>
protocol Q4: Q1 {
associatedtype X: P2 // expected-warning{{redeclaration of associated type 'X'}}
}
// multiple inheritance
// CHECK-LABEL: .Q5@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4>
protocol Q5: Q2, Q3, Q4 {}
// multiple inheritance without any new requirements
// CHECK-LABEL: .Q6@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4>
protocol Q6: Q2,
Q3, Q4 {
associatedtype X: P1 // expected-warning{{redundant conformance constraint 'Self.X' : 'P1'}}
// expected-warning@-1{{redeclaration of associated type 'X' from protocol 'Q1' is}}
}
// multiple inheritance with a new conformance
// CHECK-LABEL: .Q7@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4, Self.[Q1]X : P3>
protocol Q7: Q2, Q3, Q4 {
associatedtype X: P3 // expected-warning{{redeclaration of associated type 'X'}}
}
// SR-5945
class SomeBaseClass {}
// CHECK-DAG: .P4@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[P4]BType.[P5]AType, Self.[P4]BType : P5, Self.[P4]Native : SomeBaseClass>
protocol P4 {
associatedtype Native : SomeBaseClass
associatedtype BType : P5 where BType.AType == Self
}
// CHECK-DAG: .P5@
// CHECK-NEXT: <Self where Self == Self.[P5]AType.[P4]BType, Self.[P5]AType : P4>
protocol P5 {
associatedtype AType : P4 where AType.BType == Self
}
// SR-8119
protocol P6 {
associatedtype A1: P7
}
// CHECK-DAG: .P7@
// CHECK-NEXT: <Self where Self == Self.[P7]A2.[P6]A1, Self.[P7]A2 : P6>
protocol P7 {
associatedtype A2: P6 where A2.A1 == Self
}
| apache-2.0 | 4a73a7c87cd210c94dc68e899efb62b0 | 29.168539 | 137 | 0.679702 | 3.03733 | false | false | false | false |
daniel-barros/TV-Calendar | TV Calendar/ShowTracker.swift | 1 | 4604 | //
// ShowTracker.swift
// TV Calendar
//
// Created by Daniel Barros López on 11/9/16.
// Copyright © 2016 Daniel Barros. All rights reserved.
//
import ExtendedFoundation
import RealmSwift
protocol ShowTrackingConfirmer: class {
func confirmTracking(of show: Show, tracker: ShowTracker, completion: @escaping (Bool) -> ())
func confirmStopTracking(_ show: Show, tracker: ShowTracker, completion: @escaping (_ confirmed: Bool) -> ())
}
protocol ShowTrackingResponder: class {
func didTrack(_ show: Show, withSuccess: Bool, tracker: ShowTracker)
func didStopTracking(_ show: Show, withSuccess: Bool, tracker: ShowTracker)
}
/// Allows to track and stop tracking a show.
class ShowTracker {
weak var delegate: (ShowTrackingResponder & ShowTrackingConfirmer)?
init(realm: Realm) {
trackRealm = realm
}
/// The Realm where all the tracked shows and their episodes are persisted.
let trackRealm: Realm
/// All the tracked shows.
var trackedShows: Results<Show> {
return trackRealm.objects(Show.self)
}
/// All episodes belonging to `trackedShows`.
var trackedEpisodes: Results<Episode> {
return trackRealm.objects(Episode.self)
}
/// `true` if the show is being persisted in the `ShowTracker`'s `trackRealm`.
func isTracking(_ show: Show) -> Bool {
return trackRealm == show.realm
}
/// Starts tracking an event, persisting it into Realm.
func track(_ show: Show, completion: ((Bool) -> ())?) {
guard !isTracking(show) else {
delegate?.didTrack(show, withSuccess: false, tracker: self)
completion?(false)
assertionFailure(); return
}
func performTracking() {
let success = persist(show)
delegate?.didTrack(show, withSuccess: success, tracker: self)
completion?(success)
}
// If delegate exists, confirm before tracking
if let delegate = delegate {
delegate.confirmTracking(of: show, tracker: self) { confirmed in
if confirmed {
performTracking()
} else {
completion?(false)
}
}
}
// Otherwise track right away
else {
performTracking()
}
}
/// Stops tracking an event, removing it from Realm.
/// - parameter completion: A closure that takes a Result parameter, which in the success case will contain a valid copy of the show, now non-persistent (after removing an object from Realm, it becomes invalid).
func stopTracking(_ show: Show, completion: ((Result<Show>) -> ())?) {
guard isTracking(show) else {
delegate?.didStopTracking(show, withSuccess: false, tracker: self)
completion?(.failure(nil))
assertionFailure(); return
}
func performStopTracking() {
let showCopy = Show(show)
let success = unpersist(show)
delegate?.didStopTracking(showCopy, withSuccess: success, tracker: self)
completion?(success ? .success(showCopy) : .failure(nil))
}
// If delegate exists, confirm before untracking
if let delegate = delegate {
delegate.confirmStopTracking(show, tracker: self) { confirmed in
if confirmed {
performStopTracking()
} else {
completion?(.failure(nil))
}
}
}
// Otherwise untrack right away
else {
performStopTracking()
}
}
}
// MARK: Helpers
fileprivate extension ShowTracker {
func persist(_ show: Show) -> Bool {
do {
// Add to realm
try trackRealm.write {
trackRealm.add(show)
trackRealm.add(show.episodes)
}
// These generate more info now that the show is persisted
_ = show.updateSeasonsInfo()
_ = show.updateCurrentSeasonAiredEpisodes()
_ = show.updateEndedStatus()
_ = show.updateAirDay()
return true
} catch {
return false
}
}
func unpersist(_ show: Show) -> Bool {
do {
try trackRealm.write {
trackRealm.delete(show.episodes)
trackRealm.delete(show)
}
return true
} catch {
return false
}
}
}
| gpl-3.0 | aa408f3309b57f21b9090605641db764 | 30.520548 | 215 | 0.568883 | 4.88017 | false | false | false | false |
thiagolioy/pitchPerfect | pitchPerfect/pitchPerfect/RecordSoundsViewController.swift | 1 | 1178 | //
// RecordSoundsViewController.swift
// pitchPerfect
//
// Created by Thiago Lioy on 8/24/15.
// Copyright (c) 2015 Thiago Lioy. All rights reserved.
//
import UIKit
class RecordSoundsViewController: UIViewController {
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var recordingMessage: UILabel!
@IBOutlet weak var recordingButton: UIButton!
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
@IBAction func startRecording() {
recordingButton.enabled = false;
recordingMessage.hidden = false;
stopButton.enabled = true;
}
@IBAction func stopRecording() {
recordingButton.enabled = true;
recordingMessage.hidden = true;
stopButton.enabled = false;
self.performSegueWithIdentifier("showPlaySoundsVC", sender: nil)
}
}
| mit | 8b8ade44ba2e5fc99716e48b64c119a5 | 23.040816 | 81 | 0.658744 | 5.055794 | false | false | false | false |
rnystrom/GitHawk | Classes/Issues/Comments/IssueCommentSectionController.swift | 1 | 20848 | //
// IssueCommentSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 5/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
import TUSafariActivity
import Squawk
import GitHubAPI
import ContextMenu
protocol IssueCommentSectionControllerDelegate: class {
func didSelectReply(
to sectionController: IssueCommentSectionController,
commentModel: IssueCommentModel
)
}
final class IssueCommentSectionController: ListBindingSectionController<IssueCommentModel>,
ListBindingSectionControllerDataSource,
ListBindingSectionControllerSelectionDelegate,
IssueCommentDetailCellDelegate,
IssueCommentReactionCellDelegate,
EditCommentViewControllerDelegate,
MarkdownStyledTextViewDelegate,
IssueCommentDoubleTapDelegate,
ContextMenuDelegate {
private weak var issueCommentDelegate: IssueCommentSectionControllerDelegate?
private var collapsed = true
private let generator = UIImpactFeedbackGenerator()
private let client: GithubClient
private let model: IssueDetailsModel
private var hasBeenDeleted = false
private let autocomplete: IssueCommentAutocomplete
private lazy var webviewCache: WebviewCellHeightCache = {
return WebviewCellHeightCache(sectionController: self)
}()
private lazy var photoHandler: PhotoViewHandler = {
return PhotoViewHandler(viewController: self.viewController)
}()
private lazy var imageCache: ImageCellHeightCache = {
return ImageCellHeightCache(sectionController: self)
}()
// set when sending a mutation and override the original issue query reactions
private var reactionMutation: IssueCommentReactionViewModel?
// set after succesfully editing the body
private var bodyEdits: (markdown: String, models: [ListDiffable])?
private var currentMarkdown: String? {
return bodyEdits?.markdown ?? object?.rawMarkdown
}
// empty space cell placeholders
private let headModel = "headModel" as ListDiffable
private let tailModel = "tailModel" as ListDiffable
init(model: IssueDetailsModel,
client: GithubClient,
autocomplete: IssueCommentAutocomplete,
issueCommentDelegate: IssueCommentSectionControllerDelegate? = nil
) {
self.model = model
self.client = client
self.autocomplete = autocomplete
super.init()
self.dataSource = self
self.selectionDelegate = self
self.issueCommentDelegate = issueCommentDelegate
}
override func didUpdate(to object: Any) {
super.didUpdate(to: object)
inset = self.object?.commentSectionControllerInset ?? .zero
}
// MARK: Private API
func shareAction(sender: UIView) -> UIAlertAction? {
let attribute = object?.asReviewComment == true ? "discussion_r" : "issuecomment-"
guard let number = object?.number,
let url = URLBuilder.github()
.add(paths: [model.owner, model.repo, "issues", model.number])
.set(fragment: "\(attribute)\(number)")
.url
else { return nil }
weak var weakSelf = self
return AlertAction(AlertActionBuilder { $0.rootViewController = weakSelf?.viewController })
.share([url], activities: [TUSafariActivity()], type: .shareUrl) { $0.popoverPresentationController?.sourceView = sender }
}
var deleteAction: UIAlertAction? {
guard object?.viewerCanDelete == true else { return nil }
return AlertAction.delete { [weak self] _ in
let title = NSLocalizedString("Are you sure?", comment: "")
let message = NSLocalizedString("Deleting this comment is irreversible, do you want to continue?", comment: "")
let alert = UIAlertController.configured(title: title, message: message, preferredStyle: .alert)
alert.addActions([
AlertAction.cancel(),
AlertAction.delete { [weak self] _ in
self?.deleteComment()
}
])
self?.viewController?.present(alert, animated: trueUnlessReduceMotionEnabled)
}
}
var editAction: UIAlertAction? {
guard object?.viewerCanUpdate == true else { return nil }
return UIAlertAction(title: NSLocalizedString("Edit", comment: ""), style: .default, handler: { [weak self] _ in
guard let strongSelf = self,
let object = strongSelf.object,
let number = object.number,
let markdown = strongSelf.currentMarkdown
else { return }
let edit = EditCommentViewController(
client: strongSelf.client,
markdown: markdown,
issueModel: strongSelf.model,
commentID: number,
isRoot: object.isRoot,
autocomplete: strongSelf.autocomplete
)
edit.delegate = self
let nav = UINavigationController(rootViewController: edit)
nav.modalPresentationStyle = .formSheet
self?.viewController?.route_present(to: nav)
})
}
var replyAction: UIAlertAction? {
return UIAlertAction(
title: NSLocalizedString("Reply", comment: ""),
style: .default,
handler: { [weak self] _ in
guard let strongSelf = self,
let commentModel = strongSelf.object
else { return }
strongSelf.issueCommentDelegate?.didSelectReply(
to: strongSelf,
commentModel: commentModel
)
}
)
}
var viewMarkdownAction: UIAlertAction? {
return UIAlertAction(
title: NSLocalizedString("View Markdown", comment: ""),
style: .default,
handler: { [weak self] _ in
guard let markdown = self?.object?.rawMarkdown else { return }
let nav = UINavigationController(
rootViewController: ViewMarkdownViewController(markdown: markdown)
)
self?.viewController?.route_present(to: nav)
}
)
}
private func clearCollapseCells() {
// clear any collapse state before updating so we don't have a dangling overlay
for cell in collectionContext?.visibleCells(for: self) ?? [] {
if let cell = cell as? IssueCommentBaseCell {
cell.collapsed = false
}
}
}
@discardableResult
private func uncollapse() -> Bool {
guard collapsed else { return false }
collapsed = false
clearCollapseCells()
collectionContext?.invalidateLayout(for: self, completion: nil)
update(animated: trueUnlessReduceMotionEnabled)
return true
}
private func react(cell: IssueCommentReactionCell?, content: ReactionContent, isAdd: Bool) {
guard let object = self.object else { return }
let previousReaction = reactionMutation
let result = IssueLocalReaction(
fromServer: object.reactions,
previousLocal: reactionMutation,
content: content,
add: isAdd
)
reactionMutation = result.viewModel
cell?.perform(operation: result.operation, content: content)
update(animated: trueUnlessReduceMotionEnabled)
generator.impactOccurred()
client.react(subjectID: object.id, content: content, isAdd: isAdd) { [weak self] result in
switch result {
case .success: break
case .error(let error):
self?.reactionMutation = previousReaction
self?.update(animated: trueUnlessReduceMotionEnabled)
Squawk.show(error: error)
}
}
}
func edit(markdown: String) {
let width = collectionContext.cellWidth()
let bodyModels = MarkdownModels(
// strip githawk signatures on edit
CheckIfSentWithGitHawk(markdown: markdown).markdown,
owner: model.owner,
repo: model.repo,
width: width,
viewerCanUpdate: true,
contentSizeCategory: UIContentSizeCategory.preferred,
isRoot: self.object?.isRoot == true
)
bodyEdits = (markdown, bodyModels)
collapsed = false
clearCollapseCells()
update(animated: trueUnlessReduceMotionEnabled)
}
func didTap(attribute: DetectedMarkdownAttribute) {
if viewController?.handle(attribute: attribute) == true {
return
}
switch attribute {
case .issue(let issue):
viewController?.route_push(to: IssuesViewController(client: client, model: issue))
case .checkbox(let checkbox):
didTapCheckbox(checkbox: checkbox)
default: break
}
}
/// Deletes the comment and optimistically removes it from the feed
private func deleteComment() {
guard let number = object?.number else { return }
// Optimistically delete the comment
hasBeenDeleted = true
update(animated: trueUnlessReduceMotionEnabled)
client.client.send(V3DeleteCommentRequest(
owner: model.owner,
repo: model.repo,
commentID: "\(number)")
) { [weak self] result in
switch result {
case .failure(let error):
self?.hasBeenDeleted = false
self?.update(animated: trueUnlessReduceMotionEnabled)
Squawk.show(error: error)
case .success: break // Don't need to handle success since updated optimistically
}
}
}
func didTapCheckbox(checkbox: MarkdownCheckboxModel) {
guard object?.viewerCanUpdate == true,
let commentID = object?.number,
let isRoot = object?.isRoot,
let originalMarkdown = currentMarkdown
else { return }
let range = checkbox.originalMarkdownRange
let originalMarkdownNSString = originalMarkdown as NSString
guard range.location + range.length < originalMarkdownNSString.length
else { return }
let invertedToken = checkbox.checked ? "[ ]" : "[x]"
let edited = originalMarkdownNSString.replacingCharacters(in: range, with: invertedToken)
edit(markdown: edited)
client.client.send(V3EditCommentRequest(
owner: model.owner,
repo: model.repo,
issueNumber: model.number,
commentID: commentID,
body: edited,
isRoot: isRoot)
) { [weak self] result in
switch result {
case .success: break
case .failure(let error):
self?.edit(markdown: originalMarkdown)
Squawk.show(error: error)
}
}
}
// MARK: ListBindingSectionControllerDataSource
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
viewModelsFor object: Any
) -> [ListDiffable] {
guard let object = self.object else { return [] }
guard !hasBeenDeleted else { return [] }
var bodies = [ListDiffable]()
let bodyModels = bodyEdits?.models ?? object.bodyModels
for body in bodyModels {
bodies.append(body)
if collapsed && body === object.collapse?.model {
break
}
}
// if this is a PR comment, if this is the tail model, append an empty space cell at the end so there's a divider
// otherwise append reactions
let tail: [ListDiffable] = object.asReviewComment
? (object.threadState == .tail ? [tailModel] : [])
: [ reactionMutation ?? object.reactions ]
// return [ object.details, headModel ]
return [ object.details ]
+ bodies
+ tail
}
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
sizeForViewModel viewModel: Any,
at index: Int
) -> CGSize {
guard let viewModel = viewModel as? ListDiffable
else { fatalError("Collection context must be set") }
let height: CGFloat
if collapsed && (viewModel as AnyObject) === object?.collapse?.model {
height = object?.collapse?.height ?? 0
} else if viewModel is IssueCommentReactionViewModel {
height = 38.0
} else if viewModel is IssueCommentDetailsViewModel {
height = Styles.Sizes.rowSpacing * 2 + Styles.Sizes.avatar.height
} else if viewModel === tailModel || viewModel === headModel {
height = Styles.Sizes.rowSpacing
} else {
height = BodyHeightForComment(
viewModel: viewModel,
width: collectionContext.safeContentWidth(),
webviewCache: webviewCache,
imageCache: imageCache
)
}
return collectionContext.cellSize(with: height)
}
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
cellForViewModel viewModel: Any,
at index: Int
) -> UICollectionViewCell & ListBindable {
guard let context = self.collectionContext,
let viewModel = viewModel as? ListDiffable
else { fatalError("Collection context must be set") }
if viewModel === tailModel {
guard let cell = context.dequeueReusableCell(of: IssueReviewEmptyTailCell.self, for: self, at: index) as? UICollectionViewCell & ListBindable
else { fatalError("Cell not bindable") }
return cell
} else if viewModel === headModel {
guard let cell = context.dequeueReusableCell(of: IssueCommentEmptyCell.self, for: self, at: index) as? IssueCommentEmptyCell
else { fatalError("Wrong cell type") }
return cell
}
let cellClass: AnyClass
switch viewModel {
case is IssueCommentDetailsViewModel: cellClass = IssueCommentDetailCell.self
case is IssueCommentReactionViewModel: cellClass = IssueCommentReactionCell.self
default: cellClass = CellTypeForComment(viewModel: viewModel)
}
guard let cell = context.dequeueReusableCell(of: cellClass, for: self, at: index) as? UICollectionViewCell & ListBindable
else { fatalError("Cell not bindable") }
// extra config outside of bind API. applies to multiple cell types.
if let cell = cell as? IssueCommentBaseCell {
cell.collapsed = collapsed && (viewModel as AnyObject) === object?.collapse?.model
}
// connect specific cell delegates
if let cell = cell as? IssueCommentDetailCell {
cell.delegate = self
} else if let cell = cell as? IssueCommentReactionCell {
cell.delegate = self
}
if let object = self.object,
!object.asReviewComment,
let cell = cell as? IssueCommentBaseCell {
cell.doubleTapDelegate = self
}
ExtraCommentCellConfigure(
cell: cell,
imageDelegate: photoHandler,
htmlDelegate: webviewCache,
htmlNavigationDelegate: viewController,
htmlImageDelegate: photoHandler,
markdownDelegate: self,
imageHeightDelegate: imageCache
)
return cell
}
// MARK: ListBindingSectionControllerSelectionDelegate
func sectionController(
_ sectionController: ListBindingSectionController<ListDiffable>,
didSelectItemAt index: Int,
viewModel: Any
) {
switch viewModel {
case is IssueCommentReactionViewModel,
is IssueCommentDetailsViewModel: return
default: break
}
uncollapse()
}
// MARK: IssueCommentDoubleTapDelegate
func didDoubleTap(cell: IssueCommentBaseCell) {
guard let reaction = ReactionContent.defaultReaction else { return }
guard let reactions = reactionMutation ?? self.object?.reactions,
!reactions.viewerDidReact(reaction: reaction)
else { return }
react(
cell: collectionContext?.cellForItem(at: numberOfItems() - 1, sectionController: self) as? IssueCommentReactionCell,
content: reaction,
isAdd: true
)
}
// MARK: IssueCommentDetailCellDelegate
func didTapProfile(cell: IssueCommentDetailCell) {
guard let login = object?.details.login else {
Squawk.showGenericError()
return
}
viewController?.presentProfile(login: login)
}
// MARK: IssueCommentReactionCellDelegate
func didAdd(cell: IssueCommentReactionCell, reaction: ReactionContent) {
// don't add a reaction if already reacted
guard let reactions = reactionMutation ?? self.object?.reactions,
!reactions.viewerDidReact(reaction: reaction)
else { return }
react(cell: cell, content: reaction, isAdd: true)
}
func didRemove(cell: IssueCommentReactionCell, reaction: ReactionContent) {
// don't remove a reaction if it doesn't exist
guard let reactions = reactionMutation ?? self.object?.reactions,
reactions.viewerDidReact(reaction: reaction)
else { return }
react(cell: cell, content: reaction, isAdd: false)
}
func didTapMore(cell: IssueCommentReactionCell, sender: UIView) {
guard let login = object?.details.login else {
Squawk.showGenericError()
return
}
let alertTitle = NSLocalizedString("%@'s comment", comment: "Used in an action sheet title, eg. \"Basthomas's comment\".")
let alert = UIAlertController.configured(
title: String(format: alertTitle, login),
preferredStyle: .actionSheet
)
alert.popoverPresentationController?.sourceView = sender
alert.addActions([
shareAction(sender: sender),
viewMarkdownAction,
editAction,
replyAction,
deleteAction,
AlertAction.cancel()
])
viewController?.present(alert, animated: trueUnlessReduceMotionEnabled)
}
func didTapAddReaction(cell: IssueCommentReactionCell, sender: UIView) {
guard let viewController = self.viewController else { return }
ContextMenu.shared.show(
sourceViewController: viewController,
viewController: ReactionsMenuViewController(),
options: ContextMenu.Options(
durations: ContextMenu.AnimationDurations(present: 0.2),
containerStyle: ContextMenu.ContainerStyle(
xPadding: -4,
yPadding: 8,
backgroundColor: Styles.Colors.menuBackgroundColor.color
),
menuStyle: .minimal,
hapticsStyle: .medium
),
sourceView: sender,
delegate: self
)
}
// MARK: MarkdownStyledTextViewDelegate
func didTap(cell: MarkdownStyledTextView, attribute: DetectedMarkdownAttribute) {
didTap(attribute: attribute)
}
// MARK: EditCommentViewControllerDelegate
func didEditComment(viewController: EditCommentViewController, markdown: String) {
viewController.dismiss(animated: trueUnlessReduceMotionEnabled)
edit(markdown: markdown)
}
func didCancel(viewController: EditCommentViewController) {
viewController.dismiss(animated: trueUnlessReduceMotionEnabled)
}
// MARK: ContextMenuDelegate
func contextMenuWillDismiss(viewController: UIViewController, animated: Bool) {}
func contextMenuDidDismiss(viewController: UIViewController, animated: Bool) {
guard let reactionViewController = viewController as? ReactionsMenuViewController,
let reaction = reactionViewController.selectedReaction,
let reactions = reactionMutation ?? self.object?.reactions
else { return }
var index = -1
for (i, model) in viewModels.reversed().enumerated() where model is IssueCommentReactionViewModel {
index = viewModels.count - 1 - i
break
}
guard index >= 0 else { return }
react(
cell: collectionContext?.cellForItem(at: index, sectionController: self) as? IssueCommentReactionCell,
content: reaction,
isAdd: !reactions.viewerDidReact(reaction: reaction)
)
}
}
| mit | 82e47f1598bb0ad1dbc023e0d863ebdd | 35.445804 | 153 | 0.624934 | 5.480284 | false | false | false | false |
knehez/edx-app-ios | Source/CourseDashboardViewController.swift | 2 | 6676 | //
// CourseDashboardViewController.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 11/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public class CourseDashboardViewControllerEnvironment : NSObject {
let config: OEXConfig?
weak var router: OEXRouter?
let networkManager : NetworkManager?
public init(config: OEXConfig?, router: OEXRouter?, networkManager: NetworkManager?) {
self.config = config
self.router = router
self.networkManager = networkManager
}
}
struct CourseDashboardItem {
let title: String
let detail: String
let icon : Icon
let action:(() -> Void)
}
public class CourseDashboardViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
private let headerHeight = 180
private let environment: CourseDashboardViewControllerEnvironment!
private var course: OEXCourse?
private var tableView: UITableView = UITableView()
private var cellItems: [CourseDashboardItem] = []
public init(environment: CourseDashboardViewControllerEnvironment, course: OEXCourse?) {
self.environment = environment
self.course = course
super.init(nibName: nil, bundle: nil)
navigationItem.title = course?.name
navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
}
public required init(coder aDecoder: NSCoder) {
// required by the compiler because UIViewController implements NSCoding,
// but we don't actually want to serialize these things
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
// Set up tableView
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.clearColor()
self.view.addSubview(tableView)
tableView.snp_makeConstraints { make -> Void in
make.edges.equalTo(self.view)
}
let courseView = CourseDashboardCourseInfoView(frame: CGRect(x : 0, y: 0, width: 0, height : headerHeight))
if let course = self.course {
courseView.titleText = course.name
courseView.detailText = (course.org ?? "") + (course.number.map { " | " + $0 } ?? "")
//TODO: the way to load image is not perfect, need to do refactoring later
courseView.course = course
courseView.setCoverImage()
}
tableView.tableHeaderView = courseView
// Register tableViewCell
tableView.registerClass(CourseDashboardCell.self, forCellReuseIdentifier: CourseDashboardCell.identifier)
prepareTableViewData()
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if let indexPath = tableView.indexPathForSelectedRow() {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
public func prepareTableViewData() {
var item = CourseDashboardItem(title: OEXLocalizedString("COURSE_DASHBOARD_COURSEWARE", nil), detail: OEXLocalizedString("COURSE_DASHBOARD_COURSE_DETAIL", nil), icon : .Courseware) {[weak self] () -> Void in
self?.showCourseware()
}
cellItems.append(item)
if let courseID = course?.course_id where shouldEnableDiscussions() {
item = CourseDashboardItem(title: OEXLocalizedString("COURSE_DASHBOARD_DISCUSSION", nil), detail: OEXLocalizedString("COURSE_DASHBOARD_DISCUSSION_DETAIL", nil), icon: .Discussions) {[weak self] () -> Void in
self?.showDiscussionsForCourseID(courseID)
}
cellItems.append(item)
}
item = CourseDashboardItem(title: OEXLocalizedString("COURSE_DASHBOARD_HANDOUTS", nil), detail: OEXLocalizedString("COURSE_DASHBOARD_HANDOUTS_DETAIL", nil), icon: .Handouts) {[weak self] () -> Void in
self?.showHandouts()
}
cellItems.append(item)
item = CourseDashboardItem(title: OEXLocalizedString("COURSE_DASHBOARD_ANNOUNCEMENTS", nil), detail: OEXLocalizedString("COURSE_DASHBOARD_ANNOUNCEMENTS_DETAIL", nil), icon: .Announcements) {[weak self] () -> Void in
self?.showAnnouncements()
}
cellItems.append(item)
}
func shouldEnableDiscussions() -> Bool {
return self.environment.config!.shouldEnableDiscussions()
}
// MARK: - TableView Data and Delegate
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellItems.count
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80.0
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CourseDashboardCell.identifier, forIndexPath: indexPath) as! CourseDashboardCell
let dashboardItem = cellItems[indexPath.row]
cell.useItem(dashboardItem)
return cell
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dashboardItem = cellItems[indexPath.row]
dashboardItem.action()
}
func showCourseware() {
if let course = self.course, courseID = course.course_id {
self.environment.router?.showCoursewareForCourseWithID(courseID, fromController: self)
}
}
func showDiscussionsForCourseID(courseID: String) {
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
self.environment.router?.showDiscussionTopicsFromController(self, courseID: courseID)
}
func showHandouts() {
self.environment.router?.showHandouts(self.course?.course_handouts, fromViewController: self)
}
func showAnnouncements() {
self.environment.router?.showAnnouncementsForCourseWithID(course?.course_id)
}
}
// MARK: Testing
extension CourseDashboardViewController {
public func t_canVisitDiscussions() -> Bool {
if self.cellItems.count == 4 {
return true
}
return false
}
}
| apache-2.0 | 034a20dcafd56b03c609051d3e7603fe | 36.088889 | 223 | 0.663571 | 5.06525 | false | false | false | false |
tavultesoft/keymanweb | oem/firstvoices/ios/FirstVoices/KeyboardSettingsRepository.swift | 1 | 9540 | /*
* KeyboardSettingsRepository.swift
* FirstVoices app
*
* License: MIT
*
* Copyright © 2022 FirstVoices.
*
* Created by Shawn Schantz on 2022-01-26.
*
* Class responsible for reading and writing the selected keyboards and related settings
* from the application's UserDefaults database.
*
*/
import Foundation
class KeyboardSettingsRepository {
static let shared: KeyboardSettingsRepository = {
let instance = KeyboardSettingsRepository()
return instance
}()
private init() {
}
private var _activeKeyboards: [String:KeyboardState]!
public var activeKeyboards: [String:KeyboardState] {
get {
if _activeKeyboards == nil {
_activeKeyboards = self.loadKeyboardStateFromUserDefaults()
}
return _activeKeyboards!
}
set {
_activeKeyboards = newValue
}
}
/*
* Attempts to load an existing keyboard state from storage.
* If it is not in storage, create a new default keyboard state or return nil if
* keyboard is not defined.
*/
func loadKeyboardState(keyboardId: String) -> KeyboardState? {
var state:KeyboardState? = nil;
if let state = activeKeyboards[keyboardId] {
return state
} else {
state = createDefaultKeyboardState(for: keyboardId, isActive: false)
}
return state
}
func hasActiveKeyboards() -> Bool {
return !activeKeyboards.isEmpty
}
/*
* Create a new default keyboard state object or nil if specified keyboard is not defined.
*/
func createDefaultKeyboardState(for keyboardId: String, isActive: Bool) -> KeyboardState? {
if let keyboardDefinition = KeyboardRepository.shared.findKeyboardDefinition(for: keyboardId) {
return KeyboardState(definition: keyboardDefinition,
isActive: isActive)
} else {
return nil
}
}
func saveKeyboardState(state: KeyboardState) {
if (state.isActive) {
// add to keyboard state map (or update if already exists)
self.activeKeyboards[state.keyboardId] = state
} else {
// is not active, so remove from keyboard state map if it is there
self.activeKeyboards.removeValue(forKey: state.keyboardId)
}
// persist the entire map
self.saveKeyboardStateMapToSettingsMap()
}
/*
* Load persisted keyboard settings from UserDefaults.
* If new and old format of the settings exist, delete the old format.
*/
func loadKeyboardStateFromUserDefaults() -> [String:KeyboardState] {
var keyboardsMap: [String:KeyboardState] = [:]
let sharedData: UserDefaults = FVShared.userDefaults()
if let data = sharedData.data(forKey: FVConstants.kFVKeyboardSettingsMap) {
do {
let settingsMap = try JSONDecoder().decode([String:KeyboardSettings].self, from: data)
// if there is a keyboard settings map, then create a KeyboardState map from it
keyboardsMap = self.createKeyboardMapFromKeyboardSettings(settingsMap: settingsMap)
} catch {
print(error)
}
// data is already in the latest format, so it is safe to remove old format, if it exists
if (sharedData.object(forKey: FVConstants.kFVLoadedKeyboardList) != nil) {
sharedData.removeObject(forKey: FVConstants.kFVLoadedKeyboardList)
}
}
else
if let keyboardIds = sharedData.array(forKey: FVConstants.kFVLoadedKeyboardList) as? [String] {
// else if the legacy String array is found, then build default settings objects for it
keyboardsMap = self.createKeyboardMapFromKeyboardNameArray(keyboardIds: keyboardIds)
}
else {
// else if no data is found in UserDefaults, then return an empty map
keyboardsMap = [:]
}
return keyboardsMap
}
/*
* Convert the hashmap of KeyboardState objects into a hashmap of KeyboardSettings structs
* which can then be persisted to the UserDefaults.
*/
func createSettingsMapFromKeyboardStateMap(keyboards: [String:KeyboardState]) -> [String:KeyboardSettings] {
var settingsMap: [String:KeyboardSettings] = [:]
for (name, keyboard) in keyboards {
let settings = KeyboardSettings(keyboardName: keyboard.name,
keyboardId: keyboard.keyboardId,
isActive: keyboard.isActive,
suggestCorrections: keyboard.suggestCorrections, suggestPredictions: keyboard.suggestPredictions, lexicalModelName: keyboard.lexicalModelName!, lexicalModelId: keyboard.lexicalModelId!)
settingsMap[name] = settings
}
return settingsMap
}
func createKeyboardState(for keyboardId: String, isActive: Bool) -> KeyboardState? {
if let keyboardDefinition = KeyboardRepository.shared.findKeyboardDefinition(for: keyboardId) {
return KeyboardState(definition: keyboardDefinition,
isActive: isActive)
} else {
return nil
}
}
/*
* used to convert map of KeyboardSettings to map of KeyboardState object
*/
func createKeyboardMapFromKeyboardSettings(settingsMap: [String:KeyboardSettings]) -> [String:KeyboardState] {
var keyboardsMap: [String:KeyboardState] = [:]
for (name, settings) in settingsMap {
if let keyboardState = createKeyboardState(for: name, isActive: settings.isActive) {
keyboardState.suggestCorrections = settings.suggestCorrections
keyboardState.suggestPredictions = settings.suggestPredictions
keyboardState.lexicalModelName = settings.lexicalModelName
keyboardState.lexicalModelId = settings.lexicalModelId
keyboardsMap[name] = keyboardState
}
}
return keyboardsMap
}
/*
* used to convert legacy format keyboard name array to keyboard map
*/
func createKeyboardMapFromKeyboardNameArray(keyboardIds: [String]) -> [String:KeyboardState] {
var keyboardsMap: [String:KeyboardState] = [:]
// the keyboard array contains only active keyboards
for keyboardId in keyboardIds {
let keyboardState = createDefaultKeyboardState(for: keyboardId, isActive: true)
keyboardsMap[keyboardId] = keyboardState
}
return keyboardsMap
}
func saveKeyboardStateMapToSettingsMap() {
let settings:[String:KeyboardSettings] = createSettingsMapFromKeyboardStateMap(keyboards: self.activeKeyboards)
let sharedData: UserDefaults = FVShared.userDefaults()
guard let data = try? JSONEncoder().encode(settings) else { return }
sharedData.set(data, forKey: FVConstants.kFVKeyboardSettingsMap)
}
// deprecated but retained in case of need to test with data saved in old format
func saveKeyboardIdArrayToUserDefaults() {
let sharedData: UserDefaults = FVShared.userDefaults()
let keyboardIds: [String] = Array(activeKeyboards.keys)
sharedData.set(keyboardIds, forKey: FVConstants.kFVLoadedKeyboardList)
}
}
struct KeyboardSettings: Codable {
internal init(keyboardName: String, keyboardId: String, isActive: Bool, suggestCorrections: Bool, suggestPredictions: Bool, lexicalModelName: String, lexicalModelId: String) {
self.keyboardName = keyboardName
self.keyboardId = keyboardId
self.isActive = isActive
self.suggestCorrections = suggestCorrections
self.suggestPredictions = suggestPredictions
self.lexicalModelName = lexicalModelName
self.lexicalModelId = lexicalModelId
}
let keyboardName: String
let keyboardId: String
let isActive: Bool
let suggestCorrections: Bool
let suggestPredictions: Bool
let lexicalModelName: String
let lexicalModelId: String
}
class KeyboardState {
let definition: FVKeyboardDefinition
var isActive: Bool
var suggestCorrections: Bool
var suggestPredictions: Bool
var lexicalModelName: String?
var lexicalModelId: String?
var name: String {
get {
return definition.name
}
}
var keyboardId: String {
get {
return definition.keyboardId
}
}
var languageTag: String {
get {
return definition.languageTag
}
}
var version: String {
get {
return definition.keyboardVersion
}
}
internal init(definition: FVKeyboardDefinition, isActive: Bool) {
self.definition = definition
self.isActive = isActive
self.suggestCorrections = false
self.suggestPredictions = false
self.lexicalModelName = ""
self.lexicalModelId = ""
}
func selectDictionary(lexicalModel: FVLexicalModel) {
self.lexicalModelName = lexicalModel.name
self.lexicalModelId = lexicalModel.id
self.suggestPredictions = true
self.suggestCorrections = true
}
func clearDictionary() {
self.lexicalModelName = ""
self.lexicalModelId = ""
self.suggestPredictions = false
self.suggestCorrections = false
}
func updatePredictions(on: Bool) {
self.suggestPredictions = on
// we cannot do corrections when predictions are off
if (!on) {
self.suggestCorrections = false
}
}
func canSelectDictionary() -> Bool {
return self.isActive
}
func isDictionarySelected() -> Bool {
return !(self.lexicalModelName ?? "").isEmpty
}
// if a dictionary is selected the suggestPredictions option is available
func canSuggestPredictions() -> Bool {
return isDictionarySelected()
}
// if the suggestPredictions option is active, then suggestCorrections is available
func canSuggestCorrections() -> Bool {
return self.canSuggestPredictions() && self.suggestPredictions
}
}
| apache-2.0 | 318ba7055ed8f6104f6ebda18b35e40a | 31.335593 | 224 | 0.699654 | 4.61044 | false | false | false | false |
helloworldpark/nomoregatcha | NoMoreGatcha/NoMoreGatcha/Gatcha.swift | 1 | 4202 | //
// Gatcha.swift
// NoMoreGatcha
//
// Created by Helloworld Park on 2017. 3. 17..
// Copyright © 2017년 Helloworld Park. All rights reserved.
//
import Foundation
public struct Report
{
public static let EMPTY = Report(items: -1, rounds: -1, min: 0, max: 0, mean: 0, stdev: -1)
public let items: Int
public let rounds: Int
public let min: UInt64
public let max: UInt64
public let mean: Double
public let stdev: Double
public func report()
{
print("Random Boxes \(self.items) Rounds \(self.rounds)")
print("Min \(self.min) Max \(self.max)")
print("Mean \(self.mean) Stdev \(self.stdev)")
}
}
public class Gatcha
{
public var name: String
public let items: [Item]
private let discreteHelper: ERDiscrete<Item>
private var appearedItems: Set<Item>
public init(items: [Item], odds: [Double])
{
guard items.count == odds.count else {
fatalError("Items and Odds don't match")
}
self.name = "gatcha-\(Date().hashValue)"
self.items = items
self.discreteHelper = ERDiscrete(x: items, probability: odds)
self.appearedItems = Set<Item>(minimumCapacity: items.count)
}
public convenience init(odds: [Double])
{
self.init(items: Item.convenientItems(count: odds.count), odds: odds)
}
public func run(forRounds r: Int, maximumPick p: UInt64, reportAsFile: Bool = false) -> Report
{
guard r > 0 else {
return Report.EMPTY
}
guard p > 0 else {
return Report.EMPTY
}
var pickArr = [UInt64]()
for _ in 1...r
{
var picks = UInt64(0)
while self.appearedItems.count < items.count && picks < p
{
picks = picks + 1
self.appearedItems.insert(self.discreteHelper.generate())
}
self.appearedItems.removeAll(keepingCapacity: true)
pickArr.append(picks)
}
return self.report(withData: pickArr, saveAsFile: reportAsFile)
}
private func report(withData data: [UInt64], saveAsFile: Bool) -> Report
{
let mean = data.reduce(0.0) { (old, fresh) -> Double in
return old + Double(fresh)
} / Double(data.count)
let sqmean = data.reduce(0.0) { (old, fresh) -> Double in
return old + Double(fresh) * Double(fresh)
} / Double(data.count)
let stdev = sqrt(sqmean - mean*mean)
let maxPick = data.max()!
let minPick = data.min()!
let report = Report(items: items.count, rounds: data.count, min: minPick, max: maxPick, mean: mean, stdev: stdev)
if saveAsFile == true {
let path = Gatcha.documentsDirectory().appendingPathComponent("\(self.name).csv")
let joined = data.flatMap({ String($0)}).joined(separator: "\n")
let txtToWrite = "Picks\n".appending(joined)
do {
try txtToWrite.write(to: path, atomically: false, encoding: String.Encoding.utf8)
print("Saved at \(path)")
} catch {
print("Saving failed")
}
}
return report
}
private static func documentsDirectory() -> URL
{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
public static func uniformDistribution(count: Int) -> [Double]
{
guard count > 0 else {
fatalError("At least one")
}
return [Double](repeating: 1.0 / Double(count), count: count)
}
public static func rareDistribution(count: Int, rare: Double) -> [Double]
{
guard count > 1 else {
fatalError("At least two")
}
guard rare < 1.0 else {
fatalError("Rare be smaller than one")
}
var distribution = [Double](repeating: (1.0 - rare) / Double(count - 1), count: count)
distribution[distribution.count-1] = rare
return distribution
}
}
| mit | 776c134a46941eff329779d123633c7e | 30.571429 | 121 | 0.568469 | 4.04918 | false | false | false | false |
rhx/SwiftGtk | Sources/Gtk/GtkTypeAliases.swift | 1 | 9619 | import CGtk
// Private structs not exported but needed for public pointers
public typealias GtkArrowAccessiblePrivate = _GtkArrowAccessiblePrivate
public typealias GtkBooleanCellAccessiblePrivate = _GtkBooleanCellAccessiblePrivate
public typealias GtkButtonAccessiblePrivate = _GtkButtonAccessiblePrivate
public typealias GtkCellAccessibleParent = _GtkCellAccessibleParent
public typealias GtkCellAccessiblePrivate = _GtkCellAccessiblePrivate
public typealias GtkCheckMenuItemAccessiblePrivate = _GtkCheckMenuItemAccessiblePrivate
public typealias GtkComboBoxAccessible = _GtkComboBoxAccessible
public typealias GtkComboBoxAccessibleClass = _GtkComboBoxAccessibleClass
public typealias GtkComboBoxAccessiblePrivate = _GtkComboBoxAccessiblePrivate
public typealias GtkContainerAccessiblePrivate = _GtkContainerAccessiblePrivate
public typealias GtkContainerCellAccessible = _GtkContainerCellAccessible
public typealias GtkContainerCellAccessibleClass = _GtkContainerCellAccessibleClass
public typealias GtkContainerCellAccessiblePrivate = _GtkContainerCellAccessiblePrivate
public typealias GtkEntryAccessible = _GtkEntryAccessible
public typealias GtkEntryAccessibleClass = _GtkEntryAccessibleClass
public typealias GtkEntryAccessiblePrivate = _GtkEntryAccessiblePrivate
public typealias GtkEntryIconAccessible = _GtkEntryIconAccessible
public typealias GtkExpanderAccessible = _GtkExpanderAccessible
public typealias GtkExpanderAccessibleClass = _GtkExpanderAccessibleClass
public typealias GtkExpanderAccessiblePrivate = _GtkExpanderAccessiblePrivate
public typealias GtkFlowBoxAccessible = _GtkFlowBoxAccessible
public typealias GtkFlowBoxAccessibleClass = _GtkFlowBoxAccessibleClass
public typealias GtkFlowBoxAccessiblePrivate = _GtkFlowBoxAccessiblePrivate
public typealias GtkFlowBoxChildAccessible = _GtkFlowBoxChildAccessible
public typealias GtkFlowBoxChildAccessibleClass = _GtkFlowBoxChildAccessibleClass
public typealias GtkFrameAccessible = _GtkFrameAccessible
public typealias GtkFrameAccessibleClass = _GtkFrameAccessibleClass
public typealias GtkFrameAccessiblePrivate = _GtkFrameAccessiblePrivate
public typealias GtkIconViewAccessible = _GtkIconViewAccessible
public typealias GtkIconViewAccessibleClass = _GtkIconViewAccessibleClass
public typealias GtkIconViewAccessiblePrivate = _GtkIconViewAccessiblePrivate
public typealias GtkImageAccessible = _GtkImageAccessible
public typealias GtkImageAccessibleClass = _GtkImageAccessibleClass
public typealias GtkImageAccessiblePrivate = _GtkImageAccessiblePrivate
public typealias GtkImageCellAccessible = _GtkImageCellAccessible
public typealias GtkImageCellAccessibleClass = _GtkImageCellAccessibleClass
public typealias GtkImageCellAccessiblePrivate = _GtkImageCellAccessiblePrivate
public typealias GtkLabelAccessible = _GtkLabelAccessible
public typealias GtkLabelAccessibleClass = _GtkLabelAccessibleClass
public typealias GtkLabelAccessiblePrivate = _GtkLabelAccessiblePrivate
public typealias GtkLevelBarAccessible = _GtkLevelBarAccessible
public typealias GtkLevelBarAccessibleClass = _GtkLevelBarAccessibleClass
public typealias GtkLevelBarAccessiblePrivate = _GtkLevelBarAccessiblePrivate
public typealias GtkLinkButtonAccessible = _GtkLinkButtonAccessible
public typealias GtkLinkButtonAccessibleClass = _GtkLinkButtonAccessibleClass
public typealias GtkLinkButtonAccessiblePrivate = _GtkLinkButtonAccessiblePrivate
public typealias GtkListBoxAccessible = _GtkListBoxAccessible
public typealias GtkListBoxAccessibleClass = _GtkListBoxAccessibleClass
public typealias GtkListBoxAccessiblePrivate = _GtkListBoxAccessiblePrivate
public typealias GtkListBoxRowAccessible = _GtkListBoxRowAccessible
public typealias GtkListBoxRowAccessibleClass = _GtkListBoxRowAccessibleClass
public typealias GtkLockButtonAccessible = _GtkLockButtonAccessible
public typealias GtkLockButtonAccessibleClass = _GtkLockButtonAccessibleClass
public typealias GtkLockButtonAccessiblePrivate = _GtkLockButtonAccessiblePrivate
public typealias GtkMenuAccessible = _GtkMenuAccessible
public typealias GtkMenuAccessibleClass = _GtkMenuAccessibleClass
public typealias GtkMenuAccessiblePrivate = _GtkMenuAccessiblePrivate
public typealias GtkMenuButtonAccessible = _GtkMenuButtonAccessible
public typealias GtkMenuButtonAccessibleClass = _GtkMenuButtonAccessibleClass
public typealias GtkMenuButtonAccessiblePrivate = _GtkMenuButtonAccessiblePrivate
public typealias GtkMenuItemAccessiblePrivate = _GtkMenuItemAccessiblePrivate
public typealias GtkMenuShellAccessible = _GtkMenuShellAccessible
public typealias GtkMenuShellAccessibleClass = _GtkMenuShellAccessibleClass
public typealias GtkMenuShellAccessiblePrivate = _GtkMenuShellAccessiblePrivate
public typealias GtkNotebookAccessible = _GtkNotebookAccessible
public typealias GtkNotebookAccessibleClass = _GtkNotebookAccessibleClass
public typealias GtkNotebookAccessiblePrivate = _GtkNotebookAccessiblePrivate
public typealias GtkNotebookPageAccessible = _GtkNotebookPageAccessible
public typealias GtkNotebookPageAccessibleClass = _GtkNotebookPageAccessibleClass
public typealias GtkNotebookPageAccessiblePrivate = _GtkNotebookPageAccessiblePrivate
public typealias GtkPanedAccessible = _GtkPanedAccessible
public typealias GtkPanedAccessibleClass = _GtkPanedAccessibleClass
public typealias GtkPanedAccessiblePrivate = _GtkPanedAccessiblePrivate
public typealias GtkPopoverAccessible = _GtkPopoverAccessible
public typealias GtkPopoverAccessibleClass = _GtkPopoverAccessibleClass
public typealias GtkProgressBarAccessible = _GtkProgressBarAccessible
public typealias GtkProgressBarAccessibleClass = _GtkProgressBarAccessibleClass
public typealias GtkProgressBarAccessiblePrivate = _GtkProgressBarAccessiblePrivate
public typealias GtkRadioButtonAccessible = _GtkRadioButtonAccessible
public typealias GtkRadioButtonAccessibleClass = _GtkRadioButtonAccessibleClass
public typealias GtkRadioButtonAccessiblePrivate = _GtkRadioButtonAccessiblePrivate
public typealias GtkRadioMenuItemAccessible = _GtkRadioMenuItemAccessible
public typealias GtkRadioMenuItemAccessibleClass = _GtkRadioMenuItemAccessibleClass
public typealias GtkRadioMenuItemAccessiblePrivate = _GtkRadioMenuItemAccessiblePrivate
public typealias GtkRangeAccessible = _GtkRangeAccessible
public typealias GtkRangeAccessibleClass = _GtkRangeAccessibleClass
public typealias GtkRangeAccessiblePrivate = _GtkRangeAccessiblePrivate
public typealias GtkRendererCellAccessiblePrivate = _GtkRendererCellAccessiblePrivate
public typealias GtkScaleAccessible = _GtkScaleAccessible
public typealias GtkScaleAccessibleClass = _GtkScaleAccessibleClass
public typealias GtkScaleAccessiblePrivate = _GtkScaleAccessiblePrivate
public typealias GtkScaleButtonAccessible = _GtkScaleButtonAccessible
public typealias GtkScaleButtonAccessibleClass = _GtkScaleButtonAccessibleClass
public typealias GtkScaleButtonAccessiblePrivate = _GtkScaleButtonAccessiblePrivate
public typealias GtkScrolledWindowAccessible = _GtkScrolledWindowAccessible
public typealias GtkScrolledWindowAccessibleClass = _GtkScrolledWindowAccessibleClass
public typealias GtkScrolledWindowAccessiblePrivate = _GtkScrolledWindowAccessiblePrivate
public typealias GtkSpinButtonAccessible = _GtkSpinButtonAccessible
public typealias GtkSpinButtonAccessibleClass = _GtkSpinButtonAccessibleClass
public typealias GtkSpinButtonAccessiblePrivate = _GtkSpinButtonAccessiblePrivate
public typealias GtkSpinnerAccessible = _GtkSpinnerAccessible
public typealias GtkSpinnerAccessibleClass = _GtkSpinnerAccessibleClass
public typealias GtkSpinnerAccessiblePrivate = _GtkSpinnerAccessiblePrivate
public typealias GtkStatusbarAccessible = _GtkStatusbarAccessible
public typealias GtkStatusbarAccessibleClass = _GtkStatusbarAccessibleClass
public typealias GtkStatusbarAccessiblePrivate = _GtkStatusbarAccessiblePrivate
public typealias GtkSwitchAccessible = _GtkSwitchAccessible
public typealias GtkSwitchAccessibleClass = _GtkSwitchAccessibleClass
public typealias GtkSwitchAccessiblePrivate = _GtkSwitchAccessiblePrivate
public typealias GtkTextCellAccessible = _GtkTextCellAccessible
public typealias GtkTextCellAccessibleClass = _GtkTextCellAccessibleClass
public typealias GtkTextCellAccessiblePrivate = _GtkTextCellAccessiblePrivate
public typealias GtkTextViewAccessible = _GtkTextViewAccessible
public typealias GtkTextViewAccessibleClass = _GtkTextViewAccessibleClass
public typealias GtkTextViewAccessiblePrivate = _GtkTextViewAccessiblePrivate
public typealias GtkThemingEnginePrivate = _GtkThemingEnginePrivate
public typealias GtkToggleButtonAccessible = _GtkToggleButtonAccessible
public typealias GtkToggleButtonAccessibleClass = _GtkToggleButtonAccessibleClass
public typealias GtkToggleButtonAccessiblePrivate = _GtkToggleButtonAccessiblePrivate
public typealias GtkToplevelAccessible = _GtkToplevelAccessible
public typealias GtkToplevelAccessibleClass = _GtkToplevelAccessibleClass
public typealias GtkToplevelAccessiblePrivate = _GtkToplevelAccessiblePrivate
public typealias GtkTreeViewAccessible = _GtkTreeViewAccessible
public typealias GtkTreeViewAccessibleClass = _GtkTreeViewAccessibleClass
public typealias GtkTreeViewAccessiblePrivate = _GtkTreeViewAccessiblePrivate
public typealias GtkWidgetAccessiblePrivate = _GtkWidgetAccessiblePrivate
public typealias GtkWindowAccessible = _GtkWindowAccessible
public typealias GtkWindowAccessibleClass = _GtkWindowAccessibleClass
public typealias GtkWindowAccessiblePrivate = _GtkWindowAccessiblePrivate
// @convention(c) (UnsafeMutablePointer<_GtkWidget>?, UnsafeMutableRawPointer?) -> ()
//public typealias GtkCallback = CGtk.GtkCallback
| bsd-2-clause | dffde29a27c89752cc8508fbbcf3681a | 70.251852 | 89 | 0.901133 | 5.499714 | false | false | false | false |
SwiftKit/Cuckoo | Generator/Source/CuckooGeneratorFramework/Tokens/ThrowType.swift | 2 | 788 | //
// ThrowType.swift
// CuckooGeneratorFramework
//
// Created by Matyáš Kříž on 14/05/2019.
//
public enum ThrowType: CustomStringConvertible {
case throwing
case rethrowing
public init?(string: String) {
if string.trimmed.hasPrefix("throws") {
self = .throwing
} else if string.trimmed.hasPrefix("rethrows") {
self = .rethrowing
} else {
return nil
}
}
public var isThrowing: Bool {
return self == .throwing
}
public var isRethrowing: Bool {
return self == .rethrowing
}
public var description: String {
switch self {
case .throwing:
return "throws"
case .rethrowing:
return "rethrows"
}
}
}
| mit | 6bd4dddb722df888e72bfdfd22ed9725 | 19.605263 | 56 | 0.556833 | 4.474286 | false | false | false | false |
HYT2016/app | test/CustomSegmentContol.swift | 1 | 3582 | //
// CustomSegmentContol.swift
// test
//
// Created by Root HSZ HSU on 2017/7/28.
// Copyright © 2017年 Root HSZ HSU. All rights reserved.
//
import UIKit
class CustomSegmentContol: UIControl {
var buttons=[UIButton]()
var selector:UIView!
var selectedSegmentIndex = 0
// var frame: CGRect =
@IBInspectable
var borderWidth: CGFloat = 0{
didSet{
layer.borderWidth=borderWidth
}
}
@IBInspectable
var borderColor: UIColor = UIColor.clear{
didSet{
layer.borderColor=borderColor.cgColor
}
}
@IBInspectable
var commaSeparatedButtonTitles:String=""{
didSet{
updateView()
}
}
@IBInspectable
var textColor:UIColor = .lightGray{
didSet{
updateView()
}
}
@IBInspectable
var selectorColor: UIColor = .darkGray{
didSet{
updateView()
}
}
@IBInspectable
var selectorTextColor: UIColor = .white{
didSet{
updateView()
}
}
func updateView(){
buttons.removeAll()
subviews.forEach {$0.removeFromSuperview()}
let buttonTitles = commaSeparatedButtonTitles.components(separatedBy: ",")
// 不知道怎麼做
let selectorWidth = frame.width / (1*CGFloat(buttonTitles.count))
selector = UIView(frame: CGRect(x: 0, y: 0, width: selectorWidth, height: frame.height))
selector.layer.cornerRadius = frame.height/2
selector.backgroundColor = selectorColor
addSubview(selector)
for buttonsTitle in buttonTitles{
let button = UIButton(type: .system)
button.setTitle(buttonsTitle, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.addTarget(self, action: #selector(buttonTapped(button:)), for: .touchUpInside)
buttons.append(button)
}
buttons[0].setTitleColor(selectorColor, for: .normal)
let sv = UIStackView(arrangedSubviews: buttons)
sv.axis = .horizontal
sv.alignment = .fill
sv.distribution = .fillEqually
addSubview(sv)
sv.translatesAutoresizingMaskIntoConstraints=false
sv.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
sv.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive=true
sv.leftAnchor.constraint(equalTo: self.leftAnchor).isActive=true
sv.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
if self.selectedSegmentIndex==0{
self.buttons[0].setTitleColor(UIColor.init(red: 255/255, green: 221/255, blue: 0/255, alpha: 1), for: .normal)
}
}
override func draw(_ rect: CGRect) {
layer.cornerRadius=frame.height/2
// 使segment 不會超出框框外
updateView()
}
func buttonTapped(button:UIButton){
for (buttonIndex,btn) in buttons.enumerated(){
btn.setTitleColor(textColor, for: .normal)
if btn == button{
selectedSegmentIndex = buttonIndex
let selectorStartPosition = frame.width/CGFloat(buttons.count)*CGFloat(buttonIndex)
UIView.animate(withDuration: 0.3,animations: {
self.selector.frame.origin.x = selectorStartPosition
})
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
sendActions(for: .valueChanged)
}
}
| mit | 9d790bfdbff8776b8553062e53031e2f | 29.350427 | 119 | 0.600957 | 4.740988 | false | false | false | false |
tkremenek/swift | test/IRGen/prespecialized-metadata/struct-multi-conformance.swift | 12 | 4514 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -c %s -DBASE -emit-library -emit-module -module-name Base -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/Base.swiftmodule -o %t/%target-library-name(Base)
// RUN: %target-build-swift -c %s -DCONFORMANCE_1 -emit-library -emit-module -module-name Conformance1 -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/Conformance1.swiftmodule -o %t/%target-library-name(Conformance1) -lBase -I %t -L %t
// RUN: %target-build-swift -c %s -DCONFORMANCE_2 -emit-library -emit-module -module-name Conformance2 -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/Conformance2.swiftmodule -o %t/%target-library-name(Conformance2) -lBase -I %t -L %t
// RUN: %target-build-swift -c %s -DGENERIC -emit-library -emit-module -module-name Generic -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/Generic.swiftmodule -o %t/%target-library-name(Generic) -lBase -lConformance1 -I %t -L %t
// RUN: %target-build-swift -c %s -DERASE -emit-library -emit-module -module-name Erase -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/Erase.swiftmodule -o %t/%target-library-name(Erase) -lBase -lConformance2 -I %t -L %t
// RUN: %clang -c -v %target-cc-options -g -O0 -isysroot %sdk %S/Inputs/isPrespecialized.cpp -o %t/isPrespecialized.o -I %clang-include-dir -I %swift_src_root/include/ -I %llvm_src_root/include -I %llvm_obj_root/include -L %clang-include-dir/../lib/swift/macosx
// RUN: %target-build-swift %s %S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift %t/isPrespecialized.o -import-objc-header %S/Inputs/isPrespecialized.h -DMAIN -target %module-target-future -Xfrontend -prespecialize-generic-metadata -lBase -lConformance1 -lConformance2 -lGeneric -lErase -lc++ -I %t -L %t -L %clang-include-dir/../lib/swift/macosx -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
// UNSUPPORTED: remote_run
#if BASE
public struct K {
public init() {}
}
public protocol P {
var name: String { get }
}
#endif
#if CONFORMANCE_1
import Base
extension K : P {
public var name: String { "Conformance1" }
}
#endif
#if CONFORMANCE_2
import Base
extension K : P {
public var name: String { "Conformance2" }
}
#endif
#if GENERIC
import Base
import Conformance1
public struct G<T : P> {
public let t: T
public init(_ t: T) {
self.t = t
}
public var name: String {
t.name
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) {}
}
public func prespecialize() {
consume(G<K>.self)
}
#endif
#if ERASE
import Base
import Conformance2
public struct AnyP : P {
private class _BoxBase {
public var name: String {
fatalError()
}
public func visit<Visitor : PVisitor>(_ v: Visitor) {
fatalError()
}
}
private final class _Box<T : P> : _BoxBase {
private let t: T
init(_ t: T) {
self.t = t
}
override var name: String {
t.name
}
override func visit<Visitor : PVisitor>(_ v: Visitor) {
v.visit(t)
}
}
private let _box: _BoxBase
init<T : P>(_ t: T) {
self._box = _Box(t)
}
public var name: String {
_box.name
}
public func visit<Visitor : PVisitor>(_ v: Visitor) {
_box.visit(v)
}
}
public protocol PVisitor {
func visit<T : P>(_ t: T)
}
public func getKAsAnyP() -> AnyP {
AnyP(K())
}
#endif
#if MAIN
import Base
import Generic
import Conformance2
import Erase
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
func printTheName<T : P>(_ t: T, prespecialized: Bool) {
print(G(t).name)
assert(isCanonicalStaticallySpecializedGenericMetadata(ptr(to: G<T>.self)) == prespecialized)
}
struct Visitor : PVisitor {
func visit<T : P>(_ t: T) {
printTheName(t, prespecialized: false)
}
}
func doit() {
// CHECK: Conformance1
printTheName(K(), prespecialized: true)
// CHECK: Conformance2
getKAsAnyP().visit(Visitor())
}
#endif
| apache-2.0 | 5af721ef7971dd62bb2b05cd62a57f2d | 27.56962 | 375 | 0.666593 | 3.247482 | false | false | false | false |
brightdigit/speculid | frameworks/speculid/Controllers/SpeculidBuilder.swift | 1 | 4357 | import Foundation
// TODO: Separate into Files
public typealias ImageConversionPair = (image: AssetSpecificationProtocol, conversion: Result<ImageConversionTaskProtocol>?)
public typealias ImageConversionDictionary = [String: ImageConversionPair]
public extension SpeculidDocumentProtocol {
var sourceImageURL: URL {
url.deletingLastPathComponent().appendingPathComponent(specificationsFile.sourceImageRelativePath)
}
func destinationName(forImage image: AssetSpecificationProtocol) -> String {
if let filename = image.filename {
return filename
} else if let scale = image.scale {
if let size = image.size {
return
sourceImageURL.deletingPathExtension().appendingPathExtension("\(size.width.cleanValue)x\(size.height.cleanValue)@\(scale.cleanValue)x~\(image.idiom.rawValue).png").lastPathComponent
} else {
return sourceImageURL.deletingPathExtension().appendingPathExtension("\(scale.cleanValue)x~\(image.idiom.rawValue).png").lastPathComponent
}
} else {
return sourceImageURL.deletingPathExtension().appendingPathExtension("pdf").lastPathComponent
}
}
@available(*, unavailable)
func destinationURL(forImage image: AssetSpecificationProtocol) -> URL {
url.deletingLastPathComponent().appendingPathComponent(specificationsFile.assetDirectoryRelativePath, isDirectory: true).appendingPathComponent(destinationName(forImage: image))
}
func destinationURL(forFileName fileName: String) -> URL {
url.deletingLastPathComponent().appendingPathComponent(specificationsFile.assetDirectoryRelativePath, isDirectory: true).appendingPathComponent(fileName)
}
// destinationFileNames
}
public struct SpeculidBuilder: SpeculidBuilderProtocol {
public let tracker: AnalyticsTrackerProtocol?
public let configuration: SpeculidConfigurationProtocol
public let imageSpecificationBuilder: SpeculidImageSpecificationBuilderProtocol
public func build(document: SpeculidDocumentProtocol, callback: @escaping ((Error?) -> Void)) {
let imageSpecifications: [ImageSpecification]
let destinationFileNames = document.assetFile.document.images.map {
asset in
(asset, document.destinationName(forImage: asset))
}
do {
imageSpecifications = try destinationFileNames.map { (asset, fileName) -> ImageSpecification in
try self.imageSpecificationBuilder.imageSpecification(forURL: document.destinationURL(forFileName: fileName), withSpecifications: document.specificationsFile, andAsset: asset)
}
} catch {
return callback(error)
}
Application.current.service.exportImageAtURL(document.sourceImageURL, toSpecifications: imageSpecifications) {
error in
if let error = error {
callback(error)
return
}
let mode = self.configuration.mode
guard case let .command(args) = mode else {
callback(error)
return
}
guard case let .process(_, true) = args else {
callback(error)
return
}
let items = destinationFileNames.map(
AssetCatalogItem.init
)
Application.current.service.updateAssetCatalogAtURL(document.assetFile.url, withItems: items, callback)
}
}
}
public extension SpeculidBuilderProtocol {
@available(*, deprecated: 2.0.0)
func build(document: SpeculidDocumentProtocol) -> Error? {
var result: Error?
let semaphone = DispatchSemaphore(value: 0)
build(document: document) { error in
result = error
semaphone.signal()
}
semaphone.wait()
return result
}
func build(documents: [SpeculidDocumentProtocol]) -> Error? {
var errors = [Error]()
let group = DispatchGroup()
let errorQueue = DispatchQueue(label: "errors", qos: .default, attributes: .concurrent)
let buildQueue = DispatchQueue(label: "builder", qos: .userInitiated, attributes: .concurrent)
for document in documents {
group.enter()
buildQueue.async {
self.build(document: document) { errorOpt in
if let error = errorOpt {
errorQueue.async(group: nil, qos: .default, flags: .barrier) {
errors.append(error)
group.leave()
}
} else {
group.leave()
}
}
}
}
group.wait()
return ArrayError.error(for: errors)
}
}
| mit | 14fb89cb07247ce929fb28575d2f41f8 | 36.560345 | 192 | 0.710581 | 4.751363 | false | false | false | false |
MarceloOscarJose/DynamicTextField | DynamicTextField/DynamicField.swift | 1 | 1254 | //
// DynamicTextField.swift
// TrastornoBipolar
//
// Created by Marcelo Oscar José on 10/31/16.
// Copyright © 2016 Marcelo Oscar José. All rights reserved.
//
import UIKit
open class DynamicField {
private var registeredFields:[DynamicFieldDelegate] = []
private var fieldError: String?
public init() {
}
public func getFieldError() -> String {
return self.fieldError!
}
public func registerField(field: DynamicFieldDelegate, maxLength: Int?, entryType: String?, validationRules: [DynamicFieldRule]?, maskText: String?) {
if let max = maxLength {
field.setMaxLength(max: max)
}
if let entry = entryType {
field.setEntryType(entry: entry)
}
if let validations = validationRules {
field.setValidationRules(rules: validations)
}
if let mask = maskText {
field.setMask(mask: mask)
}
registeredFields.append(field)
}
public func validateFields() -> Bool{
for field in registeredFields {
if !field.isValid() {
self.fieldError = field.getFieldError()
return false
}
}
return true
}
}
| gpl-3.0 | 923e07e2c40e8fae78b0ce5492653382 | 23.057692 | 154 | 0.591527 | 4.389474 | false | false | false | false |
simonwhitehouse/ULIDSwift | ULID.playground/Contents.swift | 1 | 2271 | //: Playground - noun: a place where people can play
import UIKit
public extension Double {
/// Returns value between 0.0 and 1.0, inclusive.
public static var random: Double {
get {
return Double(arc4random()) / 0xFFFFFFFF
}
}
}
public extension String {
static func generateULID(timeStamp: Double? = nil) -> String {
return ULID.generateULID(timeStamp: timeStamp)
}
}
/// ULID
struct ULID {
let t: String
let r: String
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
static let encodingChars = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
static let encodedArray = encodingChars.characters.map { String($0) }
static let encodingLength: Double = Double(encodedArray.count)
/// random part of the ULID
static func encodeRandom(length: Int) -> String {
var str = ""
for _ in (0..<length).reversed() {
let rand = floor(encodingLength * Double.random)
str = encodedArray[Int(rand)] + str
}
return str
}
/// time stamp part of the ULID
static func encodeTime(time: Double, length: Int) -> String {
var chaingTime = time
var xstr = ""
for _ in (0..<length).reversed() {
let mod: Int = Int(chaingTime.truncatingRemainder(dividingBy: encodingLength))
xstr = encodedArray[mod] + xstr
chaingTime = (chaingTime - Double(mod)) / encodingLength
}
return xstr
}
static func generateULID(timeStamp: Double? = nil) -> String {
let now = timeStamp ?? (Date().timeIntervalSince1970)
return encodeTime(time: now, length: 10) + encodeRandom(length: 16)
}
init(timeStamp: Double? = nil) {
let now = timeStamp ?? (Date().timeIntervalSince1970)
self.t = ULID.encodeTime(time: now, length: 10)
self.r = ULID.encodeRandom(length: 16)
}
}
let a = String.generateULID(timeStamp: nil)
let b = String.generateULID(timeStamp: nil)
let x = ULID.generateULID()
let y = ULID.generateULID(timeStamp: 1469918176385)
let ulid = ULID(timeStamp: nil)
let ulidTime = ulid.t
let ulidRandom = ulid.r
| mit | c9439d5e790138ad926bd321e30c7c9d | 24.806818 | 90 | 0.602378 | 3.908778 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderSubscribeCommentsAction.swift | 1 | 2967 | /// Encapsulates a command to subscribe or unsubscribe to a posts comments.
final class ReaderSubscribeCommentsAction {
func execute(with post: ReaderPost,
context: NSManagedObjectContext,
followCommentsService: FollowCommentsService,
sourceViewController: UIViewController,
completion: (() -> Void)? = nil,
failure: ((Error?) -> Void)? = nil) {
let subscribing = !post.isSubscribedComments
followCommentsService.toggleSubscribed(post.isSubscribedComments, success: { subscribeSuccess in
followCommentsService.toggleNotificationSettings(subscribing, success: {
ReaderHelpers.dispatchToggleSubscribeCommentMessage(subscribing: subscribing, success: subscribeSuccess) { actionSuccess in
self.disableNotificationSettings(followCommentsService: followCommentsService)
Self.trackNotificationUndo(post: post, sourceViewController: sourceViewController)
}
completion?()
}, failure: { error in
DDLogError("Error toggling comment notification status: \(error.debugDescription)")
ReaderHelpers.dispatchToggleCommentNotificationMessage(subscribing: false, success: false)
failure?(error)
})
}, failure: { error in
DDLogError("Error toggling comment subscription status: \(error.debugDescription)")
ReaderHelpers.dispatchToggleSubscribeCommentErrorMessage(subscribing: subscribing)
failure?(error)
})
}
private func disableNotificationSettings(followCommentsService: FollowCommentsService) {
followCommentsService.toggleNotificationSettings(false, success: {
ReaderHelpers.dispatchToggleCommentNotificationMessage(subscribing: false, success: true)
}, failure: { error in
DDLogError("Error toggling comment notification status: \(error.debugDescription)")
ReaderHelpers.dispatchToggleCommentNotificationMessage(subscribing: false, success: false)
})
}
private static func trackNotificationUndo(post: ReaderPost, sourceViewController: UIViewController) {
var properties = [String: Any]()
properties["notifications_enabled"] = false
properties[WPAppAnalyticsKeyBlogID] = post.siteID
properties[WPAppAnalyticsKeySource] = sourceForTrackingEvents(sourceViewController: sourceViewController)
WPAnalytics.trackReader(.readerToggleCommentNotifications, properties: properties)
}
private static func sourceForTrackingEvents(sourceViewController: UIViewController) -> String {
if sourceViewController is ReaderDetailViewController {
return "reader_post_details_menu"
} else if sourceViewController is ReaderStreamViewController {
return "reader"
}
return "unknown"
}
}
| gpl-2.0 | 80968a8bab702dc2c484c3830008b1ac | 51.052632 | 139 | 0.691945 | 6.220126 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/Networking/Remote Objects/RemotePublicizeService.swift | 1 | 408 | import Foundation
@objc public class RemotePublicizeService : NSObject
{
public var connectURL = ""
public var detail = ""
public var icon = ""
public var jetpackSupport = false
public var jetpackModuleRequired = ""
public var label = ""
public var multipleExternalUserIDSupport = false
public var order: NSNumber = 0
public var serviceID = ""
public var type = ""
}
| gpl-2.0 | 70e9987e8395d2018fa012dcec46be77 | 26.2 | 52 | 0.678922 | 4.636364 | false | false | false | false |
coodly/laughing-adventure | Source/UI/MultiEntryCell.swift | 1 | 1637 | /*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
open class MultiEntryCell: UITableViewCell, EntryValidated {
public var validators = [UITextField: InputValidation]()
@IBOutlet public var entryFields: [UITextField]!
private lazy var sorted: [UITextField] = {
return self.entryFields.sorted(by: {
one, two in
if one.frame.minX == two.frame.minX {
return one.frame.minY < two.frame.minY
} else {
return one.frame.minX < two.frame.minX
}
})
}()
func firstField() -> UITextField? {
return sorted.first
}
func nextEntry(after field: UITextField) -> UITextField? {
guard let index = sorted.index(of: field) else {
return nil
}
guard index < sorted.count - 1 else {
return nil
}
let field = sorted[index + 1]
if field.isUserInteractionEnabled {
return field
}
return nextEntry(after: field)
}
}
| apache-2.0 | 9850fb07e486218415c26d79484fae0d | 28.232143 | 75 | 0.60843 | 4.572626 | false | false | false | false |
imkerberos/ReactiveCocoa | ReactiveCocoaTests/Swift/ActionSpec.swift | 10 | 5311 | //
// ActionSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-12-11.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Result
import Nimble
import Quick
import ReactiveCocoa
class ActionSpec: QuickSpec {
override func spec() {
describe("Action") {
var action: Action<Int, String, NSError>!
var enabled: MutableProperty<Bool>!
var executionCount = 0
var values: [String] = []
var errors: [NSError] = []
var scheduler: TestScheduler!
let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil)
beforeEach {
executionCount = 0
values = []
errors = []
enabled = MutableProperty(false)
scheduler = TestScheduler()
action = Action(enabledIf: enabled) { number in
return SignalProducer { observer, disposable in
executionCount++
if number % 2 == 0 {
sendNext(observer, "\(number)")
sendNext(observer, "\(number)\(number)")
scheduler.schedule {
sendCompleted(observer)
}
} else {
scheduler.schedule {
sendError(observer, testError)
}
}
}
}
action.values.observe(next: { values.append($0) })
action.errors.observe(next: { errors.append($0) })
}
it("should be disabled and not executing after initialization") {
expect(action.enabled.value).to(beFalsy())
expect(action.executing.value).to(beFalsy())
}
it("should error if executed while disabled") {
var receivedError: ActionError<NSError>?
action.apply(0).start(error: {
receivedError = $0
})
expect(receivedError).notTo(beNil())
if let error = receivedError {
let expectedError = ActionError<NSError>.NotEnabled
expect(error == expectedError).to(beTruthy())
}
}
it("should enable and disable based on the given property") {
enabled.value = true
expect(action.enabled.value).to(beTruthy())
expect(action.executing.value).to(beFalsy())
enabled.value = false
expect(action.enabled.value).to(beFalsy())
expect(action.executing.value).to(beFalsy())
}
describe("execution") {
beforeEach {
enabled.value = true
}
it("should execute successfully") {
var receivedValue: String?
action.apply(0).start(next: {
receivedValue = $0
})
expect(executionCount).to(equal(1))
expect(action.executing.value).to(beTruthy())
expect(action.enabled.value).to(beFalsy())
expect(receivedValue).to(equal("00"))
expect(values).to(equal([ "0", "00" ]))
expect(errors).to(equal([]))
scheduler.run()
expect(action.executing.value).to(beFalsy())
expect(action.enabled.value).to(beTruthy())
expect(values).to(equal([ "0", "00" ]))
expect(errors).to(equal([]))
}
it("should execute with an error") {
var receivedError: ActionError<NSError>?
action.apply(1).start(error: {
receivedError = $0
})
expect(executionCount).to(equal(1))
expect(action.executing.value).to(beTruthy())
expect(action.enabled.value).to(beFalsy())
scheduler.run()
expect(action.executing.value).to(beFalsy())
expect(action.enabled.value).to(beTruthy())
expect(receivedError).notTo(beNil())
if let error = receivedError {
let expectedError = ActionError<NSError>.ProducerError(testError)
expect(error == expectedError).to(beTruthy())
}
expect(values).to(equal([]))
expect(errors).to(equal([ testError ]))
}
}
}
describe("CocoaAction") {
var action: Action<Int, Int, NoError>!
var cocoaAction: CocoaAction!
beforeEach {
action = Action { value in SignalProducer(value: value + 1) }
expect(action.enabled.value).to(beTruthy())
cocoaAction = CocoaAction(action, input: 0)
expect(cocoaAction.enabled).toEventually(beTruthy())
}
#if os(OSX)
it("should be compatible with AppKit") {
let control = NSControl(frame: NSZeroRect)
control.target = cocoaAction
control.action = CocoaAction.selector
control.performClick(nil)
}
#elseif os(iOS)
it("should be compatible with UIKit") {
let control = UIControl(frame: CGRectZero)
control.addTarget(cocoaAction, action: CocoaAction.selector, forControlEvents: UIControlEvents.TouchDown)
control.sendActionsForControlEvents(UIControlEvents.TouchDown)
}
#endif
it("should generate KVO notifications for enabled") {
var values: [Bool] = []
cocoaAction
.rac_valuesForKeyPath("enabled", observer: nil)
.toSignalProducer()
|> map { $0! as! Bool }
|> start(Event.sink(next: { values.append($0) }))
expect(values).to(equal([ true ]))
let result = action.apply(0) |> first
expect(result?.value).to(equal(1))
expect(values).toEventually(equal([ true, false, true ]))
}
it("should generate KVO notifications for executing") {
var values: [Bool] = []
cocoaAction
.rac_valuesForKeyPath("executing", observer: nil)
.toSignalProducer()
|> map { $0! as! Bool }
|> start(Event.sink(next: { values.append($0) }))
expect(values).to(equal([ false ]))
let result = action.apply(0) |> first
expect(result?.value).to(equal(1))
expect(values).toEventually(equal([ false, true, false ]))
}
}
}
}
| mit | 775527b98be14cac0d6026d8c4854131 | 25.555 | 110 | 0.642629 | 3.660234 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/search-a-2d-matrix-ii.swift | 2 | 1051 | /**
* https://leetcode.com/problems/search-a-2d-matrix-ii/
*
*
*/
// Date: Tue Feb 23 08:21:00 PST 2021
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
if matrix.count == 0 || matrix[0].count == 0 { return false }
var row = matrix.count - 1
var col = 0
while col < matrix[0].count, row >= 0 {
if matrix[row][col] == target { return true }
if matrix[row][col] > target { row -= 1 }
else { col += 1 }
}
return false
}
}
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
if matrix.count == 0 || matrix[0].count == 0 { return false }
var row = 0
var col = matrix[0].count - 1
while row < matrix.count, col >= 0 {
if matrix[row][col] == target {
return true
} else if matrix[row][col] > target {
col -= 1
} else {
row += 1
}
}
return false
}
}
| mit | 00ecc4b988daa3c5c3c0fca9e9cae41f | 27.405405 | 69 | 0.468126 | 3.780576 | false | false | false | false |
BasThomas/MacOSX | SpeakLine/SpeakLine/MainWindowController.swift | 1 | 4818 | //
// MainWindowController.swift
// SpeakLine
//
// Created by Bas Broek on 29/04/15.
// Copyright (c) 2015 Bas Broek. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController, NSSpeechSynthesizerDelegate, NSWindowDelegate, NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate
{
@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var speakButton: NSButton!
@IBOutlet weak var stopButton: NSButton!
@IBOutlet weak var tableView: NSTableView!
let preferenceManager = PreferenceManager()
let speechSynth = NSSpeechSynthesizer()
let voices = NSSpeechSynthesizer.availableVoices() as! [String]
var isStarted = false
{
didSet
{
self.updateButtons()
self.updateTextField()
}
}
override var windowNibName: String
{
return "MainWindowController"
}
override func windowDidLoad()
{
super.windowDidLoad()
self.updateButtons()
self.speechSynth.delegate = self
let defaultVoice = self.preferenceManager.activeVoice!
if let defaultRow = find(self.voices, defaultVoice)
{
let indices = NSIndexSet(index: defaultRow)
self.tableView.selectRowIndexes(indices, byExtendingSelection: false)
self.tableView.scrollRowToVisible(defaultRow)
}
self.textField.stringValue = self.preferenceManager.activeText!
}
func updateButtons()
{
if self.isStarted
{
self.speakButton.enabled = false
self.stopButton.enabled = true
}
else
{
self.speakButton.enabled = true
self.stopButton.enabled = false
}
}
func updateTextField()
{
if self.isStarted
{
self.textField.enabled = false
}
else
{
self.textField.enabled = true
self.textField.becomeFirstResponder()
}
}
func voiceNameForIdentifier(identifier: String) -> String?
{
if let attributes = NSSpeechSynthesizer.attributesForVoice(identifier)
{
return attributes[NSVoiceName] as? String
}
return nil
}
// MARK: - NSSpeechSynthesizerDelegate
func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool)
{
self.isStarted = false
self.textField.attributedStringValue = NSMutableAttributedString(string: self.textField.stringValue)
self.updateTextField()
}
func speechSynthesizer(sender: NSSpeechSynthesizer, willSpeakWord characterRange: NSRange, ofString string: String)
{
let range = characterRange
let theString = self.textField.stringValue
let attributedString = NSMutableAttributedString(string: theString)
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.greenColor(), range: characterRange)
self.textField.attributedStringValue = attributedString
}
// MARK: - NSWindowDelegate
func windowShouldClose(sender: AnyObject) -> Bool
{
return !self.isStarted
}
// MARK: - NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return self.voices.count
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject?
{
let voice = self.voices[row]
let voiceName = self.voiceNameForIdentifier(voice)
return voiceName
}
// MARK: - NSTableViewDelegate
func tableViewSelectionDidChange(notification: NSNotification)
{
let row = self.tableView.selectedRow
if row == -1
{
self.speechSynth.setVoice(nil)
return
}
let voice = self.voices[row]
self.speechSynth.setVoice(voice)
self.preferenceManager.activeVoice = voice
}
// MARK: - NSTextFieldDelegate
override func controlTextDidChange(obj: NSNotification)
{
self.preferenceManager.activeText = self.textField.stringValue
}
// MARK: - Action methods
@IBAction func speakIt(sender: AnyObject)
{
let string = self.textField.stringValue
if string.isEmpty
{
println("string from \(self.textField) is empty.")
}
else
{
self.speechSynth.startSpeakingString(string)
self.isStarted = true
}
}
@IBAction func stopIt(sender: AnyObject)
{
self.speechSynth.stopSpeaking()
}
} | mit | 349d68884370fab10e338648d47b66f9 | 26.537143 | 158 | 0.619137 | 5.371237 | false | false | false | false |
zzeleznick/piazza-clone | Pizzazz/Pizzazz/AppDelegate.swift | 1 | 2881 | //
// AppDelegate.swift
// Pizzazz
//
// Created by Zach Zeleznick on 5/5/16.
// Copyright © 2016 zzeleznick. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
let nav = UINavigationController()
nav.navigationBar.barTintColor = UIColor(rgb: 0x3e7aab)
nav.navigationBar.tintColor = UIColor.white
let navigationBarAppearace = UINavigationBar.appearance()
let font = UIFont(name: "Helvetica-Bold", size: 16)
if let font = font {
navigationBarAppearace.titleTextAttributes = [NSFontAttributeName : font, NSForegroundColorAttributeName : UIColor.white];
}
let mainViewController = HomeViewController()
nav.viewControllers = [mainViewController]
self.window?.rootViewController = nav
self.window?.makeKeyAndVisible()
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:.
}
}
| mit | de544c7f978602dcbce774e57c30f4e3 | 47.813559 | 285 | 0.736111 | 5.517241 | false | false | false | false |
dillonmo/AKImageCropperView | AKImageCropperViewExample/HomeViewController.swift | 3 | 1717 | //
// HomeViewController.swift
//
// Created by Artem Krachulov.
// Copyright (c) 2016 Artem Krachulov. All rights reserved.
// Website: http://www.artemkrachulov.com/
//
import UIKit
final class HomeViewController: UIViewController {
// MARK: - Connections:
// MARK: -- Actions
@IBAction func galleryAction() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
// MARK: - Life Cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = false
}
}
// MARK: - UIImagePickerControllerDelegate
extension HomeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let cropperViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "cropperViewController") as! CropperViewController
cropperViewController.image = pickedImage
picker.pushViewController(cropperViewController, animated: true)
}
}
}
| mit | c3ba29fd7f3bae8c1c79c8024cc895d9 | 31.396226 | 172 | 0.677344 | 6.198556 | false | false | false | false |
arnaudbenard/npm-stats | my-npm/ModulesTableViewController.swift | 2 | 5168 | //
// ModulesTableViewController.swift
// my-npm
//
// Created by Arnaud Benard on 28/07/2015.
// Copyright (c) 2015 Arnaud Benard. All rights reserved.
//
import UIKit
import Alamofire
class ModulesTableViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewObject: UITableView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBAction func addModule(sender: UIBarButtonItem) {
promptAddModuleModal()
}
var moduleLabels: [String] = [String]()
var moduleDetails: [String] = [String]()
let npm = npmAPI()
let userSettings = UserSettings()
override func viewDidLoad() {
super.viewDidLoad()
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.startAnimating()
var moduleNames = userSettings.modules as! [String]
npm.fetchModules(moduleNames, period: .LastDay) { response, _ in
if let res = response {
self.appendTableData(res)
self.tableViewObject.reloadData()
self.activityIndicatorView.stopAnimating()
}
}
}
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Modules"
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return moduleLabels.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.detailTextLabel?.textColor = UIColor.grayColor()
if moduleLabels.count > indexPath.row {
cell.textLabel?.text = moduleLabels[indexPath.row]
}
if moduleDetails.count > indexPath.row {
cell.detailTextLabel?.text = "Last day: \(moduleDetails[indexPath.row]) downloads"
}
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
let label = moduleLabels[indexPath.row]
// remove the deleted item from the model
self.userSettings.removeModule(label)
self.moduleLabels.removeAtIndex(indexPath.row)
self.moduleDetails.removeAtIndex(indexPath.row)
// remove the deleted item from the `UITableView`
self.tableViewObject.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destinationViewController = segue.destinationViewController as? ModuleDetailViewController {
if let cell = sender as? UITableViewCell, text = cell.textLabel?.text {
// set title of the detail view to module name
destinationViewController.moduleName = text
}
}
}
private func appendTableData(response: NSDictionary) {
for (name, data) in response {
if let dataDict = data as? Dictionary<String, AnyObject> {
self.appendRowData(dataDict)
}
}
}
private func appendRowData(data: Dictionary<String, AnyObject>) {
if let downloads = data["downloads"] as? Double, label = data["package"] as? String {
self.moduleLabels.append(label)
self.moduleDetails.append(downloads.toDecimalStyle)
}
}
private func promptAddModuleModal() {
let alertController = UIAlertController(title: "Add Module", message: "Enter the name of the module you would like to add to your list.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Add", style: .Default) { (action) in
let nameTextField = alertController.textFields![0] as! UITextField
self.addModuleToSettings(nameTextField.text)
}
alertController.addAction(OKAction)
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Name"
}
self.presentViewController(alertController, animated: true) {}
}
private func addModuleToSettings(name: String) {
npm.fetchModule(name, period: .LastDay) { response, _ in
if let module = response as? Dictionary<String, AnyObject> {
self.appendRowData(module)
self.userSettings.addModule(name)
self.tableViewObject.reloadData()
println("Added \(self.userSettings.modules.description)")
}
}
}
}
| mit | acb9836cf25ec0e5dafcc7a7b5e7f5d1 | 37 | 169 | 0.645898 | 5.383333 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Event Details/EventDetailsViewController.swift | 1 | 9113 | //
// EventDetailsViewController.swift
// ScoreReporter
//
// Created by Bradley Smith on 9/17/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import UIKit
import Anchorage
import KVOController
import ScoreReporterCore
typealias TransitionCoordinatorBlock = (UIViewControllerTransitionCoordinatorContext) -> Void
class EventDetailsViewController: UIViewController, MessageDisplayable {
fileprivate let viewModel: EventDetailsViewModel
fileprivate let dataSource: EventDetailsDataSource
fileprivate let tableView = UITableView(frame: .zero, style: .grouped)
fileprivate let headerView = EventDetailsHeaderView(frame: .zero)
fileprivate var favoriteButton: UIBarButtonItem?
fileprivate var unfavoriteButton: UIBarButtonItem?
override var topLayoutGuide: UILayoutSupport {
configureMessageView(super.topLayoutGuide)
return messageLayoutGuide
}
init(viewModel: EventDetailsViewModel, dataSource: EventDetailsDataSource) {
self.viewModel = viewModel
self.dataSource = dataSource
super.init(nibName: nil, bundle: nil)
title = "Event Details"
let favoriteImage = UIImage(named: "icn-star")
favoriteButton = UIBarButtonItem(image: favoriteImage, style: .plain, target: self, action: #selector(favoriteButtonTapped))
let unfavoriteImage = UIImage(named: "icn-star-selected")
unfavoriteButton = UIBarButtonItem(image: unfavoriteImage, style: .plain, target: self, action: #selector(unfavoriteButtonTapped))
navigationItem.rightBarButtonItem = dataSource.event.bookmarked.boolValue ? unfavoriteButton : favoriteButton
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func loadView() {
view = UIView()
view.backgroundColor = UIColor.white
configureViews()
configureLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource.refreshBlock = { [weak self] in
self?.tableView.reloadData()
}
viewModel.downloadEventDetails()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !tableView.bounds.width.isEqual(to: headerView.bounds.width) {
let size = headerView.size(with: tableView.bounds.width)
headerView.frame = CGRect(origin: .zero, size: size)
tableView.tableHeaderView = headerView
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
headerView.resetBlurAnimation()
deselectRows(in: tableView, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
configureObservers()
}
}
// MARK: - Private
private extension EventDetailsViewController {
func configureViews() {
tableView.dataSource = self
tableView.delegate = self
tableView.register(headerFooterClass: SectionHeaderView.self)
tableView.register(cellClass: GroupCell.self)
tableView.register(cellClass: GameCell.self)
tableView.backgroundColor = UIColor.white
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
view.addSubview(tableView)
headerView.configure(with: dataSource.event)
headerView.delegate = self
}
func configureLayout() {
tableView.edgeAnchors == edgeAnchors
}
func configureObservers() {
kvoController.observe(viewModel, keyPath: #keyPath(EventDetailsViewModel.loading)) { [weak self] (loading: Bool) in
if loading {
self?.display(message: "Loading...", animated: true)
}
else {
self?.hide(animated: true)
}
}
kvoController.observe(viewModel, keyPath: #keyPath(EventDetailsViewModel.error)) { [weak self] (error: NSError) in
self?.display(error: error, animated: true)
}
}
@objc func favoriteButtonTapped() {
navigationItem.setRightBarButton(unfavoriteButton, animated: true)
let event = dataSource.event
event.bookmarked = true
do {
try event.managedObjectContext?.save()
}
catch let error {
print("Error: \(error)")
}
}
@objc func unfavoriteButtonTapped() {
navigationItem.setRightBarButton(favoriteButton, animated: true)
let event = dataSource.event
event.bookmarked = false
do {
try event.managedObjectContext?.save()
}
catch let error {
print("Error: \(error)")
}
}
}
// MARK: - UITableViewDataSource
extension EventDetailsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = dataSource.item(at: indexPath) else {
return UITableViewCell()
}
switch item {
case .division(let group):
let groupViewModel = GroupViewModel(group: group)
let cell = tableView.dequeueCell(for: indexPath) as GroupCell
cell.configure(with: groupViewModel)
cell.separatorHidden = indexPath.item == 0
return cell
case .activeGame(let game):
let gameViewModel = GameViewModel(game: game, state: .full)
let cell = tableView.dequeueCell(for: indexPath) as GameCell
cell.configure(with: gameViewModel)
cell.separatorHidden = indexPath.item == 0
return cell
}
}
}
// MARK: - UITableViewDelegate
extension EventDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = dataSource.item(at: indexPath) else {
return
}
switch item {
case .division(let group):
let groupDetailsDataSource = GroupDetailsDataSource(group: group)
let groupDetailsViewController = GroupDetailsViewController(dataSource: groupDetailsDataSource)
navigationController?.pushViewController(groupDetailsViewController, animated: true)
case .activeGame(let game):
tableView.deselectRow(at: indexPath, animated: true)
let gameDetailsViewModel = GameDetailsViewModel(game: game)
let gameDetailsViewController = GameDetailsViewController(viewModel: gameDetailsViewModel)
DispatchQueue.main.async {
self.present(gameDetailsViewController, animated: true, completion: nil)
}
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let title = dataSource.headerTitle(for: section) else {
return nil
}
let headerView = tableView.dequeueHeaderFooterView() as SectionHeaderView
headerView.configure(with: title)
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let _ = dataSource.headerTitle(for: section) else {
return 0.0001
}
return SectionHeaderView.height
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0001
}
}
// MARK: - UIScrollViewDelegate
extension EventDetailsViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y / -50.0
let value = min(1.0, max(0.0, offset))
headerView.fractionComplete = value
headerView.verticalOffset = scrollView.contentOffset.y
}
}
// MARK: - EventDetailsHeaderViewDelegate
extension EventDetailsViewController: EventDetailsHeaderViewDelegate {
func didSelectMaps(in headerView: EventDetailsHeaderView) {
guard var urlComponenets = URLComponents(string: "http://maps.apple.com/"),
let address = dataSource.event.searchSubtitle else {
return
}
urlComponenets.queryItems = [URLQueryItem(name: "q", value: address)]
if let url = urlComponenets.url, UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
| mit | 1308d841e8b0aaab86a60fed041cbdbf | 31.776978 | 138 | 0.660009 | 5.282319 | false | false | false | false |
Kiandr/CrackingCodingInterview | Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Sources/ApplyConcurrently.swift | 1 | 789 | //
// ApplyConcurrently.swift
//
// Created by Matthew Carroll on 8/10/16.
// Copyright © 2016 Matthew Carroll. All rights reserved.
//
import Foundation
public struct ApplyConcurrently {
let iterations: Int
private let maxConcurrentOperations: Int
public init(iterations: Int, maxConcurrentOperations: Int = OperationQueue.defaultMaxConcurrentOperationCount) {
self.iterations = iterations
self.maxConcurrentOperations = maxConcurrentOperations
}
public func apply(f: @escaping () -> ()) {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = maxConcurrentOperations
for _ in 0..<iterations {
queue.addOperation(f)
}
queue.waitUntilAllOperationsAreFinished()
}
}
| mit | b78d9e3faae21943eccf30ee160f21e3 | 27.142857 | 116 | 0.681472 | 5.051282 | false | false | false | false |
nghialv/Sapporo | Sapporo/Sources/Core/Sapporo.swift | 1 | 9563 | //
// Sapporo.swift
// Example
//
// Created by Le VanNghia on 6/29/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import UIKit
final public class Sapporo: NSObject {
private let bumpTracker: SABumpTracker = .init()
private var offscreenCells: [String: SACell] = [:]
public private(set) var sections: [SASection] = []
public let collectionView: UICollectionView
public weak var delegate: SapporoDelegate?
public var loadmoreHandler: (() -> Void)?
public var loadmoreEnabled = false
public var loadmoreDistanceThreshold: CGFloat = 50
public var willBumpHandler: ((Int) -> Void)?
public var sectionsCount: Int {
return sections.count
}
public subscript<T: RawRepresentable & SASectionIndexType>(index: T) -> SASection {
get {
return self[index.rawValue]
}
set {
self[index.rawValue] = newValue
}
}
public subscript(index: Int) -> SASection {
get {
return sections[index]
}
set {
setupSections([newValue], fromIndex: index)
sections[index] = newValue
}
}
public subscript(indexPath: IndexPath) -> SACellModel? {
return self[indexPath.section][indexPath.row]
}
public func getSection(_ index: Int) -> SASection? {
return sections.get(index)
}
public func getSection<T: RawRepresentable & SASectionIndexType>(_ index: T) -> SASection? {
return getSection(index.rawValue)
}
public init(collectionView: UICollectionView) {
self.collectionView = collectionView
super.init()
collectionView.dataSource = self
collectionView.delegate = self
}
deinit {
collectionView.dataSource = nil
collectionView.delegate = nil
}
@discardableResult
public func bump() -> Self {
willBumpHandler?(sectionsCount)
let changedCount = sections.reduce(0) { $0 + ($1.changed ? 1 : 0) }
if changedCount == 0 {
switch bumpTracker.getSapporoBumpType() {
case .reload:
collectionView.reloadData()
case let .insert(indexSet):
collectionView.insertSections(indexSet)
case let .delete(indexSet):
collectionView.deleteSections(indexSet)
case let .move(from, to):
collectionView.moveSection(from, toSection: to)
}
} else {
collectionView.reloadData()
sections.forEach { $0.didReloadCollectionView() }
}
bumpTracker.didBump()
return self
}
}
// MARK - SACellModelDelegate, SASectionDelegate
extension Sapporo: SACellModelDelegate, SASectionDelegate {
func bumpMe(_ type: ItemBumpType) {
switch type {
case .reload(let indexPath):
collectionView.reloadItems(at: [indexPath])
}
}
func bumpMe(_ type: SectionBumpType) {
willBumpHandler?(sectionsCount)
switch type {
case .reload(let indexset):
collectionView.reloadSections(indexset)
case .insert(let indexPaths):
collectionView.insertItems(at: indexPaths)
case .move(let ori, let new):
collectionView.moveItem(at: ori, to: new)
case .delete(let indexPaths):
collectionView.deleteItems(at: indexPaths)
}
}
func getOffscreenCell(_ identifier: String) -> SACell? {
if let cell = offscreenCells[identifier] {
return cell
}
guard let cell = UINib(nibName: identifier, bundle: nil).instantiate(withOwner: nil, options: nil).first as? SACell else {
return nil
}
offscreenCells[identifier] = cell
return cell
}
func deselectItem(_ indexPath: IndexPath, animated: Bool) {
collectionView.deselectItem(at: indexPath, animated: animated)
}
}
// MARK - Public methods
public extension Sapporo {
// Reset
@discardableResult
func reset<T: RawRepresentable & SASectionIndexType>(_ listType: T.Type) -> Self {
let sections = (0..<listType.count).map { _ in SASection() }
return reset(sections)
}
@discardableResult
func reset() -> Self {
return reset([])
}
@discardableResult
func reset(_ section: SASection) -> Self {
return reset([section])
}
@discardableResult
func reset(_ sections: [SASection]) -> Self {
setupSections(sections, fromIndex: 0)
self.sections = sections
bumpTracker.didReset()
return self
}
// Append
@discardableResult
func append(_ section: SASection) -> Self {
return append([section])
}
@discardableResult
func append(_ sections: [SASection]) -> Self {
return insert(sections, atIndex: sectionsCount)
}
// Insert
@discardableResult
func insert(_ section: SASection, atIndex index: Int) -> Self {
return insert([section], atIndex: index)
}
@discardableResult
func insert(_ sections: [SASection], atIndex index: Int) -> Self {
guard sections.isNotEmpty else {
return self
}
let sIndex = min(max(index, 0), sectionsCount)
setupSections(sections, fromIndex: sIndex)
let r = self.sections.insert(sections, atIndex: sIndex)
bumpTracker.didInsert(Array(r))
return self
}
@discardableResult
func insertBeforeLast(_ section: SASection) -> Self {
return insertBeforeLast([section])
}
@discardableResult
func insertBeforeLast(_ sections: [SASection]) -> Self {
let index = max(sections.count - 1, 0)
return insert(sections, atIndex: index)
}
// Remove
@discardableResult
func remove(_ index: Int) -> Self {
return remove(indexes: [index])
}
@discardableResult
func remove(_ range: CountableRange<Int>) -> Self {
let indexes = Array(range)
return remove(indexes: indexes)
}
@discardableResult
func remove(_ range: CountableClosedRange<Int>) -> Self {
let indexes = Array(range)
return remove(indexes: indexes)
}
@discardableResult
func remove(indexes: [Int]) -> Self {
guard indexes.isNotEmpty else {
return self
}
let sortedIndexes = indexes
.sorted(by: <)
.filter { $0 >= 0 && $0 < self.sectionsCount }
var remainSections: [SASection] = []
var i = 0
for j in 0..<sectionsCount {
if let k = sortedIndexes.get(i) , k == j {
i += 1
} else {
remainSections.append(sections[j])
}
}
sections = remainSections
setupSections(sections, fromIndex: 0)
bumpTracker.didRemove(sortedIndexes)
return self
}
@discardableResult
func removeLast() -> Self {
let index = sectionsCount - 1
guard index >= 0 else {
return self
}
return remove(index)
}
@discardableResult
func remove(_ section: SASection) -> Self {
let index = section.index
guard index >= 0 && index < sectionsCount else {
return self
}
return remove(index)
}
func removeAll() -> Self {
return reset()
}
// Move
@discardableResult
func move(_ from: Int, to: Int) -> Self {
sections.move(fromIndex: from, toIndex: to)
setupSections([sections[from]], fromIndex: from)
setupSections([sections[to]], fromIndex: to)
bumpTracker.didMove(from, to: to)
return self
}
}
// MARK - Layout
public extension Sapporo {
public func setLayout(_ layout: UICollectionViewLayout) {
collectionView.collectionViewLayout = layout
}
public func setLayout(_ layout: UICollectionViewLayout, animated: Bool) {
collectionView.setCollectionViewLayout(layout, animated: animated)
}
public func setLayout(_ layout: UICollectionViewLayout, animated: Bool, completion: ((Bool) -> Void)? = nil) {
collectionView.setCollectionViewLayout(layout, animated: animated, completion: completion)
}
}
// MARK - Utilities
public extension Sapporo {
var isEmpty: Bool {
return sections.isEmpty
}
var isNotEmpty: Bool {
return !isEmpty
}
var isFlowLayout: Bool {
return collectionView.collectionViewLayout is SAFlowLayout
}
var direction: UICollectionViewScrollDirection {
let layout = collectionView.collectionViewLayout as? SAFlowLayout
return layout?.scrollDirection ?? .vertical
}
func cellForRow(at indexPath: IndexPath) -> SACell? {
return collectionView.cellForItem(at: indexPath) as? SACell
}
}
// MARK - Private methods
private extension Sapporo {
func setupSections(_ sections: [SASection], fromIndex start: Int) {
var start = start
sections.forEach {
$0.setup(start, delegate: self)
start += 1
}
}
}
| mit | 0d7816d7108115e005f6f0e7a615ff5e | 25.787115 | 130 | 0.578584 | 4.919239 | false | false | false | false |
joalbright/Gameboard | Gameboards.playground/Sources/Core/Operators.swift | 1 | 1674 | import UIKit
public func * (lhs: CGFloat, rhs: Int) -> CGFloat {
return lhs * CGFloat(rhs)
}
public func * (lhs: Int, rhs: CGFloat) -> CGFloat {
return CGFloat(lhs) * rhs
}
public func / (lhs: CGFloat, rhs: Int) -> CGFloat {
return lhs / CGFloat(rhs)
}
public func / (lhs: Int, rhs: CGFloat) -> CGFloat {
return CGFloat(lhs) / rhs
}
public func + (lhs: CGFloat, rhs: Int) -> CGFloat {
return lhs + CGFloat(rhs)
}
public func + (lhs: Int, rhs: CGFloat) -> CGFloat {
return CGFloat(lhs) + rhs
}
public func - (lhs: CGFloat, rhs: Int) -> CGFloat {
return lhs - CGFloat(rhs)
}
public func - (lhs: Int, rhs: CGFloat) -> CGFloat {
return CGFloat(lhs) - rhs
}
// MATRIX
infix operator ✕: AdditionPrecedence
public func ✕ (lhs: Int, rhs: (Int) -> String) -> [String] {
var a: [String] = []
for i in 0..<lhs { let r = rhs(i); a.append(r) }
return a
}
public func ✕ (lhs: Int, rhs: (Int) -> [String]) -> [[String]] {
var a: [[String]] = []
for i in 0..<lhs { let r = rhs(i); a.append(r) }
return a
}
public func ✕ (lhs: Int, rhs: String) -> [String] {
return [String](repeating: rhs, count: lhs)
}
public func ✕ (lhs: Int, rhs: [String]) -> [[String]] {
return [[String]](repeating: rhs, count: lhs)
}
infix operator %% : AssignmentPrecedence
public func %% (lhs: String, rhs: String) -> (Int) -> String {
return { $0 % 2 == 0 ? lhs : rhs }
}
public func %% (lhs: [String], rhs: [String]) -> (Int) -> [String] {
return { $0 % 2 == 0 ? lhs : rhs }
}
| apache-2.0 | d76b1b36e66d945d5ca9e971cc295835 | 15.808081 | 68 | 0.529447 | 3.206166 | false | false | false | false |
downie/swift-daily-programmer | SwiftDailyChallenge.playground/Pages/260 - Garage Door Opener.xcplaygroundpage/Contents.swift | 1 | 3359 | /*:
# [2016-03-21] Challenge #259 [Easy] Clarence the Slow Typist
Published on: 2016-03-28\
Difficulty: Easy\
[reddit link](https://www.reddit.com/r/dailyprogrammer/comments/4cb7eh/20160328_challenge_260_easy_garage_door_opener/)
*/
import Foundation
enum GarageState : CustomStringConvertible {
case Closed, Open, Opening, Closing, StoppedWhileClosing, StoppedWhileOpening
var description: String {
var suffix = "UNKNOWN"
switch(self) {
case .Closed:
suffix = "CLOSED"
case .Opening:
suffix = "OPENING"
case .Closing:
suffix = "CLOSING"
case .Open:
suffix = "OPEN"
case .StoppedWhileClosing:
suffix = "STOPPED_WHILE_CLOSING"
case .StoppedWhileOpening:
suffix = "STOPPED_WHILE_OPENING"
}
return "Door: " + suffix
}
}
enum GarageInputs: String {
case ClickButton = "button_clicked"
case WaitForCycleToComplete = "cycle_complete"
}
func playWithDoor(defaultState : GarageState, inputs: [GarageInputs]) -> [String] {
var state = defaultState;
var output: [String] = [state.description];
inputs.forEach { input in
// Echo input state to output log
switch (input) {
case .ClickButton:
output.append("> Button clicked.")
case .WaitForCycleToComplete:
output.append("> Cycle complete.")
}
// Choose the new state
switch(input, state) {
case (.ClickButton, .Closed):
state = .Opening
case (.ClickButton, .Open):
state = .Closing
case (.ClickButton, .Opening):
state = .StoppedWhileOpening
case (.ClickButton, .Closing):
state = .StoppedWhileClosing
case (.ClickButton, .StoppedWhileOpening):
state = .Closing
case (.ClickButton, .StoppedWhileClosing):
state = .Opening
case (.WaitForCycleToComplete, .Opening):
state = .Open
case (.WaitForCycleToComplete, .Closing):
state = .Closed
default: break
}
output.append(state.description)
}
return output;
}
#if swift(>=3.0)
#else
func playWithDoor(defaultState defaultState : GarageState, inputs: [GarageInputs]) -> [String] {
return playWithDoor(defaultState, inputs: inputs)
}
#endif
//: Testing
let simpleInput = [
"button_clicked",
"cycle_complete",
"button_clicked",
"button_clicked",
"button_clicked",
"button_clicked",
"button_clicked",
"cycle_complete",
]
let expectedOutput = [
"Door: CLOSED",
"> Button clicked.",
"Door: OPENING",
"> Cycle complete.",
"Door: OPEN",
"> Button clicked.",
"Door: CLOSING",
"> Button clicked.",
"Door: STOPPED_WHILE_CLOSING",
"> Button clicked.",
"Door: OPENING",
"> Button clicked.",
"Door: STOPPED_WHILE_OPENING",
"> Button clicked.",
"Door: CLOSING",
"> Cycle complete.",
"Door: CLOSED",
]
let transformedInput = simpleInput.map { input in
return GarageInputs(rawValue: input)!
}
let output = playWithDoor(defaultState: .Closed, inputs: transformedInput)
output == expectedOutput
//: [back to Table of Contents](Table%20of%20Contents)
| mit | e60424cbd94fc27e41735e383c8ee529 | 24.838462 | 120 | 0.595713 | 4.086375 | false | false | false | false |
kz56cd/ios_sandbox_animate | IosSandboxAnimate/Utils/UILabel+Util.swift | 1 | 486 | //
// UILabel+Util.swift
// e-park
//
// Created by KaiKeima on 2016/01/31.
// Copyright © 2016年 OHAKO,inc. All rights reserved.
//
import UIKit
extension UILabel {
func setSelfAttributedText(var text: String?) {
if text?.characters.count == 0 {
text = " "
}
let attributes = attributedText?.attributesAtIndex(0, effectiveRange: nil)
attributedText = NSAttributedString(string: text ?? " ", attributes: attributes)
}
}
| mit | fd2ca4d7f3eda12dc13b9d9d64ae3f50 | 21.809524 | 88 | 0.63048 | 3.801587 | false | false | false | false |
clonezer/FreeForm | FreeForm/Classes/FreeFormPushCell.swift | 1 | 1836 | //
// FreeFormPushCell.swift
// Pods
//
// Created by Peerasak Unsakon on 1/5/17.
//
//
import UIKit
public class FreeFormPushRow: FreeFormRow {
public var options = [String]()
public init(tag: String, title: String, value: String, options: [String]) {
super.init(tag: tag, title: title, value: value as AnyObject?)
self.cellType = String(describing: FreeFormPushCell.self)
self.options = options
}
}
public class FreeFormPushCell: FreeFormCell {
@IBOutlet public weak var titleLabel: UILabel!
@IBOutlet public weak var valueLabel: UILabel!
override public func update() {
super.update()
guard let row = self.row as? FreeFormPushRow else { return }
self.titleLabel.text = row.title
row.didTapped = { cell in
self.pushOptionViewController(row: row)
}
guard let value = row.value as? String else {
self.valueLabel.text = ""
return
}
self.valueLabel.text = value
}
private func pushOptionViewController(row: FreeFormPushRow) {
let optionViewController = FreeFormOptionsViewController()
optionViewController.title = row.title
optionViewController.options = row.options
optionViewController.didSelectedBlock = { option in
self.optionDidSelected(option: option, row: row)
}
row.formViewController.navigationController?.pushViewController(optionViewController, animated: true)
}
private func optionDidSelected(option: String, row: FreeFormPushRow) {
row.value = option as AnyObject?
if let changeBlock = row.didChanged {
changeBlock(option as AnyObject, row)
}
self.update()
}
}
| mit | cf9b0b4dc1441397cf73c7c973fe769e | 26.818182 | 109 | 0.624183 | 4.613065 | false | false | false | false |
SmallwolfiOS/ChangingToSwift | ChangingToSwift03/ChangingToSwift03/AppDelegate.swift | 1 | 7085 | //
// AppDelegate.swift
// ChangingToSwift03
//
// Created by Jason on 16/6/14.
// Copyright © 2016年 Jason. All rights reserved.
//
/// 自定义通知的Action
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationSettings : UIUserNotificationSettings! = UIApplication.sharedApplication().currentUserNotificationSettings()
if notificationSettings.types == UIUserNotificationType.None {
setupNotificationSettings()
}
return true
}
func setupNotificationSettings() {
/*标示符(identifier):字符串,标示了一个对于整个App唯一的字符串。很明显,你永远不应该在同一个App中定义两个同样地标示符。通过此标示符,我们可以决定在用户点击不同的通知时,调用哪个动作。
标题(title):用来在展示给用户的动作按钮上。可以是简单地或者本地化的字符串。为了让用户能马上理解动作的含义,一定要仔细考虑这个标题的值,最好是1到2个字符。
(destructive):布尔值。当设置为true时,通知中相应地按钮的背景色会变成红色。这只会在banner通知中出现。通常,当动作代表着删除、移除或者其他关键的动作是都会被标记为destructive以获得用户的注意。
authenticationRequired:布尔值。当设置为true时,用户在点击动作之前必须确认自己的身份。当一个动作十分关键时这非常有用,因为为认证的操作有可能会破坏App的数据。
ActivationMode:枚举。决定App在通知动作点击后是应该被启动还是不被启动。此枚举有两个值: (a)UIUserNotificationActivationModeForeground, (b)UIUserNotificationActivationModeBackground。在background中,App被给予了几秒中来运行 代码。*/
let firstAction : UIMutableUserNotificationAction = UIMutableUserNotificationAction()
firstAction.identifier = "FIRST_ACTION"
firstAction.title = "First Action"
firstAction.activationMode = UIUserNotificationActivationMode.Background
firstAction.destructive = true
firstAction.authenticationRequired = false
let secondAction : UIMutableUserNotificationAction = UIMutableUserNotificationAction()
secondAction.identifier = "SECOND_ACTION"
secondAction.title = "Second Action"
secondAction.activationMode = UIUserNotificationActivationMode.Foreground
secondAction.destructive = false
secondAction.authenticationRequired = false
let thirdAction : UIMutableUserNotificationAction = UIMutableUserNotificationAction()
thirdAction.identifier = "THIRD_ACTION"
thirdAction.title = "Third Action"
thirdAction.activationMode = UIUserNotificationActivationMode.Background
thirdAction.destructive = true
thirdAction.authenticationRequired = false
//category
let firstCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
firstCategory.identifier = "FIRST_CATEGORY"
let defaultActions = [firstAction,secondAction,thirdAction]
let minimalACtions = [firstAction,secondAction]
firstCategory.setActions(defaultActions, forContext: UIUserNotificationActionContext.Default)//在屏幕的中央展示一个完整的alert。(未锁屏时)
firstCategory.setActions(minimalACtions, forContext: UIUserNotificationActionContext.Minimal)//展示一个banner alert。
//NSSet if our categories
let categories = NSSet (object:firstCategory)
let mySettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes:[.Badge, .Sound, .Alert] ,categories:categories as? Set<UIUserNotificationCategory>)
UIApplication.sharedApplication().registerUserNotificationSettings(mySettings)
}
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:.
}
/**
* 通知的代理
通过上述的方法,你可以得到所有UIUserNotificationSettings支持的类型。当你需要检查你的App所支持的通知和动作的类型时,这个方法非常有用。别忘了,用户可以通过用户设置来改变通知类型,所以我们不能保证,初始的通知类型一直都有效。
*/
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
print(notificationSettings.types.rawValue)
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("Received Local Notification:")
print(notification.alertBody)
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
print(identifier)
if identifier == "FIRST_ACTION" {
print("哈哈哈哈哈")
}else if identifier == "SECOND_ACTION"{
print("嘿嘿嘿嘿嘿嘿")
}
}
}
| mit | e220ca798690ee40014f7c39223c70ca | 50.559322 | 285 | 0.744247 | 4.898551 | false | false | false | false |
csound/csound | iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/ConsoleOutputViewController.swift | 3 | 5839 | /*
ConsoleOutputViewController.swift
Nikhil Singh, Dr. Richard Boulanger
Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini
This file is part of Csound iOS SwiftExamples.
The Csound for iOS Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
import UIKit
class ConsoleOutputViewController: BaseCsoundViewController {
@IBOutlet var renderButton: UIButton!
@IBOutlet var mTextView: UITextView!
var string: String?
var csdTable = UITableView()
fileprivate var csdArray: [String]?
fileprivate var csdPath: String?
private var folderPath: String?
private var csdListVC: UIViewController?
// This method is called by CsoundObj() to output console messages
@objc func messageCallback(_ infoObj: NSValue) {
var info = Message() // Create instance of Message (a C Struct)
infoObj.getValue(&info) // Store the infoObj value in Message
let message = UnsafeMutablePointer<Int8>.allocate(capacity: 1024) // Create an empty C-String
let va_ptr: CVaListPointer = CVaListPointer(_fromUnsafeMutablePointer: &(info.valist)) // Get reference to variable argument list
vsnprintf(message, 1024, info.format, va_ptr) // Store in our C-String
let output = String(cString: message) // Create String object with C-String
DispatchQueue.main.async { [unowned self] in
self.updateUIWithNewMessage(output) // Update UI on main thread
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
csdPath = folderPath?.appending((tableView.cellForRow(at: indexPath)?.textLabel?.text)!)
csdListVC?.dismiss(animated: true, completion: nil)
}
// MARK: IBActions
@IBAction func run(_ sender: UIButton) {
if sender.isSelected == false {
mTextView.text = ""
sender.isSelected = true
csound.stop()
csound = CsoundObj()
csound.setMessageCallback(#selector(messageCallback(_:)), withListener: self)
csound.add(self)
if csdPath != nil {
csound.play(csdPath)
}
} else {
csound.stop()
sender.isSelected = false
}
}
@IBAction func showCSDs(_ sender: UIButton) {
csdListVC = UIViewController()
csdListVC?.modalPresentationStyle = .popover
let popover = csdListVC?.popoverPresentationController
popover?.sourceView = sender
popover?.sourceRect = sender.bounds
csdListVC?.preferredContentSize = CGSize(width: 300, height: 600)
csdTable = UITableView(frame: CGRect(x: 0, y: 0, width: (csdListVC?.preferredContentSize.width)!, height:
(csdListVC?.preferredContentSize.height)!))
csdTable.delegate = self
csdTable.dataSource = self
csdListVC?.view.addSubview(csdTable)
popover?.delegate = self
if csdListVC != nil {
present(csdListVC!, animated: true, completion: nil)
}
}
@IBAction func showInfo(_ sender: UIButton) {
infoVC.preferredContentSize = CGSize(width: 300, height: 160)
infoText = "Renders, by default, a simple 5-second 'countdown' csd and publishes information to a virtual Csound console every second. Click the CSD button on the right to select a different csd file."
displayInfo(sender)
}
override func viewDidLoad() {
folderPath = Bundle.main.resourcePath?.appending("/csdStorage/")
if folderPath != nil {
do {
csdArray = try FileManager.default.contentsOfDirectory(atPath: folderPath!)
} catch {
print(error.localizedDescription)
}
}
csdPath = Bundle.main.path(forResource: "TextOnly - Countdown", ofType: "csd", inDirectory: "csdStorage")
super.viewDidLoad()
}
func updateUIWithNewMessage(_ newMessage: String) {
mTextView.insertText(newMessage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ConsoleOutputViewController: CsoundObjListener {
func csoundObjCompleted(_ csoundObj: CsoundObj!) {
DispatchQueue.main.async { [unowned self] in
self.renderButton.isSelected = false
}
}
}
// MARK: TableView delegate/data source methods
extension ConsoleOutputViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if csdArray != nil {
return csdArray!.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.dequeueReusableCell(withIdentifier: "Cell")
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
if csdArray != nil {
cell.textLabel?.text = csdArray?[indexPath.row]
}
return cell
}
}
| lgpl-2.1 | 2276ee137e6db8fa937ee9a715b92e42 | 36.191083 | 209 | 0.657476 | 4.708871 | false | false | false | false |
jfosterdavis/Charles | Charles/BasicClueViewController.swift | 1 | 8036 | //
// BasicClueViewController.swift
// Charles
//
// Created by Jacob Foster Davis on 6/16/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
/******************************************************/
/*******************///MARK: A basic clue is one with up to 5 paragraphs that appear in order, with a title. Presented to user over time to help them understand the game.
/******************************************************/
class BasicClueViewController: UIViewController {
@IBOutlet weak var dismissButton: UIButton!
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var clueTitle: UILabel!
@IBOutlet weak var part1: UILabel!
@IBOutlet weak var part1ImageView: UIImageView!
@IBOutlet weak var part2: UILabel!
@IBOutlet weak var part2ImageView: UIImageView!
@IBOutlet weak var part3: UILabel!
@IBOutlet weak var part3ImageView: UIImageView!
var clue: Clue!
var delayDismissButton = true
var didLayout = false
var overrideTextColor: UIColor? = nil
var overrideGoldenRatio = false
var overrideStackViewDistribution: UIStackViewDistribution? = nil
var numNilSections = 0
var blurEffectView = UIVisualEffectView()
override func viewDidLoad() {
super.viewDidLoad()
if delayDismissButton {
dismissButton.isHidden = true
dismissButton.isEnabled = true
dismissButton.alpha = 0
} else {
dismissButton.isHidden = false
dismissButton.isEnabled = true
dismissButton.alpha = 1
}
//view.backgroundColor = .clear
//view.isOpaque = false
//self.preferredContentSize = CGSize(width: 100, height: 150)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let newDistribution = overrideStackViewDistribution {
stackView.distribution = newDistribution
}
loadClue(clue: clue)
if !didLayout {
let width:CGFloat = self.view.bounds.width * 0.92
let height:CGFloat = width * 1.618 //golden ratio
let adjustedHeight:CGFloat
if overrideGoldenRatio {
let heightToRemove = CGFloat(numNilSections) * (height * (1.0/6.0)) - 100
//allows some versions to get smaller
//remove 1/6 - height of title and top bottom margins of the height for every nil section
adjustedHeight = height - heightToRemove
} else {
adjustedHeight = height
}
self.view.superview!.backgroundColor = .clear //UIColor(red: 0, green: 0, blue: 0, alpha: 0.6) //dim the background to focus on the modal
let screen = self.view.superview!.bounds
let frame = CGRect(x: 0, y: 0, width: width, height: adjustedHeight)
let x = (screen.size.width - frame.size.width) * 0.5
let y = (screen.size.height - frame.size.height) * 0.5
let mainFrame = CGRect(x: x, y: y, width: frame.size.width, height: frame.size.height)
self.view.frame = mainFrame
//add a blur layer to background.
//add blur effect
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.view.superview!.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.superview!.insertSubview(blurEffectView, belowSubview: self.view)
didLayout = true
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
blurEffectView.removeFromSuperview()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// if let part1Image = part1ImageView {
// part1Image.roundCorners(with: 3)
// }
// if let part2Image = part2ImageView {
// part2Image.roundCorners(with: 3)
// }
// if let part3Image = part3ImageView {
// part3Image.roundCorners(with: 3)
// }
//stackView.roundCorners(with: 4)
let radius = dismissButton.bounds.width / 2
self.view.roundCorners(with: radius)
dismissButton.roundCorners(with: radius)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if delayDismissButton {
dismissButton.fade(.in, withDuration: 3, delay: 5, completion: nil)
}
}
func loadClue(clue: Clue) {
self.numNilSections = 0
self.clueTitle.text = clue.clueTitle
if let textColor = overrideTextColor {
self.clueTitle.textColor = textColor
}
if let part1 = clue.part1 {
self.part1.text = part1
self.part1.backgroundColor = self.view.backgroundColor
if let textColor = overrideTextColor {
self.part1.textColor = textColor
}
} else {
stackView.removeArrangedSubview(self.part1)
self.part1.removeFromSuperview()
self.part1.isHidden = true
self.numNilSections += 1
}
if let part1Image = clue.part1Image {
self.part1ImageView.image = part1Image
self.part1ImageView.backgroundColor = self.view.backgroundColor
} else {
stackView.removeArrangedSubview(self.part1ImageView)
self.part1ImageView.removeFromSuperview()
self.part1ImageView.isHidden = true
self.numNilSections += 1
}
if let part2 = clue.part2 {
self.part2.text = part2
self.part2.backgroundColor = self.view.backgroundColor
if let textColor = overrideTextColor {
self.part2.textColor = textColor
}
} else {
stackView.removeArrangedSubview(self.part2)
self.part2.removeFromSuperview()
self.part2.isHidden = true
self.numNilSections += 1
}
if let part2Image = clue.part2Image {
self.part2ImageView.image = part2Image
self.part2ImageView.backgroundColor = self.view.backgroundColor
} else {
stackView.removeArrangedSubview(self.part2ImageView)
self.part2ImageView.removeFromSuperview()
self.part2ImageView.isHidden = true
self.numNilSections += 1
}
if let part3 = clue.part3 {
self.part3.text = part3
self.part3.backgroundColor = self.view.backgroundColor
if let textColor = overrideTextColor {
self.part3.textColor = textColor
}
} else {
stackView.removeArrangedSubview(self.part3)
self.part3.removeFromSuperview()
self.part3.isHidden = true
self.numNilSections += 1
}
if let part3Image = clue.part3Image {
self.part3ImageView.image = part3Image
self.part3ImageView.backgroundColor = self.view.backgroundColor
} else {
stackView.removeArrangedSubview(self.part3ImageView)
self.part3ImageView.removeFromSuperview()
self.part3ImageView.isHidden = true
self.numNilSections += 1
}
}
@IBAction func dismissButtonPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | dfdcb2e2d21c4788007e43744d68c533 | 32.619247 | 171 | 0.569757 | 5.063012 | false | false | false | false |
coderQuanjun/RxSwift-Table-Collection | RxSwift-Table-Collection1/Pods/Differentiator/Sources/Differentiator/Diff.swift | 4 | 32726 | //
// Differentiator.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
fileprivate extension AnimatableSectionModelType {
init(safeOriginal: Self, safeItems: [Item]) throws {
self.init(original: safeOriginal, items: safeItems)
if self.items != safeItems || self.identity != safeOriginal.identity {
throw Diff.Error.invalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity)
}
}
}
public enum Diff {
public enum Error : Swift.Error, CustomDebugStringConvertible {
case duplicateItem(item: Any)
case duplicateSection(section: Any)
case invalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any)
public var debugDescription: String {
switch self {
case let .duplicateItem(item):
return "Duplicate item \(item)"
case let .duplicateSection(section):
return "Duplicate section \(section)"
case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier):
return "Wrong initializer implementation for: \(section)\n" +
"Expected it should return items: \(expectedItems)\n" +
"Expected it should have id: \(expectedIdentifier)"
}
}
}
private enum EditEvent : CustomDebugStringConvertible {
case inserted // can't be found in old sections
case insertedAutomatically // Item inside section being inserted
case deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated
case deletedAutomatically // Item inside section that is being deleted
case moved // same item, but was on different index, and needs explicit move
case movedAutomatically // don't need to specify any changes for those rows
case untouched
var debugDescription: String {
get {
switch self {
case .inserted:
return "Inserted"
case .insertedAutomatically:
return "InsertedAutomatically"
case .deleted:
return "Deleted"
case .deletedAutomatically:
return "DeletedAutomatically"
case .moved:
return "Moved"
case .movedAutomatically:
return "MovedAutomatically"
case .untouched:
return "Untouched"
}
}
}
}
private struct SectionAssociatedData : CustomDebugStringConvertible {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: Int?
var itemCount: Int
var debugDescription: String {
get {
return "\(event), \(String(describing: indexAfterDelete))"
}
}
static var initial: SectionAssociatedData {
return SectionAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil, itemCount: 0)
}
}
private struct ItemAssociatedData: CustomDebugStringConvertible {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: ItemPath?
var debugDescription: String {
get {
return "\(event) \(String(describing: indexAfterDelete))"
}
}
static var initial : ItemAssociatedData {
return ItemAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
private static func indexSections<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Identity : Int] {
var indexedSections: [S.Identity : Int] = [:]
for (i, section) in sections.enumerated() {
guard indexedSections[section.identity] == nil else {
#if DEBUG
if indexedSections[section.identity] != nil {
print("Section \(section) has already been indexed at \(indexedSections[section.identity]!)")
}
#endif
throw Error.duplicateSection(section: section)
}
indexedSections[section.identity] = i
}
return indexedSections
}
//================================================================================
// Optimizations because Swift dictionaries are extremely slow (ARC, bridging ...)
//================================================================================
// swift dictionary optimizations {
private struct OptimizedIdentity<E: Hashable> : Hashable {
let hashValue: Int
let identity: UnsafePointer<E>
init(_ identity: UnsafePointer<E>) {
self.identity = identity
self.hashValue = identity.pointee.hashValue
}
static func == <E: Hashable>(lhs: OptimizedIdentity<E>, rhs: OptimizedIdentity<E>) -> Bool {
if lhs.hashValue != rhs.hashValue {
return false
}
if lhs.identity.distance(to: rhs.identity) == 0 {
return true
}
return lhs.identity.pointee == rhs.identity.pointee
}
}
private static func calculateAssociatedData<Item: IdentifiableType>(
initialItemCache: ContiguousArray<ContiguousArray<Item>>,
finalItemCache: ContiguousArray<ContiguousArray<Item>>
) throws
-> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) {
typealias Identity = Item.Identity
let totalInitialItems = initialItemCache.map { $0.count }.reduce(0, +)
var initialIdentities: ContiguousArray<Identity> = ContiguousArray()
var initialItemPaths: ContiguousArray<ItemPath> = ContiguousArray()
initialIdentities.reserveCapacity(totalInitialItems)
initialItemPaths.reserveCapacity(totalInitialItems)
for (i, items) in initialItemCache.enumerated() {
for j in 0 ..< items.count {
let item = items[j]
initialIdentities.append(item.identity)
initialItemPaths.append(ItemPath(sectionIndex: i, itemIndex: j))
}
}
var initialItemData = ContiguousArray(initialItemCache.map { items in
return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count)
})
var finalItemData = ContiguousArray(finalItemCache.map { items in
return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count)
})
try initialIdentities.withUnsafeBufferPointer { (identitiesBuffer: UnsafeBufferPointer<Identity>) -> () in
var dictionary: [OptimizedIdentity<Identity>: Int] = Dictionary(minimumCapacity: totalInitialItems * 2)
for i in 0 ..< initialIdentities.count {
let identityPointer = identitiesBuffer.baseAddress!.advanced(by: i)
let key = OptimizedIdentity(identityPointer)
if let existingValueItemPathIndex = dictionary[key] {
let itemPath = initialItemPaths[existingValueItemPathIndex]
let item = initialItemCache[itemPath.sectionIndex][itemPath.itemIndex]
#if DEBUG
print("Item \(item) has already been indexed at \(itemPath)" )
#endif
throw Error.duplicateItem(item: item)
}
dictionary[key] = i
}
for (i, items) in finalItemCache.enumerated() {
for j in 0 ..< items.count {
let item = items[j]
var identity = item.identity
let key = OptimizedIdentity(&identity)
guard let initialItemPathIndex = dictionary[key] else {
continue
}
let itemPath = initialItemPaths[initialItemPathIndex]
if initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex != nil {
throw Error.duplicateItem(item: item)
}
initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex = ItemPath(sectionIndex: i, itemIndex: j)
finalItemData[i][j].moveIndex = itemPath
}
}
return ()
}
return (initialItemData, finalItemData)
}
// } swift dictionary optimizations
/*
I've uncovered this case during random stress testing of logic.
This is the hardest generic update case that causes two passes, first delete, and then move/insert
[
NumberSection(model: "1", items: [1111]),
NumberSection(model: "2", items: [2222]),
]
[
NumberSection(model: "2", items: [0]),
NumberSection(model: "1", items: []),
]
If update is in the form
* Move section from 2 to 1
* Delete Items at paths 0 - 0, 1 - 0
* Insert Items at paths 0 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 1 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 0 - 0
it crashes table view.
No matter what change is performed, it fails for me.
If anyone knows how to make this work for one Changeset, PR is welcome.
*/
// If you are considering working out your own algorithm, these are tricky
// transition cases that you can use.
// case 1
/*
from = [
NumberSection(model: "section 4", items: [10, 11, 12]),
NumberSection(model: "section 9", items: [25, 26, 27]),
]
to = [
HashableSectionModel(model: "section 9", items: [11, 26, 27]),
HashableSectionModel(model: "section 4", items: [10, 12])
]
*/
// case 2
/*
from = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 7", items: [5, 29]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 5", items: [16]),
HashableSectionModel(model: "section 4", items: []),
HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20])
]
to = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 9", items: [3]),
HashableSectionModel(model: "section 5", items: [16, 8]),
HashableSectionModel(model: "section 8", items: [15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20]),
HashableSectionModel(model: "Section 2", items: [7])
]
*/
// case 3
/*
from = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: []),
HashableSectionModel(model: "section 2", items: [2, 26]),
HashableSectionModel(model: "section 8", items: [23]),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
to = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: [16]),
HashableSectionModel(model: "section 7", items: [17, 15, 4]),
HashableSectionModel(model: "section 2", items: [2, 26, 23]),
HashableSectionModel(model: "section 8", items: []),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
*/
// Generates differential changes suitable for sectioned view consumption.
// It will not only detect changes between two states, but it will also try to compress those changes into
// almost minimal set of changes.
//
// I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and
// avoids UITableView quirks.
//
// Please take into consideration that I was also convinced about 20 times that I've found a simple general
// solution, but then UITableView falls apart under stress testing :(
//
// Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think
// that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :)
//
// Maybe it can be made somewhat simpler, but don't think it can be made much simpler.
//
// The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates.
//
// * stage 1 - remove deleted sections and items
// * stage 2 - move sections into place
// * stage 3 - fix moved and new items
//
// There maybe exists a better division, but time will tell.
//
public static func differencesForSectionedView<S: AnimatableSectionModelType>(
initialSections: [S],
finalSections: [S])
throws -> [Changeset<S>] {
typealias I = S.Item
var result: [Changeset<S>] = []
var sectionCommands = try CommandGenerator<S>.generatorForInitialSections(initialSections, finalSections: finalSections)
result.append(contentsOf: try sectionCommands.generateDeleteSectionsDeletedItemsAndUpdatedItems())
result.append(contentsOf: try sectionCommands.generateInsertAndMoveSections())
result.append(contentsOf: try sectionCommands.generateInsertAndMovedItems())
return result
}
@available(*, deprecated, renamed: "differencesForSectionedView(initialSections:finalSections:)")
public static func differencesForSectionedView<S: AnimatableSectionModelType>(
_ initialSections: [S],
finalSections: [S])
throws -> [Changeset<S>] {
return try differencesForSectionedView(initialSections: initialSections, finalSections: finalSections)
}
private struct CommandGenerator<S: AnimatableSectionModelType> {
typealias Item = S.Item
let initialSections: [S]
let finalSections: [S]
let initialSectionData: ContiguousArray<SectionAssociatedData>
let finalSectionData: ContiguousArray<SectionAssociatedData>
let initialItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>>
let finalItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>>
let initialItemCache: ContiguousArray<ContiguousArray<Item>>
let finalItemCache: ContiguousArray<ContiguousArray<Item>>
static func generatorForInitialSections(
_ initialSections: [S],
finalSections: [S]
) throws -> CommandGenerator<S> {
let (initialSectionData, finalSectionData) = try calculateSectionMovements(initialSections: initialSections, finalSections: finalSections)
let initialItemCache = ContiguousArray(initialSections.map {
ContiguousArray($0.items)
})
let finalItemCache = ContiguousArray(finalSections.map {
ContiguousArray($0.items)
})
let (initialItemData, finalItemData) = try calculateItemMovements(
initialItemCache: initialItemCache,
finalItemCache: finalItemCache,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData
)
return CommandGenerator<S>(
initialSections: initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData,
initialItemData: initialItemData,
finalItemData: finalItemData,
initialItemCache: initialItemCache,
finalItemCache: finalItemCache
)
}
static func calculateItemMovements(
initialItemCache: ContiguousArray<ContiguousArray<Item>>,
finalItemCache: ContiguousArray<ContiguousArray<Item>>,
initialSectionData: ContiguousArray<SectionAssociatedData>,
finalSectionData: ContiguousArray<SectionAssociatedData>) throws
-> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) {
var (initialItemData, finalItemData) = try Diff.calculateAssociatedData(
initialItemCache: initialItemCache,
finalItemCache: finalItemCache
)
let findNextUntouchedOldIndex = { (initialSectionIndex: Int, initialSearchIndex: Int?) -> Int? in
guard var i2 = initialSearchIndex else {
return nil
}
while i2 < initialSectionData[initialSectionIndex].itemCount {
if initialItemData[initialSectionIndex][i2].event == .untouched {
return i2
}
i2 = i2 + 1
}
return nil
}
// first mark deleted items
for i in 0 ..< initialItemCache.count {
guard let _ = initialSectionData[i].moveIndex else {
continue
}
var indexAfterDelete = 0
for j in 0 ..< initialItemCache[i].count {
guard let finalIndexPath = initialItemData[i][j].moveIndex else {
initialItemData[i][j].event = .deleted
continue
}
// from this point below, section has to be move type because it's initial and not deleted
// because there is no move to inserted section
if finalSectionData[finalIndexPath.sectionIndex].event == .inserted {
initialItemData[i][j].event = .deleted
continue
}
initialItemData[i][j].indexAfterDelete = indexAfterDelete
indexAfterDelete += 1
}
}
// mark moved or moved automatically
for i in 0 ..< finalItemCache.count {
guard let originalSectionIndex = finalSectionData[i].moveIndex else {
continue
}
var untouchedIndex: Int? = 0
for j in 0 ..< finalItemCache[i].count {
untouchedIndex = findNextUntouchedOldIndex(originalSectionIndex, untouchedIndex)
guard let originalIndex = finalItemData[i][j].moveIndex else {
finalItemData[i][j].event = .inserted
continue
}
// In case trying to move from deleted section, abort, otherwise it will crash table view
if initialSectionData[originalIndex.sectionIndex].event == .deleted {
finalItemData[i][j].event = .inserted
continue
}
// original section can't be inserted
else if initialSectionData[originalIndex.sectionIndex].event == .inserted {
try precondition(false, "New section in initial sections, that is wrong")
}
let initialSectionEvent = initialSectionData[originalIndex.sectionIndex].event
try precondition(initialSectionEvent == .moved || initialSectionEvent == .movedAutomatically, "Section not moved")
let eventType = originalIndex == ItemPath(sectionIndex: originalSectionIndex, itemIndex: untouchedIndex ?? -1)
? EditEvent.movedAutomatically : EditEvent.moved
initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].event = eventType
finalItemData[i][j].event = eventType
}
}
return (initialItemData, finalItemData)
}
static func calculateSectionMovements(initialSections: [S], finalSections: [S]) throws
-> (ContiguousArray<SectionAssociatedData>, ContiguousArray<SectionAssociatedData>) {
let initialSectionIndexes = try Diff.indexSections(initialSections)
var initialSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: initialSections.count)
var finalSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: finalSections.count)
for (i, section) in finalSections.enumerated() {
finalSectionData[i].itemCount = finalSections[i].items.count
guard let initialSectionIndex = initialSectionIndexes[section.identity] else {
continue
}
if initialSectionData[initialSectionIndex].moveIndex != nil {
throw Error.duplicateSection(section: section)
}
initialSectionData[initialSectionIndex].moveIndex = i
finalSectionData[i].moveIndex = initialSectionIndex
}
var sectionIndexAfterDelete = 0
// deleted sections
for i in 0 ..< initialSectionData.count {
initialSectionData[i].itemCount = initialSections[i].items.count
if initialSectionData[i].moveIndex == nil {
initialSectionData[i].event = .deleted
continue
}
initialSectionData[i].indexAfterDelete = sectionIndexAfterDelete
sectionIndexAfterDelete += 1
}
// moved sections
var untouchedOldIndex: Int? = 0
let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in
guard var i = initialSearchIndex else {
return nil
}
while i < initialSections.count {
if initialSectionData[i].event == .untouched {
return i
}
i = i + 1
}
return nil
}
// inserted and moved sections {
// this should fix all sections and move them into correct places
// 2nd stage
for i in 0 ..< finalSections.count {
untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex)
// oh, it did exist
if let oldSectionIndex = finalSectionData[i].moveIndex {
let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.moved : EditEvent.movedAutomatically
finalSectionData[i].event = moveType
initialSectionData[oldSectionIndex].event = moveType
}
else {
finalSectionData[i].event = .inserted
}
}
// inserted sections
for (i, section) in finalSectionData.enumerated() {
if section.moveIndex == nil {
_ = finalSectionData[i].event == .inserted
}
}
return (initialSectionData, finalSectionData)
}
mutating func generateDeleteSectionsDeletedItemsAndUpdatedItems() throws -> [Changeset<S>] {
var deletedSections = [Int]()
var deletedItems = [ItemPath]()
var updatedItems = [ItemPath]()
var afterDeleteState = [S]()
// mark deleted items {
// 1rst stage again (I know, I know ...)
for (i, initialItems) in initialItemCache.enumerated() {
let event = initialSectionData[i].event
// Deleted section will take care of deleting child items.
// In case of moving an item from deleted section, tableview will
// crash anyway, so this is not limiting anything.
if event == .deleted {
deletedSections.append(i)
continue
}
var afterDeleteItems: [S.Item] = []
for j in 0 ..< initialItems.count {
let event = initialItemData[i][j].event
switch event {
case .deleted:
deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved, .movedAutomatically:
let finalItemIndex = try initialItemData[i][j].moveIndex.unwrap()
let finalItem = finalItemCache[finalItemIndex.sectionIndex][finalItemIndex.itemIndex]
if finalItem != initialSections[i].items[j] {
updatedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
}
afterDeleteItems.append(finalItem)
default:
try precondition(false, "Unhandled case")
}
}
afterDeleteState.append(try S.init(safeOriginal: initialSections[i], safeItems: afterDeleteItems))
}
// }
if deletedItems.count == 0 && deletedSections.count == 0 && updatedItems.count == 0 {
return []
}
return [Changeset(
finalSections: afterDeleteState,
deletedSections: deletedSections,
deletedItems: deletedItems,
updatedItems: updatedItems
)]
}
func generateInsertAndMoveSections() throws -> [Changeset<S>] {
var movedSections = [(from: Int, to: Int)]()
var insertedSections = [Int]()
for i in 0 ..< initialSections.count {
switch initialSectionData[i].event {
case .deleted:
break
case .moved:
movedSections.append((from: try initialSectionData[i].indexAfterDelete.unwrap(), to: try initialSectionData[i].moveIndex.unwrap()))
case .movedAutomatically:
break
default:
try precondition(false, "Unhandled case in initial sections")
}
}
for i in 0 ..< finalSections.count {
switch finalSectionData[i].event {
case .inserted:
insertedSections.append(i)
default:
break
}
}
if insertedSections.count == 0 && movedSections.count == 0 {
return []
}
// sections should be in place, but items should be original without deleted ones
let sectionsAfterChange: [S] = try self.finalSections.enumerated().map { i, s -> S in
let event = self.finalSectionData[i].event
if event == .inserted {
// it's already set up
return s
}
else if event == .moved || event == .movedAutomatically {
let originalSectionIndex = try finalSectionData[i].moveIndex.unwrap()
let originalSection = initialSections[originalSectionIndex]
var items: [S.Item] = []
items.reserveCapacity(originalSection.items.count)
let itemAssociatedData = self.initialItemData[originalSectionIndex]
for j in 0 ..< originalSection.items.count {
let initialData = itemAssociatedData[j]
guard initialData.event != .deleted else {
continue
}
guard let finalIndex = initialData.moveIndex else {
try precondition(false, "Item was moved, but no final location.")
continue
}
items.append(finalItemCache[finalIndex.sectionIndex][finalIndex.itemIndex])
}
let modifiedSection = try S.init(safeOriginal: s, safeItems: items)
return modifiedSection
}
else {
try precondition(false, "This is weird, this shouldn't happen")
return s
}
}
return [Changeset(
finalSections: sectionsAfterChange,
insertedSections: insertedSections,
movedSections: movedSections
)]
}
mutating func generateInsertAndMovedItems() throws -> [Changeset<S>] {
var insertedItems = [ItemPath]()
var movedItems = [(from: ItemPath, to: ItemPath)]()
// mark new and moved items {
// 3rd stage
for i in 0 ..< finalSections.count {
let finalSection = finalSections[i]
let sectionEvent = finalSectionData[i].event
// new and deleted sections cause reload automatically
if sectionEvent != .moved && sectionEvent != .movedAutomatically {
continue
}
for j in 0 ..< finalSection.items.count {
let currentItemEvent = finalItemData[i][j].event
try precondition(currentItemEvent != .untouched, "Current event is not untouched")
let event = finalItemData[i][j].event
switch event {
case .inserted:
insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved:
let originalIndex = try finalItemData[i][j].moveIndex.unwrap()
let finalSectionIndex = try initialSectionData[originalIndex.sectionIndex].moveIndex.unwrap()
let moveFromItemWithIndex = try initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].indexAfterDelete.unwrap()
let moveCommand = (
from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex),
to: ItemPath(sectionIndex: i, itemIndex: j)
)
movedItems.append(moveCommand)
default:
break
}
}
}
// }
if insertedItems.count == 0 && movedItems.count == 0 {
return []
}
return [Changeset(
finalSections: finalSections,
insertedItems: insertedItems,
movedItems: movedItems
)]
}
}
}
| mit | 6c3676635c98c355f419bd5112e7bf3b | 40.267339 | 151 | 0.550191 | 6.05122 | false | false | false | false |
practicalswift/swift | test/SILGen/generic_tuples.swift | 24 | 1594 |
// RUN: %target-swift-emit-silgen -module-name generic_tuples -parse-as-library %s | %FileCheck %s
func dup<T>(_ x: T) -> (T, T) { return (x,x) }
// CHECK-LABEL: sil hidden [ossa] @$s14generic_tuples3dup{{[_0-9a-zA-Z]*}}F
// CHECK: ([[RESULT_0:%.*]] : $*T, [[RESULT_1:%.*]] : $*T, [[XVAR:%.*]] : $*T):
// CHECK-NEXT: debug_value_addr [[XVAR]] : $*T, let, name "x"
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_0]]
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_1]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]]
// <rdar://problem/13822463>
// Specializing a generic function on a tuple type changes the number of
// SIL parameters, which caused a failure in the ownership conventions code.
struct Blub {}
// CHECK-LABEL: sil hidden [ossa] @$s14generic_tuples3foo{{[_0-9a-zA-Z]*}}F
func foo<T>(_ x: T) {}
// CHECK-LABEL: sil hidden [ossa] @$s14generic_tuples3bar{{[_0-9a-zA-Z]*}}F
func bar(_ x: (Blub, Blub)) { foo(x) }
// rdar://26279628
// A type parameter constrained to be a concrete type must be handled
// as that concrete type throughout SILGen. That's especially true
// if it's constrained to be a tuple.
protocol HasAssoc {
associatedtype A
}
extension HasAssoc where A == (Int, Int) {
func returnTupleAlias() -> A {
return (0, 0)
}
}
// CHECK-LABEL: sil hidden [ossa] @$s14generic_tuples8HasAssocPAASi_Sit1ARtzrlE16returnTupleAliasSi_SityF : $@convention(method) <Self where Self : HasAssoc, Self.A == (Int, Int)> (@in_guaranteed Self) -> (Int, Int) {
// CHECK: return {{.*}} : $(Int, Int)
| apache-2.0 | 1189202a8dd4e918e7d5994b25f6d6d1 | 39.871795 | 217 | 0.636136 | 3.030418 | false | false | false | false |
huonw/swift | stdlib/public/core/PlaygroundDisplay.swift | 40 | 2832 | //===--- PlaygroundDisplay.swift ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that supplies a custom description for playground logging.
///
/// Playground logging can generate, at a minimum, a structured description
/// of any type. If you want to provide a custom description of your type to be
/// logged in place of the default description, conform to the
/// `CustomPlaygroundDisplayConvertible` protocol.
///
/// Playground logging generates a richer, more specialized description of core
/// types. For example, the contents of a `String` are logged, as are the
/// components of an `NSColor` or `UIColor`. The current playground logging
/// implementation logs specialized descriptions of at least the following
/// types:
///
/// - `String` and `NSString`
/// - `Int`, `UInt`, and the other standard library integer types
/// - `Float` and `Double`
/// - `Bool`
/// - `Date` and `NSDate`
/// - `NSAttributedString`
/// - `NSNumber`
/// - `NSRange`
/// - `URL` and `NSURL`
/// - `CGPoint`, `CGSize`, and `CGRect`
/// - `NSColor`, `UIColor`, `CGColor`, and `CIColor`
/// - `NSImage`, `UIImage`, `CGImage`, and `CIImage`
/// - `NSBezierPath` and `UIBezierPath`
/// - `NSView` and `UIView`
///
/// Playground logging may also be able to support specialized descriptions
/// of other types.
///
/// Conforming to the CustomPlaygroundDisplayConvertible Protocol
/// -------------------------------------------------------------
///
/// To add `CustomPlaygroundDisplayConvertible` conformance to your custom type,
/// implement the `playgroundDescription` property. If your implementation
/// returns an instance of one of the types above, that type's specialized
/// description is used. If you return any other type, a structured description
/// is generated.
///
/// If your type has value semantics, the `playgroundDescription` should be
/// unaffected by subsequent mutations, if possible.
///
/// If your type's `playgroundDescription` returns an instance which itself
/// conforms to `CustomPlaygroundDisplayConvertible`, then that type's
/// `playgroundDescription` will be used, and so on. To prevent infinite loops,
/// playground logging implementations can place a reasonable limit on this
/// kind of chaining.
public protocol CustomPlaygroundDisplayConvertible {
/// A custom playground description for this instance.
var playgroundDescription: Any { get }
}
| apache-2.0 | 8ef06118e2f1550b58729cbba7122d98 | 43.25 | 80 | 0.67726 | 4.712146 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.